@kidecms/core 0.1.10 → 0.13.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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/admin/components/AssetsGrid.tsx +366 -173
  3. package/admin/components/BlockEditor.tsx +260 -679
  4. package/admin/components/CheckboxField.tsx +2 -2
  5. package/admin/components/CollaborationReviewBar.tsx +384 -0
  6. package/admin/components/ColorField.tsx +87 -0
  7. package/admin/components/CommandPalette.tsx +169 -0
  8. package/admin/components/ContentEditor.tsx +687 -0
  9. package/admin/components/DocumentActions.tsx +4 -2
  10. package/admin/components/DocumentsDataTable.tsx +91 -10
  11. package/admin/components/FieldControl.astro +151 -26
  12. package/admin/components/FocalPointSelector.tsx +27 -1
  13. package/admin/components/InternalLinkPicker.tsx +4 -3
  14. package/admin/components/LinkField.tsx +126 -0
  15. package/admin/components/RelationField.tsx +105 -26
  16. package/admin/components/RepeaterInput.tsx +46 -0
  17. package/admin/components/RichTextEditor.tsx +44 -9
  18. package/admin/components/SharedSectionBlockField.tsx +93 -0
  19. package/admin/components/SidebarUserMenu.tsx +1 -1
  20. package/admin/components/Toast.astro +1 -1
  21. package/admin/components/TreeItemsEditor.tsx +20 -19
  22. package/admin/components/TreeSelect.tsx +2 -2
  23. package/admin/components/YoutubeField.tsx +48 -0
  24. package/admin/components/block-fields.tsx +777 -0
  25. package/admin/components/content-block-spec.ts +114 -0
  26. package/admin/components/slash-command.tsx +242 -0
  27. package/admin/components/tree-utils.ts +14 -2
  28. package/admin/components/ui/badge.tsx +2 -3
  29. package/admin/components/ui/button.tsx +5 -4
  30. package/admin/components/ui/checkbox.tsx +1 -1
  31. package/admin/components/ui/input.tsx +1 -1
  32. package/admin/components/ui/select.tsx +1 -1
  33. package/admin/components/ui/table.tsx +1 -1
  34. package/admin/components/ui/textarea.tsx +1 -1
  35. package/admin/layouts/AdminLayout.astro +323 -123
  36. package/admin/lib/access.ts +54 -0
  37. package/admin/lib/collaboration.ts +178 -0
  38. package/admin/lib/edit-data.ts +448 -0
  39. package/admin/views/AccessDeniedView.astro +8 -0
  40. package/admin/views/EditView.astro +706 -0
  41. package/admin/views/ListView.astro +202 -0
  42. package/admin/views/RecentView.astro +76 -0
  43. package/admin/views/SinglesView.astro +65 -0
  44. package/admin/views/edit/EditScripts.astro +145 -0
  45. package/admin/views/edit/ReverseReferencesList.astro +68 -0
  46. package/core/admin.ts +193 -0
  47. package/core/ai.ts +87 -0
  48. package/core/api.ts +1392 -0
  49. package/core/assets.ts +336 -0
  50. package/core/audit.ts +84 -0
  51. package/core/auth-config.ts +44 -0
  52. package/core/auth.ts +303 -0
  53. package/core/collaboration.ts +276 -0
  54. package/core/content.ts +27 -0
  55. package/core/create-admin.ts +28 -0
  56. package/core/define.ts +625 -0
  57. package/core/field-model.ts +172 -0
  58. package/core/generator.ts +519 -0
  59. package/core/http.ts +42 -0
  60. package/core/image.ts +219 -0
  61. package/core/index.ts +211 -0
  62. package/core/locks.ts +52 -0
  63. package/core/log.ts +37 -0
  64. package/core/migrate.ts +278 -0
  65. package/core/rate-limit.ts +110 -0
  66. package/core/request-scope.ts +33 -0
  67. package/core/richtext.ts +1 -0
  68. package/core/runtime.ts +63 -0
  69. package/core/schema.ts +32 -0
  70. package/core/search.ts +489 -0
  71. package/core/seed.ts +101 -0
  72. package/core/shared-sections.ts +96 -0
  73. package/core/tasks.ts +176 -0
  74. package/core/values.ts +433 -0
  75. package/core/webhooks.ts +85 -0
  76. package/core/youtube.ts +39 -0
  77. package/internals/cli.mjs +34 -0
  78. package/internals/context.ts +67 -0
  79. package/internals/create-admin.ts +40 -0
  80. package/internals/describe.ts +25 -0
  81. package/internals/eject.ts +144 -0
  82. package/internals/generator.ts +11 -0
  83. package/internals/integration.ts +481 -0
  84. package/internals/mcp.ts +397 -0
  85. package/internals/project.ts +26 -0
  86. package/internals/push.ts +160 -0
  87. package/internals/reindex.ts +11 -0
  88. package/internals/restore.ts +257 -0
  89. package/internals/seed.data.ts +7 -0
  90. package/internals/seed.ts +11 -0
  91. package/internals/upgrade.ts +776 -0
  92. package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
  93. package/middleware/auth.ts +130 -17
  94. package/middleware/push.ts +121 -0
  95. package/package.json +55 -67
  96. package/platform/cloudflare/cf-env.ts +60 -0
  97. package/platform/cloudflare/database.ts +28 -0
  98. package/platform/cloudflare/globals.d.ts +5 -0
  99. package/platform/cloudflare/storage.ts +33 -0
  100. package/platform/cloudflare/uploads-route.ts +37 -0
  101. package/platform/node/database.ts +39 -0
  102. package/platform/node/storage.ts +52 -0
  103. package/routes/admin/[...path].astro +71 -0
  104. package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
  105. package/routes/admin/assets/index.astro +90 -0
  106. package/routes/admin/forgot-password.astro +60 -0
  107. package/routes/{pages/admin → admin}/invite.astro +7 -6
  108. package/routes/admin/login.astro +103 -0
  109. package/routes/admin/reset-password.astro +73 -0
  110. package/routes/{pages/admin → admin}/setup.astro +32 -8
  111. package/routes/api/{cms/[collection] → [collection]}/[...path].ts +66 -14
  112. package/routes/api/admin/search.ts +89 -0
  113. package/routes/api/{cms/assets → assets}/[id].ts +24 -14
  114. package/routes/api/{cms/assets → assets}/index.ts +4 -2
  115. package/routes/api/assets/upload.ts +147 -0
  116. package/routes/api/auth/forgot-password.ts +77 -0
  117. package/routes/api/{cms/auth → auth}/invite.ts +41 -9
  118. package/routes/api/auth/login.ts +167 -0
  119. package/routes/api/{cms/auth → auth}/logout.ts +11 -2
  120. package/routes/api/auth/reset-password.ts +85 -0
  121. package/routes/api/auth/setup.ts +110 -0
  122. package/routes/api/auth/sso/[provider]/start.ts +34 -0
  123. package/routes/api/collaboration/index.ts +106 -0
  124. package/routes/api/cron/_authorize.ts +25 -0
  125. package/routes/api/{cms/cron → cron}/publish.ts +3 -9
  126. package/routes/api/cron/tasks.ts +33 -0
  127. package/routes/api/forms/submit/[slug].ts +143 -0
  128. package/routes/api/img/[...path].ts +65 -0
  129. package/routes/api/{cms/preview → preview}/render.ts +8 -3
  130. package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
  131. package/routes/api/webhooks/[provider].ts +54 -0
  132. package/README.md +0 -28
  133. package/dist/admin.d.ts +0 -33
  134. package/dist/admin.js +0 -92
  135. package/dist/ai.d.ts +0 -15
  136. package/dist/ai.js +0 -70
  137. package/dist/api.d.ts +0 -14
  138. package/dist/api.js +0 -833
  139. package/dist/assets.d.ts +0 -51
  140. package/dist/assets.js +0 -163
  141. package/dist/auth.d.ts +0 -30
  142. package/dist/auth.js +0 -132
  143. package/dist/content.d.ts +0 -3
  144. package/dist/content.js +0 -29
  145. package/dist/create-admin.d.ts +0 -5
  146. package/dist/create-admin.js +0 -23
  147. package/dist/define.d.ts +0 -254
  148. package/dist/define.js +0 -36
  149. package/dist/generator.d.ts +0 -9
  150. package/dist/generator.js +0 -370
  151. package/dist/image.d.ts +0 -9
  152. package/dist/image.js +0 -69
  153. package/dist/index.d.ts +0 -28
  154. package/dist/index.js +0 -16
  155. package/dist/integration.d.ts +0 -14
  156. package/dist/integration.js +0 -327
  157. package/dist/locks.d.ts +0 -7
  158. package/dist/locks.js +0 -37
  159. package/dist/richtext.d.ts +0 -1
  160. package/dist/richtext.js +0 -1
  161. package/dist/runtime.d.ts +0 -24
  162. package/dist/runtime.js +0 -26
  163. package/dist/schema.d.ts +0 -17
  164. package/dist/schema.js +0 -13
  165. package/dist/seed.d.ts +0 -2
  166. package/dist/seed.js +0 -84
  167. package/dist/values.d.ts +0 -8
  168. package/dist/values.js +0 -102
  169. package/dist/webhooks.d.ts +0 -2
  170. package/dist/webhooks.js +0 -73
  171. package/routes/api/cms/assets/upload.ts +0 -112
  172. package/routes/api/cms/auth/login.ts +0 -124
  173. package/routes/api/cms/auth/setup.ts +0 -77
  174. package/routes/api/cms/img/[...path].ts +0 -24
  175. package/routes/pages/admin/[...path].astro +0 -1107
  176. package/routes/pages/admin/assets/index.astro +0 -63
  177. package/routes/pages/admin/login.astro +0 -57
  178. /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
  179. /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
  180. /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
  181. /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
  182. /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
package/core/define.ts ADDED
@@ -0,0 +1,625 @@
1
+ export type CollectionLabels = {
2
+ singular: string;
3
+ plural: string;
4
+ };
5
+
6
+ export type DatabaseConfig = {
7
+ dialect: "sqlite" | "postgres";
8
+ url?: string;
9
+ };
10
+
11
+ export type LocaleConfig = {
12
+ default: string;
13
+ supported: string[];
14
+ };
15
+
16
+ export type AdminFieldComponent = {
17
+ component?: string;
18
+ placeholder?: string;
19
+ position?: "content" | "sidebar";
20
+ rows?: number;
21
+ help?: string;
22
+ hidden?: boolean;
23
+ /**
24
+ * Titled section in the edit form: consecutive fields sharing a group render
25
+ * inside one framed panel. The object form makes the panel collapsible —
26
+ * `collapsible: true` starts open, `"collapsed"` starts closed. Fields in
27
+ * the same run may mix forms; the first collapsible declaration wins.
28
+ */
29
+ group?: string | { label: string; collapsible?: boolean | "collapsed" };
30
+ /** Per-field colour palette for `fields.color()`; overrides the global `admin.colors`. */
31
+ colors?: ColorOption[];
32
+ };
33
+
34
+ export type FieldCondition = {
35
+ field: string;
36
+ value: string | string[] | boolean;
37
+ };
38
+
39
+ type BaseFieldConfig<TType extends string, TValue = unknown> = {
40
+ type: TType;
41
+ label?: string;
42
+ description?: string;
43
+ required?: boolean;
44
+ defaultValue?: TValue;
45
+ indexed?: boolean;
46
+ unique?: boolean;
47
+ translatable?: boolean;
48
+ condition?: FieldCondition;
49
+ admin?: AdminFieldComponent;
50
+ access?: {
51
+ read?: (context: {
52
+ user?: { id: string; role?: string; email?: string } | null;
53
+ doc?: Record<string, unknown> | null;
54
+ operation: string;
55
+ collection: string;
56
+ }) => boolean | Promise<boolean>;
57
+ update?: (context: {
58
+ user?: { id: string; role?: string; email?: string } | null;
59
+ doc?: Record<string, unknown> | null;
60
+ operation: string;
61
+ collection: string;
62
+ }) => boolean | Promise<boolean>;
63
+ };
64
+ };
65
+
66
+ export type TextFieldConfig = BaseFieldConfig<"text", string> & {
67
+ maxLength?: number;
68
+ };
69
+
70
+ export type SlugFieldConfig = BaseFieldConfig<"slug", string> & {
71
+ from?: string;
72
+ };
73
+
74
+ export type EmailFieldConfig = BaseFieldConfig<"email", string>;
75
+ export type NumberFieldConfig = BaseFieldConfig<"number", number>;
76
+ export type BooleanFieldConfig = BaseFieldConfig<"boolean", boolean>;
77
+ export type DateFieldConfig = BaseFieldConfig<"date", string>;
78
+
79
+ export type SelectFieldConfig = BaseFieldConfig<"select", string> & {
80
+ options: string[];
81
+ };
82
+
83
+ export type RichTextNode = {
84
+ type: string;
85
+ value?: string;
86
+ level?: number;
87
+ children?: RichTextNode[];
88
+ [key: string]: unknown;
89
+ };
90
+
91
+ export type RichTextDocument = {
92
+ type: "root";
93
+ children: RichTextNode[];
94
+ };
95
+
96
+ export type RichTextFieldConfig = BaseFieldConfig<"richText", RichTextDocument>;
97
+ export type ImageFieldConfig = BaseFieldConfig<"image", string>;
98
+
99
+ /**
100
+ * An embedded component block inside a `content` field. Shares the same shape as
101
+ * a `blocks` entry but lives inline in the rich-text stream, identified by `blockType`.
102
+ */
103
+ export type ContentBlockNode = {
104
+ type: "block";
105
+ blockType: string;
106
+ fields: Record<string, unknown>;
107
+ [key: string]: unknown;
108
+ };
109
+
110
+ export type ContentNode = RichTextNode | ContentBlockNode;
111
+
112
+ /**
113
+ * Storage shape for a `content` field: a rich-text document whose children may
114
+ * also include inline component blocks. Compatible with RichTextDocument — plain
115
+ * rich-text renderers simply skip the `block` nodes.
116
+ */
117
+ export type ContentDocument = {
118
+ type: "root";
119
+ children: ContentNode[];
120
+ };
121
+
122
+ export type ContentFieldConfig = BaseFieldConfig<"content", ContentDocument> & {
123
+ /** Component block types that can be embedded inline, same shape as `blocks`. Omit for pure rich text. */
124
+ blocks?: Record<string, Record<string, FieldConfig>>;
125
+ /**
126
+ * Show a button that expands the editor into a distraction-free fullscreen
127
+ * overlay (hides the sidemenu and every other field). Defaults to true; set
128
+ * `false` to hide the button.
129
+ */
130
+ fullscreen?: boolean;
131
+ };
132
+
133
+ export type RelationFieldConfig = BaseFieldConfig<"relation", string | string[]> & {
134
+ collection: string;
135
+ hasMany?: boolean;
136
+ /** Maximum number of selected documents (hasMany only) — enforced on save and in the admin picker. */
137
+ maxItems?: number;
138
+ };
139
+
140
+ export type ArrayFieldConfig = BaseFieldConfig<"array", unknown[]> & {
141
+ of: FieldConfig;
142
+ /** Maximum number of items — enforced on save. */
143
+ maxItems?: number;
144
+ };
145
+
146
+ export type JsonFieldConfig = BaseFieldConfig<"json", unknown> & {
147
+ schema?: string;
148
+ /**
149
+ * Typed repeater rows. When set together with `admin.component: "repeater"`,
150
+ * the block editor renders each array item as these named sub-fields (text,
151
+ * select, boolean, image, richText, …) instead of a flat string row. The
152
+ * value is stored as an array of objects keyed by these field names.
153
+ */
154
+ itemFields?: Record<string, FieldConfig>;
155
+ /** Maximum number of items when the value is an array (e.g. repeater rows) — enforced on save. */
156
+ maxItems?: number;
157
+ };
158
+
159
+ export type BlocksFieldConfig = BaseFieldConfig<"blocks", Array<Record<string, unknown>>> & {
160
+ types: Record<string, Record<string, FieldConfig>>;
161
+ /** Allow this block field to insert shared section references. Defaults to true. */
162
+ shared?: boolean;
163
+ };
164
+
165
+ export type FieldConfig =
166
+ | TextFieldConfig
167
+ | SlugFieldConfig
168
+ | EmailFieldConfig
169
+ | NumberFieldConfig
170
+ | BooleanFieldConfig
171
+ | DateFieldConfig
172
+ | SelectFieldConfig
173
+ | RichTextFieldConfig
174
+ | ContentFieldConfig
175
+ | ImageFieldConfig
176
+ | RelationFieldConfig
177
+ | ArrayFieldConfig
178
+ | JsonFieldConfig
179
+ | BlocksFieldConfig;
180
+
181
+ export type CollectionFieldMap = Record<string, FieldConfig>;
182
+ export type SeedDocument = Record<string, unknown>;
183
+
184
+ export type CollectionViewConfig = {
185
+ list?: {
186
+ columns?: string[];
187
+ defaultSort?: { field: string; direction: "asc" | "desc" };
188
+ };
189
+ };
190
+
191
+ export type CollectionAdminConfig = {
192
+ /** Sidebar group label. Built-ins include Content, Library, and Team. */
193
+ group?: string;
194
+ /** Hide from the sidebar while keeping the collection available to APIs and relations. */
195
+ sidebar?: boolean;
196
+ /** Lucide icon name used in the sidebar. */
197
+ icon?: string;
198
+ /** Sort order inside the sidebar group. Lower values appear first. */
199
+ weight?: number;
200
+ };
201
+
202
+ export type SearchableConfig = boolean | { fields: string[] };
203
+
204
+ export type CollectionConfig = {
205
+ slug: string;
206
+ labels: CollectionLabels;
207
+ labelField?: string;
208
+ pathPrefix?: string;
209
+ preview?: boolean | string;
210
+ timestamps?: boolean;
211
+ drafts?: boolean;
212
+ versions?: { max: number };
213
+ auth?: boolean;
214
+ singleton?: boolean;
215
+ searchable?: SearchableConfig;
216
+ access?: CollectionAccess;
217
+ hooks?: CollectionHooks;
218
+ fields: CollectionFieldMap;
219
+ views?: CollectionViewConfig;
220
+ admin?: CollectionAdminConfig;
221
+ seed?: SeedDocument[];
222
+ };
223
+
224
+ export type AdminNavItem = {
225
+ label: string;
226
+ href: string;
227
+ icon?: string;
228
+ /** Sort order — lower values appear first (default: 0) */
229
+ weight?: number;
230
+ };
231
+
232
+ export type WebhookEvent = "create" | "update" | "delete" | "publish" | "unpublish";
233
+
234
+ export type WebhookContext = {
235
+ user?: { id: string; role?: string; email?: string } | null;
236
+ event: WebhookEvent;
237
+ collection: string;
238
+ timestamp: string;
239
+ };
240
+
241
+ export type WebhookConfig = {
242
+ /** Shown in logs, and used to route durable deliveries back to this config — must be unique. */
243
+ name: string;
244
+ /** URL to POST to */
245
+ url: string;
246
+ /** Events that trigger this webhook */
247
+ events: WebhookEvent[];
248
+ /** Restrict to specific collections (omit for all) */
249
+ collections?: string[];
250
+ /** HTTP method (default: POST) */
251
+ method?: "POST" | "PUT" | "PATCH";
252
+ /** Custom headers */
253
+ headers?: Record<string, string>;
254
+ /** Transform the payload (default: { event, collection, doc, user, timestamp }) */
255
+ payload?: (doc: Record<string, unknown>, context: WebhookContext) => any;
256
+ };
257
+
258
+ /** Durable task handler. Throw to retry with backoff; return to complete. */
259
+ export type TaskHandler = (payload: unknown, context: { config: CMSConfig }) => void | Promise<void>;
260
+
261
+ export type TaskScheduleConfig = {
262
+ /** Task type to enqueue — must have a handler in `integrations.tasks`. */
263
+ task: string;
264
+ /** Payload passed to the handler; also part of the schedule's identity. */
265
+ payload?: unknown;
266
+ /** Minimum minutes between runs, evaluated on each cron tick. */
267
+ everyMinutes: number;
268
+ };
269
+
270
+ export type IntegrationsConfig = {
271
+ /**
272
+ * Handlers for durable background tasks (cms_outbox), keyed by task type.
273
+ * Inbound webhooks arrive as `webhook.<provider>` tasks. Delivery is
274
+ * at-least-once — handlers must tolerate re-runs.
275
+ */
276
+ tasks?: Record<string, TaskHandler>;
277
+ /** Recurring tasks enqueued by the `/api/cms/cron/tasks` tick. */
278
+ schedules?: TaskScheduleConfig[];
279
+ };
280
+
281
+ export type AdminUploadConfig = {
282
+ /** Allowed MIME types (default: images, PDF, video) */
283
+ allowedTypes?: string[];
284
+ /** Max file size in bytes (default: 50 MB) */
285
+ maxFileSize?: number;
286
+ };
287
+
288
+ export type AdminRateLimitConfig = {
289
+ /** Max login attempts before blocking (default: 5) */
290
+ maxAttempts?: number;
291
+ /** Time window in milliseconds (default: 15 minutes) */
292
+ windowMs?: number;
293
+ };
294
+
295
+ export type AdminAuthPasswordConfig = {
296
+ /** Enable email/password sign-in. Default true. */
297
+ enabled?: boolean;
298
+ /** Enable forgot-password reset flow. Default true for local/better-auth providers. */
299
+ forgotPassword?: boolean;
300
+ /** Require or expose email verification in auth providers that support it. Default false. */
301
+ emailVerification?: boolean;
302
+ };
303
+
304
+ export type AdminAuthMfaConfig = {
305
+ /** Enable authenticator-app TOTP where supported by the auth provider. */
306
+ totp?: boolean;
307
+ /** Enable single-use recovery codes where supported by the auth provider. */
308
+ backupCodes?: boolean;
309
+ /** Enable passkey/WebAuthn sign-in where supported by the auth provider. */
310
+ passkeys?: boolean;
311
+ };
312
+
313
+ export type AdminAuthSsoProviderConfig = {
314
+ /** Stable provider id used in URLs, e.g. "azure" or "okta". */
315
+ id: string;
316
+ /** Human label shown on the login screen. */
317
+ label: string;
318
+ /** Protocol/backend used by the auth provider. */
319
+ type: "oidc" | "saml" | "oauth" | "workos" | "custom";
320
+ /** OIDC issuer/discovery URL, SAML entity ID, or broker-specific issuer. */
321
+ issuer?: string;
322
+ clientId?: string;
323
+ clientSecret?: string;
324
+ /** Optional explicit authorization URL for custom/broker flows. */
325
+ authorizationUrl?: string;
326
+ /** Optional callback URL override. Defaults to Kide's callback route. */
327
+ callbackUrl?: string;
328
+ scopes?: string[];
329
+ /** Restrict JIT sign-in/provisioning to these email domains. */
330
+ allowedDomains?: string[];
331
+ /** Default Kide role for newly provisioned users. */
332
+ role?: string;
333
+ /** Provider-specific options passed through to the selected auth backend. */
334
+ options?: Record<string, unknown>;
335
+ };
336
+
337
+ export type AdminCustomAuthProvider = {
338
+ kind: "custom";
339
+ getSession: (request: Request) => Promise<Record<string, unknown> | null>;
340
+ loginUrl?: string;
341
+ logoutUrl?: string;
342
+ };
343
+
344
+ export type AdminAuthConfig = {
345
+ /**
346
+ * Auth backend. "local" keeps Kide's built-in session/password flow.
347
+ * "better-auth" is the batteries-included backend for MFA, passkeys, OIDC/SAML,
348
+ * and forgot-password flows. "workos" and "custom" are escape hatches.
349
+ */
350
+ provider?: "local" | "better-auth" | "workos" | AdminCustomAuthProvider;
351
+ password?: AdminAuthPasswordConfig;
352
+ mfa?: AdminAuthMfaConfig;
353
+ sso?: {
354
+ providers?: AdminAuthSsoProviderConfig[];
355
+ };
356
+ workos?: {
357
+ clientId?: string;
358
+ apiKey?: string;
359
+ organizationId?: string;
360
+ defaultRole?: string;
361
+ };
362
+ /** Escape hatch for provider-specific options, e.g. raw Better Auth config. */
363
+ advanced?: Record<string, unknown>;
364
+ };
365
+
366
+ /** A named colour offered by `fields.color()` pickers. */
367
+ export type ColorOption = { label: string; value: string };
368
+
369
+ export type AdminConfig = {
370
+ /** BCP-47 locale for admin date/time display (e.g. "en-US", "en-GB", "fi-FI"). Default "en-US". */
371
+ dateFormat?: string;
372
+ /** IANA time zone for admin date/time display (e.g. "Europe/Helsinki"). Overrides the browser's zone. */
373
+ timeZone?: string;
374
+ /**
375
+ * Overrides for how admin dates/times are rendered, merged over the defaults
376
+ * (numeric date + 2-digit hour/minute). Use e.g. `{ hour12: false }` for 24-hour time,
377
+ * `{ second: "2-digit" }` to show seconds, or `{ hour: undefined, minute: undefined }` for date-only.
378
+ */
379
+ dateTimeFormat?: Intl.DateTimeFormatOptions;
380
+ /**
381
+ * Explicit render pattern; when set it wins over `dateFormat`/`dateTimeFormat`.
382
+ * Tokens: `yyyy yy MM M dd d HH H hh h mm m ss s a`. Wrap literal text in single
383
+ * quotes, e.g. `"d.M.yyyy 'klo' HH:mm"` → `1.7.2026 klo 14:30`. `timeZone` still applies.
384
+ */
385
+ dateTimePattern?: string;
386
+ nav?: AdminNavItem[];
387
+ uploads?: AdminUploadConfig;
388
+ rateLimit?: AdminRateLimitConfig;
389
+ auth?: AdminAuthConfig;
390
+ /** Webhooks fired on content events */
391
+ webhooks?: WebhookConfig[];
392
+ /** Predefined palette offered by every `fields.color()` picker. */
393
+ colors?: ColorOption[];
394
+ };
395
+
396
+ export type ImagePreset = {
397
+ /** Aspect ratio as "W/H" (e.g. "21/9"). Omit for width-only resizing (no crop). */
398
+ aspect?: string;
399
+ /** Candidate widths for srcset (should stay within the pipeline's allowed widths). */
400
+ widths: number[];
401
+ /** Output formats, most-preferred first. Defaults to ["avif", "webp"]. */
402
+ formats?: Array<"webp" | "avif" | "jpeg" | "png">;
403
+ /** Default `sizes` attribute for this rendition. */
404
+ sizes?: string;
405
+ };
406
+
407
+ export type ImagesConfig = {
408
+ /** Named renditions, merged over the built-in defaults in core/image.ts. */
409
+ presets?: Record<string, ImagePreset>;
410
+ };
411
+
412
+ // A collection opts into collaboration by appearing in `collections` — either as a
413
+ // bare slug, or as an object that overrides the group defaults for that collection.
414
+ export type CollaborationCollection = string | { slug: string; requireApproval?: boolean };
415
+
416
+ export type CollaborationConfig = {
417
+ // Default publish gate for the listed collections. When true, publishing a
418
+ // draft-enabled document is blocked until its review is "approved" (approvers
419
+ // bypass). A per-collection entry can override this.
420
+ requireApproval?: boolean;
421
+ // User roles allowed to approve / request changes. Defaults to ["admin"].
422
+ approverRoles?: string[];
423
+ // Which collections get editorial collaboration (review workflow, assignee,
424
+ // comments, activity). Presence in this list is the on switch — a collection
425
+ // absent from it has no review UI, list columns, or gate.
426
+ collections?: CollaborationCollection[];
427
+ };
428
+
429
+ export type ResolvedCollaboration = { enabled: boolean; requireApproval: boolean };
430
+
431
+ // Resolve collaboration settings for a single collection: whether it's enabled,
432
+ // and whether publishing requires approval (per-collection override → group default).
433
+ export const resolveCollaboration = (config: CMSConfig, collectionSlug: string): ResolvedCollaboration => {
434
+ const collab = config.collaboration;
435
+ const entry = collab?.collections?.find((c) => (typeof c === "string" ? c : c.slug) === collectionSlug);
436
+ if (!entry) return { enabled: false, requireApproval: false };
437
+ const override = typeof entry === "object" ? entry.requireApproval : undefined;
438
+ return { enabled: true, requireApproval: override ?? collab?.requireApproval ?? false };
439
+ };
440
+
441
+ // Whether a user role can approve content (approve / request changes) and bypass
442
+ // the publish gate. Defaults to admins only.
443
+ export const isApprover = (config: CMSConfig, role: string | null | undefined): boolean => {
444
+ const roles = config.collaboration?.approverRoles ?? ["admin"];
445
+ return !!role && roles.includes(role);
446
+ };
447
+
448
+ export type CMSConfig = {
449
+ database?: DatabaseConfig;
450
+ locales?: LocaleConfig;
451
+ admin?: AdminConfig;
452
+ images?: ImagesConfig;
453
+ integrations?: IntegrationsConfig;
454
+ collaboration?: CollaborationConfig;
455
+ collections: CollectionConfig[];
456
+ };
457
+
458
+ export type AccessContext = {
459
+ user?: {
460
+ id: string;
461
+ role?: string;
462
+ email?: string;
463
+ [key: string]: unknown;
464
+ } | null;
465
+ doc?: Record<string, unknown> | null;
466
+ operation: string;
467
+ collection: string;
468
+ };
469
+
470
+ export type AccessRule = (context: AccessContext) => boolean | Promise<boolean>;
471
+
472
+ export type CollectionAccess = Partial<
473
+ Record<"read" | "create" | "update" | "delete" | "publish" | "schedule", AccessRule>
474
+ >;
475
+
476
+ export const hasRole =
477
+ (...roles: string[]): AccessRule =>
478
+ ({ user }) =>
479
+ !!user?.role && roles.includes(user.role);
480
+
481
+ export type HookContext = {
482
+ user?: AccessContext["user"];
483
+ operation: string;
484
+ collection: string;
485
+ timestamp: string;
486
+ cache?: {
487
+ invalidate: (opts: { tags: string[] }) => void;
488
+ };
489
+ };
490
+
491
+ export type CollectionHooks = {
492
+ beforeCreate?: (
493
+ data: Record<string, unknown>,
494
+ context: HookContext,
495
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
496
+ afterCreate?: (doc: Record<string, unknown>, context: HookContext) => void | Promise<void>;
497
+ beforeUpdate?: (
498
+ data: Record<string, unknown>,
499
+ existing: Record<string, unknown>,
500
+ context: HookContext,
501
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
502
+ afterUpdate?: (doc: Record<string, unknown>, context: HookContext) => void | Promise<void>;
503
+ /** Runs on `upsertTranslation`, which writes translatable fields directly and does not
504
+ * go through `beforeCreate`/`beforeUpdate` — validate/transform translated field values here. */
505
+ beforeUpsertTranslation?: (
506
+ data: Record<string, unknown>,
507
+ locale: string,
508
+ existing: Record<string, unknown>,
509
+ context: HookContext,
510
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
511
+ beforeDelete?: (doc: Record<string, unknown>, context: HookContext) => void | Promise<void>;
512
+ afterDelete?: (doc: Record<string, unknown>, context: HookContext) => void | Promise<void>;
513
+ beforePublish?: (
514
+ doc: Record<string, unknown>,
515
+ context: HookContext,
516
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
517
+ afterPublish?: (doc: Record<string, unknown>, context: HookContext) => void | Promise<void>;
518
+ beforeUnpublish?: (
519
+ doc: Record<string, unknown>,
520
+ context: HookContext,
521
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
522
+ afterUnpublish?: (doc: Record<string, unknown>, context: HookContext) => void | Promise<void>;
523
+ beforeSchedule?: (
524
+ doc: Record<string, unknown>,
525
+ context: HookContext,
526
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
527
+ afterSchedule?: (doc: Record<string, unknown>, context: HookContext) => void | Promise<void>;
528
+ };
529
+
530
+ const createField = <T extends FieldConfig>(type: T["type"], options?: Omit<T, "type">): T =>
531
+ ({ type, ...(options ?? {}) }) as T;
532
+
533
+ export const fields = {
534
+ text: (options?: Omit<TextFieldConfig, "type">) => createField<TextFieldConfig>("text", options),
535
+ slug: (options?: Omit<SlugFieldConfig, "type">) =>
536
+ // Slugs default to unique: true since they're almost always used as URL identifiers.
537
+ // Pass `unique: false` explicitly to opt out.
538
+ createField<SlugFieldConfig>("slug", { unique: true, ...(options ?? {}) }),
539
+ email: (options?: Omit<EmailFieldConfig, "type">) => createField<EmailFieldConfig>("email", options),
540
+ number: (options?: Omit<NumberFieldConfig, "type">) => createField<NumberFieldConfig>("number", options),
541
+ boolean: (options?: Omit<BooleanFieldConfig, "type">) => createField<BooleanFieldConfig>("boolean", options),
542
+ date: (options?: Omit<DateFieldConfig, "type">) => createField<DateFieldConfig>("date", options),
543
+ select: (options: Omit<SelectFieldConfig, "type">) => createField<SelectFieldConfig>("select", options),
544
+ richText: (options?: Omit<RichTextFieldConfig, "type">) => createField<RichTextFieldConfig>("richText", options),
545
+ content: (options?: Omit<ContentFieldConfig, "type">) => createField<ContentFieldConfig>("content", options),
546
+ image: (options?: Omit<ImageFieldConfig, "type">) => createField<ImageFieldConfig>("image", options),
547
+ /**
548
+ * A palette colour picker. Stored as a hex text string ('' = inherit). Editors choose
549
+ * from `admin.colors` in cms.config.ts, or a per-field `colors` palette passed here.
550
+ */
551
+ color: (options?: Omit<TextFieldConfig, "type"> & { colors?: ColorOption[] }) => {
552
+ const { colors, ...rest } = options ?? {};
553
+ return createField<TextFieldConfig>("text", {
554
+ ...rest,
555
+ admin: { ...(rest.admin ?? {}), component: "color", ...(colors ? { colors } : {}) },
556
+ });
557
+ },
558
+ /** A structured link control. Stored as JSON { type, url, label, newTab }. */
559
+ link: (options?: Omit<JsonFieldConfig, "type">) =>
560
+ createField<JsonFieldConfig>("json", {
561
+ ...(options ?? {}),
562
+ admin: { ...(options?.admin ?? {}), component: "link" },
563
+ }),
564
+ relation: (options: Omit<RelationFieldConfig, "type">) => createField<RelationFieldConfig>("relation", options),
565
+ array: (options: Omit<ArrayFieldConfig, "type">) => createField<ArrayFieldConfig>("array", options),
566
+ json: (options?: Omit<JsonFieldConfig, "type">) => createField<JsonFieldConfig>("json", options),
567
+ blocks: (options: Omit<BlocksFieldConfig, "type">) => createField<BlocksFieldConfig>("blocks", options),
568
+ };
569
+
570
+ export const defineCollection = (collection: CollectionConfig): CollectionConfig => collection;
571
+ export const defineConfig = (config: CMSConfig): CMSConfig => config;
572
+
573
+ export type WithSiteOptions = {
574
+ /** Field name added to the collection. Defaults to "site". */
575
+ field?: string;
576
+ /** Site collection slug. Defaults to "sites". */
577
+ collection?: string;
578
+ /** Whether every document must choose a site. Defaults to true. */
579
+ required?: boolean;
580
+ /** Override admin options for the injected relation field. */
581
+ admin?: AdminFieldComponent;
582
+ };
583
+
584
+ export const withSite = (collection: CollectionConfig, options: WithSiteOptions = {}): CollectionConfig => {
585
+ const fieldName = options.field ?? "site";
586
+
587
+ if (collection.fields[fieldName]) {
588
+ throw new Error(`withSite() cannot add "${fieldName}" to "${collection.slug}" because that field already exists.`);
589
+ }
590
+
591
+ return {
592
+ ...collection,
593
+ fields: {
594
+ [fieldName]: fields.relation({
595
+ collection: options.collection ?? "sites",
596
+ required: options.required ?? true,
597
+ admin: { position: "sidebar", ...(options.admin ?? {}) },
598
+ }),
599
+ ...collection.fields,
600
+ },
601
+ };
602
+ };
603
+
604
+ export const getCollectionMap = (config: CMSConfig) =>
605
+ Object.fromEntries(config.collections.map((collection) => [collection.slug, collection]));
606
+
607
+ export const getDefaultLocale = (config: CMSConfig) => config.locales?.default ?? null;
608
+
609
+ export const getTranslatableFieldNames = (collection: CollectionConfig) =>
610
+ Object.entries(collection.fields)
611
+ .filter(([, field]) => field.translatable)
612
+ .map(([name]) => name);
613
+
614
+ export const isStructuralField = (field: FieldConfig) =>
615
+ ["number", "boolean", "relation", "image", "date"].includes(field.type);
616
+
617
+ export const getCollectionLabel = (collection: CollectionConfig) => collection.labels.plural;
618
+
619
+ export const getLabelField = (collection: CollectionConfig): string => {
620
+ if (collection.labelField && collection.labelField in collection.fields) return collection.labelField;
621
+ if ("title" in collection.fields) return "title";
622
+ if ("name" in collection.fields) return "name";
623
+ const firstTextField = Object.entries(collection.fields).find(([, field]) => field.type === "text");
624
+ return firstTextField ? firstTextField[0] : Object.keys(collection.fields)[0];
625
+ };