cogens 0.0.0-stage → 0.2.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.
Files changed (192) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +25 -0
  4. package/README.md +394 -2
  5. package/dist/admin/app.d.ts +21 -0
  6. package/dist/admin/app.d.ts.map +1 -0
  7. package/dist/admin/app.js +561 -0
  8. package/dist/admin/app.js.map +1 -0
  9. package/dist/admin/assets.d.ts +17 -0
  10. package/dist/admin/assets.d.ts.map +1 -0
  11. package/dist/admin/assets.js +51 -0
  12. package/dist/admin/assets.js.map +1 -0
  13. package/dist/admin/fields.d.ts +27 -0
  14. package/dist/admin/fields.d.ts.map +1 -0
  15. package/dist/admin/fields.js +128 -0
  16. package/dist/admin/fields.js.map +1 -0
  17. package/dist/admin/forms.d.ts +18 -0
  18. package/dist/admin/forms.d.ts.map +1 -0
  19. package/dist/admin/forms.js +53 -0
  20. package/dist/admin/forms.js.map +1 -0
  21. package/dist/admin/index.d.ts +15 -0
  22. package/dist/admin/index.d.ts.map +1 -0
  23. package/dist/admin/index.js +13 -0
  24. package/dist/admin/index.js.map +1 -0
  25. package/dist/admin/rules.d.ts +24 -0
  26. package/dist/admin/rules.d.ts.map +1 -0
  27. package/dist/admin/rules.js +51 -0
  28. package/dist/admin/rules.js.map +1 -0
  29. package/dist/admin/types.d.ts +96 -0
  30. package/dist/admin/types.d.ts.map +1 -0
  31. package/dist/admin/types.js +2 -0
  32. package/dist/admin/types.js.map +1 -0
  33. package/dist/admin/views.d.ts +109 -0
  34. package/dist/admin/views.d.ts.map +1 -0
  35. package/dist/admin/views.js +202 -0
  36. package/dist/admin/views.js.map +1 -0
  37. package/dist/auth/handoff.d.ts +27 -0
  38. package/dist/auth/handoff.d.ts.map +1 -0
  39. package/dist/auth/handoff.js +41 -0
  40. package/dist/auth/handoff.js.map +1 -0
  41. package/dist/auth/index.d.ts +10 -0
  42. package/dist/auth/index.d.ts.map +1 -0
  43. package/dist/auth/index.js +10 -0
  44. package/dist/auth/index.js.map +1 -0
  45. package/dist/auth/password.d.ts +48 -0
  46. package/dist/auth/password.d.ts.map +1 -0
  47. package/dist/auth/password.js +154 -0
  48. package/dist/auth/password.js.map +1 -0
  49. package/dist/auth/principal.d.ts +30 -0
  50. package/dist/auth/principal.d.ts.map +1 -0
  51. package/dist/auth/principal.js +30 -0
  52. package/dist/auth/principal.js.map +1 -0
  53. package/dist/auth/session.d.ts +68 -0
  54. package/dist/auth/session.d.ts.map +1 -0
  55. package/dist/auth/session.js +92 -0
  56. package/dist/auth/session.js.map +1 -0
  57. package/dist/core/access/ability.d.ts +24 -0
  58. package/dist/core/access/ability.d.ts.map +1 -0
  59. package/dist/core/access/ability.js +64 -0
  60. package/dist/core/access/ability.js.map +1 -0
  61. package/dist/core/access/can.d.ts +41 -0
  62. package/dist/core/access/can.d.ts.map +1 -0
  63. package/dist/core/access/can.js +38 -0
  64. package/dist/core/access/can.js.map +1 -0
  65. package/dist/core/access/compile.d.ts +12 -0
  66. package/dist/core/access/compile.d.ts.map +1 -0
  67. package/dist/core/access/compile.js +53 -0
  68. package/dist/core/access/compile.js.map +1 -0
  69. package/dist/core/access/permits.d.ts +24 -0
  70. package/dist/core/access/permits.d.ts.map +1 -0
  71. package/dist/core/access/permits.js +29 -0
  72. package/dist/core/access/permits.js.map +1 -0
  73. package/dist/core/access/when.d.ts +6 -0
  74. package/dist/core/access/when.d.ts.map +1 -0
  75. package/dist/core/access/when.js +64 -0
  76. package/dist/core/access/when.js.map +1 -0
  77. package/dist/core/access/where.d.ts +25 -0
  78. package/dist/core/access/where.d.ts.map +1 -0
  79. package/dist/core/access/where.js +81 -0
  80. package/dist/core/access/where.js.map +1 -0
  81. package/dist/core/columns.d.ts +6 -0
  82. package/dist/core/columns.d.ts.map +1 -0
  83. package/dist/core/columns.js +6 -0
  84. package/dist/core/columns.js.map +1 -0
  85. package/dist/core/config/define.d.ts +101 -0
  86. package/dist/core/config/define.d.ts.map +1 -0
  87. package/dist/core/config/define.js +97 -0
  88. package/dist/core/config/define.js.map +1 -0
  89. package/dist/core/config/field.d.ts +71 -0
  90. package/dist/core/config/field.d.ts.map +1 -0
  91. package/dist/core/config/field.js +64 -0
  92. package/dist/core/config/field.js.map +1 -0
  93. package/dist/core/errors.d.ts +66 -0
  94. package/dist/core/errors.d.ts.map +1 -0
  95. package/dist/core/errors.js +94 -0
  96. package/dist/core/errors.js.map +1 -0
  97. package/dist/core/index.d.ts +31 -0
  98. package/dist/core/index.d.ts.map +1 -0
  99. package/dist/core/index.js +20 -0
  100. package/dist/core/index.js.map +1 -0
  101. package/dist/core/media/index.d.ts +36 -0
  102. package/dist/core/media/index.d.ts.map +1 -0
  103. package/dist/core/media/index.js +99 -0
  104. package/dist/core/media/index.js.map +1 -0
  105. package/dist/core/principal.d.ts +28 -0
  106. package/dist/core/principal.d.ts.map +1 -0
  107. package/dist/core/principal.js +25 -0
  108. package/dist/core/principal.js.map +1 -0
  109. package/dist/core/store/assets.d.ts +3 -0
  110. package/dist/core/store/assets.d.ts.map +1 -0
  111. package/dist/core/store/assets.js +3 -0
  112. package/dist/core/store/assets.js.map +1 -0
  113. package/dist/core/store/cms.d.ts +53 -0
  114. package/dist/core/store/cms.d.ts.map +1 -0
  115. package/dist/core/store/cms.js +154 -0
  116. package/dist/core/store/cms.js.map +1 -0
  117. package/dist/core/store/content.d.ts +57 -0
  118. package/dist/core/store/content.d.ts.map +1 -0
  119. package/dist/core/store/content.js +455 -0
  120. package/dist/core/store/content.js.map +1 -0
  121. package/dist/core/store/sql.d.ts +88 -0
  122. package/dist/core/store/sql.d.ts.map +1 -0
  123. package/dist/core/store/sql.js +149 -0
  124. package/dist/core/store/sql.js.map +1 -0
  125. package/dist/core/store/types.d.ts +107 -0
  126. package/dist/core/store/types.d.ts.map +1 -0
  127. package/dist/core/store/types.js +2 -0
  128. package/dist/core/store/types.js.map +1 -0
  129. package/dist/core/testing/index.d.ts +27 -0
  130. package/dist/core/testing/index.d.ts.map +1 -0
  131. package/dist/core/testing/index.js +60 -0
  132. package/dist/core/testing/index.js.map +1 -0
  133. package/dist/migrations-tool/bin.d.ts +3 -0
  134. package/dist/migrations-tool/bin.d.ts.map +1 -0
  135. package/dist/migrations-tool/bin.js +40 -0
  136. package/dist/migrations-tool/bin.js.map +1 -0
  137. package/dist/migrations-tool/index.d.ts +16 -0
  138. package/dist/migrations-tool/index.d.ts.map +1 -0
  139. package/dist/migrations-tool/index.js +24 -0
  140. package/dist/migrations-tool/index.js.map +1 -0
  141. package/dist/testing/db.d.ts +16 -0
  142. package/dist/testing/db.d.ts.map +1 -0
  143. package/dist/testing/db.js +43 -0
  144. package/dist/testing/db.js.map +1 -0
  145. package/dist/testing/index.d.ts +10 -0
  146. package/dist/testing/index.d.ts.map +1 -0
  147. package/dist/testing/index.js +8 -0
  148. package/dist/testing/index.js.map +1 -0
  149. package/editor/editor-dark.css +2 -0
  150. package/editor/editor.css +9 -0
  151. package/editor/entry.js +28 -0
  152. package/migrations/0001_entries.sql +43 -0
  153. package/migrations/auth/0001_sessions.sql +50 -0
  154. package/migrations/koguma-upgrade.sql +13 -0
  155. package/package.json +108 -4
  156. package/scripts/build-admin-editor.ts +155 -0
  157. package/src/admin/app.ts +608 -0
  158. package/src/admin/assets.ts +52 -0
  159. package/src/admin/fields.ts +172 -0
  160. package/src/admin/forms.ts +64 -0
  161. package/src/admin/index.ts +16 -0
  162. package/src/admin/rules.ts +63 -0
  163. package/src/admin/types.ts +99 -0
  164. package/src/admin/views.ts +360 -0
  165. package/src/auth/handoff.ts +56 -0
  166. package/src/auth/index.ts +29 -0
  167. package/src/auth/password.ts +201 -0
  168. package/src/auth/principal.ts +40 -0
  169. package/src/auth/session.ts +143 -0
  170. package/src/core/access/ability.ts +86 -0
  171. package/src/core/access/can.ts +66 -0
  172. package/src/core/access/compile.ts +62 -0
  173. package/src/core/access/permits.ts +45 -0
  174. package/src/core/access/when.ts +59 -0
  175. package/src/core/access/where.ts +95 -0
  176. package/src/core/columns.ts +7 -0
  177. package/src/core/config/define.ts +206 -0
  178. package/src/core/config/field.ts +119 -0
  179. package/src/core/errors.ts +99 -0
  180. package/src/core/index.ts +44 -0
  181. package/src/core/media/index.ts +132 -0
  182. package/src/core/principal.ts +49 -0
  183. package/src/core/store/assets.ts +2 -0
  184. package/src/core/store/cms.ts +199 -0
  185. package/src/core/store/content.ts +453 -0
  186. package/src/core/store/sql.ts +239 -0
  187. package/src/core/store/types.ts +100 -0
  188. package/src/core/testing/index.ts +75 -0
  189. package/src/migrations-tool/bin.ts +34 -0
  190. package/src/migrations-tool/index.ts +37 -0
  191. package/src/testing/db.ts +53 -0
  192. package/src/testing/index.ts +9 -0
@@ -0,0 +1,172 @@
1
+ /**
2
+ * The field renderers: nine kinds, each with a form to edit in and a read-only
3
+ * form. A field the caller may not write is drawn with its read form, as text.
4
+ * Every value reaches the page through `hono/html`'s template, which escapes it;
5
+ * markdown is shown in a text area or a `pre`, never as markup.
6
+ */
7
+ import { html } from 'hono/html';
8
+ import type { HtmlEscapedString } from 'hono/utils/html';
9
+ import type { FieldMeta, FieldType } from '../core/index.ts';
10
+
11
+ export type Html = HtmlEscapedString | Promise<HtmlEscapedString>;
12
+
13
+ /** The nine renderers. */
14
+ export type Kind = 'text' | 'number' | 'boolean' | 'date' | 'select' | 'reference' | 'markdown' | 'files' | 'json';
15
+
16
+ export const KIND: Record<FieldType, Kind> = {
17
+ text: 'text',
18
+ longText: 'text',
19
+ url: 'text',
20
+ email: 'text',
21
+ number: 'number',
22
+ boolean: 'boolean',
23
+ date: 'date',
24
+ select: 'select',
25
+ reference: 'reference',
26
+ references: 'reference',
27
+ markdown: 'markdown',
28
+ files: 'files',
29
+ json: 'json'
30
+ };
31
+
32
+ /** What a reference field links to: where the entry it names is shown, and a name for it. */
33
+ export interface RefTarget {
34
+ href: string | null;
35
+ label: string;
36
+ }
37
+ export type ResolveRef = (type: string, id: string) => RefTarget;
38
+
39
+ export interface RenderInput {
40
+ name: string;
41
+ /** The content type id the field belongs to; a markdown text area carries it as `data-type` for the editor plugin. */
42
+ type?: string;
43
+ meta: FieldMeta;
44
+ value: unknown;
45
+ refs: ResolveRef;
46
+ }
47
+
48
+ export interface Renderer {
49
+ edit(input: RenderInput): Html;
50
+ read(input: RenderInput): Html;
51
+ }
52
+
53
+ const MUTED = html`<span data-tone="secondary" data-variant="ghost">—</span>`;
54
+ /** HTML drops one newline right after a textarea's or pre's start tag, so each is written with one, and a value that begins with a newline keeps it. */
55
+ const present = (value: unknown) => value !== undefined && value !== null && value !== '';
56
+ const asText = (value: unknown): string => (typeof value === 'string' ? value : value === undefined || value === null ? '' : String(value));
57
+ const idOf = (name: string) => `f-${name}`;
58
+
59
+ /** A link target is shown as a link only when it cannot run script. */
60
+ const safeHref = (value: string) => /^(https?:\/\/|\/(?!\/))/i.test(value);
61
+
62
+ function formatBytes(n: number): string {
63
+ if (n < 1024) return `${n} B`;
64
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
65
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
66
+ }
67
+
68
+ const text: Renderer = {
69
+ edit({ name, meta, value }) {
70
+ if (meta.fieldType === 'longText') {
71
+ return html`<textarea id="${idOf(name)}" name="${name}" rows="6">
72
+ ${asText(value)}</textarea>`;
73
+ }
74
+ const type = meta.fieldType === 'url' ? 'url' : meta.fieldType === 'email' ? 'email' : 'text';
75
+ return html`<input id="${idOf(name)}" type="${type}" name="${name}" value="${asText(value)}">`;
76
+ },
77
+ read({ meta, value }) {
78
+ if (!present(value)) return MUTED;
79
+ const s = asText(value);
80
+ if (meta.fieldType === 'url' && safeHref(s)) return html`<a href="${s}">${s}</a>`;
81
+ return html`<span>${s}</span>`;
82
+ }
83
+ };
84
+
85
+ const number: Renderer = {
86
+ edit: ({ name, value }) => html`<input id="${idOf(name)}" type="number" step="any" name="${name}" value="${asText(value)}">`,
87
+ read: ({ value }) => (present(value) ? html`<span>${asText(value)}</span>` : MUTED)
88
+ };
89
+
90
+ const boolean: Renderer = {
91
+ // A select, not a checkbox: an unchecked box sends nothing, which a save could not tell from a field that is not on the form.
92
+ edit: ({ name, meta, value }) => html`<select id="${idOf(name)}" name="${name}">${
93
+ meta.required ? '' : html`<option value=""${value === undefined || value === null ? ' selected' : ''}>—</option>`
94
+ }<option value="true"${value === true ? ' selected' : ''}>Yes</option><option value="false"${value === false ? ' selected' : ''}>No</option></select>`,
95
+ read: ({ value }) => (value === true ? html`<span>Yes</span>` : value === false ? html`<span>No</span>` : MUTED)
96
+ };
97
+
98
+ const date: Renderer = {
99
+ edit: ({ name, value }) =>
100
+ html`<input id="${idOf(name)}" type="text" name="${name}" value="${asText(value)}" placeholder="2026-11-14T09:30:00Z" autocomplete="off">`,
101
+ read: ({ value }) => (present(value) ? html`<time datetime="${asText(value)}">${asText(value)}</time>` : MUTED)
102
+ };
103
+
104
+ const select: Renderer = {
105
+ edit: ({ name, meta, value }) => html`<select id="${idOf(name)}" name="${name}">${
106
+ meta.required && present(value) ? '' : html`<option value="">—</option>`
107
+ }${(meta.options ?? []).map(option => html`<option value="${option}"${value === option ? ' selected' : ''}>${option}</option>`)}</select>`,
108
+ read: ({ value }) => (present(value) ? html`<span>${asText(value)}</span>` : MUTED)
109
+ };
110
+
111
+ function refLink(meta: FieldMeta, id: string, refs: ResolveRef): Html {
112
+ const target = refs(meta.refContentType ?? '', id);
113
+ return target.href ? html`<a href="${target.href}">${target.label}</a>` : html`<span>${target.label}</span>`;
114
+ }
115
+
116
+ const reference: Renderer = {
117
+ edit({ name, meta, value }) {
118
+ if (meta.fieldType === 'references') {
119
+ const ids = Array.isArray(value) ? value.map(asText).join('\n') : '';
120
+ return html`<textarea id="${idOf(name)}" name="${name}" rows="3" placeholder="One id per line">
121
+ ${ids}</textarea>`;
122
+ }
123
+ return html`<input id="${idOf(name)}" type="text" name="${name}" value="${asText(value)}">`;
124
+ },
125
+ read({ meta, value, refs }) {
126
+ if (meta.fieldType === 'references') {
127
+ const ids = Array.isArray(value) ? value.map(asText) : [];
128
+ if (ids.length === 0) return MUTED;
129
+ return html`<ul class="stack">${ids.map(id => html`<li>${refLink(meta, id, refs)}</li>`)}</ul>`;
130
+ }
131
+ return present(value) ? refLink(meta, asText(value), refs) : MUTED;
132
+ }
133
+ };
134
+
135
+ const markdown: Renderer = {
136
+ // The editor, when it loads, takes the place of this text area and writes back to it; without it this is the field.
137
+ edit: ({ name, type, value }) => html`<textarea id="${idOf(name)}" name="${name}" rows="14" data-markdown${type === undefined ? '' : html` data-type="${type}"`} data-field="${name}">
138
+ ${asText(value)}</textarea>`,
139
+ read: ({ value }) => (present(value) ? html`<pre>
140
+ ${asText(value)}</pre>` : MUTED)
141
+ };
142
+
143
+ const files: Renderer = {
144
+ edit: input => files.read(input),
145
+ read({ value }) {
146
+ const list = Array.isArray(value) ? (value as { name?: unknown; size?: unknown; url?: unknown }[]) : [];
147
+ if (list.length === 0) return html`<span data-tone="secondary" data-variant="ghost">No files stored.</span>`;
148
+ return html`<ul class="stack">${list.map(file => {
149
+ const name = asText(file.name);
150
+ const url = asText(file.url);
151
+ const size = typeof file.size === 'number' ? html` <small>${formatBytes(file.size)}</small>` : '';
152
+ return safeHref(url) ? html`<li><a href="${url}" download="${name}">${name}</a>${size}</li>` : html`<li>${name}${size}</li>`;
153
+ })}</ul>`;
154
+ }
155
+ };
156
+
157
+ const pretty = (value: unknown) => (typeof value === 'string' ? value : JSON.stringify(value, null, 2));
158
+
159
+ const json: Renderer = {
160
+ edit: ({ name, value }) =>
161
+ html`<textarea id="${idOf(name)}" name="${name}" rows="8" spellcheck="false">
162
+ ${present(value) ? pretty(value) : ''}</textarea>`,
163
+ read: ({ value }) => (present(value) ? html`<pre><code>
164
+ ${pretty(value)}</code></pre>` : MUTED)
165
+ };
166
+
167
+ export const RENDERERS: Record<Kind, Renderer> = { text, number, boolean, date, select, reference, markdown, files, json };
168
+
169
+ export function renderField(input: RenderInput, mode: 'edit' | 'read'): Html {
170
+ const renderer = RENDERERS[KIND[input.meta.fieldType]];
171
+ return mode === 'edit' && input.meta.fieldType !== 'files' ? renderer.edit(input) : renderer.read(input);
172
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A posted form into what the store takes. Every key in the body is passed on,
3
+ * whether or not the page drew an input for it, so a forged field reaches the
4
+ * store's own rules and is refused there; nothing here decides what may be written.
5
+ */
6
+ import type { ContentType, FieldMeta } from '../core/index.ts';
7
+
8
+ export interface Parsed {
9
+ values: Record<string, unknown>;
10
+ /** Fields whose text could not be read (JSON that is not JSON). */
11
+ errors: { field: string; message: string }[];
12
+ }
13
+
14
+ function coerce(meta: FieldMeta, raw: string): unknown {
15
+ switch (meta.fieldType) {
16
+ case 'number': {
17
+ if (raw.trim() === '') return null;
18
+ const n = Number(raw);
19
+ return Number.isNaN(n) ? raw : n;
20
+ }
21
+ case 'boolean':
22
+ return raw === 'true' ? true : raw === 'false' ? false : null;
23
+ case 'references':
24
+ return raw.split(/[\n,]/).map(s => s.trim()).filter(Boolean);
25
+ case 'markdown':
26
+ case 'longText':
27
+ // A text area submits line ends as CRLF; the stored text keeps LF.
28
+ return raw === '' ? null : raw.replace(/\r\n/g, '\n');
29
+ default:
30
+ return raw === '' ? null : raw;
31
+ }
32
+ }
33
+
34
+ export function parseForm(type: Pick<ContentType<any>, 'fieldMeta'>, form: FormData): Parsed {
35
+ const values: Record<string, unknown> = {};
36
+ const errors: Parsed['errors'] = [];
37
+ const keys = new Set<string>();
38
+ form.forEach((_, key) => keys.add(key));
39
+ for (const key of keys) {
40
+ const raw = form.getAll(key).filter((v): v is string => typeof v === 'string');
41
+ const last = raw[raw.length - 1] ?? '';
42
+ const meta = type.fieldMeta[key];
43
+ if (!meta) {
44
+ values[key] = last === '' ? null : last;
45
+ continue;
46
+ }
47
+ if (meta.fieldType === 'json') {
48
+ if (last.trim() === '') values[key] = null;
49
+ else {
50
+ try {
51
+ values[key] = JSON.parse(last);
52
+ } catch {
53
+ errors.push({ field: key, message: 'is not valid JSON.' });
54
+ }
55
+ }
56
+ continue;
57
+ }
58
+ values[key] = coerce(meta, last);
59
+ }
60
+ return { values, errors };
61
+ }
62
+
63
+ /** A form's text for a built-in column: empty means none. */
64
+ export const columnValue = (value: unknown): string | null => (typeof value === 'string' && value !== '' ? value : null);
@@ -0,0 +1,16 @@
1
+ /**
2
+ * cogens/admin: the server-rendered admin pages.
3
+ * May import `cogens` core and `hono`, nothing else of ours.
4
+ *
5
+ * app.route('/admin', createAdmin({ cms, resolvePrincipal, mount: '/admin' }));
6
+ *
7
+ * The pages are Hono routes rendered with `hono/html` and styled by Largen. The
8
+ * markdown editor is a static file the host serves (`scripts/build-admin-editor.ts` builds it).
9
+ */
10
+ export { createAdmin, mountAdmin, DEFAULT_ASSETS } from './app.ts';
11
+ export { ADMIN_CSS, ADMIN_JS } from './assets.ts';
12
+ export { KIND, RENDERERS, renderField } from './fields.ts';
13
+ export type { Html, Kind, RefTarget, RenderInput, Renderer, ResolveRef } from './fields.ts';
14
+ export type {
15
+ ActionContext, AdminAction, AdminAssets, AdminSession, AdminOptions, ExternalCollection, ExternalRow
16
+ } from './types.ts';
@@ -0,0 +1,63 @@
1
+ /**
2
+ * What the pages show and hide, worked out from `cms.access.rulesFor`. This is
3
+ * display only: a control that is hidden here is still refused by the store if
4
+ * a request names it, and a control shown here is still checked there.
5
+ */
6
+ import { permits, type ContentType, type Entry, type FieldMeta, type Operation, type PackedRules } from '../core/index.ts';
7
+
8
+ const PROTECTED = ['owner_id', 'slug', 'parent_id', 'sort_key'];
9
+
10
+ /** The row as a condition sees it: the built-in columns and the indexed fields (booleans as 0 and 1). */
11
+ export function ruleRow(type: ContentType<any>, entry: Entry): Record<string, unknown> {
12
+ const row: Record<string, unknown> = {
13
+ id: entry.id,
14
+ owner_id: entry.owner_id,
15
+ slug: entry.slug,
16
+ status: entry.status,
17
+ parent_id: entry.parent_id,
18
+ parent_status: entry.parent_status
19
+ };
20
+ for (const field of type.indexed) {
21
+ const value = entry.data[field];
22
+ if (typeof value === 'boolean') row[field] = value ? 1 : 0;
23
+ else if (typeof value === 'string' || typeof value === 'number') row[field] = value;
24
+ }
25
+ return row;
26
+ }
27
+
28
+ export const can = (rules: PackedRules, type: string, operation: Operation, row?: Record<string, unknown>) =>
29
+ permits(rules, type, operation, row);
30
+
31
+ export interface Writable {
32
+ /** Some matching grant lets the caller write every ordinary field. */
33
+ ordinary: boolean;
34
+ /** Fields a matching grant names (system fields and protected columns are writable only by name). */
35
+ listed: Set<string>;
36
+ /** Whether any grant matches at all. */
37
+ any: boolean;
38
+ }
39
+
40
+ /** The fields a caller may write for create or update: those of the grants that match the row (any grant, for a create). */
41
+ export function writable(rules: PackedRules, type: string, operation: 'create' | 'update', row?: Record<string, unknown>): Writable {
42
+ const grants = (rules.find(r => r.type === type)?.grants ?? []).filter(
43
+ g => g.operation === operation && !g.bySlug && (row === undefined || permits([{ type, grants: [g] }], type, operation, row))
44
+ );
45
+ return {
46
+ any: grants.length > 0,
47
+ ordinary: grants.some(g => g.fields === undefined),
48
+ listed: new Set(grants.flatMap(g => g.fields ?? []))
49
+ };
50
+ }
51
+
52
+ /** Whether the caller may write one of the type's fields; false drawn as text. */
53
+ export function mayWrite(w: Writable, name: string, meta: FieldMeta): boolean {
54
+ if (meta.fieldType === 'files') return false;
55
+ if (meta.system) return w.listed.has(name);
56
+ return w.ordinary || w.listed.has(name);
57
+ }
58
+
59
+ /** Whether the caller may write a built-in column (`slug`, `owner_id`); on create any create grant lets them name it. */
60
+ export function mayWriteColumn(w: Writable, name: string, operation: 'create' | 'update'): boolean {
61
+ if (!PROTECTED.includes(name)) return false;
62
+ return operation === 'create' ? w.any : w.listed.has(name);
63
+ }
@@ -0,0 +1,99 @@
1
+ /** What a host gives the admin, and what it may add: external collections and actions. */
2
+ import type { Context } from 'hono';
3
+ import type { Cms, FieldBuilder, HostPrincipal, Operation, Principal } from '../core/index.ts';
4
+
5
+ /** What an action's `run` is told. */
6
+ export interface ActionContext<H extends HostPrincipal = never> {
7
+ /** The request, for the host's bindings (`c.env`). */
8
+ c: Context;
9
+ principal: Principal<H>;
10
+ /** The entry or row the action was pressed on. */
11
+ id: string;
12
+ /** The entry chosen when the action has a `target`. */
13
+ target?: string;
14
+ }
15
+
16
+ /**
17
+ * A button on an entry or row. Pressing it opens a page that shows `confirm`
18
+ * (and a picker when there is a `target`), and `run` is called only when that
19
+ * page is confirmed. A thrown error is shown on a page; a thrown error with a
20
+ * numeric `status` answers with that status.
21
+ */
22
+ export interface AdminAction<H extends HostPrincipal = never> {
23
+ id: string;
24
+ label: string;
25
+ /** The question the confirmation page asks. */
26
+ confirm: string;
27
+ destructive?: boolean;
28
+ /** A store type or external collection to pick an entry of first; its id arrives as `ActionContext.target`. */
29
+ target?: string;
30
+ /** Store types only: the operation the caller must hold on the entry for the button to be offered and the action to run. */
31
+ requires?: Operation;
32
+ run(context: ActionContext<H>): Promise<void>;
33
+ }
34
+
35
+ export interface ExternalRow {
36
+ id: string;
37
+ /** `published` shows the row as live, anything else as not; absent shows no state. */
38
+ status?: string;
39
+ [field: string]: unknown;
40
+ }
41
+
42
+ /** A read-only view over a table of the host's own. It is never stored as entries and has no create, save or publish. */
43
+ export interface ExternalCollection<H extends HostPrincipal = never> {
44
+ id: string;
45
+ name: string;
46
+ /** The field shown as the row's title. */
47
+ displayField: string;
48
+ /** Its fields, built with `field.*` from core; `ref` and `refs` name a store type or another external collection. */
49
+ fields: Record<string, FieldBuilder<any, any>>;
50
+ list(c: Context, page: { limit: number; offset: number }): Promise<ExternalRow[]>;
51
+ get(c: Context, id: string): Promise<ExternalRow | null>;
52
+ actions?: AdminAction<H>[];
53
+ /** Who may see it: only the admin kind when absent. */
54
+ allow?(principal: Principal<H>): boolean;
55
+ /** Whether a row is offered when this collection is an action's target; every row but the one acted on when absent. */
56
+ pickable?(row: ExternalRow): boolean;
57
+ }
58
+
59
+ /** Where the admin's pages find the host's static files. Each is a URL the host serves. */
60
+ export interface AdminAssets {
61
+ largen: string;
62
+ largenDark: string;
63
+ /** The markdown editor module (`scripts/build-admin-editor.ts` builds it to `admin-editor.js`). */
64
+ editor: string;
65
+ editorStyles: string;
66
+ editorStylesDark: string;
67
+ }
68
+
69
+ /**
70
+ * The host's sign-in, for a host whose credential is a cookie. Each function does the host's own work and answers its
71
+ * own Response: a 2xx is success and its `set-cookie` headers are passed on, 401 is a wrong password, 429 too many
72
+ * tries, anything else a failure. Given this, the admin draws a sign-in page for a caller who is not signed in
73
+ * (instead of answering `unauthorized`), handles its three forms, and shows Sign out and Sign out everywhere.
74
+ */
75
+ export interface AdminSession {
76
+ signIn(c: Context, password: string): Promise<Response>;
77
+ signOut(c: Context): Promise<Response>;
78
+ signOutEverywhere(c: Context): Promise<Response>;
79
+ }
80
+
81
+ export interface AdminOptions<H extends HostPrincipal = never> {
82
+ cms: Cms<H>;
83
+ /** Who is calling, from the host's own credential; null for nobody, which answers `unauthorized` (401 by default). */
84
+ resolvePrincipal(c: Context): Principal<H> | null | Promise<Principal<H> | null>;
85
+ externalCollections?: ExternalCollection<H>[];
86
+ /**
87
+ * Actions on a store type's entries, by type id. One with the id `unpublish` or `delete` takes the place of the
88
+ * page's own Unpublish or Delete, for a type whose host does more than the store does.
89
+ */
90
+ typeActions?: Record<string, AdminAction<H>[]>;
91
+ /** The path the host mounts the admin at, with no trailing slash; every link starts with it. */
92
+ mount: string;
93
+ siteName?: string;
94
+ assets?: Partial<AdminAssets>;
95
+ /** The host's sign-in; when given, a caller who is not signed in gets the sign-in page (401) and signed-in pages carry the sign-out forms. */
96
+ session?: AdminSession;
97
+ /** What to answer when `resolvePrincipal` gives null and there is no `session`. */
98
+ unauthorized?(c: Context): Response | Promise<Response>;
99
+ }