@glw907/cairn-cms 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/adapter.d.ts +34 -1
- package/dist/adapter.d.ts.map +1 -1
- package/dist/auth/capabilities.d.ts +7 -0
- package/dist/auth/capabilities.d.ts.map +1 -0
- package/dist/auth/capabilities.js +26 -0
- package/dist/auth/config.d.ts +9 -9
- package/dist/auth/config.d.ts.map +1 -1
- package/dist/auth/config.js +5 -5
- package/dist/auth/guard.d.ts +1 -1
- package/dist/auth/guard.d.ts.map +1 -1
- package/dist/auth/guard.js +2 -2
- package/dist/auth/index.d.ts +1 -0
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +1 -0
- package/dist/carta.d.ts +1 -1
- package/dist/carta.d.ts.map +1 -1
- package/dist/components/AdminLayout.svelte +74 -18
- package/dist/components/AdminLayout.svelte.d.ts +9 -0
- package/dist/components/AdminLayout.svelte.d.ts.map +1 -1
- package/dist/components/CollectionList.svelte +96 -0
- package/dist/components/CollectionList.svelte.d.ts +8 -0
- package/dist/components/CollectionList.svelte.d.ts.map +1 -0
- package/dist/components/ComponentPalette.svelte +34 -0
- package/dist/components/ComponentPalette.svelte.d.ts +9 -0
- package/dist/components/ComponentPalette.svelte.d.ts.map +1 -0
- package/dist/components/ConfirmPage.svelte +2 -2
- package/dist/components/EditPage.svelte +69 -31
- package/dist/components/EditPage.svelte.d.ts +2 -0
- package/dist/components/EditPage.svelte.d.ts.map +1 -1
- package/dist/components/LoginPage.svelte +5 -5
- package/dist/components/NavTree.svelte +128 -0
- package/dist/components/NavTree.svelte.d.ts +8 -0
- package/dist/components/NavTree.svelte.d.ts.map +1 -0
- package/dist/components/index.d.ts +3 -1
- package/dist/components/index.d.ts.map +1 -1
- package/dist/components/index.js +3 -1
- package/dist/editor.d.ts +25 -0
- package/dist/editor.d.ts.map +1 -0
- package/dist/editor.js +20 -0
- package/dist/email.js +4 -4
- package/dist/frontmatter.d.ts +3 -0
- package/dist/frontmatter.d.ts.map +1 -0
- package/dist/frontmatter.js +16 -0
- package/dist/github.d.ts +22 -2
- package/dist/github.d.ts.map +1 -1
- package/dist/github.js +40 -5
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/nav.d.ts +58 -0
- package/dist/nav.d.ts.map +1 -0
- package/dist/nav.js +86 -0
- package/dist/render/glyph.d.ts +6 -0
- package/dist/render/glyph.d.ts.map +1 -0
- package/dist/render/glyph.js +5 -0
- package/dist/render/index.d.ts +6 -0
- package/dist/render/index.d.ts.map +1 -0
- package/dist/render/index.js +8 -0
- package/dist/render/pipeline.d.ts +16 -0
- package/dist/render/pipeline.d.ts.map +1 -0
- package/dist/render/pipeline.js +29 -0
- package/dist/render/registry.d.ts +28 -0
- package/dist/render/registry.d.ts.map +1 -0
- package/dist/render/registry.js +11 -0
- package/dist/render/rehype-dispatch.d.ts +24 -0
- package/dist/render/rehype-dispatch.d.ts.map +1 -0
- package/dist/render/rehype-dispatch.js +86 -0
- package/dist/render/remark-directives.d.ts +4 -0
- package/dist/render/remark-directives.d.ts.map +1 -0
- package/dist/render/remark-directives.js +74 -0
- package/dist/slug.d.ts +7 -0
- package/dist/slug.d.ts.map +1 -0
- package/dist/slug.js +15 -0
- package/dist/sveltekit/index.d.ts +118 -13
- package/dist/sveltekit/index.d.ts.map +1 -1
- package/dist/sveltekit/index.js +250 -24
- package/dist/utils.d.ts +1 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +2 -2
- package/package.json +20 -3
- package/src/lib/adapter.ts +37 -3
- package/src/lib/auth/capabilities.ts +35 -0
- package/src/lib/auth/config.ts +6 -6
- package/src/lib/auth/guard.ts +3 -3
- package/src/lib/auth/index.ts +1 -0
- package/src/lib/carta.ts +2 -2
- package/src/lib/components/AdminLayout.svelte +74 -18
- package/src/lib/components/CollectionList.svelte +96 -0
- package/src/lib/components/ComponentPalette.svelte +34 -0
- package/src/lib/components/ConfirmPage.svelte +2 -2
- package/src/lib/components/EditPage.svelte +69 -31
- package/src/lib/components/LoginPage.svelte +5 -5
- package/src/lib/components/NavTree.svelte +128 -0
- package/src/lib/components/index.ts +3 -1
- package/src/lib/editor.ts +38 -0
- package/src/lib/email.ts +4 -4
- package/src/lib/frontmatter.ts +17 -0
- package/src/lib/github.ts +38 -6
- package/src/lib/index.ts +3 -0
- package/src/lib/nav.ts +117 -0
- package/src/lib/render/glyph.ts +14 -0
- package/src/lib/render/index.ts +8 -0
- package/src/lib/render/pipeline.ts +37 -0
- package/src/lib/render/registry.ts +36 -0
- package/src/lib/render/rehype-dispatch.ts +97 -0
- package/src/lib/render/remark-directives.ts +71 -0
- package/src/lib/slug.ts +16 -0
- package/src/lib/sveltekit/index.ts +355 -37
- package/src/lib/utils.ts +2 -2
- package/dist/components/AdminList.svelte +0 -33
- package/dist/components/AdminList.svelte.d.ts +0 -10
- package/dist/components/AdminList.svelte.d.ts.map +0 -1
- package/src/lib/components/AdminList.svelte +0 -33
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { Paragraph, PhrasingContent, Root, Text } from 'mdast';
|
|
2
|
+
import type { ContainerDirective, LeafDirective, TextDirective } from 'mdast-util-directive';
|
|
3
|
+
import { visit } from 'unist-util-visit';
|
|
4
|
+
import type { ComponentRegistry } from './registry';
|
|
5
|
+
|
|
6
|
+
// Reconstruct a directive's authored attribute block (`{#id .class key="value"}`).
|
|
7
|
+
// Accidental prose directives carry none, so this is almost always empty.
|
|
8
|
+
function serializeAttributes(attributes?: Record<string, string | null | undefined> | null): string {
|
|
9
|
+
if (!attributes) return '';
|
|
10
|
+
const tokens: string[] = [];
|
|
11
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
12
|
+
if (value == null) tokens.push(key);
|
|
13
|
+
else if (key === 'id') tokens.push(`#${value}`);
|
|
14
|
+
else if (key === 'class') for (const c of value.split(/\s+/).filter(Boolean)) tokens.push(`.${c}`);
|
|
15
|
+
else tokens.push(`${key}="${value}"`);
|
|
16
|
+
}
|
|
17
|
+
return tokens.length ? `{${tokens.join(' ')}}` : '';
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// The vocabulary is container-only (`:::name`). A text directive (`:name`) or
|
|
21
|
+
// leaf directive (`::name`) is therefore always an accidental colon in prose
|
|
22
|
+
// ("4:00", "9:30", "ratio 16:9") that micromark tokenized as a directive.
|
|
23
|
+
// Restore it to its literal source text so prose renders verbatim.
|
|
24
|
+
function restoreLiteral(node: TextDirective | LeafDirective): PhrasingContent[] {
|
|
25
|
+
const marker = node.type === 'leafDirective' ? '::' : ':';
|
|
26
|
+
const attrs = serializeAttributes(node.attributes);
|
|
27
|
+
if (node.children.length === 0) {
|
|
28
|
+
return [{ type: 'text', value: marker + node.name + attrs }];
|
|
29
|
+
}
|
|
30
|
+
const open: Text = { type: 'text', value: `${marker}${node.name}[` };
|
|
31
|
+
const close: Text = { type: 'text', value: `]${attrs}` };
|
|
32
|
+
return [open, ...(node.children as PhrasingContent[]), close];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Stamp each registered container directive with data-* markers carrying its
|
|
36
|
+
// component name, icon, and role. No structure is built here; the rehype
|
|
37
|
+
// dispatcher rewrites the marked elements once their children are hast.
|
|
38
|
+
// Text and leaf directives are restored to literal text (accidental prose colons).
|
|
39
|
+
export function remarkDirectiveStamp(registry: ComponentRegistry) {
|
|
40
|
+
const known = new Set(registry.names);
|
|
41
|
+
return (tree: Root) => {
|
|
42
|
+
visit(tree, 'containerDirective', (node: ContainerDirective) => {
|
|
43
|
+
if (!known.has(node.name)) return;
|
|
44
|
+
const attrs = node.attributes ?? {};
|
|
45
|
+
const role = attrs.role || undefined;
|
|
46
|
+
let icon = attrs.icon || undefined;
|
|
47
|
+
if (!icon && role) icon = registry.defaultIcon(node.name, role);
|
|
48
|
+
|
|
49
|
+
const properties: Record<string, string> = { dataPrimitive: node.name };
|
|
50
|
+
if (icon) properties.dataIcon = icon;
|
|
51
|
+
if (role) properties.dataRole = role;
|
|
52
|
+
|
|
53
|
+
const data = node.data ?? (node.data = {});
|
|
54
|
+
data.hName = 'div';
|
|
55
|
+
data.hProperties = properties;
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
visit(tree, ['textDirective', 'leafDirective'], (node, index, parent) => {
|
|
59
|
+
if (!parent || index == null) return;
|
|
60
|
+
const literal = restoreLiteral(node as TextDirective | LeafDirective);
|
|
61
|
+
if (node.type === 'leafDirective') {
|
|
62
|
+
// Leaf directives sit at block level; wrap the restored text in a paragraph.
|
|
63
|
+
const paragraph: Paragraph = { type: 'paragraph', children: literal };
|
|
64
|
+
parent.children.splice(index, 1, paragraph);
|
|
65
|
+
} else {
|
|
66
|
+
parent.children.splice(index, 1, ...literal);
|
|
67
|
+
}
|
|
68
|
+
return index;
|
|
69
|
+
});
|
|
70
|
+
};
|
|
71
|
+
}
|
package/src/lib/slug.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// cairn-core: derive a filename-safe slug stem from a human title, for the create-entry form.
|
|
2
|
+
// The admin is filename-based (Pass E): this produces the editable stem an author can adjust,
|
|
3
|
+
// matching the server-side SLUG_RE (lowercase alphanumerics and internal hyphens). Pure.
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Lowercase a title into a filename-safe slug stem.
|
|
7
|
+
* Apostrophes are dropped so "Geoff's" becomes "geoffs" (no spurious hyphen).
|
|
8
|
+
* All other non-alphanumeric runs become a single hyphen; leading/trailing hyphens are trimmed.
|
|
9
|
+
*/
|
|
10
|
+
export function slugify(title: string): string {
|
|
11
|
+
return title
|
|
12
|
+
.toLowerCase()
|
|
13
|
+
.replace(/'/g, '')
|
|
14
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
15
|
+
.replace(/^-+|-+$/g, '');
|
|
16
|
+
}
|
|
@@ -2,20 +2,30 @@
|
|
|
2
2
|
// route files are thin shims (`export const load = (event) => editLoad(event, cairn)`).
|
|
3
3
|
//
|
|
4
4
|
// SvelteKit's filesystem routing requires the route *files* to live in each site's
|
|
5
|
-
// `src/routes/`, but their bodies are identical across sites
|
|
5
|
+
// `src/routes/`, but their bodies are identical across sites. Only the adapter differs.
|
|
6
6
|
// These functions take the SvelteKit event (typed structurally, to avoid depending on the
|
|
7
7
|
// site-generated `App.*` ambient types) plus the site `CairnAdapter`, and throw
|
|
8
8
|
// `redirect`/`error` from `@sveltejs/kit` (a peer dependency, so the thrown objects share
|
|
9
|
-
// class identity with the host's runtime
|
|
9
|
+
// class identity with the host's runtime; otherwise the redirect 500s). Auth/session/manage-editors
|
|
10
10
|
// logic lives under `@glw907/cairn-cms/auth`; this module is content-only (list/edit/save).
|
|
11
11
|
import { redirect, error } from '@sveltejs/kit';
|
|
12
12
|
import matter from 'gray-matter';
|
|
13
13
|
import type { CairnUser } from '../auth/guard';
|
|
14
|
-
import {
|
|
14
|
+
import { can, requireCapability } from '../auth/capabilities';
|
|
15
|
+
import {
|
|
16
|
+
listMarkdown,
|
|
17
|
+
readRaw,
|
|
18
|
+
commitFile,
|
|
19
|
+
installationToken,
|
|
20
|
+
signingSelfTest,
|
|
21
|
+
CommitConflictError,
|
|
22
|
+
type RepoFile,
|
|
23
|
+
} from '../github';
|
|
15
24
|
import { serializeMarkdown } from '../content';
|
|
16
25
|
import { findCollection, frontmatterFromForm, type CairnAdapter, type CairnField } from '../adapter';
|
|
26
|
+
import { validateNavTree, extractMenu, parseSiteConfig, setMenu, type NavNode } from '../nav';
|
|
17
27
|
|
|
18
|
-
/** The `platform.env` bindings the content routes read. All optional
|
|
28
|
+
/** The `platform.env` bindings the content routes read. All optional; the handlers guard. */
|
|
19
29
|
export interface AdminEnv {
|
|
20
30
|
GITHUB_APP_ID?: string;
|
|
21
31
|
GITHUB_APP_INSTALLATION_ID?: string;
|
|
@@ -30,7 +40,7 @@ interface PlatformEvent {
|
|
|
30
40
|
* Mint a GitHub App installation token for *reads* when the App is configured, else undefined
|
|
31
41
|
* (reads then fall back to anonymous). Authenticated reads get the 5000/hr limit; anonymous
|
|
32
42
|
* reads share GitHub's 60/hr-per-IP budget across Cloudflare's egress IPs, so they 403 in prod.
|
|
33
|
-
* A mint failure degrades gracefully to anonymous rather than 500ing
|
|
43
|
+
* A mint failure degrades gracefully to anonymous rather than 500ing. Unlike the commit path,
|
|
34
44
|
* where a missing App is fatal, a read can still succeed unauthenticated.
|
|
35
45
|
*/
|
|
36
46
|
async function readToken(env: AdminEnv | undefined): Promise<string | undefined> {
|
|
@@ -51,52 +61,195 @@ async function readToken(env: AdminEnv | undefined): Promise<string | undefined>
|
|
|
51
61
|
|
|
52
62
|
// ── /admin layout ──────────────────────────────────────────────────────────
|
|
53
63
|
|
|
64
|
+
/** A collection reduced to what the sidebar nav needs (no plugin graph crosses to the client). */
|
|
65
|
+
export interface NavCollection {
|
|
66
|
+
type: string;
|
|
67
|
+
label: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
54
70
|
export interface AdminLayoutData {
|
|
55
71
|
user: CairnUser | null;
|
|
56
72
|
siteName: string;
|
|
57
73
|
pathname: string;
|
|
74
|
+
collections: NavCollection[];
|
|
75
|
+
/** Managed menus (name+label only) so the shell can show a Navigation entry. */
|
|
76
|
+
navMenus: { name: string; label: string }[];
|
|
77
|
+
/** Whether the viewer may manage navigation (gates the Navigation nav entry). */
|
|
78
|
+
canManageNav: boolean;
|
|
58
79
|
}
|
|
59
80
|
|
|
60
81
|
/**
|
|
61
|
-
* Branding
|
|
62
|
-
* its plugin graph into client bundles
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
82
|
+
* Branding, session, and collection nav for every admin page. `siteName` and the collection
|
|
83
|
+
* list flow from the adapter without pulling its plugin graph into client bundles (the import
|
|
84
|
+
* stays server-side in the layout load; only `{type,label}` crosses). `pathname` lets the
|
|
85
|
+
* shared shell highlight the active nav item without a `$app/*` import (those kit virtual
|
|
86
|
+
* modules have no types outside a kit app); reading `event.url` also opts the layout load into
|
|
87
|
+
* rerunning on navigation, keeping the active class correct.
|
|
66
88
|
*/
|
|
67
89
|
export function adminLayoutLoad(
|
|
68
90
|
event: { locals: { user: CairnUser | null }; url: URL },
|
|
69
91
|
adapter: CairnAdapter,
|
|
70
92
|
): AdminLayoutData {
|
|
71
|
-
return {
|
|
93
|
+
return {
|
|
94
|
+
user: event.locals.user,
|
|
95
|
+
siteName: adapter.siteName,
|
|
96
|
+
pathname: event.url.pathname,
|
|
97
|
+
collections: adapter.collections.map(({ type, label }) => ({ type, label })),
|
|
98
|
+
navMenus: adapter.navMenu ? [{ name: adapter.navMenu.menuName, label: adapter.navMenu.label }] : [],
|
|
99
|
+
canManageNav: can(event.locals.user, 'nav:manage'),
|
|
100
|
+
};
|
|
72
101
|
}
|
|
73
102
|
|
|
74
|
-
|
|
103
|
+
/**
|
|
104
|
+
* The `/admin` index has no content of its own now that each collection is its own page; send
|
|
105
|
+
* the editor straight to the first collection's entries list (a Sveltia-style landing).
|
|
106
|
+
*/
|
|
107
|
+
export function adminIndexRedirect(adapter: CairnAdapter): never {
|
|
108
|
+
const first = adapter.collections[0];
|
|
109
|
+
if (!first) throw error(404, 'No collections configured');
|
|
110
|
+
throw redirect(307, `/admin/${first.type}`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ── /admin/[collection] (entries list) ─────────────────────────────────────
|
|
114
|
+
|
|
115
|
+
/** One entry row: id (filename stem), display title, optional date, draft flag. */
|
|
116
|
+
export interface CollectionEntry {
|
|
117
|
+
id: string;
|
|
118
|
+
path: string;
|
|
119
|
+
title: string;
|
|
120
|
+
date: string | null;
|
|
121
|
+
draft: boolean;
|
|
122
|
+
}
|
|
75
123
|
|
|
76
|
-
export interface
|
|
124
|
+
export interface CollectionListData {
|
|
77
125
|
type: string;
|
|
78
126
|
label: string;
|
|
79
|
-
|
|
127
|
+
kind: 'page' | 'story';
|
|
128
|
+
entries: CollectionEntry[];
|
|
129
|
+
/** Set when the directory listing itself failed (rate limit, network). */
|
|
80
130
|
error?: string;
|
|
131
|
+
/** A create-flow error bounced back via `?error=` (an invalid or taken slug). */
|
|
132
|
+
formError: string | null;
|
|
133
|
+
/** Whether the viewer may create an entry in this collection (page-create is owner-only). */
|
|
134
|
+
canCreate: boolean;
|
|
81
135
|
}
|
|
82
136
|
|
|
83
|
-
/**
|
|
84
|
-
|
|
85
|
-
|
|
137
|
+
/** Coerce a frontmatter `date` (gray-matter may parse YAML dates to `Date`) to `YYYY-MM-DD`. */
|
|
138
|
+
function entryDate(value: unknown): string | null {
|
|
139
|
+
if (value instanceof Date) return value.toISOString().slice(0, 10);
|
|
140
|
+
if (typeof value === 'string') return value;
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* List one collection's entries, reading each file's frontmatter for the display title, date,
|
|
146
|
+
* and draft badge. Reads run in parallel; a single failed read degrades that row to the slug
|
|
147
|
+
* (rather than failing the page), and a failed directory listing returns an inline `error`.
|
|
148
|
+
* Collections are small here; the 1,000-entry / Git-Trees sharding concern is risk #11, deferred.
|
|
149
|
+
*/
|
|
150
|
+
export async function collectionListLoad(
|
|
151
|
+
event: PlatformEvent & { params: { collection: string }; url: URL; locals: { user: CairnUser | null } },
|
|
86
152
|
adapter: CairnAdapter,
|
|
87
|
-
): Promise<
|
|
153
|
+
): Promise<CollectionListData> {
|
|
154
|
+
const collection = findCollection(adapter, event.params.collection);
|
|
155
|
+
if (!collection) throw error(404, 'Unknown collection');
|
|
156
|
+
|
|
157
|
+
const kind = collection.kind ?? 'story';
|
|
158
|
+
const canCreate = can(event.locals.user, kind === 'page' ? 'page:create' : 'story:create');
|
|
159
|
+
const formError = event.url.searchParams.get('error');
|
|
88
160
|
const token = await readToken(event.platform?.env);
|
|
89
|
-
|
|
90
|
-
|
|
161
|
+
|
|
162
|
+
let files: RepoFile[];
|
|
163
|
+
try {
|
|
164
|
+
files = await listMarkdown(adapter.backend, collection.dir, token);
|
|
165
|
+
} catch (err) {
|
|
166
|
+
return {
|
|
167
|
+
type: collection.type,
|
|
168
|
+
label: collection.label,
|
|
169
|
+
kind,
|
|
170
|
+
entries: [],
|
|
171
|
+
error: err instanceof Error ? err.message : 'Failed to load',
|
|
172
|
+
formError,
|
|
173
|
+
canCreate,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const entries = await Promise.all(
|
|
178
|
+
files.map(async (file): Promise<CollectionEntry> => {
|
|
179
|
+
const fallback: CollectionEntry = {
|
|
180
|
+
id: file.id,
|
|
181
|
+
path: file.path,
|
|
182
|
+
title: file.id,
|
|
183
|
+
date: null,
|
|
184
|
+
draft: false,
|
|
185
|
+
};
|
|
91
186
|
try {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
return {
|
|
187
|
+
const raw = await readRaw(adapter.backend, file.path, token);
|
|
188
|
+
if (raw === null) return fallback;
|
|
189
|
+
const { data } = matter(raw);
|
|
190
|
+
return {
|
|
191
|
+
id: file.id,
|
|
192
|
+
path: file.path,
|
|
193
|
+
title: typeof data.title === 'string' ? data.title : file.id,
|
|
194
|
+
date: entryDate(data.date),
|
|
195
|
+
draft: data.draft === true,
|
|
196
|
+
};
|
|
197
|
+
} catch {
|
|
198
|
+
return fallback;
|
|
96
199
|
}
|
|
97
200
|
}),
|
|
98
201
|
);
|
|
99
|
-
|
|
202
|
+
|
|
203
|
+
return {
|
|
204
|
+
type: collection.type,
|
|
205
|
+
label: collection.label,
|
|
206
|
+
kind,
|
|
207
|
+
entries,
|
|
208
|
+
formError,
|
|
209
|
+
canCreate,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ── /admin/[collection]?/create (POST) ─────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
/** A safe filename stem: starts and ends with a lowercase alphanumeric, hyphens allowed within. */
|
|
216
|
+
const SLUG_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The "New entry" form action. Validates the requested slug, rejects one that already exists,
|
|
220
|
+
* then redirects into the editor in create mode (`?new=1`, where `editLoad` serves a blank
|
|
221
|
+
* document and `saveCommit`'s create path commits a new file). cairn is filename-based, so the
|
|
222
|
+
* slug is the filename stem the author types; a title-driven auto-slug is a later (Pass K) concern.
|
|
223
|
+
*/
|
|
224
|
+
export async function createEntry(
|
|
225
|
+
event: PlatformEvent & {
|
|
226
|
+
params: { collection: string };
|
|
227
|
+
locals: { user: CairnUser | null };
|
|
228
|
+
request: Request;
|
|
229
|
+
},
|
|
230
|
+
adapter: CairnAdapter,
|
|
231
|
+
): Promise<never> {
|
|
232
|
+
const collection = findCollection(adapter, event.params.collection);
|
|
233
|
+
if (!collection) throw error(404, 'Unknown collection');
|
|
234
|
+
const kind = collection.kind ?? 'story';
|
|
235
|
+
requireCapability(event.locals.user, kind === 'page' ? 'page:create' : 'story:create');
|
|
236
|
+
|
|
237
|
+
const form = await event.request.formData();
|
|
238
|
+
const id = String(form.get('id') ?? '').trim();
|
|
239
|
+
const back = (message: string) =>
|
|
240
|
+
redirect(303, `/admin/${collection.type}?error=${encodeURIComponent(message)}`);
|
|
241
|
+
|
|
242
|
+
if (!SLUG_RE.test(id)) {
|
|
243
|
+
throw back('Enter a slug using lowercase letters, numbers, and hyphens (for example 2026-05-my-entry).');
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const token = await readToken(event.platform?.env);
|
|
247
|
+
const existing = await readRaw(adapter.backend, `${collection.dir}/${id}.md`, token);
|
|
248
|
+
if (existing !== null) throw back(`An entry named "${id}" already exists.`);
|
|
249
|
+
const date = String(form.get('date') ?? '').trim();
|
|
250
|
+
const dateSuffix = kind === 'story' && date ? `&date=${encodeURIComponent(date)}` : '';
|
|
251
|
+
|
|
252
|
+
throw redirect(303, `/admin/edit/${collection.type}/${id}?new=1${dateSuffix}`);
|
|
100
253
|
}
|
|
101
254
|
|
|
102
255
|
// ── /admin/edit/[type]/[id] ─────────────────────────────────────────────────
|
|
@@ -105,6 +258,7 @@ export interface EditData {
|
|
|
105
258
|
type: string;
|
|
106
259
|
id: string;
|
|
107
260
|
label: string;
|
|
261
|
+
kind: 'page' | 'story';
|
|
108
262
|
fields: CairnField[];
|
|
109
263
|
path: string;
|
|
110
264
|
body: string;
|
|
@@ -112,6 +266,8 @@ export interface EditData {
|
|
|
112
266
|
title: string;
|
|
113
267
|
saved: boolean;
|
|
114
268
|
error: string | null;
|
|
269
|
+
/** True when editing a not-yet-committed new entry (reached via `?new=1`). */
|
|
270
|
+
isNew: boolean;
|
|
115
271
|
}
|
|
116
272
|
|
|
117
273
|
export async function editLoad(
|
|
@@ -124,16 +280,27 @@ export async function editLoad(
|
|
|
124
280
|
const token = await readToken(event.platform?.env);
|
|
125
281
|
const path = `${collection.dir}/${event.params.id}.md`;
|
|
126
282
|
const raw = await readRaw(adapter.backend, path, token);
|
|
127
|
-
|
|
283
|
+
const isNew = event.url.searchParams.get('new') === '1';
|
|
128
284
|
|
|
129
|
-
//
|
|
130
|
-
|
|
131
|
-
|
|
285
|
+
// A missing file is a 404 normally, but in create mode (`?new=1`) it's a blank new document.
|
|
286
|
+
if (raw === null && !isNew) throw error(404, 'Content not found');
|
|
287
|
+
|
|
288
|
+
// Split frontmatter from body server-side; the editor form binds to the frontmatter and the
|
|
289
|
+
// Carta editor to the body, and /admin/save reassembles them on commit. A new document starts
|
|
290
|
+
// empty so the author fills the fields from scratch.
|
|
291
|
+
const { data: frontmatter, content: body } =
|
|
292
|
+
raw === null ? { data: {} as Record<string, unknown>, content: '' } : matter(raw);
|
|
293
|
+
|
|
294
|
+
const seedDate = event.url.searchParams.get('date');
|
|
295
|
+
if (isNew && seedDate && frontmatter.date === undefined) {
|
|
296
|
+
frontmatter.date = seedDate;
|
|
297
|
+
}
|
|
132
298
|
|
|
133
299
|
return {
|
|
134
300
|
type: event.params.type,
|
|
135
301
|
id: event.params.id,
|
|
136
302
|
label: collection.label,
|
|
303
|
+
kind: collection.kind ?? 'story',
|
|
137
304
|
fields: collection.fields,
|
|
138
305
|
path,
|
|
139
306
|
body,
|
|
@@ -141,6 +308,7 @@ export async function editLoad(
|
|
|
141
308
|
title: typeof frontmatter.title === 'string' ? frontmatter.title : event.params.id,
|
|
142
309
|
saved: event.url.searchParams.get('saved') === '1',
|
|
143
310
|
error: event.url.searchParams.get('error'),
|
|
311
|
+
isNew,
|
|
144
312
|
};
|
|
145
313
|
}
|
|
146
314
|
|
|
@@ -162,6 +330,7 @@ export async function saveCommit(
|
|
|
162
330
|
const type = String(form.get('type') ?? '');
|
|
163
331
|
const id = String(form.get('id') ?? '');
|
|
164
332
|
const body = String(form.get('body') ?? '');
|
|
333
|
+
const newSuffix = form.get('new') === '1' ? '&new=1' : '';
|
|
165
334
|
const collection = findCollection(adapter, type);
|
|
166
335
|
if (!collection || !id) throw error(400, 'Bad request');
|
|
167
336
|
|
|
@@ -172,7 +341,7 @@ export async function saveCommit(
|
|
|
172
341
|
frontmatter = collection.validate(frontmatterFromForm(collection, form), `${id}.md`);
|
|
173
342
|
} catch (err) {
|
|
174
343
|
const message = err instanceof Error ? err.message : 'Invalid frontmatter';
|
|
175
|
-
throw redirect(303, `/admin/edit/${type}/${id}?error=${encodeURIComponent(message)}`);
|
|
344
|
+
throw redirect(303, `/admin/edit/${type}/${id}?error=${encodeURIComponent(message)}${newSuffix}`);
|
|
176
345
|
}
|
|
177
346
|
|
|
178
347
|
const markdown = serializeMarkdown(frontmatter, body);
|
|
@@ -182,13 +351,162 @@ export async function saveCommit(
|
|
|
182
351
|
privateKeyB64: env.GITHUB_APP_PRIVATE_KEY_B64,
|
|
183
352
|
});
|
|
184
353
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
354
|
+
try {
|
|
355
|
+
await commitFile(
|
|
356
|
+
adapter.backend,
|
|
357
|
+
`${collection.dir}/${id}.md`,
|
|
358
|
+
markdown,
|
|
359
|
+
{ message: `Update ${collection.label.toLowerCase()}: ${id}`, author: { name: user.name, email: user.email } },
|
|
360
|
+
token,
|
|
361
|
+
);
|
|
362
|
+
} catch (err) {
|
|
363
|
+
// Concurrent-edit 409 (C3): fail safe. Bounce back with a reload prompt; the editor reloads
|
|
364
|
+
// the current version and reapplies. Any other error is unexpected, so rethrow.
|
|
365
|
+
if (err instanceof CommitConflictError) {
|
|
366
|
+
const message = 'This file changed since you opened it. Reload and reapply your edits.';
|
|
367
|
+
throw redirect(303, `/admin/edit/${type}/${id}?error=${encodeURIComponent(message)}${newSuffix}`);
|
|
368
|
+
}
|
|
369
|
+
throw err;
|
|
370
|
+
}
|
|
192
371
|
|
|
193
372
|
throw redirect(303, `/admin/edit/${type}/${id}?saved=1`);
|
|
194
373
|
}
|
|
374
|
+
|
|
375
|
+
// ── /admin/nav (navigation tree) ───────────────────────────────────────────
|
|
376
|
+
|
|
377
|
+
/** A page the picker can insert: its display label and the URL the nav item points at. */
|
|
378
|
+
export interface NavPageOption {
|
|
379
|
+
label: string;
|
|
380
|
+
url: string;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export interface NavLoadData {
|
|
384
|
+
menu: { name: string; label: string; maxDepth: number };
|
|
385
|
+
tree: NavNode[];
|
|
386
|
+
pages: NavPageOption[];
|
|
387
|
+
saved: boolean;
|
|
388
|
+
error: string | null;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** List page-collection entries for the picker (one directory listing per page collection). */
|
|
392
|
+
async function navPageOptions(adapter: CairnAdapter, env: AdminEnv | undefined): Promise<NavPageOption[]> {
|
|
393
|
+
const token = await readToken(env);
|
|
394
|
+
const pageCollections = adapter.collections.filter((c) => (c.kind ?? 'story') === 'page');
|
|
395
|
+
const lists = await Promise.all(
|
|
396
|
+
pageCollections.map(async (c) => {
|
|
397
|
+
try {
|
|
398
|
+
const files = await listMarkdown(adapter.backend, c.dir, token);
|
|
399
|
+
return files.map((f): NavPageOption => ({ label: f.id, url: `/${f.id}` }));
|
|
400
|
+
} catch {
|
|
401
|
+
return [];
|
|
402
|
+
}
|
|
403
|
+
}),
|
|
404
|
+
);
|
|
405
|
+
return lists.flat();
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
export async function navLoad(
|
|
409
|
+
event: PlatformEvent & { locals: { user: CairnUser | null }; url: URL },
|
|
410
|
+
adapter: CairnAdapter,
|
|
411
|
+
): Promise<NavLoadData> {
|
|
412
|
+
requireCapability(event.locals.user, 'nav:manage');
|
|
413
|
+
const config = adapter.navMenu;
|
|
414
|
+
if (!config) throw error(404, 'No navigation menu configured');
|
|
415
|
+
const maxDepth = config.maxDepth ?? 2;
|
|
416
|
+
const menu = { name: config.menuName, label: config.label, maxDepth };
|
|
417
|
+
|
|
418
|
+
// Read the menu from the committed YAML. A missing/unparsable file degrades to an empty tree so
|
|
419
|
+
// the editor still loads (a first edit then creates the menu); only the read itself is best-effort.
|
|
420
|
+
const token = await readToken(event.platform?.env);
|
|
421
|
+
let tree: NavNode[] = [];
|
|
422
|
+
try {
|
|
423
|
+
const raw = await readRaw(adapter.backend, config.configPath, token);
|
|
424
|
+
if (raw !== null) tree = extractMenu(parseSiteConfig(raw), config.menuName, maxDepth);
|
|
425
|
+
} catch (err) {
|
|
426
|
+
console.error(`cairn nav: failed to read "${config.configPath}":`, err);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
return {
|
|
430
|
+
menu,
|
|
431
|
+
tree,
|
|
432
|
+
pages: await navPageOptions(adapter, event.platform?.env),
|
|
433
|
+
saved: event.url.searchParams.get('saved') === '1',
|
|
434
|
+
error: event.url.searchParams.get('error'),
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
export async function navSave(
|
|
439
|
+
event: PlatformEvent & { locals: { user: CairnUser | null }; request: Request },
|
|
440
|
+
adapter: CairnAdapter,
|
|
441
|
+
): Promise<never> {
|
|
442
|
+
const user = requireCapability(event.locals.user, 'nav:manage');
|
|
443
|
+
const config = adapter.navMenu;
|
|
444
|
+
if (!config) throw error(404, 'No navigation menu configured');
|
|
445
|
+
const maxDepth = config.maxDepth ?? 2;
|
|
446
|
+
|
|
447
|
+
const env = event.platform?.env;
|
|
448
|
+
if (!env?.GITHUB_APP_ID || !env.GITHUB_APP_INSTALLATION_ID || !env.GITHUB_APP_PRIVATE_KEY_B64) {
|
|
449
|
+
throw error(500, 'GitHub App is not configured');
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const form = await event.request.formData();
|
|
453
|
+
let tree: NavNode[];
|
|
454
|
+
try {
|
|
455
|
+
tree = validateNavTree(JSON.parse(String(form.get('tree') ?? '[]')), maxDepth);
|
|
456
|
+
} catch (err) {
|
|
457
|
+
const message = err instanceof Error ? err.message : 'Invalid navigation';
|
|
458
|
+
throw redirect(303, `/admin/nav?error=${encodeURIComponent(message)}`);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const token = await installationToken({
|
|
462
|
+
appId: env.GITHUB_APP_ID,
|
|
463
|
+
installationId: env.GITHUB_APP_INSTALLATION_ID,
|
|
464
|
+
privateKeyB64: env.GITHUB_APP_PRIVATE_KEY_B64,
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
// Read-modify-commit: replace only this menu in the current file, preserving the rest.
|
|
468
|
+
const raw = await readRaw(adapter.backend, config.configPath, token);
|
|
469
|
+
if (raw === null) throw error(404, `Site config not found at ${config.configPath}`);
|
|
470
|
+
|
|
471
|
+
try {
|
|
472
|
+
await commitFile(
|
|
473
|
+
adapter.backend,
|
|
474
|
+
config.configPath,
|
|
475
|
+
setMenu(raw, config.menuName, tree),
|
|
476
|
+
{ message: `Update ${config.label.toLowerCase()}`, author: { name: user.name, email: user.email } },
|
|
477
|
+
token,
|
|
478
|
+
);
|
|
479
|
+
} catch (err) {
|
|
480
|
+
// Concurrent-edit 409 (C3): fail safe, same as the content save path.
|
|
481
|
+
if (err instanceof CommitConflictError) {
|
|
482
|
+
const message = 'The site config changed since you opened it. Reload and reapply your edits.';
|
|
483
|
+
throw redirect(303, `/admin/nav?error=${encodeURIComponent(message)}`);
|
|
484
|
+
}
|
|
485
|
+
throw err;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
throw redirect(303, '/admin/nav?saved=1');
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// ── /admin/healthz (GET) ──────────────────────────────────────────────────────
|
|
492
|
+
|
|
493
|
+
export interface HealthData {
|
|
494
|
+
ok: boolean;
|
|
495
|
+
checks: { githubAppSigning: { ok: boolean; detail?: string } };
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Deploy-time health check (M2): signs a dummy App JWT to prove the GitHub App key loads and
|
|
500
|
+
* the PKCS#1→PKCS#8 conversion still works, before an editor hits it on save. Behind the
|
|
501
|
+
* `/admin` guard (signed-in editors only); returns ok/fail with no secret in the body.
|
|
502
|
+
*/
|
|
503
|
+
export async function healthLoad(event: PlatformEvent): Promise<HealthData> {
|
|
504
|
+
const env = event.platform?.env;
|
|
505
|
+
let githubAppSigning: { ok: boolean; detail?: string };
|
|
506
|
+
if (env?.GITHUB_APP_ID && env.GITHUB_APP_PRIVATE_KEY_B64) {
|
|
507
|
+
githubAppSigning = await signingSelfTest(env.GITHUB_APP_ID, env.GITHUB_APP_PRIVATE_KEY_B64);
|
|
508
|
+
} else {
|
|
509
|
+
githubAppSigning = { ok: false, detail: 'GitHub App not configured' };
|
|
510
|
+
}
|
|
511
|
+
return { ok: githubAppSigning.ok, checks: { githubAppSigning } };
|
|
512
|
+
}
|
package/src/lib/utils.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// cairn-core: internal encoding helpers shared across modules.
|
|
2
2
|
//
|
|
3
|
-
// Deliberately NOT re-exported from index.ts
|
|
3
|
+
// Deliberately NOT re-exported from index.ts. These are implementation details of the
|
|
4
4
|
// auth/github crypto, not part of the public API (auth.ts signs tokens, github.ts builds
|
|
5
5
|
// the App JWT; both need base64url). Keeping them here stops bytesToB64url leaking through
|
|
6
6
|
// the `export *` barrel.
|
|
7
7
|
|
|
8
|
-
/** Encode bytes as unpadded base64url (RFC 4648 §5)
|
|
8
|
+
/** Encode bytes as unpadded base64url (RFC 4648 §5), the JWT/token wire format. */
|
|
9
9
|
export function bytesToB64url(bytes: Uint8Array): string {
|
|
10
10
|
const binary = Array.from(bytes, (b) => String.fromCharCode(b)).join('');
|
|
11
11
|
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
<script lang="ts">
|
|
2
|
-
// The /admin content list: every collection's files, linking into the editor. Data comes
|
|
3
|
-
// from `adminListLoad` (collections) merged with `adminLayoutLoad` (siteName). The shell
|
|
4
|
-
// (AdminLayout) owns the chrome — site title, signed-in identity, nav, sign out — so this
|
|
5
|
-
// page renders only the content body.
|
|
6
|
-
import type { AdminCollectionList } from '../sveltekit';
|
|
7
|
-
|
|
8
|
-
interface Props {
|
|
9
|
-
data: { collections: AdminCollectionList[] };
|
|
10
|
-
}
|
|
11
|
-
let { data }: Props = $props();
|
|
12
|
-
</script>
|
|
13
|
-
|
|
14
|
-
<h1 class="text-2xl font-bold">Content</h1>
|
|
15
|
-
|
|
16
|
-
{#each data.collections as collection (collection.type)}
|
|
17
|
-
<section class="mt-8">
|
|
18
|
-
<h2 class="mb-3 text-lg font-semibold">{collection.label}</h2>
|
|
19
|
-
{#if collection.error}
|
|
20
|
-
<div class="alert alert-warning">Couldn't load {collection.label.toLowerCase()}: {collection.error}</div>
|
|
21
|
-
{:else if collection.files.length === 0}
|
|
22
|
-
<p class="opacity-60">No content yet.</p>
|
|
23
|
-
{:else}
|
|
24
|
-
<ul class="menu rounded-box border border-base-300 bg-base-100 p-2">
|
|
25
|
-
{#each collection.files as file (file.path)}
|
|
26
|
-
<li>
|
|
27
|
-
<a href="/admin/edit/{collection.type}/{file.id}">{file.id}</a>
|
|
28
|
-
</li>
|
|
29
|
-
{/each}
|
|
30
|
-
</ul>
|
|
31
|
-
{/if}
|
|
32
|
-
</section>
|
|
33
|
-
{/each}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { AdminCollectionList } from '../sveltekit';
|
|
2
|
-
interface Props {
|
|
3
|
-
data: {
|
|
4
|
-
collections: AdminCollectionList[];
|
|
5
|
-
};
|
|
6
|
-
}
|
|
7
|
-
declare const AdminList: import("svelte").Component<Props, {}, "">;
|
|
8
|
-
type AdminList = ReturnType<typeof AdminList>;
|
|
9
|
-
export default AdminList;
|
|
10
|
-
//# sourceMappingURL=AdminList.svelte.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"AdminList.svelte.d.ts","sourceRoot":"","sources":["../../src/lib/components/AdminList.svelte.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAGtD,UAAU,KAAK;IACb,IAAI,EAAE;QAAE,WAAW,EAAE,mBAAmB,EAAE,CAAA;KAAE,CAAC;CAC9C;AAkCH,QAAA,MAAM,SAAS,2CAAwC,CAAC;AACxD,KAAK,SAAS,GAAG,UAAU,CAAC,OAAO,SAAS,CAAC,CAAC;AAC9C,eAAe,SAAS,CAAC"}
|