@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
@@ -0,0 +1,172 @@
1
+ /**
2
+ * The canonical model of Kide's field types: what each stores, how the admin
3
+ * renders it, and the exact value shape an importer must write. This is the
4
+ * single source of truth behind `kide describe` (the migration manifest) and the
5
+ * import validator — so agents and humans never have to reverse-engineer the
6
+ * admin to learn "what control will this field show / what do I write into it".
7
+ */
8
+ import type { CMSConfig, CollectionConfig, FieldConfig } from "./define";
9
+ import { getLabelField, getTranslatableFieldNames } from "./define";
10
+
11
+ export type FieldModelEntry = {
12
+ /** How the value is persisted: a SQLite column type, or JSON-serialized into one. */
13
+ storage: string;
14
+ /** The admin control rendered for this field type. */
15
+ control: string;
16
+ /** The stored value shape an importer must produce (TypeScript-ish). */
17
+ valueShape: string;
18
+ /** Guidance for importers / migration agents. */
19
+ notes?: string;
20
+ };
21
+
22
+ /** Field type → storage / admin control / value shape. */
23
+ export const FIELD_MODEL: Record<string, FieldModelEntry> = {
24
+ text: { storage: "text", control: "text input (textarea when admin.rows set)", valueShape: "string" },
25
+ slug: {
26
+ storage: "text",
27
+ control: "slug input (auto-derives from `from`)",
28
+ valueShape: "string (url-safe)",
29
+ notes: "unique:true by default — set unique:false for hierarchical or per-locale reused slugs.",
30
+ },
31
+ email: { storage: "text", control: "email input", valueShape: "string" },
32
+ number: { storage: "real", control: "number input", valueShape: "number" },
33
+ boolean: { storage: "integer", control: "checkbox", valueShape: "boolean" },
34
+ date: { storage: "text", control: "date input", valueShape: "ISO date string (YYYY-MM-DD or full ISO)" },
35
+ select: { storage: "text", control: "dropdown", valueShape: "string (one of `options`)" },
36
+ color: {
37
+ storage: "text",
38
+ control: "colour swatch picker (brand palette + custom + hex)",
39
+ valueShape: "hex string e.g. '#00BB5F' (empty string = inherit default)",
40
+ },
41
+ richText: {
42
+ storage: "json",
43
+ control: "rich-text editor",
44
+ valueShape: "{ type:'root', children: RichTextNode[] }",
45
+ notes: "Build from HTML with htmlToRichText(html).",
46
+ },
47
+ content: {
48
+ storage: "json",
49
+ control: "content editor (prose + inline component blocks)",
50
+ valueShape: "{ type:'root', children: (RichTextNode | { type:'block', blockType:string, fields:object })[] }",
51
+ notes:
52
+ "Inline block `fields` are NOT validated on write; declare `blocks` so the editor can render them. Stored discriminator is 'block'.",
53
+ },
54
+ image: {
55
+ storage: "text",
56
+ control: "asset picker",
57
+ valueShape: "storagePath string '/uploads/<id>.<ext>'",
58
+ notes: "Upload originals with assets.upload(file, { alt }); store the returned storagePath.",
59
+ },
60
+ link: {
61
+ storage: "json",
62
+ control: "link control (internal page picker / external URL + label + new-tab)",
63
+ valueShape: "{ type:'internal'|'external', url:string, label?:string, newTab?:boolean }",
64
+ },
65
+ relation: {
66
+ storage: "text (json when hasMany)",
67
+ control: "relation picker (single dropdown, or chips + dropdown when hasMany)",
68
+ valueShape: "id string — or id[] when hasMany",
69
+ },
70
+ array: {
71
+ storage: "json",
72
+ control: "array control: image pickers (of:image), comma input (of:text), else JSON",
73
+ valueShape: "Array<value of `of`>",
74
+ },
75
+ json: {
76
+ storage: "json",
77
+ control: "JSON textarea — OR a typed repeater when admin.component:'repeater' (+ itemFields)",
78
+ valueShape: "any — Array<{ ...itemFields }> when used as a typed repeater",
79
+ notes: "For repeating rows of typed fields use admin.component:'repeater' with itemFields.",
80
+ },
81
+ blocks: {
82
+ storage: "json",
83
+ control: "block editor (standalone)",
84
+ valueShape: "Array<{ type:blockType, ...fields }>",
85
+ },
86
+ };
87
+
88
+ /** The rich-text / content AST node schema, surfaced verbatim in the manifest. */
89
+ export const CONTENT_AST_SCHEMA = {
90
+ root: "{ type:'root', children: Node[] }",
91
+ nodes: {
92
+ text: "{ type:'text', value:string, bold?:boolean, italic?:boolean, href?:string }",
93
+ paragraph: "{ type:'paragraph', children:Node[] }",
94
+ heading: "{ type:'heading', level:1-6, children:Node[] }",
95
+ list: "{ type:'list', ordered?:boolean, children:ListItem[] }",
96
+ "list-item": "{ type:'list-item', children:Node[] }",
97
+ quote: "{ type:'quote', children:Node[] }",
98
+ image: "{ type:'image', src:string, alt:string }",
99
+ block: "{ type:'block', blockType:string, fields:object } (content field only — inline component block)",
100
+ },
101
+ };
102
+
103
+ const typeSpecific = (field: FieldConfig): Record<string, unknown> => {
104
+ const out: Record<string, unknown> = {};
105
+ if (field.type === "select") out.options = field.options;
106
+ if (field.type === "relation") {
107
+ out.collection = field.collection;
108
+ out.hasMany = field.hasMany ?? false;
109
+ }
110
+ if (field.type === "array") out.of = describeField("of", field.of);
111
+ if (field.type === "json" && field.itemFields) {
112
+ out.itemFields = Object.fromEntries(
113
+ Object.entries(field.itemFields).map(([name, f]) => [name, describeField(name, f)]),
114
+ );
115
+ }
116
+ if (field.type === "content") out.blockTypes = describeBlockTypes(field.blocks);
117
+ if (field.type === "blocks") out.blockTypes = describeBlockTypes(field.types);
118
+ return out;
119
+ };
120
+
121
+ export const describeField = (name: string, field: FieldConfig): Record<string, unknown> => {
122
+ // `color`/`link` are admin.component helpers over text/json — report them as
123
+ // their effective semantic type so the manifest is honest about the control.
124
+ const component = field.admin?.component;
125
+ const effectiveType = component === "color" || component === "link" ? component : field.type;
126
+ const model = FIELD_MODEL[effectiveType] ?? { storage: "json", control: "unknown", valueShape: "unknown" };
127
+ return {
128
+ name,
129
+ type: effectiveType,
130
+ label: field.label,
131
+ required: field.required ?? false,
132
+ translatable: field.translatable ?? false,
133
+ storage: model.storage,
134
+ control: model.control,
135
+ valueShape: model.valueShape,
136
+ ...(model.notes ? { notes: model.notes } : {}),
137
+ ...typeSpecific(field),
138
+ };
139
+ };
140
+
141
+ export const describeBlockTypes = (blocks: Record<string, Record<string, FieldConfig>> | undefined) =>
142
+ blocks
143
+ ? Object.fromEntries(
144
+ Object.entries(blocks).map(([blockType, fieldMap]) => [
145
+ blockType,
146
+ Object.fromEntries(Object.entries(fieldMap).map(([name, f]) => [name, describeField(name, f)])),
147
+ ]),
148
+ )
149
+ : {};
150
+
151
+ export const describeCollection = (collection: CollectionConfig) => ({
152
+ slug: collection.slug,
153
+ labels: collection.labels,
154
+ labelField: getLabelField(collection),
155
+ table: `cms_${collection.slug}`,
156
+ drafts: collection.drafts ?? false,
157
+ versions: collection.versions ?? null,
158
+ searchable: collection.searchable ?? false,
159
+ translatableFields: getTranslatableFieldNames(collection),
160
+ fields: Object.fromEntries(
161
+ Object.entries(collection.fields).map(([name, field]) => [name, describeField(name, field)]),
162
+ ),
163
+ });
164
+
165
+ /** Build the full machine-readable model manifest from a CMS config. */
166
+ export const describeModel = (config: CMSConfig) => ({
167
+ generatedBy: "kide describe",
168
+ locales: config.locales ?? { default: "en", supported: ["en"] },
169
+ fieldTypes: FIELD_MODEL,
170
+ contentAst: CONTENT_AST_SCHEMA,
171
+ collections: config.collections.map(describeCollection),
172
+ });
@@ -0,0 +1,519 @@
1
+ import { mkdir, rename, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+
5
+ import type { CMSConfig, CollectionConfig, FieldConfig } from "./define";
6
+ import { getTranslatableFieldNames } from "./define";
7
+
8
+ type GeneratorOptions = {
9
+ outputDir: string;
10
+ coreImportPath?: string;
11
+ runtimeImportPath?: string;
12
+ configImportPath?: string;
13
+ };
14
+
15
+ const pascalCase = (value: string) =>
16
+ value
17
+ .split(/[^a-zA-Z0-9]+/)
18
+ .filter(Boolean)
19
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
20
+ .join("");
21
+
22
+ const snakeCase = (value: string) =>
23
+ value
24
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
25
+ .replace(/[^a-zA-Z0-9]+/g, "_")
26
+ .toLowerCase();
27
+
28
+ const isJsonField = (field: FieldConfig) =>
29
+ field.type === "richText" ||
30
+ field.type === "content" ||
31
+ field.type === "array" ||
32
+ field.type === "json" ||
33
+ field.type === "blocks" ||
34
+ (field.type === "relation" && field.hasMany);
35
+
36
+ const generateColumnDef = (fieldName: string, field: FieldConfig): string => {
37
+ const colName = snakeCase(fieldName);
38
+ let col: string;
39
+
40
+ if (field.type === "number") {
41
+ col = `integer("${colName}")`;
42
+ } else if (field.type === "boolean") {
43
+ col = `integer("${colName}", { mode: "boolean" })`;
44
+ } else {
45
+ col = `text("${colName}")`;
46
+ }
47
+
48
+ if (field.required && !field.condition) col += ".notNull()";
49
+ if (field.unique) col += ".unique()";
50
+ if (field.defaultValue !== undefined && !isJsonField(field)) {
51
+ if (field.type === "number" || field.type === "boolean") {
52
+ col += `.default(${field.defaultValue})`;
53
+ } else {
54
+ col += `.default(${JSON.stringify(field.defaultValue)})`;
55
+ }
56
+ }
57
+
58
+ return ` ${fieldName}: ${col},`;
59
+ };
60
+
61
+ const generateMainTable = (collection: CollectionConfig): string => {
62
+ const tableName = `cms_${snakeCase(collection.slug)}`;
63
+ const varName = `cms${pascalCase(collection.slug)}`;
64
+ const columns: string[] = [` _id: text("_id").primaryKey(),`];
65
+
66
+ for (const [fieldName, field] of Object.entries(collection.fields)) {
67
+ columns.push(generateColumnDef(fieldName, field));
68
+ }
69
+
70
+ if (collection.drafts) {
71
+ columns.push(` _status: text("_status").notNull().default("draft"),`);
72
+ columns.push(` _publishedAt: text("_published_at"),`);
73
+ columns.push(` _publishAt: text("_publish_at"),`);
74
+ columns.push(` _unpublishAt: text("_unpublish_at"),`);
75
+ columns.push(` _published: text("_published"),`);
76
+ }
77
+
78
+ if (collection.timestamps !== false) {
79
+ columns.push(` _createdAt: text("_created_at").notNull(),`);
80
+ columns.push(` _updatedAt: text("_updated_at").notNull(),`);
81
+ }
82
+
83
+ return `export const ${varName} = sqliteTable("${tableName}", {\n${columns.join("\n")}\n});`;
84
+ };
85
+
86
+ const generateTranslationsTable = (config: CMSConfig, collection: CollectionConfig): string | null => {
87
+ if (!config.locales) return null;
88
+ const translatableFields = getTranslatableFieldNames(collection);
89
+ if (translatableFields.length === 0) return null;
90
+
91
+ const tableName = `cms_${snakeCase(collection.slug)}_translations`;
92
+ const varName = `cms${pascalCase(collection.slug)}Translations`;
93
+ const mainVar = `cms${pascalCase(collection.slug)}`;
94
+
95
+ const columns: string[] = [
96
+ ` _id: text("_id").primaryKey(),`,
97
+ ` _entityId: text("_entity_id").notNull().references(() => ${mainVar}._id, { onDelete: "cascade" }),`,
98
+ ` _languageCode: text("_language_code").notNull(),`,
99
+ ];
100
+
101
+ for (const fieldName of translatableFields) {
102
+ columns.push(generateColumnDef(fieldName, collection.fields[fieldName]));
103
+ }
104
+
105
+ return `export const ${varName} = sqliteTable("${tableName}", {\n${columns.join("\n")}\n}, (table) => ({\n uniqueLocale: unique().on(table._entityId, table._languageCode),\n}));`;
106
+ };
107
+
108
+ const generateVersionsTable = (collection: CollectionConfig): string | null => {
109
+ if (!collection.versions) return null;
110
+
111
+ const tableName = `cms_${snakeCase(collection.slug)}_versions`;
112
+ const varName = `cms${pascalCase(collection.slug)}Versions`;
113
+ const mainVar = `cms${pascalCase(collection.slug)}`;
114
+
115
+ return `export const ${varName} = sqliteTable("${tableName}", {
116
+ _id: text("_id").primaryKey(),
117
+ _docId: text("_doc_id").notNull().references(() => ${mainVar}._id, { onDelete: "cascade" }),
118
+ _version: integer("_version").notNull(),
119
+ _snapshot: text("_snapshot").notNull(),
120
+ _createdAt: text("_created_at").notNull(),
121
+ });`;
122
+ };
123
+
124
+ const generateSchemaFile = (config: CMSConfig): string => {
125
+ const parts: string[] = [
126
+ `// auto-generated — do not edit`,
127
+ `import { sqliteTable, text, integer, real, unique, index, primaryKey } from "drizzle-orm/sqlite-core";`,
128
+ ``,
129
+ ];
130
+
131
+ for (const collection of config.collections) {
132
+ parts.push(generateMainTable(collection));
133
+ const translationsTable = generateTranslationsTable(config, collection);
134
+ if (translationsTable) parts.push("", translationsTable);
135
+ const versionsTable = generateVersionsTable(collection);
136
+ if (versionsTable) parts.push("", versionsTable);
137
+ parts.push("");
138
+ }
139
+
140
+ parts.push(`export const cmsAssets = sqliteTable("cms_assets", {
141
+ _id: text("_id").primaryKey(),
142
+ filename: text("filename").notNull(),
143
+ mimeType: text("mime_type").notNull(),
144
+ size: integer("size").notNull(),
145
+ width: integer("width"),
146
+ height: integer("height"),
147
+ focalX: real("focal_x"),
148
+ focalY: real("focal_y"),
149
+ alt: text("alt"),
150
+ folder: text("folder"),
151
+ storagePath: text("storage_path").notNull(),
152
+ hash: text("hash"),
153
+ _createdAt: text("_created_at").notNull(),
154
+ });`);
155
+ parts.push("");
156
+ parts.push(`export const cmsAssetFolders = sqliteTable("cms_asset_folders", {
157
+ _id: text("_id").primaryKey(),
158
+ name: text("name").notNull(),
159
+ parent: text("parent"),
160
+ _createdAt: text("_created_at").notNull(),
161
+ });`);
162
+ parts.push("");
163
+ parts.push(`export const cmsSessions = sqliteTable("cms_sessions", {
164
+ _id: text("_id").primaryKey(),
165
+ userId: text("user_id").notNull(),
166
+ expiresAt: text("expires_at").notNull(),
167
+ });`);
168
+ parts.push("");
169
+ parts.push(`export const cmsLocks = sqliteTable("cms_locks", {
170
+ _id: text("_id").primaryKey(),
171
+ collection: text("collection").notNull(),
172
+ documentId: text("document_id").notNull(),
173
+ userId: text("user_id").notNull(),
174
+ userEmail: text("user_email").notNull(),
175
+ lockedAt: text("locked_at").notNull(),
176
+ });`);
177
+ parts.push("");
178
+ parts.push(`export const cmsInvites = sqliteTable("cms_invites", {
179
+ _id: text("_id").primaryKey(),
180
+ userId: text("user_id").notNull(),
181
+ token: text("token").notNull().unique(),
182
+ expiresAt: text("expires_at").notNull(),
183
+ usedAt: text("used_at"),
184
+ });`);
185
+ parts.push("");
186
+ parts.push(`export const cmsPasswordResets = sqliteTable("cms_password_resets", {
187
+ _id: text("_id").primaryKey(),
188
+ userId: text("user_id").notNull(),
189
+ token: text("token").notNull().unique(),
190
+ expiresAt: text("expires_at").notNull(),
191
+ usedAt: text("used_at"),
192
+ });`);
193
+ parts.push("");
194
+ parts.push(`export const cmsRateLimits = sqliteTable("cms_rate_limits", {
195
+ _id: text("_id").primaryKey(),
196
+ windowStart: integer("window_start").notNull(),
197
+ count: integer("count").notNull(),
198
+ expiresAt: integer("expires_at").notNull(),
199
+ }, (table) => ({
200
+ expiryIdx: index("rate_limits_expiry_idx").on(table.expiresAt),
201
+ }));`);
202
+ parts.push("");
203
+ parts.push(`export const cmsAuditLog = sqliteTable("cms_audit_log", {
204
+ _id: text("_id").primaryKey(),
205
+ timestamp: integer("timestamp").notNull(),
206
+ actorId: text("actor_id"),
207
+ actorEmail: text("actor_email"),
208
+ actorRole: text("actor_role"),
209
+ action: text("action").notNull(),
210
+ resourceType: text("resource_type").notNull(),
211
+ resourceCollection: text("resource_collection"),
212
+ resourceId: text("resource_id"),
213
+ ipAddress: text("ip_address"),
214
+ userAgent: text("user_agent"),
215
+ }, (table) => ({
216
+ timestampIdx: index("audit_timestamp_idx").on(table.timestamp),
217
+ actorIdx: index("audit_actor_idx").on(table.actorId),
218
+ resourceIdx: index("audit_resource_idx").on(table.resourceType, table.resourceCollection, table.resourceId),
219
+ }));`);
220
+ parts.push("");
221
+ parts.push(`export const cmsOutbox = sqliteTable("cms_outbox", {
222
+ _id: text("_id").primaryKey(),
223
+ type: text("type").notNull(),
224
+ payload: text("payload"),
225
+ status: text("status").notNull().default("pending"),
226
+ attempts: integer("attempts").notNull().default(0),
227
+ maxAttempts: integer("max_attempts").notNull().default(5),
228
+ nextAttemptAt: integer("next_attempt_at").notNull(),
229
+ dedupeKey: text("dedupe_key"),
230
+ lastError: text("last_error"),
231
+ createdAt: integer("created_at").notNull(),
232
+ updatedAt: integer("updated_at").notNull(),
233
+ }, (table) => ({
234
+ dueIdx: index("outbox_due_idx").on(table.status, table.nextAttemptAt),
235
+ dedupeIdx: index("outbox_dedupe_idx").on(table.dedupeKey),
236
+ }));`);
237
+ parts.push("");
238
+ parts.push(`export const cmsCollaboration = sqliteTable("cms_collaboration", {
239
+ collection: text("collection").notNull(),
240
+ documentId: text("document_id").notNull(),
241
+ reviewState: text("review_state").notNull(),
242
+ editor: text("editor"),
243
+ updatedAt: text("updated_at").notNull(),
244
+ }, (table) => ({
245
+ pk: primaryKey({ columns: [table.collection, table.documentId] }),
246
+ }));`);
247
+ parts.push("");
248
+ parts.push(`export const cmsComments = sqliteTable("cms_comments", {
249
+ _id: text("_id").primaryKey(),
250
+ collection: text("collection").notNull(),
251
+ documentId: text("document_id").notNull(),
252
+ field: text("field"),
253
+ body: text("body").notNull(),
254
+ authorId: text("author_id"),
255
+ authorEmail: text("author_email"),
256
+ resolved: integer("resolved", { mode: "boolean" }).notNull().default(false),
257
+ createdAt: text("created_at").notNull(),
258
+ }, (table) => ({
259
+ docIdx: index("comments_doc_idx").on(table.collection, table.documentId),
260
+ }));`);
261
+ parts.push("");
262
+
263
+ const tableExports: string[] = [];
264
+ for (const collection of config.collections) {
265
+ const varName = `cms${pascalCase(collection.slug)}`;
266
+ const safeKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(collection.slug) ? collection.slug : `"${collection.slug}"`;
267
+ tableExports.push(` ${safeKey}: { main: ${varName}`);
268
+ const translatableFields = getTranslatableFieldNames(collection);
269
+ if (translatableFields.length > 0 && config.locales) {
270
+ tableExports[tableExports.length - 1] += `, translations: ${varName}Translations`;
271
+ }
272
+ if (collection.versions) {
273
+ tableExports[tableExports.length - 1] += `, versions: ${varName}Versions`;
274
+ }
275
+ tableExports[tableExports.length - 1] += ` },`;
276
+ }
277
+ parts.push(`export const cmsTables = {\n${tableExports.join("\n")}\n};`);
278
+
279
+ return parts.join("\n");
280
+ };
281
+
282
+ const zodTypeForField = (field: FieldConfig): string => {
283
+ if (["text", "slug", "email", "image", "date"].includes(field.type)) {
284
+ let zodType = "z.string()";
285
+ if (field.type === "email") zodType = "z.string().email()";
286
+ if (field.type === "text" && field.maxLength) zodType = `z.string().max(${field.maxLength})`;
287
+ return zodType;
288
+ }
289
+ if (field.type === "number") return "z.number()";
290
+ if (field.type === "boolean") return "z.boolean()";
291
+ if (field.type === "select") return `z.enum([${field.options.map((option) => JSON.stringify(option)).join(", ")}])`;
292
+ if (field.type === "relation") {
293
+ if (!field.hasMany) return "z.string()";
294
+ return field.maxItems ? `z.array(z.string()).max(${field.maxItems})` : "z.array(z.string())";
295
+ }
296
+ if (field.type === "array") {
297
+ const inner = `z.array(${zodTypeForField(field.of)})`;
298
+ return field.maxItems ? `${inner}.max(${field.maxItems})` : inner;
299
+ }
300
+ if (field.type === "richText" || field.type === "content")
301
+ return "z.object({ type: z.literal('root'), children: z.array(z.any()) })";
302
+ if (field.type === "json") return "z.record(z.unknown())";
303
+ if (field.type === "blocks") {
304
+ const allowShared = field.shared !== false;
305
+ const sharedVariant =
306
+ 'z.object({ type: z.literal("__shared"), ref: z.string(), title: z.string().optional(), blockType: z.string().optional() })';
307
+ const variants = Object.entries(field.types).map(([blockType, fields]) => {
308
+ const members = Object.entries(fields)
309
+ .map(
310
+ ([fieldName, nestedField]) =>
311
+ `${fieldName}: ${zodTypeForField(nestedField)}${nestedField.required ? "" : ".optional()"}`,
312
+ )
313
+ .join(", ");
314
+ return `z.object({ type: z.literal(${JSON.stringify(blockType)}), ${members} })`;
315
+ });
316
+ if (!allowShared) {
317
+ if (variants.length === 0) return "z.array(z.record(z.unknown()))";
318
+ if (variants.length === 1) return `z.array(${variants[0]})`;
319
+ return `z.array(z.discriminatedUnion("type", [\n ${variants.join(",\n ")},\n ]))`;
320
+ }
321
+ if (variants.length === 0) return `z.array(${sharedVariant})`;
322
+ if (variants.length === 1)
323
+ return `z.array(z.discriminatedUnion("type", [\n ${sharedVariant},\n ${variants[0]},\n ]))`;
324
+ return `z.array(z.discriminatedUnion("type", [\n ${sharedVariant},\n ${variants.join(",\n ")},\n ]))`;
325
+ }
326
+ return "z.unknown()";
327
+ };
328
+
329
+ const generateValidatorsFile = (config: CMSConfig): string => {
330
+ const parts: string[] = [`// auto-generated — do not edit`, `import { z } from "zod";`, ``];
331
+
332
+ for (const collection of config.collections) {
333
+ const name = pascalCase(collection.slug);
334
+ const fieldEntries = Object.entries(collection.fields).map(([fieldName, field]) => {
335
+ const zodType = zodTypeForField(field);
336
+ const isOptional = !field.required || !!field.condition;
337
+ return ` ${fieldName}: ${zodType}${isOptional ? ".optional()" : ""},`;
338
+ });
339
+
340
+ parts.push(`export const ${name}CreateSchema = z.object({\n${fieldEntries.join("\n")}\n});`);
341
+ parts.push("");
342
+
343
+ const partialEntries = Object.entries(collection.fields).map(([fieldName, field]) => {
344
+ const zodType = zodTypeForField(field);
345
+ return ` ${fieldName}: ${zodType}.optional(),`;
346
+ });
347
+ parts.push(`export const ${name}UpdateSchema = z.object({\n${partialEntries.join("\n")}\n});`);
348
+ parts.push("");
349
+ }
350
+
351
+ const mapEntries = config.collections.map((collection) => {
352
+ const name = pascalCase(collection.slug);
353
+ return ` "${collection.slug}": { create: ${name}CreateSchema, update: ${name}UpdateSchema },`;
354
+ });
355
+ parts.push(`export const validators = {\n${mapEntries.join("\n")}\n};`);
356
+
357
+ return parts.join("\n");
358
+ };
359
+
360
+ const typeForField = (field: FieldConfig): string => {
361
+ if (["text", "slug", "email", "image", "date"].includes(field.type)) return "string";
362
+ if (field.type === "number") return "number";
363
+ if (field.type === "boolean") return "boolean";
364
+ if (field.type === "select") return field.options.map((option) => JSON.stringify(option)).join(" | ");
365
+ if (field.type === "relation") return field.hasMany ? "string[]" : "string";
366
+ if (field.type === "array") return `${typeForField(field.of)}[]`;
367
+ if (field.type === "richText") return "RichTextDocument";
368
+ if (field.type === "content") return "ContentDocument";
369
+ if (field.type === "json") return "Record<string, unknown>";
370
+ if (field.type === "blocks") {
371
+ const allowShared = field.shared !== false;
372
+ const sharedVariant = `{ type: "__shared"; ref: string; title?: string; blockType?: string }`;
373
+ const variants = Object.entries(field.types).map(([blockType, fields]) => {
374
+ const members = Object.entries(fields)
375
+ .map(
376
+ ([fieldName, nestedField]) => `${fieldName}${nestedField.required ? "" : "?"}: ${typeForField(nestedField)};`,
377
+ )
378
+ .join(" ");
379
+ return `{ type: ${JSON.stringify(blockType)}; ${members} }`;
380
+ });
381
+ const union = allowShared ? [...variants, sharedVariant] : variants;
382
+ return union.length > 0 ? `Array<${union.join(" | ")}>` : "Array<Record<string, unknown>>";
383
+ }
384
+ return "unknown";
385
+ };
386
+
387
+ const generateTypesFile = (config: CMSConfig, coreImportPath: string): string => {
388
+ const parts: string[] = [
389
+ `// auto-generated — do not edit`,
390
+ `import type { RichTextDocument, ContentDocument } from "${coreImportPath}";`,
391
+ ``,
392
+ `export type CMSCollectionSlug = ${config.collections.map((collection) => JSON.stringify(collection.slug)).join(" | ")};`,
393
+ ``,
394
+ ];
395
+
396
+ for (const collection of config.collections) {
397
+ const docName = `${pascalCase(collection.slug)}Document`;
398
+ const inputName = `${pascalCase(collection.slug)}Input`;
399
+ const translationName = `${pascalCase(collection.slug)}TranslationInput`;
400
+ const translatableFields = getTranslatableFieldNames(collection);
401
+
402
+ const fieldEntries = Object.entries(collection.fields)
403
+ .map(([fieldName, field]) => {
404
+ const isOptional = !field.required || !!field.condition;
405
+ return ` ${fieldName}${isOptional ? "?" : ""}: ${typeForField(field)};`;
406
+ })
407
+ .join("\n");
408
+
409
+ const translationEntries = translatableFields.length
410
+ ? translatableFields
411
+ .map((fieldName) => ` ${fieldName}?: ${typeForField(collection.fields[fieldName])};`)
412
+ .join("\n")
413
+ : " [key: string]: never;";
414
+
415
+ parts.push(`export type ${inputName} = {\n${fieldEntries}\n};`);
416
+ parts.push("");
417
+ parts.push(`export type ${translationName} = {\n${translationEntries}\n};`);
418
+ parts.push("");
419
+ parts.push(`export type ${docName} = ${inputName} & {
420
+ _id: string;
421
+ _status: "draft" | "published" | "scheduled";
422
+ _publishedAt?: string | null;
423
+ _publishAt?: string | null;
424
+ _unpublishAt?: string | null;
425
+ _createdAt: string;
426
+ _updatedAt: string;
427
+ _locale?: string | null;
428
+ _availableLocales?: string[];
429
+ };`);
430
+ parts.push("");
431
+ }
432
+
433
+ parts.push(`export type StoredVersion = {
434
+ version: number;
435
+ createdAt: string;
436
+ snapshot: Record<string, unknown>;
437
+ };`);
438
+
439
+ return parts.join("\n");
440
+ };
441
+
442
+ const generateApiFile = (
443
+ config: CMSConfig,
444
+ coreImportPath: string,
445
+ runtimeImportPath: string,
446
+ configImportPath: string,
447
+ ) => {
448
+ const imports = config.collections
449
+ .map((collection) => {
450
+ const name = pascalCase(collection.slug);
451
+ return [`${name}Document`, `${name}Input`, `${name}TranslationInput`];
452
+ })
453
+ .flat();
454
+
455
+ const apiTypes = config.collections
456
+ .map((collection) => {
457
+ const baseName = pascalCase(collection.slug);
458
+ const ctx = `context?: { user?: { id: string; role?: string; email?: string; [key: string]: unknown } | null; _system?: boolean }`;
459
+ const apiKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(collection.slug) ? collection.slug : `"${collection.slug}"`;
460
+ return ` ${apiKey}: {
461
+ find(options?: import("${coreImportPath}").FindOptions, ${ctx}): Promise<${baseName}Document[]>;
462
+ findOne(filter: Record<string, unknown> & { locale?: string; status?: "draft" | "published" | "scheduled" | "any" }, ${ctx}): Promise<${baseName}Document | null>;
463
+ findById(id: string, options?: { locale?: string; status?: "draft" | "published" | "scheduled" | "any" }, ${ctx}): Promise<${baseName}Document | null>;
464
+ create(data: ${baseName}Input, ${ctx}): Promise<${baseName}Document>;
465
+ createMany(items: ${baseName}Input[], ${ctx}): Promise<${baseName}Document[]>;
466
+ upsert(data: ${baseName}Input & { _id?: string }, ${ctx}): Promise<${baseName}Document>;
467
+ update(id: string, data: Partial<${baseName}Input>, ${ctx}): Promise<${baseName}Document>;
468
+ delete(id: string, ${ctx}): Promise<void>;
469
+ count(filter?: Omit<import("${coreImportPath}").FindOptions, "limit" | "offset" | "sort">, ${ctx}): Promise<number>;
470
+ versions(id: string, ${ctx}): Promise<import("./types").StoredVersion[]>;
471
+ restore(id: string, versionNumber: number, ${ctx}): Promise<${baseName}Document>;
472
+ publish(id: string, ${ctx}): Promise<${baseName}Document>;
473
+ unpublish(id: string, ${ctx}): Promise<${baseName}Document>;
474
+ schedule(id: string, publishAt: string, unpublishAt?: string | null, ${ctx}): Promise<${baseName}Document>;
475
+ getTranslations(id: string, ${ctx}): Promise<Record<string, ${baseName}TranslationInput>>;
476
+ upsertTranslation(id: string, locale: string, data: ${baseName}TranslationInput, ${ctx}): Promise<${baseName}Document>;
477
+ };`;
478
+ })
479
+ .join("\n");
480
+
481
+ return `// auto-generated — do not edit
482
+ import config from "${configImportPath}";
483
+ import { createCms } from "${runtimeImportPath}";
484
+ import type {
485
+ ${imports.map((entry) => `${entry},`).join("\n ")}
486
+ } from "./types";
487
+
488
+ export const cms = createCms(config) as {
489
+ ${apiTypes}
490
+ meta: ReturnType<typeof createCms>["meta"];
491
+ scheduled: ReturnType<typeof createCms>["scheduled"];
492
+ };
493
+ `;
494
+ };
495
+
496
+ // Temp file + rename: a concurrent reader never sees a partially-written file.
497
+ const writeFileAtomic = async (filePath: string, content: string) => {
498
+ const tmpPath = `${filePath}.${randomUUID()}.tmp`;
499
+ await writeFile(tmpPath, content, "utf-8");
500
+ await rename(tmpPath, filePath);
501
+ };
502
+
503
+ export const generate = async (config: CMSConfig, options: GeneratorOptions) => {
504
+ const outputDir = options.outputDir;
505
+ const coreImportPath = options.coreImportPath ?? "../core";
506
+ const runtimeImportPath = options.runtimeImportPath ?? "../runtime";
507
+ const configImportPath = options.configImportPath ?? "../cms.config";
508
+
509
+ await mkdir(outputDir, { recursive: true });
510
+ await Promise.all([
511
+ writeFileAtomic(path.join(outputDir, "schema.ts"), generateSchemaFile(config)),
512
+ writeFileAtomic(path.join(outputDir, "types.ts"), generateTypesFile(config, coreImportPath)),
513
+ writeFileAtomic(path.join(outputDir, "validators.ts"), generateValidatorsFile(config)),
514
+ writeFileAtomic(
515
+ path.join(outputDir, "api.ts"),
516
+ generateApiFile(config, coreImportPath, runtimeImportPath, configImportPath),
517
+ ),
518
+ ]);
519
+ };