@prunellejs/cms 0.6.0 → 0.7.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.
- package/LICENSE +21 -0
- package/llms.txt +10 -3
- package/package.json +2 -2
- package/src/form-data.ts +41 -90
- package/src/guard.ts +23 -0
- package/src/handlers.ts +36 -77
- package/src/index.ts +8 -6
- package/src/inline-handlers.ts +9 -4
- package/src/sanitize.ts +3 -137
- package/src/shared.ts +6 -17
- package/src/write-file.ts +58 -0
- package/src/yaml-serialize.ts +214 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kaynooo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/llms.txt
CHANGED
|
@@ -10,11 +10,11 @@
|
|
|
10
10
|
|
|
11
11
|
Register `cms()` in `prunelle.config.ts` alongside `content()` from `@prunellejs/content`. Collections are discovered automatically via the shared `CONTENT_COLLECTIONS_SERVICE` — never declare fields twice.
|
|
12
12
|
|
|
13
|
-
- `guard?: (ctx: RequestContext) => boolean | Response | Promise<boolean | Response>`: runs on every CMS route and gates in-page overlay injection. Return `false` for `403 Forbidden`, or return a `Response` (e.g. a login redirect).
|
|
13
|
+
- `guard?: (ctx: RequestContext) => boolean | Response | Promise<boolean | Response>`: runs on every CMS route and gates in-page overlay injection. Return `false` for `403 Forbidden`, or return a `Response` (e.g. a login redirect). Optional on a loopback `prunelle dev`; with `prunelle dev --host` on an address other machines reach, the CMS throws at start without one.
|
|
14
14
|
- `basePath?: string`: URL prefix where the dev CMS is mounted (default `'/_pru/cms'`).
|
|
15
15
|
- `inline?: boolean`: inject the dev-only Shadow DOM in-page editing overlay on pages that read file-backed collections (default `true`; set `false` for `/_pru/cms`-only editing).
|
|
16
16
|
|
|
17
|
-
## Mounted Routes (dev-only — never mounted when `dev: false` or on `--static
|
|
17
|
+
## Mounted Routes (dev-only — never mounted when `dev: false` or on `--static`, and their code is not even loaded then)
|
|
18
18
|
|
|
19
19
|
- `GET /_pru/cms` — list all collections with entry counts and links to create entries.
|
|
20
20
|
- `GET /_pru/cms/:collection` — list entries with optional `?locale=...` switching and `?q=...` filtering.
|
|
@@ -22,9 +22,16 @@ Register `cms()` in `prunelle.config.ts` alongside `content()` from `@prunellejs
|
|
|
22
22
|
- `GET /_pru/cms/:collection/*slug` & `POST /_pru/cms/:collection/*slug` — edit an existing entry (supports nested slugs and `?locale=...`).
|
|
23
23
|
- `GET /_pru/cms/_entry?collection=...&slug=...&locale=...` — JSON metadata, schema fields, frontmatter, and Markdown body for the in-page overlay.
|
|
24
24
|
- `PATCH /_pru/cms/_inline` — CSRF-protected, Standard Schema-validated JSON patch/save endpoint used by the in-page overlay (`422` returns `{ ok: false, errors }`).
|
|
25
|
-
- `POST /_pru/cms/_preview` — renders
|
|
25
|
+
- `POST /_pru/cms/_preview` — renders Markdown preview HTML via `Bun.markdown.html()`, sanitized with the allowlist `@prunellejs/content` applies to the published page.
|
|
26
26
|
- `GET /_pru/cms/_assets/cms.css`, `cms.js`, `inline.css`, `inline.js` — self-contained RGAA-accessible stylesheets and scripts (0 B in production/`--static`).
|
|
27
27
|
|
|
28
|
+
## Saving and slugs
|
|
29
|
+
|
|
30
|
+
- Slugs follow `@prunellejs/content`: `_index`, `café`, `my post`, nested `a/b c`. Refused: empty, `.`, `..` and `__proto__` segments, backslash, control characters, lone surrogates. A segment over 252 bytes or a path over 4000 bytes is a `422` field error on the slug ("too long").
|
|
31
|
+
- Create is exclusive (`wx`): a concurrent second create of one slug gets `422` "An entry with this slug already exists.". Update writes a temp file in the entry's folder and renames it (a symlinked entry keeps its link).
|
|
32
|
+
- Frontmatter is edited in place: comments, order and keys the form has no field for are kept, only changed keys are rewritten (a trailing `# note` on a plain one-line value stays), new keys are appended. Comments inside a changed nested value or list are dropped.
|
|
33
|
+
- `PATCH /_pru/cms/_inline` answers `422` with `errors` naming the field when a value or key holds a lone UTF-16 surrogate.
|
|
34
|
+
|
|
28
35
|
## In-Page Editing (dev-only, zero app markup)
|
|
29
36
|
|
|
30
37
|
When `inline` is enabled (the default), `@prunellejs/content` tracks file-backed entries read during each dev request and wraps rendered `entry.html` in zero-impact HTML comment anchors (`<!--pru-cms:...-->`). Pages that render a collection entry automatically receive a Shadow DOM floating toolbar (`Alt+Shift+E` toggles Edit-on-Page mode, `Cmd/Ctrl+S` saves, `Escape` cancels):
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/cms",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Schema-driven dev-only CMS plugin for Prunelle Markdown content collections",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -21,6 +21,6 @@
|
|
|
21
21
|
"directory": "packages/plugin-cms"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
|
-
"prunelle": "^0.
|
|
24
|
+
"prunelle": "^0.7.0"
|
|
25
25
|
}
|
|
26
26
|
}
|
package/src/form-data.ts
CHANGED
|
@@ -5,13 +5,15 @@ import type { CmsField } from './schema'
|
|
|
5
5
|
import { existsSync, lstatSync, readlinkSync, realpathSync } from 'node:fs'
|
|
6
6
|
import { dirname, resolve } from 'node:path'
|
|
7
7
|
import { isInside } from 'prunelle/config'
|
|
8
|
+
import { mergeFrontmatterYaml, serializeFrontmatterYaml } from './yaml-serialize'
|
|
8
9
|
|
|
9
10
|
const FORBIDDEN_PATH_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype'])
|
|
10
11
|
|
|
11
12
|
const SAFE_LOCALE_RE = /^[a-zA-Z0-9_-]{1,32}$/
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
const
|
|
13
|
+
// Content serves any file name in the collection folder, so a segment only refuses what could escape or break it.
|
|
14
|
+
const UNSAFE_SLUG_CHAR_RE = /[\0-\x1F\x7F\\]/
|
|
15
|
+
const MAX_SLUG_SEGMENT_BYTES = 252 // 255 minus the `.md` suffix
|
|
16
|
+
const MAX_ENTRY_PATH_BYTES = 4000 // PATH_MAX 4096 minus room for the temp file of a save
|
|
15
17
|
const MAX_REPEATABLE_ROWS = 500
|
|
16
18
|
|
|
17
19
|
export interface ParsedRowAction {
|
|
@@ -31,20 +33,24 @@ export interface EntryPathError {
|
|
|
31
33
|
readonly ok: false
|
|
32
34
|
readonly status: 400 | 403
|
|
33
35
|
readonly message: string
|
|
36
|
+
/** Set when the slug is too long: shown as a field error on the slug. */
|
|
37
|
+
readonly tooLong?: true | undefined
|
|
34
38
|
}
|
|
35
39
|
|
|
36
40
|
/** 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 } {
|
|
41
|
+
export function validateSlug(raw: string): { ok: true, slug: string } | { ok: false, message: string, tooLong?: true } {
|
|
38
42
|
const trimmed = raw.trim()
|
|
39
43
|
if (trimmed.length === 0)
|
|
40
44
|
return { ok: false, message: 'Slug is required.' }
|
|
41
|
-
if (
|
|
45
|
+
if (UNSAFE_SLUG_CHAR_RE.test(trimmed) || !trimmed.isWellFormed())
|
|
42
46
|
return { ok: false, message: 'Slug contains invalid path characters.' }
|
|
43
47
|
const clean = trimmed.replace(/\.(?:md|markdown)$/i, '')
|
|
44
48
|
const segments = clean.split('/')
|
|
45
49
|
for (const seg of segments) {
|
|
46
|
-
if (seg.length === 0 || seg === '.' || seg === '..' ||
|
|
50
|
+
if (seg.length === 0 || seg === '.' || seg === '..' || seg === '__proto__')
|
|
47
51
|
return { ok: false, message: `Slug segment "${seg}" is invalid.` }
|
|
52
|
+
if (Buffer.byteLength(seg) > MAX_SLUG_SEGMENT_BYTES)
|
|
53
|
+
return { ok: false, message: `Slug segment is too long (${MAX_SLUG_SEGMENT_BYTES} bytes at most).`, tooLong: true }
|
|
48
54
|
}
|
|
49
55
|
return { ok: true, slug: segments.join('/') }
|
|
50
56
|
}
|
|
@@ -127,7 +133,7 @@ export function resolveEntryFilePath(
|
|
|
127
133
|
|
|
128
134
|
const slugCheck = validateSlug(rawSlug)
|
|
129
135
|
if (!slugCheck.ok)
|
|
130
|
-
return { ok: false, status: 400, message: slugCheck.message }
|
|
136
|
+
return { ok: false, status: 400, message: slugCheck.message, tooLong: slugCheck.tooLong }
|
|
131
137
|
|
|
132
138
|
const localeCheck = validateLocale(col, rawLocale)
|
|
133
139
|
if (!localeCheck.ok)
|
|
@@ -144,6 +150,8 @@ export function resolveEntryFilePath(
|
|
|
144
150
|
|
|
145
151
|
if (!isInside(baseDir, candidate))
|
|
146
152
|
return { ok: false, status: 400, message: 'Refused path outside collection directory.' }
|
|
153
|
+
if (Buffer.byteLength(candidate) > MAX_ENTRY_PATH_BYTES)
|
|
154
|
+
return { ok: false, status: 400, message: 'Slug is too long for this collection folder.', tooLong: true }
|
|
147
155
|
|
|
148
156
|
if (existsSync(baseDir)) {
|
|
149
157
|
const realBase = realpathSync(baseDir)
|
|
@@ -365,95 +373,38 @@ export function normalizeFieldErrorPath(path: string): string {
|
|
|
365
373
|
return path.replace(/\.(\d+)(?=\.|$)/g, '[$1]')
|
|
366
374
|
}
|
|
367
375
|
|
|
368
|
-
|
|
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
|
-
}
|
|
376
|
+
export { serializeFrontmatterYaml }
|
|
390
377
|
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
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
|
-
}
|
|
378
|
+
/** Returns the form path of the first key or string holding a lone UTF-16 surrogate, which would write a file that no longer parses. */
|
|
379
|
+
export function findLoneSurrogate(value: unknown, path = ''): string | undefined {
|
|
380
|
+
if (typeof value === 'string')
|
|
381
|
+
return value.isWellFormed() ? undefined : path
|
|
382
|
+
if (value === null || typeof value !== 'object')
|
|
383
|
+
return undefined
|
|
384
|
+
const entries: [string, unknown][] = Array.isArray(value)
|
|
385
|
+
? value.map((item, i) => [`[${i}]`, item])
|
|
386
|
+
: Object.entries(value as Record<string, unknown>)
|
|
387
|
+
for (const [key, child] of entries) {
|
|
388
|
+
const childPath = Array.isArray(value) ? `${path}${key}` : (path === '' ? key : `${path}.${key}`)
|
|
389
|
+
if (!Array.isArray(value) && !key.isWellFormed())
|
|
390
|
+
return childPath
|
|
391
|
+
const found = findLoneSurrogate(child, childPath)
|
|
392
|
+
if (found !== undefined)
|
|
393
|
+
return found
|
|
445
394
|
}
|
|
446
|
-
return
|
|
395
|
+
return undefined
|
|
447
396
|
}
|
|
448
397
|
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
398
|
+
export interface ExistingEntrySource {
|
|
399
|
+
readonly source: string
|
|
400
|
+
/** Keys the form edits; others are left untouched. Undefined means every key. */
|
|
401
|
+
readonly owned?: ReadonlySet<string> | undefined
|
|
452
402
|
}
|
|
453
403
|
|
|
454
|
-
/** Serializes frontmatter and Markdown body into a `.md` file string. */
|
|
455
|
-
export function serializeMarkdownEntry(data: Record<string, unknown>, body: string): string {
|
|
456
|
-
const
|
|
404
|
+
/** Serializes frontmatter and Markdown body into a `.md` file string, editing `existing` in place when given. */
|
|
405
|
+
export function serializeMarkdownEntry(data: Record<string, unknown>, body: string, existing?: ExistingEntrySource): string {
|
|
406
|
+
const merged = existing === undefined ? undefined : mergeFrontmatterYaml(existing.source, data, existing.owned)
|
|
407
|
+
const yaml = merged ?? serializeFrontmatterYaml(data)
|
|
457
408
|
const normalizedBody = body.replace(/\r\n/g, '\n')
|
|
458
409
|
const trimmedBody = normalizedBody.endsWith('\n') || normalizedBody.length === 0
|
|
459
410
|
? normalizedBody
|
package/src/guard.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// The access guard, kept apart from the editor so the plugin entry loads nothing else outside dev.
|
|
2
|
+
|
|
3
|
+
import type { RequestContext } from 'prunelle/server'
|
|
4
|
+
|
|
5
|
+
export type CmsGuard = (ctx: RequestContext) => boolean | Response | Promise<boolean | Response>
|
|
6
|
+
|
|
7
|
+
export function textResponse(text: string, status: number): Response {
|
|
8
|
+
return new Response(text, {
|
|
9
|
+
status,
|
|
10
|
+
headers: { 'content-type': 'text/plain; charset=utf-8' },
|
|
11
|
+
})
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function runGuard(guard: CmsGuard | undefined, ctx: RequestContext): Promise<Response | undefined> {
|
|
15
|
+
if (guard === undefined)
|
|
16
|
+
return undefined
|
|
17
|
+
const decision = await guard(ctx)
|
|
18
|
+
if (decision instanceof Response)
|
|
19
|
+
return decision
|
|
20
|
+
if (decision === false)
|
|
21
|
+
return textResponse('Forbidden', 403)
|
|
22
|
+
return undefined
|
|
23
|
+
}
|
package/src/handlers.ts
CHANGED
|
@@ -4,8 +4,7 @@ import type { ContentCollectionDescriptor, ContentCollectionEntrySummary, Server
|
|
|
4
4
|
import type { RequestContext } from 'prunelle/server'
|
|
5
5
|
import type { CmsField } from './schema'
|
|
6
6
|
import type { CmsHandlerConfig } from './shared'
|
|
7
|
-
import { existsSync
|
|
8
|
-
import { dirname } from 'node:path'
|
|
7
|
+
import { existsSync } from 'node:fs'
|
|
9
8
|
import { CONTENT_COLLECTIONS_SERVICE } from 'prunelle/config'
|
|
10
9
|
import { safeRedirect, validateSchema } from 'prunelle/server'
|
|
11
10
|
import { CMS_CSS, CMS_JS } from './assets'
|
|
@@ -34,6 +33,7 @@ import {
|
|
|
34
33
|
textResponse,
|
|
35
34
|
wrapGuarded,
|
|
36
35
|
} from './shared'
|
|
36
|
+
import { createEntryFile, readEntrySource, replaceEntryFile } from './write-file'
|
|
37
37
|
|
|
38
38
|
export type { CmsGuard, CmsHandlerConfig } from './shared'
|
|
39
39
|
|
|
@@ -129,6 +129,20 @@ async function handleEditorPost(options: {
|
|
|
129
129
|
let data: Record<string, unknown>
|
|
130
130
|
let rawFrontmatterYaml: string | undefined
|
|
131
131
|
|
|
132
|
+
const render = (status: number, errors: Record<string, string>, pageData: Record<string, unknown> = data): Response => htmlResponse(renderEditorPage({
|
|
133
|
+
basePath,
|
|
134
|
+
collection,
|
|
135
|
+
mode,
|
|
136
|
+
slug,
|
|
137
|
+
locale: localeCheck.locale,
|
|
138
|
+
fields,
|
|
139
|
+
data: pageData,
|
|
140
|
+
rawFrontmatterYaml,
|
|
141
|
+
body,
|
|
142
|
+
errors,
|
|
143
|
+
schemaWarning: warning,
|
|
144
|
+
}), status)
|
|
145
|
+
|
|
132
146
|
if (fields !== undefined) {
|
|
133
147
|
data = parseFormSubmission(formData, fields)
|
|
134
148
|
}
|
|
@@ -136,21 +150,8 @@ async function handleEditorPost(options: {
|
|
|
136
150
|
const rawYamlField = formData.get('__frontmatter_yaml')
|
|
137
151
|
rawFrontmatterYaml = typeof rawYamlField === 'string' ? rawYamlField : ''
|
|
138
152
|
const yamlRes = parseRawFrontmatterYaml(rawFrontmatterYaml)
|
|
139
|
-
if (!yamlRes.ok)
|
|
140
|
-
return
|
|
141
|
-
basePath,
|
|
142
|
-
collection,
|
|
143
|
-
mode,
|
|
144
|
-
slug,
|
|
145
|
-
locale: localeCheck.locale,
|
|
146
|
-
fields,
|
|
147
|
-
data: {},
|
|
148
|
-
rawFrontmatterYaml,
|
|
149
|
-
body,
|
|
150
|
-
errors: { __frontmatter_yaml: yamlRes.message },
|
|
151
|
-
schemaWarning: warning,
|
|
152
|
-
}), 422)
|
|
153
|
-
}
|
|
153
|
+
if (!yamlRes.ok)
|
|
154
|
+
return render(422, { __frontmatter_yaml: yamlRes.message }, {})
|
|
154
155
|
data = yamlRes.data
|
|
155
156
|
}
|
|
156
157
|
|
|
@@ -158,35 +159,11 @@ async function handleEditorPost(options: {
|
|
|
158
159
|
const rowAction = parseRowAction(typeof rawAction === 'string' ? rawAction : null)
|
|
159
160
|
if (rowAction !== undefined && fields !== undefined) {
|
|
160
161
|
applyRowAction(data, rowAction)
|
|
161
|
-
return
|
|
162
|
-
basePath,
|
|
163
|
-
collection,
|
|
164
|
-
mode,
|
|
165
|
-
slug,
|
|
166
|
-
locale: localeCheck.locale,
|
|
167
|
-
fields,
|
|
168
|
-
data,
|
|
169
|
-
body,
|
|
170
|
-
errors: {},
|
|
171
|
-
schemaWarning: warning,
|
|
172
|
-
}), 200)
|
|
162
|
+
return render(200, {})
|
|
173
163
|
}
|
|
174
164
|
|
|
175
|
-
if (mode === 'new' && slug.trim().length === 0)
|
|
176
|
-
return
|
|
177
|
-
basePath,
|
|
178
|
-
collection,
|
|
179
|
-
mode,
|
|
180
|
-
slug,
|
|
181
|
-
locale: localeCheck.locale,
|
|
182
|
-
fields,
|
|
183
|
-
data,
|
|
184
|
-
rawFrontmatterYaml,
|
|
185
|
-
body,
|
|
186
|
-
errors: { __slug: 'Slug is required.' },
|
|
187
|
-
schemaWarning: warning,
|
|
188
|
-
}), 422)
|
|
189
|
-
}
|
|
165
|
+
if (mode === 'new' && slug.trim().length === 0)
|
|
166
|
+
return render(422, { __slug: 'Slug is required.' })
|
|
190
167
|
|
|
191
168
|
const existingEntry = mode === 'edit'
|
|
192
169
|
? await collection.get(slug, localeCheck.locale)
|
|
@@ -196,48 +173,30 @@ async function handleEditorPost(options: {
|
|
|
196
173
|
|
|
197
174
|
const pathRes = resolveEntryFilePath(collection, slug, localeCheck.locale, existingEntry?.file)
|
|
198
175
|
if (!pathRes.ok)
|
|
199
|
-
return textResponse(pathRes.message, pathRes.status)
|
|
176
|
+
return mode === 'new' && pathRes.tooLong ? render(422, { __slug: pathRes.message }) : textResponse(pathRes.message, pathRes.status)
|
|
200
177
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
collection,
|
|
205
|
-
mode,
|
|
206
|
-
slug,
|
|
207
|
-
locale: localeCheck.locale,
|
|
208
|
-
fields,
|
|
209
|
-
data,
|
|
210
|
-
rawFrontmatterYaml,
|
|
211
|
-
body,
|
|
212
|
-
errors: { __slug: 'An entry with this slug already exists.' },
|
|
213
|
-
schemaWarning: warning,
|
|
214
|
-
}), 422)
|
|
215
|
-
}
|
|
178
|
+
const slugTaken = { __slug: 'An entry with this slug already exists.' }
|
|
179
|
+
if (mode === 'new' && existsSync(pathRes.filePath))
|
|
180
|
+
return render(422, slugTaken)
|
|
216
181
|
|
|
217
182
|
let dataToWrite = data
|
|
218
183
|
if (collection.schema !== undefined) {
|
|
219
184
|
const validated = await validateSchema(collection.schema, data)
|
|
220
|
-
if (!validated.ok)
|
|
221
|
-
return
|
|
222
|
-
basePath,
|
|
223
|
-
collection,
|
|
224
|
-
mode,
|
|
225
|
-
slug,
|
|
226
|
-
locale: localeCheck.locale,
|
|
227
|
-
fields,
|
|
228
|
-
data,
|
|
229
|
-
rawFrontmatterYaml,
|
|
230
|
-
body,
|
|
231
|
-
errors: collectValidationErrors(validated.issues),
|
|
232
|
-
schemaWarning: warning,
|
|
233
|
-
}), 422)
|
|
234
|
-
}
|
|
185
|
+
if (!validated.ok)
|
|
186
|
+
return render(422, collectValidationErrors(validated.issues))
|
|
235
187
|
if (validated.value !== null && typeof validated.value === 'object' && !Array.isArray(validated.value))
|
|
236
188
|
dataToWrite = validated.value as Record<string, unknown>
|
|
237
189
|
}
|
|
238
190
|
|
|
239
|
-
|
|
240
|
-
|
|
191
|
+
if (mode === 'new') {
|
|
192
|
+
if (createEntryFile(pathRes.filePath, serializeMarkdownEntry(dataToWrite, body)) === 'exists')
|
|
193
|
+
return render(422, slugTaken)
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
const source = readEntrySource(pathRes.filePath)
|
|
197
|
+
const owned = fields === undefined ? undefined : new Set(fields.map(field => field.key))
|
|
198
|
+
replaceEntryFile(pathRes.filePath, serializeMarkdownEntry(dataToWrite, body, source === undefined ? undefined : { source, owned }))
|
|
199
|
+
}
|
|
241
200
|
collection.clearCache()
|
|
242
201
|
|
|
243
202
|
const target = safeRedirect(
|
package/src/index.ts
CHANGED
|
@@ -2,15 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
import type { ContentCollectionsService, PrunellePlugin } from 'prunelle/config'
|
|
4
4
|
import type { RequestContext } from 'prunelle/server'
|
|
5
|
-
import type { CmsGuard } from './
|
|
5
|
+
import type { CmsGuard } from './guard'
|
|
6
6
|
import { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, definePlugin } from 'prunelle/config'
|
|
7
7
|
import { escAttr } from 'prunelle/server'
|
|
8
|
-
import { registerCmsRoutes } from './handlers'
|
|
9
|
-
import { registerInlineCmsRoutes } from './inline-handlers'
|
|
10
8
|
import { checkCollectionSchema } from './schema'
|
|
11
|
-
import { runGuard } from './
|
|
9
|
+
import { runGuard } from './guard'
|
|
12
10
|
|
|
13
|
-
export type { CmsGuard } from './
|
|
11
|
+
export type { CmsGuard } from './guard'
|
|
14
12
|
export type { CmsField, CmsFieldKind, CmsSchemaIssue, ParsedCmsSchema } from './schema'
|
|
15
13
|
|
|
16
14
|
export interface CmsOptions {
|
|
@@ -64,9 +62,13 @@ export function cms(options: CmsOptions = {}): PrunellePlugin {
|
|
|
64
62
|
ctx.error(err)
|
|
65
63
|
}
|
|
66
64
|
},
|
|
67
|
-
server(api) {
|
|
65
|
+
async server(api) {
|
|
68
66
|
if (!api.dev)
|
|
69
67
|
return
|
|
68
|
+
if (api.devExposed && options.guard === undefined)
|
|
69
|
+
throw new Error('@prunellejs/cms: prunelle dev --host binds an address other machines reach, and the CMS would let them read drafts and write content files: pass cms({ guard: ctx => ... }) to let only you in, or run prunelle dev without --host.')
|
|
70
|
+
// Loaded in dev only: a production server never pays for the editor's handlers, pages and scripts.
|
|
71
|
+
const [{ registerCmsRoutes }, { registerInlineCmsRoutes }] = await Promise.all([import('./handlers'), import('./inline-handlers')])
|
|
70
72
|
if (inlineEnabled) {
|
|
71
73
|
api.provide(CMS_INLINE_ENABLED_SERVICE, true)
|
|
72
74
|
registerInlineCmsRoutes(api, { basePath, guard: options.guard })
|
package/src/inline-handlers.ts
CHANGED
|
@@ -3,11 +3,10 @@
|
|
|
3
3
|
import type { ContentCollectionDescriptor, ServerPluginAPI } from 'prunelle/config'
|
|
4
4
|
import type { RequestContext } from 'prunelle/server'
|
|
5
5
|
import type { CmsHandlerConfig } from './shared'
|
|
6
|
-
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
7
|
-
import { dirname } from 'node:path'
|
|
8
6
|
import { CONTENT_COLLECTIONS_SERVICE } from 'prunelle/config'
|
|
9
7
|
import { validateSchema } from 'prunelle/server'
|
|
10
8
|
import {
|
|
9
|
+
findLoneSurrogate,
|
|
11
10
|
resolveEntryFilePath,
|
|
12
11
|
serializeFrontmatterYaml,
|
|
13
12
|
serializeMarkdownEntry,
|
|
@@ -19,11 +18,13 @@ import { encodeSlugPath, localeQueryString } from './render'
|
|
|
19
18
|
import { renderMarkdownPreview } from './sanitize'
|
|
20
19
|
import {
|
|
21
20
|
collectValidationErrors,
|
|
21
|
+
LONE_SURROGATE_MESSAGE,
|
|
22
22
|
loadCollections,
|
|
23
23
|
parseRawFrontmatterYaml,
|
|
24
24
|
resolveSchemaFields,
|
|
25
25
|
wrapGuarded,
|
|
26
26
|
} from './shared'
|
|
27
|
+
import { readEntrySource, replaceEntryFile } from './write-file'
|
|
27
28
|
|
|
28
29
|
const FORBIDDEN_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype'])
|
|
29
30
|
|
|
@@ -214,6 +215,10 @@ export function registerInlineCmsRoutes(api: ServerPluginAPI, config: CmsHandler
|
|
|
214
215
|
if (!patched.ok)
|
|
215
216
|
return ctx.json({ ok: false, errors: patched.errors }, { status: patched.status })
|
|
216
217
|
|
|
218
|
+
const badPath = findLoneSurrogate(patched.data)
|
|
219
|
+
if (badPath !== undefined)
|
|
220
|
+
return ctx.json({ ok: false, errors: { [badPath]: LONE_SURROGATE_MESSAGE } }, { status: 422 })
|
|
221
|
+
|
|
217
222
|
let dataToWrite = patched.data
|
|
218
223
|
if (col.schema !== undefined) {
|
|
219
224
|
const validated = await validateSchema(col.schema, patched.data)
|
|
@@ -224,8 +229,8 @@ export function registerInlineCmsRoutes(api: ServerPluginAPI, config: CmsHandler
|
|
|
224
229
|
}
|
|
225
230
|
|
|
226
231
|
const nextBody = typeof payload.body === 'string' ? payload.body : existingEntry.body
|
|
227
|
-
|
|
228
|
-
|
|
232
|
+
const source = readEntrySource(pathRes.filePath)
|
|
233
|
+
replaceEntryFile(pathRes.filePath, serializeMarkdownEntry(dataToWrite, nextBody, source === undefined ? undefined : { source }))
|
|
229
234
|
col.clearCache()
|
|
230
235
|
|
|
231
236
|
const plainData = clonePlainData(dataToWrite) as Record<string, unknown>
|
package/src/sanitize.ts
CHANGED
|
@@ -1,140 +1,6 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Markdown preview renderer for @prunellejs/cms, sanitized like @prunellejs/content renders the published page.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
const STRIP_VOID_DANGEROUS_RE = /<(script|style|iframe|object|embed|applet|noscript|template|svg|math|form|base|link|meta)(?=[\s/>])[^>]*\/?>/gi
|
|
5
|
-
const COMMENT_RE = /<!--[\s\S]*?(?:--!?>|$)/g
|
|
6
|
-
|
|
7
|
-
const SAFE_TAGS = new Set([
|
|
8
|
-
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
|
9
|
-
'p', 'br', 'hr', 'blockquote', 'pre', 'code',
|
|
10
|
-
'ul', 'ol', 'li', 'dl', 'dt', 'dd',
|
|
11
|
-
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
|
|
12
|
-
'a', 'img', 'strong', 'em', 'b', 'i', 'u', 's', 'del', 'ins',
|
|
13
|
-
'sup', 'sub', 'kbd', 'mark', 'abbr', 'small', 'time',
|
|
14
|
-
'details', 'summary', 'figure', 'figcaption', 'div', 'span', 'input',
|
|
15
|
-
])
|
|
16
|
-
|
|
17
|
-
const ALLOWED_ATTRS_BY_TAG: Readonly<Record<string, ReadonlySet<string>>> = {
|
|
18
|
-
a: new Set(['href', 'title', 'rel', 'target']),
|
|
19
|
-
img: new Set(['src', 'alt', 'title', 'width', 'height']),
|
|
20
|
-
th: new Set(['colspan', 'rowspan', 'scope', 'align']),
|
|
21
|
-
td: new Set(['colspan', 'rowspan', 'align']),
|
|
22
|
-
ol: new Set(['start', 'reversed']),
|
|
23
|
-
li: new Set(['value']),
|
|
24
|
-
details: new Set(['open']),
|
|
25
|
-
time: new Set(['datetime']),
|
|
26
|
-
input: new Set(['type', 'checked', 'disabled']),
|
|
27
|
-
code: new Set(['class']),
|
|
28
|
-
pre: new Set(['class']),
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const URL_PROTOCOL_OK = /^(?:https?:|mailto:|tel:|#|\/|\.)/i
|
|
32
|
-
const SAFE_DATA_IMG = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i
|
|
33
|
-
const SCHEME_PREFIX = /^[a-z][a-z0-9+.-]*:/i
|
|
34
|
-
|
|
35
|
-
function safeCodePoint(raw: string, radix: number): string {
|
|
36
|
-
const cp = Number.parseInt(raw, radix)
|
|
37
|
-
return Number.isFinite(cp) && cp >= 0 && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function escapeAttrValue(val: string): string {
|
|
41
|
-
return val
|
|
42
|
-
.replaceAll('"', '"')
|
|
43
|
-
.replaceAll('\'', ''')
|
|
44
|
-
.replaceAll('<', '<')
|
|
45
|
-
.replaceAll('>', '>')
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function isUrlAllowed(raw: string): boolean {
|
|
49
|
-
const decoded = raw
|
|
50
|
-
.replace(/&#x([0-9a-f]+);?/gi, (_, h: string) => safeCodePoint(h, 16))
|
|
51
|
-
.replace(/&#(\d+);?/g, (_, d: string) => safeCodePoint(d, 10))
|
|
52
|
-
.replace(/&(colon|tab|newline|amp);/gi, (_, name: string) => {
|
|
53
|
-
const lower = name.toLowerCase()
|
|
54
|
-
if (lower === 'colon') return ':'
|
|
55
|
-
if (lower === 'tab') return '\t'
|
|
56
|
-
if (lower === 'newline') return '\n'
|
|
57
|
-
return '&'
|
|
58
|
-
})
|
|
59
|
-
.replace(/[\u0000-\u0020\u007F]+/g, '')
|
|
60
|
-
.trim()
|
|
61
|
-
if (decoded === '')
|
|
62
|
-
return true
|
|
63
|
-
if (URL_PROTOCOL_OK.test(decoded) || SAFE_DATA_IMG.test(decoded))
|
|
64
|
-
return true
|
|
65
|
-
return !SCHEME_PREFIX.test(decoded)
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
const ATTR_PAIR_RE = /([a-zA-Z_:][a-zA-Z0-9_.:-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g
|
|
69
|
-
|
|
70
|
-
function filterTagAttributes(tag: string, rawAttrs: string): string {
|
|
71
|
-
const allowed = ALLOWED_ATTRS_BY_TAG[tag]
|
|
72
|
-
if (allowed === undefined || rawAttrs.trim() === '')
|
|
73
|
-
return ''
|
|
74
|
-
|
|
75
|
-
const kept: string[] = []
|
|
76
|
-
ATTR_PAIR_RE.lastIndex = 0
|
|
77
|
-
let match = ATTR_PAIR_RE.exec(rawAttrs)
|
|
78
|
-
while (match !== null) {
|
|
79
|
-
const attrName = match[1]!.toLowerCase()
|
|
80
|
-
const attrVal = match[2] ?? match[3] ?? match[4] ?? null
|
|
81
|
-
if (allowed.has(attrName)) {
|
|
82
|
-
if (tag === 'input' && attrName === 'type' && attrVal?.toLowerCase() !== 'checkbox') {
|
|
83
|
-
match = ATTR_PAIR_RE.exec(rawAttrs)
|
|
84
|
-
continue
|
|
85
|
-
}
|
|
86
|
-
if ((attrName === 'href' || attrName === 'src') && attrVal !== null && !isUrlAllowed(attrVal)) {
|
|
87
|
-
match = ATTR_PAIR_RE.exec(rawAttrs)
|
|
88
|
-
continue
|
|
89
|
-
}
|
|
90
|
-
kept.push(attrVal === null ? attrName : `${attrName}="${escapeAttrValue(attrVal)}"`)
|
|
91
|
-
}
|
|
92
|
-
match = ATTR_PAIR_RE.exec(rawAttrs)
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
if (tag === 'input') {
|
|
96
|
-
if (!kept.some(entry => entry.startsWith('type=')))
|
|
97
|
-
return ''
|
|
98
|
-
if (!kept.includes('disabled'))
|
|
99
|
-
kept.push('disabled')
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
return kept.length > 0 ? ` ${kept.join(' ')}` : ''
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
function sanitizePreviewPass(html: string): string {
|
|
106
|
-
const withoutDangerous = html
|
|
107
|
-
.replace(COMMENT_RE, '')
|
|
108
|
-
.replace(STRIP_BLOCK_RE, '')
|
|
109
|
-
.replace(STRIP_VOID_DANGEROUS_RE, '')
|
|
110
|
-
|
|
111
|
-
return withoutDangerous.replace(/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)([\s/][^>]*?)?(\/?)>/g, (_whole, slash: string, rawTag: string, rawAttrs: string | undefined, selfClose: string) => {
|
|
112
|
-
const tag = rawTag.toLowerCase()
|
|
113
|
-
if (!SAFE_TAGS.has(tag))
|
|
114
|
-
return ''
|
|
115
|
-
if (slash === '/')
|
|
116
|
-
return `</${tag}>`
|
|
117
|
-
const raw = rawAttrs ?? ''
|
|
118
|
-
const isSelfClose = selfClose === '/' || /\/\s*$/.test(raw)
|
|
119
|
-
const cleanedRaw = selfClose === '' && isSelfClose ? raw.replace(/\/\s*$/, '') : raw
|
|
120
|
-
const attrs = filterTagAttributes(tag, cleanedRaw)
|
|
121
|
-
if (tag === 'input' && attrs === '')
|
|
122
|
-
return ''
|
|
123
|
-
return `<${tag}${attrs}${isSelfClose ? ' /' : ''}>`
|
|
124
|
-
})
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/** Sanitizes HTML rendered from Markdown using a strict element and attribute allowlist. */
|
|
128
|
-
export function sanitizePreviewHtml(html: string): string {
|
|
129
|
-
let current = html
|
|
130
|
-
for (let pass = 0; pass < 3; pass++) {
|
|
131
|
-
const next = sanitizePreviewPass(current)
|
|
132
|
-
if (next === current)
|
|
133
|
-
return next
|
|
134
|
-
current = next
|
|
135
|
-
}
|
|
136
|
-
return current
|
|
137
|
-
}
|
|
3
|
+
import { sanitizeMarkdownHtml } from 'prunelle/internal/server'
|
|
138
4
|
|
|
139
5
|
/** Renders Markdown to sanitized HTML using Bun's native Zig Markdown engine. */
|
|
140
6
|
export function renderMarkdownPreview(markdown: string): string {
|
|
@@ -146,5 +12,5 @@ export function renderMarkdownPreview(markdown: string): string {
|
|
|
146
12
|
tasklists: true,
|
|
147
13
|
autolinks: true,
|
|
148
14
|
})
|
|
149
|
-
return
|
|
15
|
+
return sanitizeMarkdownHtml(rawHtml)
|
|
150
16
|
}
|
package/src/shared.ts
CHANGED
|
@@ -2,12 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
import type { ContentCollectionDescriptor, ContentCollectionsService } from 'prunelle/config'
|
|
4
4
|
import type { RequestContext } from 'prunelle/server'
|
|
5
|
+
import type { CmsGuard } from './guard'
|
|
6
|
+
import { runGuard } from './guard'
|
|
5
7
|
import type { CmsField } from './schema'
|
|
6
8
|
import { formatIssuePath } from 'prunelle/server'
|
|
7
9
|
import { normalizeFieldErrorPath } from './form-data'
|
|
8
10
|
import { extractJsonSchema, parseJsonSchemaFields } from './schema'
|
|
9
11
|
|
|
10
|
-
export
|
|
12
|
+
export const LONE_SURROGATE_MESSAGE = 'Contains an unpaired UTF-16 surrogate character; remove it.'
|
|
13
|
+
|
|
14
|
+
export type { CmsGuard } from './guard'
|
|
15
|
+
export { runGuard, textResponse } from './guard'
|
|
11
16
|
|
|
12
17
|
export interface CmsHandlerConfig {
|
|
13
18
|
readonly basePath: string
|
|
@@ -21,23 +26,7 @@ export function htmlResponse(html: string, status = 200): Response {
|
|
|
21
26
|
})
|
|
22
27
|
}
|
|
23
28
|
|
|
24
|
-
export function textResponse(text: string, status: number): Response {
|
|
25
|
-
return new Response(text, {
|
|
26
|
-
status,
|
|
27
|
-
headers: { 'content-type': 'text/plain; charset=utf-8' },
|
|
28
|
-
})
|
|
29
|
-
}
|
|
30
29
|
|
|
31
|
-
export async function runGuard(guard: CmsGuard | undefined, ctx: RequestContext): Promise<Response | undefined> {
|
|
32
|
-
if (guard === undefined)
|
|
33
|
-
return undefined
|
|
34
|
-
const decision = await guard(ctx)
|
|
35
|
-
if (decision instanceof Response)
|
|
36
|
-
return decision
|
|
37
|
-
if (decision === false)
|
|
38
|
-
return textResponse('Forbidden', 403)
|
|
39
|
-
return undefined
|
|
40
|
-
}
|
|
41
30
|
|
|
42
31
|
export function wrapGuarded(
|
|
43
32
|
guard: CmsGuard | undefined,
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Crash-safe entry writes: exclusive create for new entries, temp file plus rename for updates.
|
|
2
|
+
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { dirname, join } from 'node:path'
|
|
6
|
+
|
|
7
|
+
function errorCode(err: unknown): string | undefined {
|
|
8
|
+
return (err as NodeJS.ErrnoException).code
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Creates `file` only if nothing is there yet; returns `exists` when another create won the slug. */
|
|
12
|
+
export function createEntryFile(file: string, content: string): 'created' | 'exists' {
|
|
13
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
14
|
+
try {
|
|
15
|
+
writeFileSync(file, content, { encoding: 'utf8', flag: 'wx' })
|
|
16
|
+
return 'created'
|
|
17
|
+
}
|
|
18
|
+
catch (err) {
|
|
19
|
+
if (errorCode(err) === 'EEXIST')
|
|
20
|
+
return 'exists'
|
|
21
|
+
throw err
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Replaces `file` through a temp file in the same folder, so a crash never leaves a half-written entry. */
|
|
26
|
+
export function replaceEntryFile(file: string, content: string): void {
|
|
27
|
+
let target = file
|
|
28
|
+
try {
|
|
29
|
+
// A symlinked entry keeps its link: the rename lands on the real file.
|
|
30
|
+
target = realpathSync(file)
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
if (errorCode(err) !== 'ENOENT')
|
|
34
|
+
throw err
|
|
35
|
+
}
|
|
36
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
37
|
+
const tmp = join(dirname(target), `.${randomUUID()}.tmp`)
|
|
38
|
+
try {
|
|
39
|
+
writeFileSync(tmp, content, { encoding: 'utf8', flag: 'wx' })
|
|
40
|
+
try {
|
|
41
|
+
chmodSync(tmp, statSync(target).mode & 0o777)
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
if (errorCode(err) !== 'ENOENT')
|
|
45
|
+
throw err
|
|
46
|
+
}
|
|
47
|
+
renameSync(tmp, target)
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
rmSync(tmp, { force: true })
|
|
51
|
+
throw err
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Reads the current source of an entry for in-place frontmatter edits; undefined when there is no file yet. */
|
|
56
|
+
export function readEntrySource(file: string): string | undefined {
|
|
57
|
+
return existsSync(file) ? readFileSync(file, 'utf8') : undefined
|
|
58
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// Frontmatter YAML output: plain serialization, and in-place edits that keep comments and keys the form does not own.
|
|
2
|
+
|
|
3
|
+
const YAML_PLAIN_SAFE_RE = /^[a-zA-Z0-9][a-zA-Z0-9 _./@+-]*$/
|
|
4
|
+
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
|
|
5
|
+
const TOP_KEY_RE = /^("(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z0-9_.$@-]+)[ \t]*:(?=\s|$)/
|
|
6
|
+
const FRONTMATTER_RE = /^---\n(?:([\s\S]*?)\n)?---[ \t]*(?:\n|$)/
|
|
7
|
+
|
|
8
|
+
function serializeYamlScalar(value: unknown): string {
|
|
9
|
+
if (value === null || value === undefined)
|
|
10
|
+
return 'null'
|
|
11
|
+
if (typeof value === 'boolean')
|
|
12
|
+
return value ? 'true' : 'false'
|
|
13
|
+
if (typeof value === 'number')
|
|
14
|
+
return Number.isFinite(value) ? String(value) : 'null'
|
|
15
|
+
if (value instanceof Date)
|
|
16
|
+
return JSON.stringify(value.toISOString())
|
|
17
|
+
const str = String(value)
|
|
18
|
+
if (str.length === 0)
|
|
19
|
+
return '""'
|
|
20
|
+
if (str.includes('\n') || str.includes('\r'))
|
|
21
|
+
return JSON.stringify(str)
|
|
22
|
+
if (str.trim() !== str || YAML_RESERVED_RE.test(str) || !YAML_PLAIN_SAFE_RE.test(str))
|
|
23
|
+
return JSON.stringify(str)
|
|
24
|
+
return str
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
28
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function serializeYamlObject(obj: Record<string, unknown>, indent: number): string[] {
|
|
32
|
+
const pad = ' '.repeat(indent)
|
|
33
|
+
const lines: string[] = []
|
|
34
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
35
|
+
if (value === undefined)
|
|
36
|
+
continue
|
|
37
|
+
const yamlKey = /^[a-zA-Z0-9_-]+$/.test(key) ? key : JSON.stringify(key)
|
|
38
|
+
if (Array.isArray(value)) {
|
|
39
|
+
if (value.length === 0) {
|
|
40
|
+
lines.push(`${pad}${yamlKey}: []`)
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
lines.push(`${pad}${yamlKey}:`)
|
|
44
|
+
lines.push(...serializeYamlArray(value, indent + 2))
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
else if (isRecord(value)) {
|
|
48
|
+
const inner = serializeYamlObject(value, indent + 2)
|
|
49
|
+
if (inner.length === 0) {
|
|
50
|
+
lines.push(`${pad}${yamlKey}: {}`)
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
lines.push(`${pad}${yamlKey}:`)
|
|
54
|
+
lines.push(...inner)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
lines.push(`${pad}${yamlKey}: ${serializeYamlScalar(value)}`)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return lines
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function serializeYamlArray(arr: readonly unknown[], indent: number): string[] {
|
|
65
|
+
const pad = ' '.repeat(indent)
|
|
66
|
+
const lines: string[] = []
|
|
67
|
+
for (const item of arr) {
|
|
68
|
+
if (isRecord(item)) {
|
|
69
|
+
const inner = serializeYamlObject(item, indent + 2)
|
|
70
|
+
if (inner.length === 0) {
|
|
71
|
+
lines.push(`${pad}- {}`)
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
lines.push(`${pad}- ${inner[0]!.slice(indent + 2)}`)
|
|
75
|
+
for (let i = 1; i < inner.length; i++)
|
|
76
|
+
lines.push(inner[i]!)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
else if (Array.isArray(item)) {
|
|
80
|
+
lines.push(`${pad}- ${JSON.stringify(item)}`)
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
lines.push(`${pad}- ${serializeYamlScalar(item)}`)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return lines
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Serializes a frontmatter object into clean YAML text. */
|
|
90
|
+
export function serializeFrontmatterYaml(data: Record<string, unknown>): string {
|
|
91
|
+
return serializeYamlObject(data, 0).join('\n')
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
interface Segment {
|
|
95
|
+
readonly key: string
|
|
96
|
+
readonly lead: string[]
|
|
97
|
+
readonly lines: string[]
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function decodeKey(raw: string): string {
|
|
101
|
+
if (raw.startsWith('"')) {
|
|
102
|
+
try {
|
|
103
|
+
return JSON.parse(raw) as string
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return raw
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return raw.startsWith('\'') ? raw.slice(1, -1) : raw
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// A top-level key owns the indented lines under it; comment and blank lines before the next key lead that key.
|
|
113
|
+
function splitSegments(lines: readonly string[]): { segments: Segment[], tail: string[] } {
|
|
114
|
+
const segments: Segment[] = []
|
|
115
|
+
let pending: string[] = []
|
|
116
|
+
for (const line of lines) {
|
|
117
|
+
const keyMatch = TOP_KEY_RE.exec(line)
|
|
118
|
+
const current = segments.at(-1)
|
|
119
|
+
if (keyMatch !== null) {
|
|
120
|
+
segments.push({ key: decodeKey(keyMatch[1]!), lead: pending, lines: [line] })
|
|
121
|
+
pending = []
|
|
122
|
+
}
|
|
123
|
+
else if (current === undefined || line.trim() === '' || line.startsWith('#')) {
|
|
124
|
+
pending.push(line)
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
current.lines.push(...pending, line)
|
|
128
|
+
pending = []
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return { segments, tail: pending }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function sameValue(a: unknown, b: unknown): boolean {
|
|
135
|
+
if (Array.isArray(a) || Array.isArray(b))
|
|
136
|
+
return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((v, i) => sameValue(v, b[i]))
|
|
137
|
+
if (isRecord(a) && isRecord(b)) {
|
|
138
|
+
const keys = Object.keys(a).filter(k => a[k] !== undefined)
|
|
139
|
+
return keys.length === Object.keys(b).filter(k => b[k] !== undefined).length
|
|
140
|
+
&& keys.every(k => Object.hasOwn(b, k) && sameValue(a[k], b[k]))
|
|
141
|
+
}
|
|
142
|
+
return a === b
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Keeps a `# note` after a plain one-line scalar when its value changes.
|
|
146
|
+
function trailingComment(oldLines: readonly string[], value: unknown): string {
|
|
147
|
+
if (oldLines.length !== 1 || value === null || typeof value === 'object')
|
|
148
|
+
return ''
|
|
149
|
+
const line = oldLines[0]!
|
|
150
|
+
const match = /\s+#.*$/.exec(line)
|
|
151
|
+
if (match === null || /["'[{]/.test(line.slice(line.indexOf(':') + 1, match.index)))
|
|
152
|
+
return ''
|
|
153
|
+
return match[0]
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function rewriteSegment(segment: Segment, value: unknown): string[] {
|
|
157
|
+
const fresh = serializeYamlObject({ [segment.key]: value }, 0)
|
|
158
|
+
if (fresh.length === 1)
|
|
159
|
+
fresh[0] += trailingComment(segment.lines, value)
|
|
160
|
+
return [...segment.lead, ...fresh]
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function readYamlBlock(source: string): string | undefined {
|
|
164
|
+
const match = FRONTMATTER_RE.exec(source.replace(/\r\n/g, '\n'))
|
|
165
|
+
return match === null ? undefined : (match[1] ?? '')
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function parseYamlMapping(yaml: string): Record<string, unknown> | undefined {
|
|
169
|
+
if (yaml.trim() === '')
|
|
170
|
+
return {}
|
|
171
|
+
try {
|
|
172
|
+
const parsed: unknown = Bun.YAML.parse(yaml)
|
|
173
|
+
return isRecord(parsed) ? parsed : undefined
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
return undefined
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Edits the frontmatter of `source` to hold `data`: untouched keys keep their lines and comments, changed keys keep their leading comments,
|
|
182
|
+
* keys outside `owned` are left alone, new keys are appended. Returns undefined when the source has no readable frontmatter.
|
|
183
|
+
*/
|
|
184
|
+
export function mergeFrontmatterYaml(
|
|
185
|
+
source: string,
|
|
186
|
+
data: Record<string, unknown>,
|
|
187
|
+
owned: ReadonlySet<string> | undefined,
|
|
188
|
+
): string | undefined {
|
|
189
|
+
const block = readYamlBlock(source)
|
|
190
|
+
const oldData = block === undefined ? undefined : parseYamlMapping(block)
|
|
191
|
+
if (block === undefined || oldData === undefined)
|
|
192
|
+
return undefined
|
|
193
|
+
const { segments, tail } = splitSegments(block.split('\n'))
|
|
194
|
+
const out: string[] = []
|
|
195
|
+
const seen = new Set<string>()
|
|
196
|
+
for (const segment of segments) {
|
|
197
|
+
seen.add(segment.key)
|
|
198
|
+
const value = Object.hasOwn(data, segment.key) ? data[segment.key] : undefined
|
|
199
|
+
if (owned !== undefined && !owned.has(segment.key))
|
|
200
|
+
out.push(...segment.lead, ...segment.lines)
|
|
201
|
+
else if (value === undefined)
|
|
202
|
+
continue
|
|
203
|
+
else if (sameValue(oldData[segment.key], value))
|
|
204
|
+
out.push(...segment.lead, ...segment.lines)
|
|
205
|
+
else
|
|
206
|
+
out.push(...rewriteSegment(segment, value))
|
|
207
|
+
}
|
|
208
|
+
for (const [key, value] of Object.entries(data)) {
|
|
209
|
+
if (!seen.has(key) && value !== undefined)
|
|
210
|
+
out.push(...serializeYamlObject({ [key]: value }, 0))
|
|
211
|
+
}
|
|
212
|
+
out.push(...tail)
|
|
213
|
+
return out.join('\n').replace(/\n+$/, '')
|
|
214
|
+
}
|