@glw907/cairn-cms 0.38.0 → 0.40.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/CHANGELOG.md +60 -0
- package/README.md +6 -5
- package/dist/components/AdminLayout.svelte +53 -0
- package/dist/components/ComponentInsertDialog.svelte +27 -13
- package/dist/components/ComponentInsertDialog.svelte.d.ts +13 -2
- package/dist/components/ConceptList.svelte +13 -3
- package/dist/components/DeleteDialog.svelte +18 -7
- package/dist/components/DeleteDialog.svelte.d.ts +11 -1
- package/dist/components/EditPage.svelte +575 -70
- package/dist/components/EditPage.svelte.d.ts +8 -1
- package/dist/components/EditorToolbar.svelte +202 -29
- package/dist/components/EditorToolbar.svelte.d.ts +12 -4
- package/dist/components/LinkPicker.svelte +14 -6
- package/dist/components/LinkPicker.svelte.d.ts +9 -2
- package/dist/components/MarkdownEditor.svelte +80 -34
- package/dist/components/MarkdownEditor.svelte.d.ts +9 -3
- package/dist/components/MarkdownHelpDialog.svelte +58 -0
- package/dist/components/MarkdownHelpDialog.svelte.d.ts +11 -0
- package/dist/components/RenameDialog.svelte +13 -4
- package/dist/components/RenameDialog.svelte.d.ts +9 -1
- package/dist/components/WebLinkDialog.svelte +89 -0
- package/dist/components/WebLinkDialog.svelte.d.ts +23 -0
- package/dist/components/cairn-admin.css +353 -4
- package/dist/components/editor-highlight.d.ts +9 -0
- package/dist/components/editor-highlight.js +62 -0
- package/dist/components/markdown-directives.d.ts +7 -0
- package/dist/components/markdown-directives.js +22 -0
- package/dist/components/markdown-format.d.ts +1 -1
- package/dist/components/markdown-format.js +91 -12
- package/dist/content/pending.d.ts +9 -0
- package/dist/content/pending.js +24 -0
- package/dist/github/branches.d.ts +11 -0
- package/dist/github/branches.js +75 -0
- package/dist/log/events.d.ts +1 -1
- package/dist/sveltekit/content-routes.d.ts +22 -1
- package/dist/sveltekit/content-routes.js +312 -72
- package/package.json +3 -2
- package/src/lib/components/AdminLayout.svelte +53 -0
- package/src/lib/components/ComponentInsertDialog.svelte +27 -13
- package/src/lib/components/ConceptList.svelte +13 -3
- package/src/lib/components/DeleteDialog.svelte +18 -7
- package/src/lib/components/EditPage.svelte +575 -70
- package/src/lib/components/EditorToolbar.svelte +202 -29
- package/src/lib/components/LinkPicker.svelte +14 -6
- package/src/lib/components/MarkdownEditor.svelte +80 -34
- package/src/lib/components/MarkdownHelpDialog.svelte +58 -0
- package/src/lib/components/RenameDialog.svelte +13 -4
- package/src/lib/components/WebLinkDialog.svelte +89 -0
- package/src/lib/components/cairn-admin.css +26 -4
- package/src/lib/components/editor-highlight.ts +67 -0
- package/src/lib/components/markdown-directives.ts +23 -0
- package/src/lib/components/markdown-format.ts +118 -13
- package/src/lib/content/pending.ts +24 -0
- package/src/lib/github/branches.ts +83 -0
- package/src/lib/log/events.ts +3 -0
- package/src/lib/sveltekit/content-routes.ts +391 -73
|
@@ -10,6 +10,8 @@ import { isValidId, slugify, filenameFromId, composeDatedId, slugFromId, renameI
|
|
|
10
10
|
import { rewriteCairnLink } from '../components/markdown-format.js';
|
|
11
11
|
import { appCredentials } from '../github/credentials.js';
|
|
12
12
|
import { listMarkdown, readRaw, commitFiles } from '../github/repo.js';
|
|
13
|
+
import { branchHeadSha, createBranch, deleteBranch, listBranches } from '../github/branches.js';
|
|
14
|
+
import { PENDING_PREFIX, pendingBranch, parsePendingBranch } from '../content/pending.js';
|
|
13
15
|
import { cachedInstallationToken } from '../github/signing.js';
|
|
14
16
|
import { emptyManifest, manifestEntryFromFile, parseManifest, serializeManifest, upsertEntry, removeEntry, inboundLinks } from '../content/manifest.js';
|
|
15
17
|
import { CommitConflictError } from '../github/types.js';
|
|
@@ -31,8 +33,27 @@ function conceptOf(runtime, params) {
|
|
|
31
33
|
}
|
|
32
34
|
export function createContentRoutes(runtime, deps = {}) {
|
|
33
35
|
const mintToken = deps.mintToken ?? ((env) => cachedInstallationToken(appCredentials(runtime.backend, env)));
|
|
34
|
-
/**
|
|
35
|
-
|
|
36
|
+
/** Main's manifest, parsed. A missing file starts empty (a fresh repo before the first commit).
|
|
37
|
+
* Always read from main: pending branches carry no manifest copy. */
|
|
38
|
+
async function readManifest(token) {
|
|
39
|
+
const raw = await readRaw(runtime.backend, runtime.manifestPath, token);
|
|
40
|
+
return raw === null ? emptyManifest() : parseManifest(raw);
|
|
41
|
+
}
|
|
42
|
+
/** The pending entry a `cairn/` ref names, or null for a ref the engine must ignore: a
|
|
43
|
+
* malformed name, an id that fails the slug rule (entry paths are built from it, so this is
|
|
44
|
+
* the path confinement), or a concept this site does not configure. Every ref consumer
|
|
45
|
+
* (the layout count, the list view, publish-all) applies this one predicate, so a stray
|
|
46
|
+
* hand-pushed ref cannot inflate a count it can never clear or reach a contents read. */
|
|
47
|
+
function pendingEntryOf(name) {
|
|
48
|
+
const ref = parsePendingBranch(name);
|
|
49
|
+
if (!ref || !isValidId(ref.id))
|
|
50
|
+
return null;
|
|
51
|
+
const concept = findConcept(runtime.concepts, ref.concept);
|
|
52
|
+
return concept ? { concept, id: ref.id } : null;
|
|
53
|
+
}
|
|
54
|
+
/** Layout load for every admin page: the nav, the user, the active path, the resolved theme,
|
|
55
|
+
* and the pending entries behind the topbar's publish-all action. */
|
|
56
|
+
async function layoutLoad(event) {
|
|
36
57
|
const editor = sessionOf(event);
|
|
37
58
|
const cookieTheme = event.cookies?.get('cairn-admin-theme');
|
|
38
59
|
const theme = cookieTheme === 'cairn-admin-dark' ? 'cairn-admin-dark' : 'cairn-admin';
|
|
@@ -40,6 +61,20 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
40
61
|
const collapsedNav = cookieCollapsed
|
|
41
62
|
? cookieCollapsed.split(',').map((part) => decodeURIComponent(part)).filter(Boolean)
|
|
42
63
|
: [];
|
|
64
|
+
// Any failure here (the token mint, the network, a non-ok response) degrades to null rather
|
|
65
|
+
// than failing the whole admin shell or showing a wrong publish-all count.
|
|
66
|
+
let pendingEntries = null;
|
|
67
|
+
try {
|
|
68
|
+
const token = await mintToken(event.platform?.env ?? {});
|
|
69
|
+
const names = await listBranches(runtime.backend, PENDING_PREFIX, token);
|
|
70
|
+
pendingEntries = names.flatMap((name) => {
|
|
71
|
+
const entry = pendingEntryOf(name);
|
|
72
|
+
return entry ? [{ concept: entry.concept.id, id: entry.id }] : [];
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
pendingEntries = null;
|
|
77
|
+
}
|
|
43
78
|
return {
|
|
44
79
|
siteName: runtime.siteName,
|
|
45
80
|
user: { displayName: editor.displayName, email: editor.email, role: editor.role },
|
|
@@ -50,6 +85,7 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
50
85
|
theme,
|
|
51
86
|
collapsedNav,
|
|
52
87
|
csrf: event.cookies ? issueCsrfToken({ url: event.url, cookies: event.cookies }) : '',
|
|
88
|
+
pendingEntries,
|
|
53
89
|
};
|
|
54
90
|
}
|
|
55
91
|
/** Redirect /admin to the first concept's list (spec §7.6: land on the first concept). */
|
|
@@ -59,27 +95,32 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
59
95
|
throw error(404, 'No content types configured');
|
|
60
96
|
throw redirect(307, `/admin/${first.id}`);
|
|
61
97
|
}
|
|
62
|
-
/** Read a file's frontmatter for its list row, degrading to the id on any read failure.
|
|
63
|
-
|
|
98
|
+
/** Read a file's frontmatter for its list row, degrading to the id on any read failure. The
|
|
99
|
+
* repo defaults to main; a pending entry (edited or branch-only) passes its pending branch. */
|
|
100
|
+
async function summarize(file, token, status, repo = runtime.backend) {
|
|
64
101
|
try {
|
|
65
|
-
const raw = await readRaw(
|
|
102
|
+
const raw = await readRaw(repo, file.path, token);
|
|
66
103
|
if (raw === null)
|
|
67
|
-
return { id: file.id, title: file.id, date: null, draft: false };
|
|
104
|
+
return { id: file.id, title: file.id, date: null, draft: false, status };
|
|
68
105
|
const { frontmatter } = parseMarkdown(raw);
|
|
69
106
|
const title = typeof frontmatter.title === 'string' && frontmatter.title.trim() ? frontmatter.title : file.id;
|
|
70
107
|
const date = dateInputValue(frontmatter.date) || null;
|
|
71
|
-
return { id: file.id, title, date, draft: frontmatter.draft === true };
|
|
108
|
+
return { id: file.id, title, date, draft: frontmatter.draft === true, status };
|
|
72
109
|
}
|
|
73
110
|
catch {
|
|
74
|
-
return { id: file.id, title: file.id, date: null, draft: false };
|
|
111
|
+
return { id: file.id, title: file.id, date: null, draft: false, status };
|
|
75
112
|
}
|
|
76
113
|
}
|
|
77
|
-
/** List a concept's entries
|
|
114
|
+
/** List a concept's entries with their publish status. Main's files carry `edited` when a
|
|
115
|
+
* pending ref exists, else `published`; a ref with no main file appends a `new` row read from
|
|
116
|
+
* its branch. A listing failure degrades to an inline error, not a thrown 500. */
|
|
78
117
|
async function listLoad(event) {
|
|
79
118
|
sessionOf(event);
|
|
80
119
|
const concept = conceptOf(runtime, event.params);
|
|
81
120
|
const formError = event.url.searchParams.get('error');
|
|
82
|
-
const
|
|
121
|
+
const publishedAllRaw = event.url.searchParams.get('publishedAll');
|
|
122
|
+
const publishedAll = publishedAllRaw !== null && /^\d+$/.test(publishedAllRaw) ? Number(publishedAllRaw) : null;
|
|
123
|
+
const base = { conceptId: concept.id, label: concept.label, dated: concept.routing.dated, formError, publishedAll };
|
|
83
124
|
let token;
|
|
84
125
|
try {
|
|
85
126
|
token = await mintToken(event.platform?.env ?? {});
|
|
@@ -88,9 +129,29 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
88
129
|
return { ...base, entries: [], error: 'Could not authenticate with GitHub.' };
|
|
89
130
|
}
|
|
90
131
|
try {
|
|
91
|
-
const files = await
|
|
92
|
-
|
|
93
|
-
|
|
132
|
+
const [files, refs] = await Promise.all([
|
|
133
|
+
listMarkdown(runtime.backend, concept.dir, token),
|
|
134
|
+
listBranches(runtime.backend, `${PENDING_PREFIX}${concept.id}/`, token),
|
|
135
|
+
]);
|
|
136
|
+
const pendingIds = new Set(refs.flatMap((name) => {
|
|
137
|
+
const entry = pendingEntryOf(name);
|
|
138
|
+
return entry && entry.concept.id === concept.id ? [entry.id] : [];
|
|
139
|
+
}));
|
|
140
|
+
// An edited row reads branch-first like a new row, so a pending title or draft change
|
|
141
|
+
// shows in the list instead of reading as a lost save.
|
|
142
|
+
const entries = await Promise.all(files.map((f) => pendingIds.has(f.id)
|
|
143
|
+
? summarize(f, token, 'edited', { ...runtime.backend, branch: pendingBranch(concept.id, f.id) })
|
|
144
|
+
: summarize(f, token, 'published')));
|
|
145
|
+
// A ref with no main file is a never-published entry; its row reads from its branch, and
|
|
146
|
+
// summarize already degrades a failed read to an id-only row.
|
|
147
|
+
const listed = new Set(files.map((f) => f.id));
|
|
148
|
+
const newRows = await Promise.all([...pendingIds]
|
|
149
|
+
.filter((id) => !listed.has(id))
|
|
150
|
+
.map((id) => summarize({ id, path: `${concept.dir}/${filenameFromId(id)}` }, token, 'new', {
|
|
151
|
+
...runtime.backend,
|
|
152
|
+
branch: pendingBranch(concept.id, id),
|
|
153
|
+
})));
|
|
154
|
+
return { ...base, entries: [...entries, ...newRows], error: null };
|
|
94
155
|
}
|
|
95
156
|
catch {
|
|
96
157
|
return { ...base, entries: [], error: 'Could not load this content type from GitHub.' };
|
|
@@ -121,6 +182,10 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
121
182
|
const existing = await readRaw(runtime.backend, `${concept.dir}/${filenameFromId(id)}`, token);
|
|
122
183
|
if (existing !== null)
|
|
123
184
|
return bounce('An entry with that slug already exists.');
|
|
185
|
+
// A pending branch is an entry too (saved but not yet published); refuse to clobber it.
|
|
186
|
+
if ((await branchHeadSha(runtime.backend, pendingBranch(concept.id, id), token)) !== null) {
|
|
187
|
+
return bounce('An unpublished entry with that slug already exists.');
|
|
188
|
+
}
|
|
124
189
|
throw redirect(303, `/admin/${concept.id}/${id}?new=1`);
|
|
125
190
|
}
|
|
126
191
|
/** Coerce parsed frontmatter to the form-ready values the editor inputs expect. */
|
|
@@ -149,13 +214,20 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
149
214
|
const isNew = event.url.searchParams.get('new') === '1';
|
|
150
215
|
const token = await mintToken(event.platform?.env ?? {});
|
|
151
216
|
const datePrefix = concept.routing.dated ? concept.datePrefix : null;
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
217
|
+
const path = `${concept.dir}/${filenameFromId(id)}`;
|
|
218
|
+
// A pending entry reads branch-first: the editor shows the unpublished edits. The manifest
|
|
219
|
+
// (link targets and the inbound-link guard) always reads main, the authoritative copy, and a
|
|
220
|
+
// pending entry adds a main read of its own path to derive its published state.
|
|
221
|
+
const branch = pendingBranch(concept.id, id);
|
|
222
|
+
const pending = (await branchHeadSha(runtime.backend, branch, token)) !== null;
|
|
223
|
+
const [raw, manifestRaw, mainRaw] = await Promise.all([
|
|
224
|
+
readRaw(pending ? { ...runtime.backend, branch } : runtime.backend, path, token),
|
|
155
225
|
readRaw(runtime.backend, runtime.manifestPath, token),
|
|
226
|
+
pending ? readRaw(runtime.backend, path, token) : Promise.resolve(null),
|
|
156
227
|
]);
|
|
157
228
|
if (raw === null && !isNew)
|
|
158
229
|
throw error(404, 'Entry not found');
|
|
230
|
+
const published = pending ? mainRaw !== null : raw !== null;
|
|
159
231
|
const parsed = raw === null ? { frontmatter: {}, body: '' } : parseMarkdown(raw);
|
|
160
232
|
const title = typeof parsed.frontmatter.title === 'string' && parsed.frontmatter.title.trim() ? parsed.frontmatter.title : id;
|
|
161
233
|
let linkTargets = [];
|
|
@@ -187,6 +259,10 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
187
259
|
slug: slugFromId(id, datePrefix),
|
|
188
260
|
linkTargets,
|
|
189
261
|
inboundLinks: inbound,
|
|
262
|
+
pending,
|
|
263
|
+
published,
|
|
264
|
+
publishedFlash: event.url.searchParams.get('published') === '1',
|
|
265
|
+
discardedFlash: event.url.searchParams.get('discarded') === '1',
|
|
190
266
|
};
|
|
191
267
|
}
|
|
192
268
|
/** Match a commit conflict by class and by name (bundling can alias the class identity). */
|
|
@@ -194,25 +270,32 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
194
270
|
return err instanceof CommitConflictError || err?.name === 'CommitConflictError';
|
|
195
271
|
}
|
|
196
272
|
/** Log a failed commit: a conflict is the expected last-writer-wins outcome, so it warns with a
|
|
197
|
-
* reason; any other error is unexpected and logs at error with the stringified cause.
|
|
198
|
-
*
|
|
199
|
-
function logCommitFailed(fields, err) {
|
|
273
|
+
* reason; any other error is unexpected and logs at error with the stringified cause. Publish
|
|
274
|
+
* failures carry the same shape under their own event name. */
|
|
275
|
+
function logCommitFailed(fields, err, event = 'commit.failed') {
|
|
200
276
|
if (isConflict(err)) {
|
|
201
|
-
log.warn(
|
|
277
|
+
log.warn(event, { ...fields, reason: 'conflict' });
|
|
202
278
|
}
|
|
203
279
|
else {
|
|
204
|
-
log.error(
|
|
280
|
+
log.error(event, { ...fields, error: String(err) });
|
|
205
281
|
}
|
|
206
282
|
}
|
|
207
|
-
/**
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
283
|
+
/** The shared commit catch for the entry actions: log the failure, bounce a conflict back to
|
|
284
|
+
* `page` with `message` as the inline error, and rethrow anything else. `query` keeps any extra
|
|
285
|
+
* params the bounce must carry (saveAction's `&new=1`). */
|
|
286
|
+
function commitFailure(fields, err, page, message, opts = {}) {
|
|
287
|
+
logCommitFailed(fields, err, opts.event);
|
|
288
|
+
if (isConflict(err)) {
|
|
289
|
+
throw redirect(303, `${page}?error=${encodeURIComponent(message)}${opts.query ?? ''}`);
|
|
290
|
+
}
|
|
291
|
+
throw err;
|
|
292
|
+
}
|
|
293
|
+
/** The shared core of save and publish: parse the posted form, validate the frontmatter,
|
|
294
|
+
* guard the body's cairn links, ensure the pending branch, and commit the entry file there
|
|
295
|
+
* with the session editor as author. Returns the broken-link fail for the page to render,
|
|
296
|
+
* or the held state; throws the redirect bounces save has always thrown (invalid
|
|
297
|
+
* frontmatter, a branch-commit conflict). Main stays untouched. */
|
|
298
|
+
async function saveToBranch(event, editor, concept, id) {
|
|
216
299
|
const path = `${concept.dir}/${filenameFromId(id)}`;
|
|
217
300
|
const form = await event.request.formData();
|
|
218
301
|
const body = String(form.get('body') ?? '');
|
|
@@ -225,24 +308,19 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
225
308
|
}
|
|
226
309
|
const markdown = serializeMarkdown(result.data, body);
|
|
227
310
|
const token = await mintToken(event.platform?.env ?? {});
|
|
228
|
-
//
|
|
229
|
-
// commit.
|
|
230
|
-
|
|
231
|
-
// 422 retry commitFiles re-sends this manifest blob last-writer-wins. A concurrent save can then
|
|
232
|
-
// leave the committed manifest stale, which the next build rejects via verifyManifest; regenerate
|
|
233
|
-
// it with npm run cairn:manifest to recover.
|
|
234
|
-
const manifestRaw = await readRaw(runtime.backend, runtime.manifestPath, token);
|
|
235
|
-
const manifest = manifestRaw === null ? emptyManifest() : parseManifest(manifestRaw);
|
|
311
|
+
// Upsert this entry's row into main's manifest in memory, for the link guard here and for
|
|
312
|
+
// the publish commit. The save commits no manifest change; publish lands the upsert on main.
|
|
313
|
+
const manifest = await readManifest(token);
|
|
236
314
|
const row = manifestEntryFromFile(concept, { path, raw: markdown });
|
|
237
315
|
const upserted = upsertEntry(manifest, row);
|
|
238
|
-
|
|
239
|
-
//
|
|
240
|
-
//
|
|
241
|
-
//
|
|
242
|
-
//
|
|
316
|
+
// Save guard: resolve the body's cairn links against main's manifest with this entry upserted,
|
|
317
|
+
// so a self-link and a link to any published target resolves. A link to a target absent from
|
|
318
|
+
// main hard-blocks the save (publishing this entry before its target would red the deploy
|
|
319
|
+
// build); a link to a draft target commits with a warning, since it is valid and resolves once
|
|
320
|
+
// the target is published.
|
|
243
321
|
const byKey = new Map(upserted.entries.map((e) => [`${e.concept}/${e.id}`, e]));
|
|
244
322
|
const absent = [];
|
|
245
|
-
const
|
|
323
|
+
const draftLinks = [];
|
|
246
324
|
for (const ref of extractCairnLinks(body)) {
|
|
247
325
|
// A self-link is valid by construction (the upserted manifest holds this very entry), so
|
|
248
326
|
// skip it before classifying. Mirrors inboundLinks's self-exclusion.
|
|
@@ -252,29 +330,179 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
252
330
|
if (!target)
|
|
253
331
|
absent.push(formatCairnToken(ref));
|
|
254
332
|
else if (target.draft)
|
|
255
|
-
|
|
333
|
+
draftLinks.push(formatCairnToken(ref));
|
|
256
334
|
}
|
|
257
335
|
if (absent.length) {
|
|
258
336
|
return fail(400, { brokenLinks: absent, body });
|
|
259
337
|
}
|
|
338
|
+
// Ensure the entry's pending branch exists (cut lazily from main's head on first save), then
|
|
339
|
+
// commit only the entry file there. Main stays untouched until publish, so the branch differs
|
|
340
|
+
// from main at exactly this entry's path.
|
|
341
|
+
const branch = pendingBranch(concept.id, id);
|
|
342
|
+
if ((await branchHeadSha(runtime.backend, branch, token)) === null) {
|
|
343
|
+
const mainHead = await branchHeadSha(runtime.backend, runtime.backend.branch, token);
|
|
344
|
+
if (mainHead === null)
|
|
345
|
+
throw error(500, 'Cannot read the default branch');
|
|
346
|
+
await createBranch(runtime.backend, branch, mainHead, token);
|
|
347
|
+
}
|
|
348
|
+
const commitFields = { concept: concept.id, id, editor: editor.email, branch };
|
|
349
|
+
let branchSha;
|
|
350
|
+
try {
|
|
351
|
+
branchSha = await commitFiles({ ...runtime.backend, branch }, [{ path, content: markdown }], { message: `Update ${concept.label.toLowerCase()}: ${id}`, author: { name: editor.displayName, email: editor.email } }, token);
|
|
352
|
+
log.info('commit.succeeded', commitFields);
|
|
353
|
+
}
|
|
354
|
+
catch (err) {
|
|
355
|
+
commitFailure(commitFields, err, `/admin/${concept.id}/${id}`, 'This file changed since you opened it. Reload and reapply your edits.', { query: suffix });
|
|
356
|
+
}
|
|
357
|
+
return { path, markdown, branch, branchSha, manifest: upserted, draftLinks, token };
|
|
358
|
+
}
|
|
359
|
+
/** Save an edit: validate, then commit to the entry's pending branch with the session editor
|
|
360
|
+
* as author. Main and its manifest stay untouched until publish. Fails safe on 409. */
|
|
361
|
+
async function saveAction(event) {
|
|
362
|
+
const editor = sessionOf(event);
|
|
363
|
+
const concept = conceptOf(runtime, event.params);
|
|
364
|
+
const id = event.params.id ?? '';
|
|
365
|
+
// Confine the commit path to the concept dir, built from a validated id (the App token can
|
|
366
|
+
// write anywhere in the repo). Reject before touching GitHub.
|
|
367
|
+
if (!isValidId(id))
|
|
368
|
+
throw error(400, 'Invalid entry id');
|
|
369
|
+
const held = await saveToBranch(event, editor, concept, id);
|
|
370
|
+
if (!('branchSha' in held))
|
|
371
|
+
return held;
|
|
372
|
+
const savedQuery = held.draftLinks.length
|
|
373
|
+
? `saved=1&drafts=${encodeURIComponent(held.draftLinks.join(','))}`
|
|
374
|
+
: 'saved=1';
|
|
375
|
+
throw redirect(303, `/admin/${concept.id}/${id}?${savedQuery}`);
|
|
376
|
+
}
|
|
377
|
+
/** Publish an entry: validate and hold the posted form exactly like save (the branch gets the
|
|
378
|
+
* same commit), then copy that markdown to main with the manifest row upserted in one atomic
|
|
379
|
+
* commit. Publish-what-you-see: the posted form is the published content, so text typed
|
|
380
|
+
* after the last save goes live too, and publish works regardless of prior branch state.
|
|
381
|
+
* The branch is deleted only when its head still matches the commit this action made; a
|
|
382
|
+
* concurrent save moved it, so the entry stays pending and the next publish picks it up. */
|
|
383
|
+
async function publishAction(event) {
|
|
384
|
+
const editor = sessionOf(event);
|
|
385
|
+
const concept = conceptOf(runtime, event.params);
|
|
386
|
+
const id = event.params.id ?? '';
|
|
387
|
+
if (!isValidId(id))
|
|
388
|
+
throw error(400, 'Invalid entry id');
|
|
389
|
+
const held = await saveToBranch(event, editor, concept, id);
|
|
390
|
+
if (!('branchSha' in held))
|
|
391
|
+
return held;
|
|
392
|
+
const { path, markdown, branch, branchSha, manifest, token } = held;
|
|
260
393
|
const commitFields = { concept: concept.id, id, editor: editor.email };
|
|
261
394
|
try {
|
|
262
395
|
await commitFiles(runtime.backend, [
|
|
263
396
|
{ path, content: markdown },
|
|
264
|
-
{ path: runtime.manifestPath, content:
|
|
265
|
-
], { message: `
|
|
266
|
-
log.info('
|
|
397
|
+
{ path: runtime.manifestPath, content: serializeManifest(manifest) },
|
|
398
|
+
], { message: `Publish ${concept.label.toLowerCase()}: ${id}`, author: { name: editor.displayName, email: editor.email } }, token);
|
|
399
|
+
log.info('entry.published', { ...commitFields, batch: false });
|
|
267
400
|
}
|
|
268
401
|
catch (err) {
|
|
269
|
-
|
|
402
|
+
// The branch already holds the just-committed edits, so a conflict here loses nothing.
|
|
403
|
+
commitFailure(commitFields, err, `/admin/${concept.id}/${id}`, 'Your edits are saved. Reload and publish again.', { event: 'publish.failed' });
|
|
404
|
+
}
|
|
405
|
+
// Only after the main commit lands, and only when the branch head is still the commit this
|
|
406
|
+
// action made: a head that moved is a concurrent save, and deleting it would destroy edits.
|
|
407
|
+
// No log event for the skip; the pending badge is the surface.
|
|
408
|
+
if ((await branchHeadSha(runtime.backend, branch, token)) === branchSha) {
|
|
409
|
+
await deleteBranch(runtime.backend, branch, token);
|
|
410
|
+
}
|
|
411
|
+
throw redirect(303, `/admin/${concept.id}/${id}?published=1`);
|
|
412
|
+
}
|
|
413
|
+
/** Publish every pending entry site-wide: one atomic commit on main carrying each branch's
|
|
414
|
+
* entry file plus the manifest with every row upserted, then delete the consumed branches.
|
|
415
|
+
* Mounted on the concept list shim, but the topbar posts here from anywhere, so the route's
|
|
416
|
+
* concept param is ignored and the redirect lands on the first configured concept. */
|
|
417
|
+
async function publishAllAction(event) {
|
|
418
|
+
const editor = sessionOf(event);
|
|
419
|
+
const first = runtime.concepts[0];
|
|
420
|
+
if (!first)
|
|
421
|
+
throw error(404, 'No content types configured');
|
|
422
|
+
const token = await mintToken(event.platform?.env ?? {});
|
|
423
|
+
const listPage = `/admin/${first.id}`;
|
|
424
|
+
// Each cairn/ ref names a pending entry; the shared predicate skips a stray ref rather
|
|
425
|
+
// than failing the whole batch on it.
|
|
426
|
+
const names = await listBranches(runtime.backend, PENDING_PREFIX, token);
|
|
427
|
+
const pending = names.flatMap((name) => {
|
|
428
|
+
const entry = pendingEntryOf(name);
|
|
429
|
+
return entry ? [{ ...entry, branch: name, path: `${entry.concept.dir}/${filenameFromId(entry.id)}` }] : [];
|
|
430
|
+
});
|
|
431
|
+
// Read every branch in parallel, capturing each head sha BEFORE its file read: the sha
|
|
432
|
+
// guards the post-publish delete, and probing first fails safe (a save landing between the
|
|
433
|
+
// probe and the read moves the head past the capture, so the delete is skipped and the
|
|
434
|
+
// entry stays pending). A ghost ref whose entry file is missing is skipped (discard can
|
|
435
|
+
// clean it up); it carries nothing to publish.
|
|
436
|
+
const reads = await Promise.all(pending.map(async (entry) => {
|
|
437
|
+
const sha = await branchHeadSha(runtime.backend, entry.branch, token);
|
|
438
|
+
const raw = await readRaw({ ...runtime.backend, branch: entry.branch }, entry.path, token);
|
|
439
|
+
return { ...entry, sha, raw };
|
|
440
|
+
}));
|
|
441
|
+
// Fold main's manifest once over every row, so the batch lands content and index together,
|
|
442
|
+
// the same shape as a single publish.
|
|
443
|
+
let next = await readManifest(token);
|
|
444
|
+
const changes = [];
|
|
445
|
+
const published = [];
|
|
446
|
+
for (const entry of reads) {
|
|
447
|
+
if (entry.raw === null || entry.sha === null)
|
|
448
|
+
continue;
|
|
449
|
+
changes.push({ path: entry.path, content: entry.raw });
|
|
450
|
+
next = upsertEntry(next, manifestEntryFromFile(entry.concept, { path: entry.path, raw: entry.raw }));
|
|
451
|
+
published.push({ concept: entry.concept.id, id: entry.id, branch: entry.branch, sha: entry.sha });
|
|
452
|
+
}
|
|
453
|
+
if (published.length === 0)
|
|
454
|
+
throw redirect(303, listPage);
|
|
455
|
+
changes.push({ path: runtime.manifestPath, content: serializeManifest(next) });
|
|
456
|
+
try {
|
|
457
|
+
await commitFiles(runtime.backend, changes, { message: `Publish ${published.length} entries`, author: { name: editor.displayName, email: editor.email } }, token);
|
|
458
|
+
for (const entry of published) {
|
|
459
|
+
log.info('entry.published', { concept: entry.concept, id: entry.id, editor: editor.email, batch: true });
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
catch (err) {
|
|
463
|
+
// One record per entry in the failed batch, so the log names what did not go live.
|
|
464
|
+
for (const entry of published) {
|
|
465
|
+
logCommitFailed({ concept: entry.concept, id: entry.id, editor: editor.email }, err, 'publish.failed');
|
|
466
|
+
}
|
|
270
467
|
if (isConflict(err)) {
|
|
271
|
-
const message = '
|
|
272
|
-
throw redirect(303,
|
|
468
|
+
const message = 'The site changed while publishing. Reload and try again.';
|
|
469
|
+
throw redirect(303, `${listPage}?error=${encodeURIComponent(message)}`);
|
|
273
470
|
}
|
|
274
471
|
throw err;
|
|
275
472
|
}
|
|
276
|
-
|
|
277
|
-
|
|
473
|
+
// Only after the main commit lands: a failure above keeps every branch and its edits. Each
|
|
474
|
+
// branch deletes only when its head still matches the captured sha; a moved head is a
|
|
475
|
+
// concurrent save, so the entry stays pending and the next publish picks it up (no log
|
|
476
|
+
// event for the skip; the pending badge is the surface). A failed delete leaves an
|
|
477
|
+
// idempotent straggler (re-publishing copies the same content), so one failure does not
|
|
478
|
+
// abort the remaining deletes.
|
|
479
|
+
for (const entry of published) {
|
|
480
|
+
try {
|
|
481
|
+
if ((await branchHeadSha(runtime.backend, entry.branch, token)) === entry.sha) {
|
|
482
|
+
await deleteBranch(runtime.backend, entry.branch, token);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
catch {
|
|
486
|
+
// The entry is live; the straggler just shows as still pending until the next publish.
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
throw redirect(303, `${listPage}?publishedAll=${published.length}`);
|
|
490
|
+
}
|
|
491
|
+
/** Discard an entry's pending edits: delete the branch (tolerant of already-gone) and return to
|
|
492
|
+
* the edit page when the entry lives on main, else to the list (the entry is gone entirely). */
|
|
493
|
+
async function discardAction(event) {
|
|
494
|
+
const editor = sessionOf(event);
|
|
495
|
+
const concept = conceptOf(runtime, event.params);
|
|
496
|
+
const id = event.params.id ?? '';
|
|
497
|
+
if (!isValidId(id))
|
|
498
|
+
throw error(400, 'Invalid entry id');
|
|
499
|
+
const token = await mintToken(event.platform?.env ?? {});
|
|
500
|
+
await deleteBranch(runtime.backend, pendingBranch(concept.id, id), token);
|
|
501
|
+
log.info('entry.discarded', { concept: concept.id, id, editor: editor.email });
|
|
502
|
+
const onMain = await readRaw(runtime.backend, `${concept.dir}/${filenameFromId(id)}`, token);
|
|
503
|
+
if (onMain !== null)
|
|
504
|
+
throw redirect(303, `/admin/${concept.id}/${id}?discarded=1`);
|
|
505
|
+
throw redirect(303, `/admin/${concept.id}`);
|
|
278
506
|
}
|
|
279
507
|
/** The shared delete core. Block-until-clean: refuse while inbound links exist (naming them), else
|
|
280
508
|
* commit the file removal and the manifest patch in one commit. The inbound recheck here is the
|
|
@@ -286,12 +514,20 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
286
514
|
const token = await mintToken(event.platform?.env ?? {});
|
|
287
515
|
// An absent manifest degrades the inbound gate to "allow": with no manifest there is nothing to
|
|
288
516
|
// check, and the build's cairn: backstop still catches any dangling token, mirroring saveAction.
|
|
289
|
-
const
|
|
290
|
-
const manifest = manifestRaw === null ? emptyManifest() : parseManifest(manifestRaw);
|
|
517
|
+
const manifest = await readManifest(token);
|
|
291
518
|
const inbound = inboundLinks(manifest, concept.id, id);
|
|
292
519
|
if (inbound.length) {
|
|
293
520
|
return fail(409, { inboundLinks: inbound, id });
|
|
294
521
|
}
|
|
522
|
+
// When the entry was never published (absent from main), the branch delete is the whole
|
|
523
|
+
// operation; main has nothing to commit, so the only honest log record is the discard of
|
|
524
|
+
// the pending edits.
|
|
525
|
+
const onMain = await readRaw(runtime.backend, path, token);
|
|
526
|
+
if (onMain === null) {
|
|
527
|
+
await deleteBranch(runtime.backend, pendingBranch(concept.id, id), token);
|
|
528
|
+
log.info('entry.discarded', { concept: concept.id, id, editor: editor.email });
|
|
529
|
+
throw redirect(303, `/admin/${concept.id}`);
|
|
530
|
+
}
|
|
295
531
|
const nextManifest = serializeManifest(removeEntry(manifest, concept.id, id));
|
|
296
532
|
const commitFields = { concept: concept.id, id, editor: editor.email };
|
|
297
533
|
try {
|
|
@@ -302,12 +538,17 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
302
538
|
log.info('commit.succeeded', commitFields);
|
|
303
539
|
}
|
|
304
540
|
catch (err) {
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
541
|
+
commitFailure(commitFields, err, `/admin/${concept.id}/${id}`, 'This file changed since you opened it. Reload and try again.');
|
|
542
|
+
}
|
|
543
|
+
// Cascade to the pending branch only after the removal lands on main, so a commit conflict
|
|
544
|
+
// keeps the unpublished edits. A straggler ref left by a failure here is idempotent and
|
|
545
|
+
// recoverable (it lists as a never-published row a discard can clean up), matching
|
|
546
|
+
// publish's posture, so the entry's deletion still completes.
|
|
547
|
+
try {
|
|
548
|
+
await deleteBranch(runtime.backend, pendingBranch(concept.id, id), token);
|
|
549
|
+
}
|
|
550
|
+
catch {
|
|
551
|
+
// The entry is gone from main; the straggler shows as a pending row until discarded.
|
|
311
552
|
}
|
|
312
553
|
throw redirect(303, `/admin/${concept.id}`);
|
|
313
554
|
}
|
|
@@ -340,6 +581,12 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
340
581
|
const id = event.params.id ?? '';
|
|
341
582
|
if (!isValidId(id))
|
|
342
583
|
throw error(400, 'Invalid entry id');
|
|
584
|
+
const token = await mintToken(event.platform?.env ?? {});
|
|
585
|
+
// Pending edits on the branch are keyed to the old id; renaming underneath them would strand
|
|
586
|
+
// them, so refuse until the editor publishes or discards.
|
|
587
|
+
if ((await branchHeadSha(runtime.backend, pendingBranch(concept.id, id), token)) !== null) {
|
|
588
|
+
return fail(409, { renameError: 'This entry has unpublished edits. Publish or discard them, then rename.' });
|
|
589
|
+
}
|
|
343
590
|
const form = await event.request.formData();
|
|
344
591
|
const newSlug = String(form.get('slug') ?? '').trim();
|
|
345
592
|
if (!isValidId(newSlug)) {
|
|
@@ -355,7 +602,6 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
355
602
|
const newId = renameId(id, newSlug, datePrefix);
|
|
356
603
|
const oldPath = `${concept.dir}/${filenameFromId(id)}`;
|
|
357
604
|
const newPath = `${concept.dir}/${filenameFromId(newId)}`;
|
|
358
|
-
const token = await mintToken(event.platform?.env ?? {});
|
|
359
605
|
// Collision guard: refuse if a file already exists at the new path. This 409 covers two cases a
|
|
360
606
|
// single readRaw cannot tell apart: a static collision with an existing entry, and a
|
|
361
607
|
// concurrent-rename race where another editor renamed onto this path between load and submit.
|
|
@@ -363,13 +609,12 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
363
609
|
if (clobber !== null) {
|
|
364
610
|
return fail(409, { renameError: 'An entry with that slug already exists.' });
|
|
365
611
|
}
|
|
366
|
-
const [entryRaw,
|
|
612
|
+
const [entryRaw, manifest] = await Promise.all([
|
|
367
613
|
readRaw(runtime.backend, oldPath, token),
|
|
368
|
-
|
|
614
|
+
readManifest(token),
|
|
369
615
|
]);
|
|
370
616
|
if (entryRaw === null)
|
|
371
617
|
throw error(404, 'Entry not found');
|
|
372
|
-
const manifest = manifestRaw === null ? emptyManifest() : parseManifest(manifestRaw);
|
|
373
618
|
const oldHref = formatCairnToken({ concept: concept.id, id });
|
|
374
619
|
const newHref = formatCairnToken({ concept: concept.id, id: newId });
|
|
375
620
|
// The moved file keeps its content, except a self-token rewrite. Re-derive its manifest row from
|
|
@@ -402,14 +647,9 @@ export function createContentRoutes(runtime, deps = {}) {
|
|
|
402
647
|
log.info('commit.succeeded', commitFields);
|
|
403
648
|
}
|
|
404
649
|
catch (err) {
|
|
405
|
-
|
|
406
|
-
if (isConflict(err)) {
|
|
407
|
-
const message = 'This file changed since you opened it. Reload and try again.';
|
|
408
|
-
throw redirect(303, `/admin/${concept.id}/${id}?error=${encodeURIComponent(message)}`);
|
|
409
|
-
}
|
|
410
|
-
throw err;
|
|
650
|
+
commitFailure(commitFields, err, `/admin/${concept.id}/${id}`, 'This file changed since you opened it. Reload and try again.');
|
|
411
651
|
}
|
|
412
652
|
throw redirect(303, `/admin/${concept.id}/${newId}?renamed=1`);
|
|
413
653
|
}
|
|
414
|
-
return { layoutLoad, indexRedirect, listLoad, createAction, editLoad, saveAction, deleteAction, listDeleteAction, renameAction, mintToken };
|
|
654
|
+
return { layoutLoad, indexRedirect, listLoad, createAction, editLoad, saveAction, publishAction, publishAllAction, discardAction, deleteAction, listDeleteAction, renameAction, mintToken };
|
|
415
655
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glw907/cairn-cms",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.40.0",
|
|
4
4
|
"description": "Embedded, magic-link, GitHub-committing CMS for SvelteKit/Cloudflare sites.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": [
|
|
@@ -100,6 +100,7 @@
|
|
|
100
100
|
"@codemirror/language": "^6.12.3",
|
|
101
101
|
"@codemirror/state": "^6.6.0",
|
|
102
102
|
"@codemirror/view": "^6.43.0",
|
|
103
|
+
"@lezer/highlight": "^1.2.3",
|
|
103
104
|
"@lucide/svelte": "^1.17.0",
|
|
104
105
|
"@rodrigodagostino/svelte-sortable-list": "^2.1.17",
|
|
105
106
|
"@types/hast": "^3.0.4",
|
|
@@ -139,7 +140,7 @@
|
|
|
139
140
|
"postcss": "^8.5.15",
|
|
140
141
|
"postcss-prefix-selector": "^2.1.1",
|
|
141
142
|
"publint": "^0.3.21",
|
|
142
|
-
"svelte": "^5.
|
|
143
|
+
"svelte": "^5.56.3",
|
|
143
144
|
"svelte-check": "^4",
|
|
144
145
|
"tailwindcss": "^4.3.0",
|
|
145
146
|
"typescript": "^6.0.3",
|