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,239 @@
1
+ /**
2
+ * The SQL layer: the only file that names the tables that hold entries and
3
+ * assets. Everything else reaches them through the functions here, and a test
4
+ * fails on any file outside src/core/store that imports this one. Every
5
+ * function takes the access condition already compiled; there is no variant that
6
+ * leaves it out.
7
+ */
8
+ import { ConditionError } from '../errors.ts';
9
+ import { MAX_IN_VALUES } from '../access/where.ts';
10
+ import type { Sql } from '../access/compile.ts';
11
+ import type { Entry, OrderBy, Status } from './types.ts';
12
+
13
+ /** D1 allows 100 bound values in one statement. */
14
+ const MAX_PARAMS = 100;
15
+
16
+ const SELECT = 'SELECT id, content_type, owner_id, slug, status, parent_id, sort_key, parent_status, data, created_at, updated_at FROM entries';
17
+
18
+ function bind(db: D1Database, sql: string, params: unknown[]): D1PreparedStatement {
19
+ if (params.length > MAX_PARAMS) {
20
+ throw new ConditionError(`One statement binds ${params.length} values; D1 allows ${MAX_PARAMS}. Narrow the condition.`);
21
+ }
22
+ return db.prepare(sql).bind(...params);
23
+ }
24
+
25
+ interface Row {
26
+ id: string;
27
+ content_type: string;
28
+ owner_id: string | null;
29
+ slug: string | null;
30
+ status: string;
31
+ parent_id: string | null;
32
+ sort_key: string | null;
33
+ parent_status: string | null;
34
+ data: string;
35
+ created_at: string;
36
+ updated_at: string;
37
+ }
38
+
39
+ export function toEntry<D = Record<string, unknown>>(row: Row): Entry<D> {
40
+ return {
41
+ id: row.id,
42
+ type: row.content_type,
43
+ owner_id: row.owner_id,
44
+ slug: row.slug,
45
+ status: row.status as Status,
46
+ parent_id: row.parent_id,
47
+ sort_key: row.sort_key,
48
+ parent_status: row.parent_status as Status | null,
49
+ created_at: row.created_at,
50
+ updated_at: row.updated_at,
51
+ data: JSON.parse(row.data) as D
52
+ };
53
+ }
54
+
55
+ const ORDER_COLUMNS: Record<OrderBy, string> = {
56
+ created_at: 'created_at',
57
+ updated_at: 'updated_at',
58
+ sort_key: 'sort_key',
59
+ slug: 'slug'
60
+ };
61
+
62
+ export interface SelectOptions {
63
+ orderBy?: OrderBy;
64
+ direction?: 'asc' | 'desc';
65
+ limit?: number;
66
+ offset?: number;
67
+ }
68
+
69
+ /** Entries of one type that match every condition given (each already compiled). */
70
+ export async function selectEntries<D = Record<string, unknown>>(db: D1Database, type: string, conditions: Sql[], options: SelectOptions = {}): Promise<Entry<D>[]> {
71
+ const order = ORDER_COLUMNS[options.orderBy ?? 'created_at'];
72
+ const direction = options.direction === 'asc' ? 'ASC' : 'DESC';
73
+ const sql = `${SELECT} WHERE content_type = ?${conditions.map(c => ` AND ${c.sql}`).join('')} ORDER BY ${order} ${direction}, id LIMIT ? OFFSET ?`;
74
+ const params = [type, ...conditions.flatMap(c => c.params), options.limit ?? 100, options.offset ?? 0];
75
+ const result = await bind(db, sql, params).all<Row>();
76
+ return (result.results ?? []).map(r => toEntry<D>(r));
77
+ }
78
+
79
+ /** How many ids one statement may name beside the type, the access condition and (for a read) a limit and an offset. */
80
+ export function idChunkSize(access: Sql): number {
81
+ return Math.max(1, Math.min(MAX_IN_VALUES, MAX_PARAMS - 3 - access.params.length));
82
+ }
83
+
84
+ const inList = (ids: string[]): Sql => ({ sql: `id IN (${ids.map(() => '?').join(', ')})`, params: ids });
85
+
86
+ /** The entries of one type with these ids (at most `idChunkSize` of them) that the access condition lets through. */
87
+ export function selectByIds<D = Record<string, unknown>>(db: D1Database, type: string, ids: string[], conditions: Sql[]): Promise<Entry<D>[]> {
88
+ return selectEntries<D>(db, type, [inList(ids), ...conditions], { orderBy: 'created_at', limit: ids.length });
89
+ }
90
+
91
+ /**
92
+ * A statement that fails the whole batch it is in (SQLite's "integer overflow") unless every one of these ids is an
93
+ * entry of the type that the access condition lets through. A batch is one transaction, so it checks the rows at the
94
+ * moment the writes after it run, and a failure rolls back the writes before it.
95
+ */
96
+ export function assertReachable(db: D1Database, type: string, ids: string[], access: Sql): D1PreparedStatement {
97
+ return bind(
98
+ db,
99
+ `SELECT CASE WHEN (SELECT COUNT(*) FROM entries WHERE content_type = ? AND ${inList(ids).sql} AND ${access.sql}) = ? THEN 1 ELSE abs(-9223372036854775807 - 1) END`,
100
+ [type, ...ids, ...access.params, ids.length]
101
+ );
102
+ }
103
+
104
+ /** True when an error from `assertReachable` is what a batch failed with. */
105
+ export const isUnreachable = (error: unknown): boolean =>
106
+ error instanceof Error && /integer overflow/i.test(`${error.message} ${(error as { cause?: Error }).cause?.message ?? ''}`);
107
+
108
+ export async function selectOne<D = Record<string, unknown>>(db: D1Database, type: string, conditions: Sql[]): Promise<Entry<D> | null> {
109
+ const sql = `${SELECT} WHERE content_type = ?${conditions.map(c => ` AND ${c.sql}`).join('')} LIMIT 1`;
110
+ const row = await bind(db, sql, [type, ...conditions.flatMap(c => c.params)]).first<Row>();
111
+ return row ? toEntry<D>(row) : null;
112
+ }
113
+
114
+ export interface NewRow {
115
+ id: string;
116
+ type: string;
117
+ owner_id: string | null;
118
+ slug: string | null;
119
+ parent_id: string | null;
120
+ sort_key: string | null;
121
+ /** The type of the parent whose status the entry mirrors; null when it mirrors nothing. */
122
+ mirrorParentType: string | null;
123
+ data: Record<string, unknown>;
124
+ }
125
+
126
+ export function insertEntry(db: D1Database, row: NewRow): D1PreparedStatement {
127
+ const mirrored = row.mirrorParentType !== null && row.parent_id !== null;
128
+ return bind(
129
+ db,
130
+ `INSERT INTO entries (id, content_type, owner_id, slug, status, parent_id, sort_key, parent_status, data)
131
+ VALUES (?, ?, ?, ?, 'draft', ?, ?, ${mirrored ? '(SELECT status FROM entries WHERE id = ? AND content_type = ?)' : 'NULL'}, ?)`,
132
+ [row.id, row.type, row.owner_id, row.slug, row.parent_id, row.sort_key, ...(mirrored ? [row.parent_id, row.mirrorParentType] : []), JSON.stringify(row.data)]
133
+ );
134
+ }
135
+
136
+ export interface Change {
137
+ /** Fields of `data`, replaced whole (null stores a JSON null). */
138
+ data?: Record<string, unknown>;
139
+ columns?: Partial<Record<'owner_id' | 'slug' | 'parent_id' | 'sort_key', string | null>>;
140
+ status?: Status;
141
+ /** Re-read parent_status from this parent type's entry (after parent_id changed in a type that mirrors). */
142
+ mirrorParentType?: string | null;
143
+ }
144
+
145
+ /** An UPDATE of one entry, applied only where the access condition (and the precondition) hold. */
146
+ export function updateEntry(db: D1Database, type: string, id: string, change: Change, access: Sql, when: Sql | null): D1PreparedStatement {
147
+ const sets: string[] = [];
148
+ const params: unknown[] = [];
149
+ if (change.status !== undefined) {
150
+ sets.push('status = ?');
151
+ params.push(change.status);
152
+ }
153
+ const names = Object.keys(change.data ?? {});
154
+ if (names.length > 0) {
155
+ sets.push(`data = json_set(data${names.map(() => ", '$.' || ?, json(?)").join('')})`);
156
+ for (const name of names) params.push(name, JSON.stringify((change.data as Record<string, unknown>)[name] ?? null));
157
+ }
158
+ for (const [column, value] of Object.entries(change.columns ?? {})) {
159
+ sets.push(`${column} = ?`);
160
+ params.push(value);
161
+ }
162
+ if (change.columns && 'parent_id' in change.columns) {
163
+ if (change.mirrorParentType && change.columns.parent_id) {
164
+ sets.push('parent_status = (SELECT status FROM entries WHERE id = ? AND content_type = ?)');
165
+ params.push(change.columns.parent_id, change.mirrorParentType);
166
+ } else {
167
+ sets.push('parent_status = NULL');
168
+ }
169
+ }
170
+ sets.push("updated_at = datetime('now')");
171
+ const sql = `UPDATE entries SET ${sets.join(', ')} WHERE id = ? AND content_type = ? AND ${access.sql}${when ? ` AND ${when.sql}` : ''}`;
172
+ return bind(db, sql, [...params, id, type, ...access.params, ...(when?.params ?? [])]);
173
+ }
174
+
175
+ export function deleteEntry(db: D1Database, type: string, id: string, access: Sql): D1PreparedStatement {
176
+ return bind(db, `DELETE FROM entries WHERE id = ? AND content_type = ? AND ${access.sql}`, [id, type, ...access.params]);
177
+ }
178
+
179
+ /**
180
+ * The children of a parent that mirror its status take the parent's status in the
181
+ * same batch as the parent's own write. The update runs only while the parent holds
182
+ * that status, so a parent write that matched no row copies nothing.
183
+ */
184
+ export function mirrorChildren(db: D1Database, childType: string, parentId: string, status: Status): D1PreparedStatement {
185
+ return bind(
186
+ db,
187
+ 'UPDATE entries SET parent_status = ? WHERE content_type = ? AND parent_id = ? AND EXISTS (SELECT 1 FROM entries WHERE id = ? AND status = ?)',
188
+ [status, childType, parentId, parentId, status]
189
+ );
190
+ }
191
+
192
+ export async function countChildren(db: D1Database, childTypes: string[], parentId: string): Promise<number> {
193
+ if (childTypes.length === 0) return 0;
194
+ const row = await bind(
195
+ db,
196
+ `SELECT COUNT(*) AS n FROM entries WHERE parent_id = ? AND content_type IN (${childTypes.map(() => '?').join(', ')})`,
197
+ [parentId, ...childTypes]
198
+ ).first<{ n: number }>();
199
+ return row?.n ?? 0;
200
+ }
201
+
202
+ /** The columns of `entries`, with SQLite's `hidden` flag (2 and 3 are generated columns). */
203
+ export async function entryColumns(db: D1Database): Promise<{ name: string; hidden: number }[]> {
204
+ const result = await db.prepare('PRAGMA table_xinfo(entries)').all<{ name: string; hidden: number }>();
205
+ return (result.results ?? []).map(r => ({ name: r.name, hidden: r.hidden }));
206
+ }
207
+
208
+ // ── Assets ───────────────────────────────────────────────────────────
209
+
210
+ export interface AssetRow {
211
+ id: string;
212
+ owner_id: string | null;
213
+ data: Record<string, unknown>;
214
+ created_at: string;
215
+ updated_at: string;
216
+ }
217
+
218
+ const ASSET_SELECT = 'SELECT id, owner_id, data, created_at, updated_at FROM assets';
219
+
220
+ const toAsset = (r: { id: string; owner_id: string | null; data: string; created_at: string; updated_at: string }): AssetRow => ({
221
+ ...r,
222
+ data: JSON.parse(r.data) as Record<string, unknown>
223
+ });
224
+
225
+ export async function selectAssets(db: D1Database, access: Sql, id?: string): Promise<AssetRow[]> {
226
+ const result = await bind(db, `${ASSET_SELECT} WHERE ${access.sql}${id === undefined ? '' : ' AND id = ?'} ORDER BY created_at DESC, id`, [
227
+ ...access.params,
228
+ ...(id === undefined ? [] : [id])
229
+ ]).all<Parameters<typeof toAsset>[0]>();
230
+ return (result.results ?? []).map(toAsset);
231
+ }
232
+
233
+ export function insertAsset(db: D1Database, row: { id: string; owner_id: string | null; data: Record<string, unknown> }): D1PreparedStatement {
234
+ return bind(db, 'INSERT INTO assets (id, owner_id, data) VALUES (?, ?, ?)', [row.id, row.owner_id, JSON.stringify(row.data)]);
235
+ }
236
+
237
+ export function deleteAsset(db: D1Database, id: string, access: Sql): D1PreparedStatement {
238
+ return bind(db, `DELETE FROM assets WHERE id = ? AND ${access.sql}`, [id, ...access.params]);
239
+ }
@@ -0,0 +1,100 @@
1
+ /** The shapes the store takes and gives. Types only, so config and the store may name each other. */
2
+ import type { Operation } from '../errors.ts';
3
+ import type { Where } from '../access/where.ts';
4
+ import type { Principal, HostPrincipal } from '../principal.ts';
5
+
6
+ export type Status = 'draft' | 'published';
7
+
8
+ /** One entry. The built-in columns keep their column names, the type's own fields are in `data`. */
9
+ export interface Entry<D = Record<string, unknown>> {
10
+ id: string;
11
+ type: string;
12
+ owner_id: string | null;
13
+ slug: string | null;
14
+ status: Status;
15
+ parent_id: string | null;
16
+ sort_key: string | null;
17
+ /** The parent's status, for a type that mirrors it; null otherwise. */
18
+ parent_status: Status | null;
19
+ created_at: string;
20
+ updated_at: string;
21
+ data: D;
22
+ }
23
+
24
+ export type OrderBy = 'created_at' | 'updated_at' | 'sort_key' | 'slug';
25
+
26
+ export interface ListOptions {
27
+ /** More conditions, ANDed to what the caller's rules allow (equals, `in`, `and`, `or` over built-in and indexed fields). */
28
+ where?: Where;
29
+ orderBy?: OrderBy;
30
+ direction?: 'asc' | 'desc';
31
+ /** At most 1000; 100 when absent. */
32
+ limit?: number;
33
+ offset?: number;
34
+ }
35
+
36
+ /** What `create` takes: the type's fields and the built-in `id`, `owner_id`, `slug`, `parent_id` and `sort_key`. */
37
+ export type CreateInput = Record<string, unknown>;
38
+
39
+ /** What `update` takes: the fields to change. `status` is never writable here; `owner_id`, `slug`, `parent_id` and `sort_key` only by a rule that lists them. */
40
+ export type UpdatePatch = Record<string, unknown>;
41
+
42
+ /** A precondition on an entry's current state, checked in the same statement as the write. */
43
+ export type Compare = { equals: unknown } | { lt: number } | { gt: number } | { isNull: boolean };
44
+ export type When = { or: When[] } | { [field: string]: Compare };
45
+
46
+ /** One entry's patch in an `updateEach`: the same fields an `update` takes. */
47
+ export interface UpdateEachChange {
48
+ id: string;
49
+ patch: UpdatePatch;
50
+ }
51
+
52
+ export interface WriteOptions {
53
+ when?: When;
54
+ /** Fields to set in the same statement as a publish or unpublish; only those the publish grant lists. */
55
+ set?: UpdatePatch;
56
+ }
57
+
58
+ export type UpdateResult<D = Record<string, unknown>> =
59
+ | { applied: true; entry: Entry<D> }
60
+ | { applied: false; reason: 'precondition' };
61
+
62
+ /** A type given by id or by the object `contentType` returned. */
63
+ export type TypeRef = string | { readonly id: string };
64
+
65
+ export interface ContentApi {
66
+ list<D = Record<string, unknown>>(type: TypeRef, options?: ListOptions): Promise<Entry<D>[]>;
67
+ /** The entry, or null when it does not exist or the caller may not read it. */
68
+ get<D = Record<string, unknown>>(type: TypeRef, id: string): Promise<Entry<D> | null>;
69
+ getBySlug<D = Record<string, unknown>>(type: TypeRef, slug: string): Promise<Entry<D> | null>;
70
+ create<D = Record<string, unknown>>(type: TypeRef, input: CreateInput): Promise<Entry<D>>;
71
+ update<D = Record<string, unknown>>(type: TypeRef, id: string, patch: UpdatePatch, options?: { when?: When }): Promise<UpdateResult<D>>;
72
+ /**
73
+ * Several entries of one type updated in one write, all or nothing: every row must be one the caller may update, each
74
+ * patch meets the rules `update` applies, and the hooks run per row. Returns the entries as written, in the order given.
75
+ * More entries than the host's limit (500 by default) are refused with `TooManyEntries`.
76
+ */
77
+ updateEach<D = Record<string, unknown>>(type: TypeRef, changes: UpdateEachChange[]): Promise<Entry<D>[]>;
78
+ remove(type: TypeRef, id: string): Promise<void>;
79
+ publish<D = Record<string, unknown>>(type: TypeRef, id: string, options?: WriteOptions): Promise<UpdateResult<D>>;
80
+ unpublish<D = Record<string, unknown>>(type: TypeRef, id: string, options?: WriteOptions): Promise<UpdateResult<D>>;
81
+ }
82
+
83
+ /** What a hook is told. `principal` is the caller; `content` is the store, as that same caller. */
84
+ export interface WriteContext<P = Principal<HostPrincipal>> {
85
+ operation: Operation | 'unpublish';
86
+ type: string;
87
+ principal: P;
88
+ /** The entry as it is before the write; null for a create. */
89
+ existing: Entry | null;
90
+ /** The fields being written. */
91
+ input: Record<string, unknown>;
92
+ content: ContentApi;
93
+ /** Refuses the write with a message; nothing is stored. */
94
+ refuse(message: string): never;
95
+ }
96
+
97
+ export interface AfterWriteContext<P = Principal<HostPrincipal>> extends Omit<WriteContext<P>, 'refuse'> {
98
+ /** The entry as written; null after a remove. */
99
+ entry: Entry | null;
100
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The policy test helper. A host lists its sample callers and what each should
3
+ * be able to do on each type; the helper asserts every operation on every type
4
+ * (an operation not listed must be denied) and that the rules packed for display
5
+ * agree with what the engine enforces. It uses no test framework: it throws
6
+ * `PolicyMismatch`, which any runner reports with the message.
7
+ */
8
+ import { RuleSet } from '../access/ability.ts';
9
+ import { OPERATIONS, runAccess } from '../access/can.ts';
10
+ import { permits, type PackedRules } from '../access/permits.ts';
11
+ import type { Operation } from '../errors.ts';
12
+ import type { HostPrincipal, Principal } from '../principal.ts';
13
+ import type { Cms } from '../store/cms.ts';
14
+
15
+ /** The operations a caller has on a type (on at least one row), or a map where a missing operation is denied. */
16
+ export type Expectation = readonly (Operation | 'lookup')[] | Partial<Record<Operation | 'lookup', boolean>>;
17
+
18
+ export interface PolicyMatrixOptions<H extends HostPrincipal = never> {
19
+ cms: Cms<H>;
20
+ /** Sample callers by name. */
21
+ callers: Record<string, Principal<H>>;
22
+ /** For each caller, for each type: what it may do. A caller or type left out may do nothing. `lookup` is a read by slug. */
23
+ expect: Record<string, Record<string, Expectation>>;
24
+ /**
25
+ * Sample rows per type, as the rules see a row (the built-in columns and the indexed fields), to check that the
26
+ * packed rules and the engine give the same answer row by row.
27
+ */
28
+ rows?: Record<string, Record<string, unknown>[]>;
29
+ /** The packed rules to test against enforcement; `cms.access.rulesFor` when absent. */
30
+ rules?: (principal: Principal<H>) => PackedRules;
31
+ }
32
+
33
+ export class PolicyMismatch extends Error {
34
+ override readonly name = 'PolicyMismatch';
35
+ constructor(readonly failures: string[]) {
36
+ super(`${failures.length} policy mismatch${failures.length === 1 ? '' : 'es'}:\n${failures.map(f => ` ${f}`).join('\n')}`);
37
+ }
38
+ }
39
+
40
+ const ALL: readonly (Operation | 'lookup')[] = [...OPERATIONS, 'lookup'];
41
+
42
+ function wanted(expectation: Expectation | undefined, operation: Operation | 'lookup'): boolean {
43
+ if (expectation === undefined) return false;
44
+ if (Array.isArray(expectation)) return (expectation as readonly string[]).includes(operation);
45
+ return (expectation as Partial<Record<string, boolean>>)[operation] === true;
46
+ }
47
+
48
+ export function policyMatrix<H extends HostPrincipal = never>(options: PolicyMatrixOptions<H>): void {
49
+ const failures: string[] = [];
50
+ for (const [name, principal] of Object.entries(options.callers)) {
51
+ const packed = (options.rules ?? options.cms.access.rulesFor)(principal);
52
+ for (const type of options.cms.types.values()) {
53
+ if (type.service) continue;
54
+ const rules = new RuleSet(type.id, type.access ? runAccess(type.access, principal) : []);
55
+ const expectation = options.expect[name]?.[type.id];
56
+ for (const operation of ALL) {
57
+ const enforced = operation === 'lookup' ? rules.has('read') || rules.has('lookup') : rules.has(operation);
58
+ const shown = permits(packed, type.id, operation);
59
+ const expected = wanted(expectation, operation);
60
+ const where = `${name} / ${type.id} / ${operation}`;
61
+ if (enforced !== expected) failures.push(`${where}: expected ${expected ? 'allowed' : 'denied'}, the rules ${enforced ? 'allow' : 'deny'} it`);
62
+ if (shown !== enforced) failures.push(`${where}: the packed rules ${shown ? 'allow' : 'deny'} it, enforcement ${enforced ? 'allows' : 'denies'} it`);
63
+ for (const row of options.rows?.[type.id] ?? []) {
64
+ if (operation === 'lookup') continue;
65
+ const rowEnforced = rules.allows(operation, row);
66
+ const rowShown = permits(packed, type.id, operation, row);
67
+ if (rowEnforced !== rowShown) {
68
+ failures.push(`${where} on row ${JSON.stringify(row)}: the packed rules ${rowShown ? 'allow' : 'deny'} it, enforcement ${rowEnforced ? 'allows' : 'denies'} it`);
69
+ }
70
+ }
71
+ }
72
+ }
73
+ }
74
+ if (failures.length > 0) throw new PolicyMismatch(failures);
75
+ }
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `cogens-print-migration <config file>`: prints the SQL the config's indexed fields need (see `index.ts`).
4
+ *
5
+ * The config's default export is `{ contentTypes }` (what `defineConfig` returns). Under Bun any config file
6
+ * loads, `.ts` included (`bunx cogens-print-migration site.config.ts`). Under Node the file is imported as
7
+ * is: `.js` and `.mjs` always work, and a `.ts` config only on a Node that strips types (22.18 or later,
8
+ * 24 and up) when the config's own imports are plain relative `.ts` or package imports.
9
+ */
10
+ import { pathToFileURL } from 'node:url';
11
+ import { resolve } from 'node:path';
12
+ import type { ContentType } from '../core/config/define.ts';
13
+ import { migrationLines } from './index.ts';
14
+
15
+ // The declaration keeps this file free of Node's types, which a Worker build does not have.
16
+ declare const process: { argv: string[]; cwd(): string; exitCode?: number };
17
+
18
+ const path = process.argv[2];
19
+ if (!path) {
20
+ console.error('Usage: cogens-print-migration <config file>');
21
+ process.exitCode = 1;
22
+ } else {
23
+ try {
24
+ const module = await import(pathToFileURL(resolve(process.cwd(), path)).href);
25
+ const config = module.default as { contentTypes?: ContentType<any>[] } | undefined;
26
+ if (!config || !Array.isArray(config.contentTypes)) {
27
+ throw new Error(`${path} must default-export { contentTypes } (what defineConfig returns).`);
28
+ }
29
+ console.log(migrationLines(config.contentTypes).join('\n'));
30
+ } catch (error) {
31
+ console.error(error instanceof Error ? error.message : String(error));
32
+ process.exitCode = 1;
33
+ }
34
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * `cogens/migrations-tool`: the SQL a config's content types need in `entries`: a virtual generated
3
+ * column and an index for each indexed field, and a unique index on the slug for
4
+ * the types that ask for one. The host's own migration holds these lines and startup checks the columns exist.
5
+ *
6
+ * `cogens-print-migration <config>` (bin.ts) prints them for a config file:
7
+ *
8
+ * bunx cogens-print-migration site.config.ts
9
+ * npx cogens-print-migration site.config.mjs
10
+ *
11
+ * The config file's default export is `{ contentTypes }` (what `defineConfig` returns).
12
+ */
13
+ import type { ContentType } from '../core/config/define.ts';
14
+ import { indexedColumn } from '../core/columns.ts';
15
+
16
+ /** `ALTER TABLE ... ADD COLUMN` allows only VIRTUAL generated columns; SQLite can index them. */
17
+ export function migrationLines(types: readonly ContentType<any>[]): string[] {
18
+ const lines: string[] = [];
19
+ const done = new Set<string>();
20
+ for (const type of types) {
21
+ if (type.service) continue;
22
+ for (const field of type.indexed) {
23
+ const column = indexedColumn(field);
24
+ if (done.has(column)) continue;
25
+ done.add(column);
26
+ lines.push(`ALTER TABLE entries ADD COLUMN ${column} GENERATED ALWAYS AS (json_extract(data, '$.${field}')) VIRTUAL;`);
27
+ lines.push(`CREATE INDEX IF NOT EXISTS idx_entries_${column} ON entries(content_type, ${column});`);
28
+ }
29
+ }
30
+ const unique = types.filter(t => !t.service && t.uniqueSlug).map(t => `'${t.id}'`);
31
+ if (unique.length > 0) {
32
+ lines.push(
33
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_slug ON entries(content_type, slug) WHERE slug IS NOT NULL AND content_type IN (${unique.join(', ')});`
34
+ );
35
+ }
36
+ return lines;
37
+ }
@@ -0,0 +1,53 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+
4
+ export interface TestDbOptions {
5
+ /** The host's own SQL files (paths, relative to the working directory), applied in order after the package's. */
6
+ migrations?: string[];
7
+ }
8
+
9
+ export interface TestDb {
10
+ db: D1Database;
11
+ r2: R2Bucket;
12
+ dispose(): Promise<void>;
13
+ }
14
+
15
+ /** The package's own migrations, in the order a host applies them. */
16
+ const PACKAGE_MIGRATIONS = ['0001_entries.sql', 'auth/0001_sessions.sql'];
17
+
18
+ /** The statements of a SQL file with `--` comment lines dropped. */
19
+ function statements(path: string | URL): string[] {
20
+ const text = readFileSync(path, 'utf8')
21
+ .split('\n')
22
+ .filter(line => !line.trim().startsWith('--'))
23
+ .join('\n');
24
+ return text.split(';').map(s => s.trim()).filter(Boolean);
25
+ }
26
+
27
+ /**
28
+ * A Miniflare D1 (`db`) and R2 bucket (`r2`) with the package's migrations applied, then each file of
29
+ * `options.migrations` (the host's columns, indexes and tables). Call `dispose()` when the test is done.
30
+ * Needs `miniflare` installed in the host (`bun add -d miniflare`).
31
+ */
32
+ export async function createTestDb(options: TestDbOptions = {}): Promise<TestDb> {
33
+ const { Miniflare } = await import('miniflare');
34
+ const mf = new Miniflare({
35
+ modules: true,
36
+ script: 'export default {}',
37
+ d1Databases: { DB: 'cogens-test-db' },
38
+ r2Buckets: { FILES: 'cogens-test-files' }
39
+ });
40
+ const db = (await mf.getD1Database('DB')) as unknown as D1Database;
41
+ const r2 = (await mf.getR2Bucket('FILES')) as unknown as R2Bucket;
42
+ const files = [
43
+ ...PACKAGE_MIGRATIONS.map(f => new URL(`../../migrations/${f}`, import.meta.url)),
44
+ ...(options.migrations ?? []).map(f => resolve(process.cwd(), f))
45
+ ];
46
+ try {
47
+ for (const file of files) for (const statement of statements(file)) await db.prepare(statement).run();
48
+ } catch (error) {
49
+ await mf.dispose();
50
+ throw error;
51
+ }
52
+ return { db, r2, dispose: () => mf.dispose() };
53
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `cogens/testing`: the policy test helper (`policyMatrix`, which uses no test framework) and `createTestDb`, a
3
+ * Miniflare D1 with the package's migrations and the host's own applied. Miniflare is an optional peer dependency,
4
+ * imported only when `createTestDb` runs; the Worker and core never import this folder.
5
+ */
6
+ export { policyMatrix, PolicyMismatch } from '../core/testing/index.ts';
7
+ export type { PolicyMatrixOptions, Expectation } from '../core/testing/index.ts';
8
+ export { createTestDb } from './db.ts';
9
+ export type { TestDb, TestDbOptions } from './db.ts';