cogens 0.0.0-stage → 0.2.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.
Files changed (46) hide show
  1. package/LICENSE +22 -0
  2. package/NOTICE +25 -0
  3. package/README.md +385 -2
  4. package/editor/editor-dark.css +2 -0
  5. package/editor/editor.css +9 -0
  6. package/editor/entry.js +28 -0
  7. package/migrations/0001_entries.sql +43 -0
  8. package/migrations/auth/0001_sessions.sql +50 -0
  9. package/migrations/koguma-upgrade.sql +13 -0
  10. package/package.json +86 -4
  11. package/scripts/build-admin-editor.ts +155 -0
  12. package/scripts/print-migration.ts +50 -0
  13. package/src/admin/app.ts +608 -0
  14. package/src/admin/assets.ts +52 -0
  15. package/src/admin/fields.ts +172 -0
  16. package/src/admin/forms.ts +64 -0
  17. package/src/admin/index.ts +16 -0
  18. package/src/admin/rules.ts +63 -0
  19. package/src/admin/types.ts +99 -0
  20. package/src/admin/views.ts +360 -0
  21. package/src/auth/handoff.ts +56 -0
  22. package/src/auth/index.ts +29 -0
  23. package/src/auth/password.ts +201 -0
  24. package/src/auth/principal.ts +40 -0
  25. package/src/auth/session.ts +143 -0
  26. package/src/core/access/ability.ts +86 -0
  27. package/src/core/access/can.ts +66 -0
  28. package/src/core/access/compile.ts +62 -0
  29. package/src/core/access/permits.ts +45 -0
  30. package/src/core/access/when.ts +59 -0
  31. package/src/core/access/where.ts +95 -0
  32. package/src/core/columns.ts +7 -0
  33. package/src/core/config/define.ts +206 -0
  34. package/src/core/config/field.ts +119 -0
  35. package/src/core/errors.ts +99 -0
  36. package/src/core/index.ts +44 -0
  37. package/src/core/media/index.ts +132 -0
  38. package/src/core/principal.ts +49 -0
  39. package/src/core/store/assets.ts +2 -0
  40. package/src/core/store/cms.ts +199 -0
  41. package/src/core/store/content.ts +453 -0
  42. package/src/core/store/sql.ts +239 -0
  43. package/src/core/store/types.ts +100 -0
  44. package/src/core/testing/index.ts +75 -0
  45. package/src/testing/db.ts +53 -0
  46. package/src/testing/index.ts +9 -0
@@ -0,0 +1,608 @@
1
+ /**
2
+ * createAdmin: the admin's routes as a Hono app for the host to mount where it
3
+ * likes. Every read and write of entries goes through `cms.content.as(principal)`
4
+ * for the principal the host resolved, so the admin can do nothing the type's
5
+ * rules refuse that caller; `cms.access.rulesFor` only decides what to draw.
6
+ *
7
+ * app.route('/admin2', createAdmin({ cms, resolvePrincipal, mount: '/admin2' }))
8
+ *
9
+ * Writes are forms that POST and answer 303. They are refused unless they are
10
+ * form posts from the admin's own origin (hono/csrf, plus a content-type check,
11
+ * since csrf looks only at form content types), and every page carries a content
12
+ * security policy that names the admin's script, the editor and the stylesheets.
13
+ */
14
+ import { Hono, type Context } from 'hono';
15
+ import { csrf } from 'hono/csrf';
16
+ import { HTTPException } from 'hono/http-exception';
17
+ import { secureHeaders } from 'hono/secure-headers';
18
+ import {
19
+ ConfigError, Conflict, Forbidden, ValidationError, WriteRefused,
20
+ type ContentType, type Entry, type FieldMeta, type HostPrincipal, type Principal, type PackedRules, type Where
21
+ } from '../core/index.ts';
22
+ import { ADMIN_CSS, ADMIN_JS } from './assets.ts';
23
+ import type { ResolveRef } from './fields.ts';
24
+ import { parseForm } from './forms.ts';
25
+ import { can, mayWrite, mayWriteColumn, ruleRow, writable, type Writable } from './rules.ts';
26
+ import type { AdminAction, AdminAssets, AdminOptions, ExternalCollection, ExternalRow } from './types.ts';
27
+ import {
28
+ confirmPage, entryListPage, entryPage, externalListPage, externalRowPage, messagePage, noticeText, signInPage, typeListPage,
29
+ type Column, type Row, type Shell
30
+ } from './views.ts';
31
+
32
+ export const DEFAULT_ASSETS: AdminAssets = {
33
+ largen: '/largen.css',
34
+ largenDark: '/largen-theme-dark.css',
35
+ editor: '/admin-editor.js',
36
+ editorStyles: '/admin-editor.css',
37
+ editorStylesDark: '/admin-editor-dark.css'
38
+ };
39
+
40
+ const PAGE = 50;
41
+ const FORM = /^(application\/x-www-form-urlencoded|multipart\/form-data)\b/i;
42
+ /** Most rows offered in a target picker. */
43
+ const PICKER_CAP = 2000;
44
+
45
+ const status = (error: unknown, fallback: number): number => {
46
+ const n = (error as { status?: unknown } | null)?.status;
47
+ return typeof n === 'number' && n >= 400 && n < 600 ? n : fallback;
48
+ };
49
+
50
+ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptions<H>): Hono<any> {
51
+ type P = Principal<H>;
52
+ type Ctx = Context<{ Variables: { principal: P } }>;
53
+
54
+ const { cms } = options;
55
+ const mount = options.mount.replace(/\/+$/, '');
56
+ const assets: AdminAssets = { ...DEFAULT_ASSETS, ...options.assets };
57
+ const shell: Shell = { mount, home: mount || '/', siteName: options.siteName ?? 'Admin', assets, session: Boolean(options.session) };
58
+ const externals = new Map((options.externalCollections ?? []).map(c => [c.id, c]));
59
+ const typeActions = options.typeActions ?? {};
60
+
61
+ const app = new Hono<{ Variables: { principal: P } }>();
62
+
63
+ // ── Headers, assets, write checks, caller ─────────────────────────
64
+
65
+ const absolute = (c: Context, url: string) => (/^https?:\/\//i.test(url) ? url : new URL(url, c.req.url).href);
66
+ const own = (...urls: string[]) => urls.map(url => (c: Context) => absolute(c, url));
67
+ app.use(
68
+ '*',
69
+ secureHeaders({
70
+ contentSecurityPolicy: {
71
+ defaultSrc: ["'none'"],
72
+ scriptSrc: own(`${mount}/assets/admin.js`, assets.editor),
73
+ styleSrc: own(assets.largen, assets.largenDark, `${mount}/assets/admin.css`, assets.editorStyles, assets.editorStylesDark),
74
+ imgSrc: ["'self'", 'data:'],
75
+ formAction: ["'self'"],
76
+ baseUri: ["'none'"],
77
+ frameAncestors: ["'none'"]
78
+ },
79
+ referrerPolicy: 'no-referrer'
80
+ })
81
+ );
82
+ app.use('*', async (c, next) => {
83
+ await next();
84
+ if (!c.res.headers.has('cache-control')) c.header('cache-control', 'private, no-store');
85
+ });
86
+
87
+ const asset = (type: string, body: string) => (c: Context) =>
88
+ c.body(body, 200, { 'content-type': type, 'x-content-type-options': 'nosniff', 'cache-control': 'no-cache' });
89
+ app.get('/assets/admin.css', asset('text/css; charset=utf-8', ADMIN_CSS));
90
+ app.get('/assets/admin.js', asset('text/javascript; charset=utf-8', ADMIN_JS));
91
+
92
+ // A write is a form post. csrf checks only form content types, so a post of anything else (a bare fetch with no
93
+ // body, say) is refused here, before it can pass for no form at all.
94
+ app.use('*', async (c, next) => {
95
+ if (c.req.method !== 'GET' && c.req.method !== 'HEAD' && !FORM.test(c.req.header('content-type') ?? '')) {
96
+ return c.html(messagePage(shell, 'Not accepted', 'The admin takes form posts only.'), 415);
97
+ }
98
+ await next();
99
+ });
100
+ app.use('*', csrf());
101
+
102
+ // ── Sign-in (only when the host gave a session) ───────────────────
103
+
104
+ /** Where to go after signing in: a page of this admin, never another site. */
105
+ const safeNext = (value: unknown): string => {
106
+ const next = typeof value === 'string' ? value : '';
107
+ return (next === mount || next.startsWith(`${mount}/`)) && !next.startsWith('//') && !/[\\\r\n]/.test(next) ? next : shell.home;
108
+ };
109
+ /** A redirect that carries the cookies the host's answer set. */
110
+ const withCookies = (c: Context, from: Response, to: string) => {
111
+ for (const cookie of from.headers.getSetCookie()) c.header('set-cookie', cookie, { append: true });
112
+ return c.redirect(to, 303);
113
+ };
114
+ const signedOutPage = (c: Context, next: string, error?: string, status: 200 | 401 | 429 | 500 = 401) =>
115
+ c.html(signInPage(shell, next, error), status);
116
+ const session = options.session;
117
+ if (session) {
118
+ app.post('/sign-in', async c => {
119
+ const body = await c.req.parseBody();
120
+ const next = safeNext(body.next);
121
+ const password = typeof body.password === 'string' ? body.password : '';
122
+ if (!password) return signedOutPage(c, next, 'Enter the password.');
123
+ const answer = await session.signIn(c, password);
124
+ if (answer.ok) return withCookies(c, answer, next);
125
+ const message =
126
+ answer.status === 401 ? 'That password is not right.'
127
+ : answer.status === 429 ? 'Too many tries. Wait a while and try again.'
128
+ : 'Sign-in is not available right now.';
129
+ return signedOutPage(c, next, message, answer.status === 401 || answer.status === 429 ? answer.status : 500);
130
+ });
131
+ // Signing out needs no sign-in: it ends whatever session the request carries.
132
+ app.post('/sign-out', async c => withCookies(c, await session.signOut(c), shell.home));
133
+ }
134
+
135
+ app.use('*', async (c, next) => {
136
+ const principal = await options.resolvePrincipal(c);
137
+ if (!principal) {
138
+ if (session) {
139
+ const url = new URL(c.req.url);
140
+ return signedOutPage(c, c.req.method === 'GET' ? safeNext(url.pathname + url.search) : shell.home);
141
+ }
142
+ return options.unauthorized ? options.unauthorized(c) : c.html(messagePage(shell, 'Sign in', 'You are not signed in.'), 401);
143
+ }
144
+ c.set('principal', principal);
145
+ await next();
146
+ });
147
+
148
+ if (session) {
149
+ app.post('/sign-out-everywhere', async c => withCookies(c, await session.signOutEverywhere(c), shell.home));
150
+ // A signed-in caller who opens the sign-in address goes home.
151
+ app.get('/sign-in', c => c.redirect(shell.home, 303));
152
+ }
153
+
154
+ app.onError((error, c) => {
155
+ if (error instanceof HTTPException) return error.getResponse();
156
+ if (error instanceof Forbidden) return c.html(messagePage(shell, 'Not allowed', error.message, { label: 'Back', href: shell.home }), 403);
157
+ if (error instanceof WriteRefused) return c.html(messagePage(shell, 'Refused', error.message, { label: 'Back', href: shell.home }), 422);
158
+ if (error instanceof ValidationError || error instanceof Conflict) {
159
+ return c.html(messagePage(shell, 'Not saved', error.message, { label: 'Back', href: shell.home }), error instanceof Conflict ? 409 : 422);
160
+ }
161
+ if (!(error instanceof ConfigError)) console.error(error);
162
+ else console.error(error.message);
163
+ return c.html(messagePage(shell, 'Something went wrong', 'The request could not be completed.'), 500);
164
+ });
165
+
166
+ // ── Lookups ───────────────────────────────────────────────────────
167
+
168
+ const principalOf = (c: Ctx) => c.get('principal');
169
+ const rulesOf = (c: Ctx): PackedRules => cms.access.rulesFor(principalOf(c));
170
+ const apiOf = (c: Ctx) => cms.content.as(principalOf(c));
171
+ const notFound = (c: Ctx) => c.html(messagePage(shell, 'Not found', 'There is nothing here.', { label: 'Back to the list', href: shell.home }), 404);
172
+
173
+ /** A stored type the caller may read, else undefined (a type they may not read looks like one that does not exist). */
174
+ const readable = (c: Ctx, id: string): ContentType<any> | undefined => {
175
+ const type = cms.types.get(id);
176
+ return type && !type.service && can(rulesOf(c), id, 'read') ? type : undefined;
177
+ };
178
+ const external = (c: Ctx, id: string): ExternalCollection<H> | undefined => {
179
+ const collection = externals.get(id);
180
+ return collection && allowed(collection, principalOf(c)) ? collection : undefined;
181
+ };
182
+ const allowed = (collection: ExternalCollection<H>, principal: P) =>
183
+ collection.allow ? collection.allow(principal) : principal.kind === 'admin';
184
+
185
+ const notice = (c: Ctx) => noticeText(c.req.query('notice'));
186
+ const label = (type: ContentType<any>, e: Entry) => String(e.data[type.displayField] ?? '') || e.slug || e.id;
187
+
188
+ /** Where each reference field's ids lead and what to call them. Reads only what the caller may read. */
189
+ async function resolver(c: Ctx, fields: Record<string, FieldMeta>, data: Record<string, unknown>): Promise<ResolveRef> {
190
+ const wanted = new Map<string, Set<string>>();
191
+ for (const [name, meta] of Object.entries(fields)) {
192
+ if ((meta.fieldType !== 'reference' && meta.fieldType !== 'references') || !meta.refContentType) continue;
193
+ const value = data[name];
194
+ const ids = Array.isArray(value) ? value : typeof value === 'string' && value ? [value] : [];
195
+ const set = wanted.get(meta.refContentType) ?? new Set<string>();
196
+ for (const id of ids) if (typeof id === 'string') set.add(id);
197
+ wanted.set(meta.refContentType, set);
198
+ }
199
+ const names = new Map<string, string>();
200
+ for (const [refType, ids] of wanted) {
201
+ const list = [...ids].slice(0, 90);
202
+ if (list.length === 0) continue;
203
+ const type = readable(c, refType);
204
+ const collection = external(c, refType);
205
+ if (type) {
206
+ for (const e of await apiOf(c).list(refType, { where: { id: { in: list } }, limit: 90 })) names.set(`${refType}:${e.id}`, label(type, e));
207
+ } else if (collection) {
208
+ for (const id of list.slice(0, 20)) {
209
+ const row = await collection.get(c, id);
210
+ if (row) names.set(`${refType}:${id}`, String(row[collection.displayField] ?? '') || id);
211
+ }
212
+ }
213
+ }
214
+ return (refType, id) => {
215
+ const href = readable(c, refType) ? `${mount}/t/${refType}/${encodeURIComponent(id)}` : external(c, refType) ? `${mount}/x/${refType}/${encodeURIComponent(id)}` : null;
216
+ return { href, label: names.get(`${refType}:${id}`) ?? id };
217
+ };
218
+ }
219
+
220
+ // ── Types ─────────────────────────────────────────────────────────
221
+
222
+ app.get('/', c => {
223
+ const rules = rulesOf(c);
224
+ const stored = [...cms.types.values()].filter(t => !t.service && can(rules, t.id, 'read')).map(t => ({ id: t.id, name: t.name }));
225
+ const outside = [...externals.values()].filter(x => allowed(x, principalOf(c))).map(x => ({ id: x.id, name: x.name }));
226
+ return c.html(typeListPage(shell, stored, outside));
227
+ });
228
+
229
+ // ── Entry lists ───────────────────────────────────────────────────
230
+
231
+ app.get('/t/:type', async c => {
232
+ const type = readable(c, c.req.param('type'));
233
+ if (!type) return notFound(c);
234
+ const q = (c.req.query('q') ?? '').trim();
235
+ const statusFilter = c.req.query('status') === 'published' || c.req.query('status') === 'draft' ? c.req.query('status')! : '';
236
+ const owner = (c.req.query('owner') ?? '').trim();
237
+ const offset = Math.max(Math.trunc(Number(c.req.query('offset') ?? 0)) || 0, 0);
238
+ const conditions: Where[] = [];
239
+ // The store's conditions are equality, so a slug search is exact.
240
+ if (q) conditions.push({ slug: q });
241
+ if (statusFilter) conditions.push({ status: statusFilter });
242
+ if (owner && type.owned) conditions.push({ owner_id: owner });
243
+ const found = await apiOf(c).list(type.id, {
244
+ ...(conditions.length === 0 ? {} : { where: conditions.length === 1 ? conditions[0]! : { and: conditions } }),
245
+ orderBy: 'updated_at',
246
+ direction: 'desc',
247
+ limit: PAGE + 1,
248
+ offset
249
+ });
250
+ return c.html(
251
+ entryListPage(shell, {
252
+ type,
253
+ entries: found.slice(0, PAGE),
254
+ q,
255
+ status: statusFilter,
256
+ owner: type.owned ? owner : '',
257
+ offset,
258
+ limit: PAGE,
259
+ hasNext: found.length > PAGE,
260
+ canCreate: can(rulesOf(c), type.id, 'create'),
261
+ notice: notice(c)
262
+ })
263
+ );
264
+ });
265
+
266
+ // ── One entry ─────────────────────────────────────────────────────
267
+
268
+ interface FormState {
269
+ values?: Record<string, unknown>;
270
+ problems?: string[];
271
+ fieldErrors?: Record<string, string>;
272
+ }
273
+
274
+ async function renderEntry(c: Ctx, type: ContentType<any>, entry: Entry | undefined, state: FormState = {}) {
275
+ const rules = rulesOf(c);
276
+ const operation = entry ? 'update' : 'create';
277
+ const row = entry ? ruleRow(type, entry) : undefined;
278
+ const w: Writable = writable(rules, type.id, operation, row);
279
+ const shown = (name: string) => (state.values && name in state.values ? state.values[name] : entry?.data[name]);
280
+ const columns: Column[] = [];
281
+ if (entry) {
282
+ columns.push({ label: 'Id', name: 'id', value: entry.id, editable: false });
283
+ columns.push({ label: 'Status', name: 'status', value: entry.status, editable: false });
284
+ }
285
+ const slugText = state.values && 'slug' in state.values ? (state.values.slug as string | null) : (entry?.slug ?? null);
286
+ if (entry || mayWriteColumn(w, 'slug', 'create')) {
287
+ columns.push({ label: 'Slug', name: 'slug', value: slugText, editable: mayWriteColumn(w, 'slug', operation) });
288
+ }
289
+ if (type.owned && (entry || mayWriteColumn(w, 'owner_id', 'create'))) {
290
+ const ownerText = state.values && 'owner_id' in state.values ? (state.values.owner_id as string | null) : (entry?.owner_id ?? null);
291
+ columns.push({ label: 'Owner', name: 'owner_id', value: ownerText, editable: mayWriteColumn(w, 'owner_id', operation) });
292
+ }
293
+ if (entry) {
294
+ columns.push({ label: 'Created', name: 'created_at', value: entry.created_at, editable: false });
295
+ columns.push({ label: 'Updated', name: 'updated_at', value: entry.updated_at, editable: false });
296
+ }
297
+ const rows: Row[] = [];
298
+ for (const [name, meta] of Object.entries(type.fieldMeta)) {
299
+ const editable = mayWrite(w, name, meta);
300
+ if (!entry && !editable) continue;
301
+ rows.push({ name, meta, value: shown(name), editable, error: state.fieldErrors?.[name] });
302
+ }
303
+ const data = Object.fromEntries(Object.keys(type.fieldMeta).map(name => [name, shown(name)]));
304
+ const refs = await resolver(c, type.fieldMeta, data);
305
+ const actions = entry
306
+ ? (typeActions[type.id] ?? []).filter(a => (a.requires ? can(rules, type.id, a.requires, row) : true))
307
+ : [];
308
+ return entryPage(shell, {
309
+ type,
310
+ entry,
311
+ columns,
312
+ rows,
313
+ refs,
314
+ canSave: columns.some(col => col.editable) || rows.some(r => r.editable),
315
+ canPublish: !!entry && can(rules, type.id, 'publish', row),
316
+ // A type's own `unpublish` and `delete` actions take the place of the plain controls.
317
+ canUnpublish: !!entry && can(rules, type.id, 'publish', row) && !(typeActions[type.id] ?? []).some(a => a.id === 'unpublish'),
318
+ canDelete: !!entry && can(rules, type.id, 'delete', row) && !(typeActions[type.id] ?? []).some(a => a.id === 'delete'),
319
+ actions,
320
+ notice: notice(c),
321
+ problems: state.problems
322
+ });
323
+ }
324
+
325
+ /** What went wrong with a write, as page text, when the page can be shown again with the values typed. */
326
+ const problemsOf = (error: unknown): { problems: string[]; fieldErrors: Record<string, string>; status: 409 | 422 } | null => {
327
+ if (error instanceof ValidationError) {
328
+ return {
329
+ problems: error.issues.map(i => `${i.field} ${i.message}`),
330
+ fieldErrors: Object.fromEntries(error.issues.map(i => [i.field, i.message])),
331
+ status: 422
332
+ };
333
+ }
334
+ if (error instanceof Conflict) return { problems: [error.message], fieldErrors: {}, status: 409 };
335
+ if (error instanceof WriteRefused) return { problems: [error.message], fieldErrors: {}, status: 422 };
336
+ return null;
337
+ };
338
+
339
+ app.get('/t/:type/new', async c => {
340
+ const type = readable(c, c.req.param('type'));
341
+ if (!type || !can(rulesOf(c), type.id, 'create')) return notFound(c);
342
+ return c.html(await renderEntry(c, type, undefined));
343
+ });
344
+
345
+ app.post('/t/:type', async c => {
346
+ const type = readable(c, c.req.param('type'));
347
+ if (!type) return notFound(c);
348
+ const { values, errors } = parseForm(type, await c.req.formData());
349
+ if (errors.length === 0) {
350
+ try {
351
+ const created = await apiOf(c).create(type.id, values);
352
+ return c.redirect(`${mount}/t/${type.id}/${encodeURIComponent(created.id)}?notice=created`, 303);
353
+ } catch (error) {
354
+ const shown = problemsOf(error);
355
+ if (!shown) throw error;
356
+ return c.html(await renderEntry(c, type, undefined, { values, ...shown }), shown.status);
357
+ }
358
+ }
359
+ return c.html(
360
+ await renderEntry(c, type, undefined, {
361
+ values,
362
+ problems: errors.map(e => `${e.field} ${e.message}`),
363
+ fieldErrors: Object.fromEntries(errors.map(e => [e.field, e.message]))
364
+ }),
365
+ 422
366
+ );
367
+ });
368
+
369
+ const entryOf = async (c: Ctx) => {
370
+ const type = readable(c, c.req.param('type') ?? '');
371
+ if (!type) return {};
372
+ const entry = await apiOf(c).get(type.id, c.req.param('id') ?? '');
373
+ return entry ? { type, entry } : {};
374
+ };
375
+
376
+ app.get('/t/:type/:id', async c => {
377
+ const { type, entry } = await entryOf(c);
378
+ if (!type || !entry) return notFound(c);
379
+ return c.html(await renderEntry(c, type, entry));
380
+ });
381
+
382
+ app.post('/t/:type/:id', async c => {
383
+ const { type, entry } = await entryOf(c);
384
+ if (!type || !entry) return notFound(c);
385
+ const { values, errors } = parseForm(type, await c.req.formData());
386
+ if (errors.length === 0) {
387
+ try {
388
+ // Every posted field goes to the store as posted; a field the caller may not write is refused there.
389
+ await apiOf(c).update(type.id, entry.id, values);
390
+ return c.redirect(`${mount}/t/${type.id}/${encodeURIComponent(entry.id)}?notice=saved`, 303);
391
+ } catch (error) {
392
+ const shown = problemsOf(error);
393
+ if (!shown) throw error;
394
+ return c.html(await renderEntry(c, type, entry, { values, ...shown }), shown.status);
395
+ }
396
+ }
397
+ return c.html(
398
+ await renderEntry(c, type, entry, {
399
+ values,
400
+ problems: errors.map(e => `${e.field} ${e.message}`),
401
+ fieldErrors: Object.fromEntries(errors.map(e => [e.field, e.message]))
402
+ }),
403
+ 422
404
+ );
405
+ });
406
+
407
+ for (const verb of ['publish', 'unpublish'] as const) {
408
+ app.post(`/t/:type/:id/${verb}`, async c => {
409
+ const { type, entry } = await entryOf(c);
410
+ if (!type || !entry) return notFound(c);
411
+ await apiOf(c)[verb](type.id, entry.id);
412
+ return c.redirect(`${mount}/t/${type.id}/${encodeURIComponent(entry.id)}?notice=${verb === 'publish' ? 'published' : 'unpublished'}`, 303);
413
+ });
414
+ }
415
+
416
+ app.get('/t/:type/:id/delete', async c => {
417
+ const { type, entry } = await entryOf(c);
418
+ if (!type || !entry) return notFound(c);
419
+ if (!can(rulesOf(c), type.id, 'delete', ruleRow(type, entry))) return notFound(c);
420
+ const name = label(type, entry);
421
+ return c.html(
422
+ confirmPage(shell, {
423
+ title: `Delete ${name}?`,
424
+ question: `Delete “${name}”? This cannot be undone.`,
425
+ action: `${mount}/t/${type.id}/${encodeURIComponent(entry.id)}/delete`,
426
+ confirmLabel: 'Delete',
427
+ destructive: true,
428
+ cancel: `${mount}/t/${type.id}/${encodeURIComponent(entry.id)}`,
429
+ crumbs: [{ label: type.name, href: `${mount}/t/${type.id}` }, { label: name }]
430
+ })
431
+ );
432
+ });
433
+
434
+ app.post('/t/:type/:id/delete', async c => {
435
+ const { type, entry } = await entryOf(c);
436
+ if (!type || !entry) return notFound(c);
437
+ await apiOf(c).remove(type.id, entry.id);
438
+ return c.redirect(`${mount}/t/${type.id}?notice=deleted`, 303);
439
+ });
440
+
441
+ // ── Actions, on a store type's entries and on external rows ───────
442
+
443
+ /** The rows an action may be aimed at: another entry of the target type, as the caller may read them. */
444
+ async function targetOptions(c: Ctx, targetId: string, selfId: string): Promise<{ title: string; options: { id: string; label: string }[] } | null> {
445
+ const collection = external(c, targetId);
446
+ const options: { id: string; label: string }[] = [];
447
+ if (collection) {
448
+ for (let offset = 0; offset < PICKER_CAP; offset += 200) {
449
+ const rows = await collection.list(c, { limit: 200, offset });
450
+ for (const row of rows) {
451
+ if (row.id !== selfId && (collection.pickable ? collection.pickable(row) : true)) {
452
+ options.push({ id: row.id, label: String(row[collection.displayField] ?? '') || row.id });
453
+ }
454
+ }
455
+ if (rows.length < 200) break;
456
+ }
457
+ return { title: collection.name, options };
458
+ }
459
+ const type = readable(c, targetId);
460
+ if (!type) return null;
461
+ for (let offset = 0; offset < PICKER_CAP; offset += 1000) {
462
+ const rows = await apiOf(c).list(type.id, { limit: 1000, offset });
463
+ for (const e of rows) if (e.id !== selfId) options.push({ id: e.id, label: label(type, e) });
464
+ if (rows.length < 1000) break;
465
+ }
466
+ return { title: type.name, options };
467
+ }
468
+
469
+ interface ActionSite {
470
+ action: AdminAction<H>;
471
+ id: string;
472
+ /** The page of the thing acted on, and the list it belongs to. */
473
+ entryUrl: string;
474
+ listUrl: string;
475
+ crumbs: { label: string; href?: string }[];
476
+ name: string;
477
+ exists(): Promise<boolean>;
478
+ }
479
+
480
+ async function confirmAction(c: Ctx, site: ActionSite) {
481
+ const { action } = site;
482
+ const target = action.target ? await targetOptions(c, action.target, site.id) : undefined;
483
+ if (action.target && !target) return notFound(c);
484
+ return c.html(
485
+ confirmPage(shell, {
486
+ title: `${action.label.replace(/…$/, '')}: ${site.name}`,
487
+ question: action.confirm,
488
+ action: `${site.entryUrl}/do/${action.id}`,
489
+ confirmLabel: action.label.replace(/…$/, ''),
490
+ destructive: !!action.destructive,
491
+ cancel: site.entryUrl,
492
+ target: target ? { label: target.title, options: target.options } : undefined,
493
+ crumbs: site.crumbs
494
+ })
495
+ );
496
+ }
497
+
498
+ async function runAction(c: Ctx, site: ActionSite) {
499
+ const { action } = site;
500
+ const form = await c.req.formData();
501
+ let chosen: string | undefined;
502
+ if (action.target) {
503
+ const picked = form.get('target');
504
+ const options = await targetOptions(c, action.target, site.id);
505
+ if (typeof picked !== 'string' || !options?.options.some(o => o.id === picked)) {
506
+ return c.html(messagePage(shell, 'Nothing was done', 'Choose one of the entries offered.', { label: 'Back', href: site.entryUrl }), 422);
507
+ }
508
+ chosen = picked;
509
+ }
510
+ try {
511
+ await action.run({ c, principal: principalOf(c), id: site.id, target: chosen });
512
+ } catch (error) {
513
+ const code = status(error, 500);
514
+ if (code === 500) console.error(error);
515
+ const message = error instanceof Error && error.message ? error.message : 'The action failed.';
516
+ return c.html(messagePage(shell, `${action.label.replace(/…$/, '')} failed`, message, { label: 'Back', href: site.entryUrl }), code as 400);
517
+ }
518
+ // An action that removed what it was pressed on (a delete) returns to the list.
519
+ const still = await site.exists();
520
+ return c.redirect(`${still ? site.entryUrl : site.listUrl}?notice=${still ? 'done' : 'deleted'}`, 303);
521
+ }
522
+
523
+ async function storeSite(c: Ctx): Promise<ActionSite | null> {
524
+ const { type, entry } = await entryOf(c);
525
+ if (!type || !entry) return null;
526
+ const action = (typeActions[type.id] ?? []).find(a => a.id === c.req.param('action'));
527
+ if (!action || (action.requires && !can(rulesOf(c), type.id, action.requires, ruleRow(type, entry)))) return null;
528
+ const name = label(type, entry);
529
+ return {
530
+ action,
531
+ id: entry.id,
532
+ name,
533
+ entryUrl: `${mount}/t/${type.id}/${encodeURIComponent(entry.id)}`,
534
+ listUrl: `${mount}/t/${type.id}`,
535
+ crumbs: [{ label: type.name, href: `${mount}/t/${type.id}` }, { label: name }],
536
+ exists: async () => (await apiOf(c).get(type.id, entry.id)) !== null
537
+ };
538
+ }
539
+
540
+ async function externalSite(c: Ctx): Promise<ActionSite | null> {
541
+ const collection = external(c, c.req.param('collection') ?? '');
542
+ if (!collection) return null;
543
+ const row = await collection.get(c, c.req.param('id') ?? '');
544
+ const action = (collection.actions ?? []).find(a => a.id === c.req.param('action'));
545
+ if (!row || !action) return null;
546
+ const name = String(row[collection.displayField] ?? '') || row.id;
547
+ return {
548
+ action,
549
+ id: row.id,
550
+ name,
551
+ entryUrl: `${mount}/x/${collection.id}/${encodeURIComponent(row.id)}`,
552
+ listUrl: `${mount}/x/${collection.id}`,
553
+ crumbs: [{ label: collection.name, href: `${mount}/x/${collection.id}` }, { label: name }],
554
+ exists: async () => (await collection.get(c, row.id)) !== null
555
+ };
556
+ }
557
+
558
+ app.get('/t/:type/:id/do/:action', async c => {
559
+ const site = await storeSite(c);
560
+ return site ? confirmAction(c, site) : notFound(c);
561
+ });
562
+ app.post('/t/:type/:id/do/:action', async c => {
563
+ const site = await storeSite(c);
564
+ return site ? runAction(c, site) : notFound(c);
565
+ });
566
+
567
+ // ── External collections ──────────────────────────────────────────
568
+
569
+ app.get('/x/:collection', async c => {
570
+ const collection = external(c, c.req.param('collection'));
571
+ if (!collection) return notFound(c);
572
+ const offset = Math.max(Math.trunc(Number(c.req.query('offset') ?? 0)) || 0, 0);
573
+ const rows = await collection.list(c, { limit: PAGE + 1, offset });
574
+ return c.html(externalListPage(shell, collection, rows.slice(0, PAGE), offset, PAGE, rows.length > PAGE));
575
+ });
576
+
577
+ app.get('/x/:collection/:id', async c => {
578
+ const collection = external(c, c.req.param('collection'));
579
+ const row: ExternalRow | null | undefined = await collection?.get(c, c.req.param('id'));
580
+ if (!collection || !row) return notFound(c);
581
+ const refs = await resolver(c, Object.fromEntries(Object.entries(collection.fields).map(([n, b]) => [n, b.meta])), row);
582
+ return c.html(externalRowPage(shell, collection, row, refs, collection.actions ?? [], notice(c)));
583
+ });
584
+
585
+ app.get('/x/:collection/:id/do/:action', async c => {
586
+ const site = await externalSite(c);
587
+ return site ? confirmAction(c, site) : notFound(c);
588
+ });
589
+ app.post('/x/:collection/:id/do/:action', async c => {
590
+ const site = await externalSite(c);
591
+ return site ? runAction(c, site) : notFound(c);
592
+ });
593
+
594
+ // An external collection is a view: no create, save, publish or delete reaches it, whatever the method or path.
595
+ app.all('/x/*', c =>
596
+ c.req.method === 'GET' || c.req.method === 'HEAD'
597
+ ? notFound(c)
598
+ : c.html(messagePage(shell, 'Not allowed', 'This is a read-only view; it has no create, save or publish.'), 405, { allow: 'GET, HEAD' })
599
+ );
600
+
601
+ app.all('*', c => notFound(c));
602
+ return app;
603
+ }
604
+
605
+ /** Mounts the admin on a host app: `mountAdmin(app, '/admin2', options)`. */
606
+ export function mountAdmin<H extends HostPrincipal = never>(host: Hono<any>, path: string, options: Omit<AdminOptions<H>, 'mount'>): void {
607
+ host.route(path, createAdmin({ ...options, mount: path }));
608
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The admin's own files, served by the admin itself at `<mount>/assets/`, so a
3
+ * host copies nothing. The style is the entry form's layout and nothing else
4
+ * (Largen styles the rest); the script is under 5 KB and loads the markdown
5
+ * editor only on a page that has a markdown field.
6
+ */
7
+
8
+ export const ADMIN_CSS = `@layer largen.components {
9
+ .fields { display: grid; grid-template-columns: minmax(7rem, 12rem) minmax(0, 1fr); gap: 0.75rem 1rem; margin: 0; }
10
+ .fields > dt { padding-block-start: 0.5em; font-weight: 600; }
11
+ .fields > dd { margin: 0; min-inline-size: 0; }
12
+ .fields pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
13
+ .fields textarea { min-block-size: 6rem; }
14
+ .fields .milkdown { border: 1px solid var(--line); border-radius: var(--radius-sm); }
15
+ @media (max-width: 40rem) { .fields { grid-template-columns: 1fr; } .fields > dt { padding-block-start: 0; } }
16
+ }
17
+ `;
18
+
19
+ /**
20
+ * Three things, all optional: Largen's dark theme answers to `data-theme="dark"`, which this sets from the system's
21
+ * preference (the style sheet itself is linked only under that preference, and a policy without inline script cannot
22
+ * set it in the page); a select marked `data-autosubmit` submits its form when changed (the filters), and a
23
+ * `textarea[data-markdown]` gains the editor when the module named by `data-editor` loads. The text area stays in the
24
+ * page, hidden only once the editor is up, and is written back from the editor when its form is submitted; if the
25
+ * module fails to load, the text area is still the field.
26
+ */
27
+ export const ADMIN_JS = `(function () {
28
+ 'use strict';
29
+ var script = document.currentScript;
30
+ var dark = window.matchMedia('(prefers-color-scheme: dark)');
31
+ function theme() { document.documentElement.setAttribute('data-theme', dark.matches ? 'dark' : 'light'); }
32
+ theme();
33
+ dark.addEventListener('change', theme);
34
+ document.querySelectorAll('select[data-autosubmit]').forEach(function (select) {
35
+ select.addEventListener('change', function () { select.form.requestSubmit(); });
36
+ });
37
+ var areas = Array.prototype.slice.call(document.querySelectorAll('textarea[data-markdown]'));
38
+ var url = script && script.getAttribute('data-editor');
39
+ if (!areas.length || !url) return;
40
+ import(url).then(function (editor) {
41
+ areas.forEach(function (area) {
42
+ var host = document.createElement('div');
43
+ host.className = 'editor';
44
+ area.after(host);
45
+ editor.createEditor(host, area.value, { type: area.getAttribute('data-type') || '', field: area.getAttribute('data-field') || area.name }).then(function (instance) {
46
+ area.style.display = 'none';
47
+ area.form.addEventListener('submit', function () { area.value = instance.getMarkdown(); });
48
+ }).catch(function () { host.remove(); });
49
+ });
50
+ }).catch(function () {});
51
+ })();
52
+ `;