opacacms 0.1.12 → 0.1.13

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 (217) hide show
  1. package/dist/admin/index.js +0 -4
  2. package/dist/admin/webcomponent.d.ts +0 -1
  3. package/dist/admin/webcomponent.js +0 -4
  4. package/dist/admin.css +1 -0
  5. package/package.json +8 -2
  6. package/bun.lock +0 -34
  7. package/dist/admin/index.css +0 -47
  8. package/dist/admin/webcomponent.css +0 -47
  9. package/global.d.ts +0 -11
  10. package/src/admin/api-client.ts +0 -63
  11. package/src/admin/auth-client.ts +0 -40
  12. package/src/admin/custom-field.ts +0 -179
  13. package/src/admin/index.ts +0 -15
  14. package/src/admin/react.tsx +0 -72
  15. package/src/admin/router.ts +0 -9
  16. package/src/admin/stores/admin-queries.ts +0 -121
  17. package/src/admin/stores/auth.ts +0 -61
  18. package/src/admin/stores/column-visibility.ts +0 -67
  19. package/src/admin/stores/config.ts +0 -15
  20. package/src/admin/stores/media.ts +0 -95
  21. package/src/admin/stores/query.ts +0 -13
  22. package/src/admin/stores/ui.ts +0 -29
  23. package/src/admin/ui/admin-client.tsx +0 -283
  24. package/src/admin/ui/admin-layout.tsx +0 -276
  25. package/src/admin/ui/components/ColumnVisibilityToggle.tsx +0 -141
  26. package/src/admin/ui/components/DataDetailSheet.tsx +0 -141
  27. package/src/admin/ui/components/DataDetailView.tsx +0 -175
  28. package/src/admin/ui/components/Table.tsx +0 -67
  29. package/src/admin/ui/components/fields/ArrayField.tsx +0 -166
  30. package/src/admin/ui/components/fields/BlocksField.tsx +0 -202
  31. package/src/admin/ui/components/fields/BooleanField.tsx +0 -50
  32. package/src/admin/ui/components/fields/CollapsibleField.tsx +0 -75
  33. package/src/admin/ui/components/fields/DateField.tsx +0 -45
  34. package/src/admin/ui/components/fields/FileField.tsx +0 -322
  35. package/src/admin/ui/components/fields/GroupField.tsx +0 -50
  36. package/src/admin/ui/components/fields/JoinField.tsx +0 -23
  37. package/src/admin/ui/components/fields/NumberField.tsx +0 -46
  38. package/src/admin/ui/components/fields/RadioField.tsx +0 -62
  39. package/src/admin/ui/components/fields/RelationshipField.tsx +0 -278
  40. package/src/admin/ui/components/fields/RowField.tsx +0 -40
  41. package/src/admin/ui/components/fields/SelectField.tsx +0 -59
  42. package/src/admin/ui/components/fields/TabsField.tsx +0 -101
  43. package/src/admin/ui/components/fields/TextAreaField.tsx +0 -54
  44. package/src/admin/ui/components/fields/TextField.tsx +0 -49
  45. package/src/admin/ui/components/fields/VirtualField.tsx +0 -53
  46. package/src/admin/ui/components/fields/index.tsx +0 -371
  47. package/src/admin/ui/components/fields/richtext-editor/index.tsx +0 -211
  48. package/src/admin/ui/components/fields/richtext-editor/nodes/ImageComponent.tsx +0 -142
  49. package/src/admin/ui/components/fields/richtext-editor/nodes/ImageNode.tsx +0 -95
  50. package/src/admin/ui/components/fields/richtext-editor/plugins/ComponentPickerPlugin.tsx +0 -226
  51. package/src/admin/ui/components/fields/richtext-editor/plugins/EditableSyncPlugin.tsx +0 -16
  52. package/src/admin/ui/components/fields/richtext-editor/plugins/NotionToolbarPlugin.tsx +0 -184
  53. package/src/admin/ui/components/fields/richtext-editor/plugins/SimpleToolbarPlugin.tsx +0 -240
  54. package/src/admin/ui/components/fields/richtext-editor/plugins/ValueSyncPlugin.tsx +0 -40
  55. package/src/admin/ui/components/fields/utils.ts +0 -1
  56. package/src/admin/ui/components/link.tsx +0 -41
  57. package/src/admin/ui/components/media/AssetManagerModal.tsx +0 -334
  58. package/src/admin/ui/components/toast.tsx +0 -72
  59. package/src/admin/ui/components/ui/accordion.tsx +0 -51
  60. package/src/admin/ui/components/ui/alert-dialog.tsx +0 -98
  61. package/src/admin/ui/components/ui/blocks.tsx +0 -32
  62. package/src/admin/ui/components/ui/breadcrumbs.tsx +0 -59
  63. package/src/admin/ui/components/ui/button.tsx +0 -26
  64. package/src/admin/ui/components/ui/collapsible.tsx +0 -124
  65. package/src/admin/ui/components/ui/dialog.tsx +0 -79
  66. package/src/admin/ui/components/ui/group.tsx +0 -20
  67. package/src/admin/ui/components/ui/index.ts +0 -17
  68. package/src/admin/ui/components/ui/input.tsx +0 -12
  69. package/src/admin/ui/components/ui/join.tsx +0 -53
  70. package/src/admin/ui/components/ui/label.tsx +0 -11
  71. package/src/admin/ui/components/ui/radio-group.tsx +0 -75
  72. package/src/admin/ui/components/ui/relationship-detail-sheet.tsx +0 -122
  73. package/src/admin/ui/components/ui/relationship.tsx +0 -58
  74. package/src/admin/ui/components/ui/scroll-area.tsx +0 -19
  75. package/src/admin/ui/components/ui/select.tsx +0 -187
  76. package/src/admin/ui/components/ui/separator.tsx +0 -21
  77. package/src/admin/ui/components/ui/sheet.tsx +0 -106
  78. package/src/admin/ui/components/ui/tabs.tsx +0 -116
  79. package/src/admin/ui/components/ui/utils.ts +0 -3
  80. package/src/admin/ui/hooks/use-debounce.ts +0 -15
  81. package/src/admin/ui/styles/_locale-switcher.scss +0 -33
  82. package/src/admin/ui/styles/accordion.scss +0 -60
  83. package/src/admin/ui/styles/animations.scss +0 -41
  84. package/src/admin/ui/styles/asset-manager.scss +0 -547
  85. package/src/admin/ui/styles/badge.scss +0 -13
  86. package/src/admin/ui/styles/base.scss +0 -22
  87. package/src/admin/ui/styles/button.scss +0 -161
  88. package/src/admin/ui/styles/card.scss +0 -13
  89. package/src/admin/ui/styles/collapsible.scss +0 -75
  90. package/src/admin/ui/styles/data-detail.scss +0 -92
  91. package/src/admin/ui/styles/dialog.scss +0 -102
  92. package/src/admin/ui/styles/empty-state.scss +0 -22
  93. package/src/admin/ui/styles/group.scss +0 -19
  94. package/src/admin/ui/styles/index.scss +0 -33
  95. package/src/admin/ui/styles/input.scss +0 -80
  96. package/src/admin/ui/styles/label.scss +0 -12
  97. package/src/admin/ui/styles/layout.scss +0 -56
  98. package/src/admin/ui/styles/lexical.scss +0 -469
  99. package/src/admin/ui/styles/loading.scss +0 -102
  100. package/src/admin/ui/styles/media-registry.scss +0 -597
  101. package/src/admin/ui/styles/pagination.scss +0 -20
  102. package/src/admin/ui/styles/radio-group.scss +0 -66
  103. package/src/admin/ui/styles/row.scss +0 -17
  104. package/src/admin/ui/styles/scrollbar.scss +0 -36
  105. package/src/admin/ui/styles/select.scss +0 -121
  106. package/src/admin/ui/styles/separator.scss +0 -14
  107. package/src/admin/ui/styles/sheet.scss +0 -152
  108. package/src/admin/ui/styles/sidebar.scss +0 -148
  109. package/src/admin/ui/styles/switch.scss +0 -59
  110. package/src/admin/ui/styles/table.scss +0 -207
  111. package/src/admin/ui/styles/tabs.scss +0 -62
  112. package/src/admin/ui/styles/toast.scss +0 -45
  113. package/src/admin/ui/styles/variables.scss +0 -24
  114. package/src/admin/ui/views/collection-list-view.tsx +0 -720
  115. package/src/admin/ui/views/dashboard-view.tsx +0 -263
  116. package/src/admin/ui/views/document-edit-view.tsx +0 -384
  117. package/src/admin/ui/views/global-edit-view.tsx +0 -226
  118. package/src/admin/ui/views/init-view.tsx +0 -182
  119. package/src/admin/ui/views/login-view.tsx +0 -123
  120. package/src/admin/ui/views/media-registry-view.tsx +0 -1104
  121. package/src/admin/ui/views/settings-view.tsx +0 -729
  122. package/src/admin/webcomponent.tsx +0 -15
  123. package/src/auth/index.ts +0 -194
  124. package/src/auth/migrations.ts +0 -87
  125. package/src/auth/premissions.ts +0 -46
  126. package/src/cli/commands/generate-types.ts +0 -116
  127. package/src/cli/commands/init.ts +0 -95
  128. package/src/cli/commands/migrate-commands.ts +0 -160
  129. package/src/cli/commands/seed-command.ts +0 -11
  130. package/src/cli/d1-mock.ts +0 -101
  131. package/src/cli/index.test.ts +0 -84
  132. package/src/cli/index.ts +0 -183
  133. package/src/cli/r2-mock.ts +0 -217
  134. package/src/cli/seeding.ts +0 -409
  135. package/src/client.ts +0 -181
  136. package/src/config-utils.ts +0 -102
  137. package/src/config.ts +0 -49
  138. package/src/db/adapter.ts +0 -53
  139. package/src/db/better-sqlite.ts +0 -657
  140. package/src/db/bun-sqlite.ts +0 -666
  141. package/src/db/d1.ts +0 -721
  142. package/src/db/index.ts +0 -10
  143. package/src/db/kysely/data-mapper.ts +0 -142
  144. package/src/db/kysely/field-mapper.ts +0 -149
  145. package/src/db/kysely/migration-generator.ts +0 -223
  146. package/src/db/kysely/query-builder.ts +0 -92
  147. package/src/db/kysely/schema-builder.ts +0 -439
  148. package/src/db/kysely/sql-utils.ts +0 -13
  149. package/src/db/postgres.ts +0 -631
  150. package/src/db/sqlite.ts +0 -670
  151. package/src/db/system-schema.ts +0 -121
  152. package/src/index.ts +0 -13
  153. package/src/runtimes/README.md +0 -59
  154. package/src/runtimes/bun.ts +0 -49
  155. package/src/runtimes/cloudflare-workers.ts +0 -38
  156. package/src/runtimes/next.ts +0 -26
  157. package/src/runtimes/node.ts +0 -52
  158. package/src/schema/collection.ts +0 -184
  159. package/src/schema/fields/base.ts +0 -164
  160. package/src/schema/fields/index.ts +0 -427
  161. package/src/schema/global.ts +0 -145
  162. package/src/schema/index.ts +0 -4
  163. package/src/schema/infer.ts +0 -72
  164. package/src/server/admin-router.ts +0 -20
  165. package/src/server/admin.ts +0 -142
  166. package/src/server/assets.ts +0 -306
  167. package/src/server/collection-router.ts +0 -55
  168. package/src/server/handlers.ts +0 -722
  169. package/src/server/middlewares/admin.ts +0 -27
  170. package/src/server/middlewares/auth.ts +0 -89
  171. package/src/server/middlewares/context.ts +0 -17
  172. package/src/server/middlewares/cors.ts +0 -24
  173. package/src/server/middlewares/database-init.ts +0 -74
  174. package/src/server/middlewares/rate-limit.ts +0 -77
  175. package/src/server/router.ts +0 -47
  176. package/src/server/setup-middlewares.ts +0 -58
  177. package/src/server/system-router.ts +0 -35
  178. package/src/server.ts +0 -9
  179. package/src/storage/adapters/cloudflare-r2.ts +0 -136
  180. package/src/storage/adapters/local.ts +0 -146
  181. package/src/storage/adapters/s3.ts +0 -186
  182. package/src/storage/errors.ts +0 -46
  183. package/src/storage/index.ts +0 -5
  184. package/src/storage/types.ts +0 -39
  185. package/src/types.ts +0 -577
  186. package/src/utils/lexical.ts +0 -37
  187. package/src/utils/logger.ts +0 -73
  188. package/src/validation.ts +0 -429
  189. package/src/validator.ts +0 -179
  190. package/test/admin-custom-field.test.ts +0 -162
  191. package/test/admin-react-field.test.tsx +0 -134
  192. package/test/api-features.test.ts +0 -78
  193. package/test/api.test.ts +0 -178
  194. package/test/auth.test.ts +0 -62
  195. package/test/cli-integration.test.ts +0 -148
  196. package/test/cli.test.ts +0 -25
  197. package/test/db/postgres.test.ts +0 -95
  198. package/test/db/sqlite-filter.test.ts +0 -53
  199. package/test/db/sqlite.test.ts +0 -82
  200. package/test/engine-features.test.ts +0 -79
  201. package/test/globals.test.ts +0 -74
  202. package/test/integration-tmp/db-app/opacacms.config.ts +0 -15
  203. package/test/integration-tmp/my-sqlite-app/opacacms.config.ts +0 -25
  204. package/test/integration-tmp/my-test-app/index.ts +0 -8
  205. package/test/integration-tmp/my-test-app/opacacms.config.ts +0 -16
  206. package/test/integration-tmp/my-test-app/package.json +0 -12
  207. package/test/populate.test.ts +0 -79
  208. package/test/runtimes.test.ts +0 -43
  209. package/test/schema-builder.test.ts +0 -107
  210. package/test/schema-features.test.ts +0 -63
  211. package/test/seeding.test.ts +0 -68
  212. package/test/storage/local.test.ts +0 -72
  213. package/test/storage/s3.test.ts +0 -60
  214. package/test/structural-data.test.ts +0 -100
  215. package/test/test-setup.ts +0 -11
  216. package/test/validation.test.ts +0 -162
  217. package/tsconfig.json +0 -42
package/src/db/index.ts DELETED
@@ -1,10 +0,0 @@
1
- import type { Kysely } from "kysely";
2
- export { sql } from "kysely";
3
- export type OpacaMigrationDb = Kysely<any>;
4
-
5
- export * from "./adapter";
6
- export * from "./postgres";
7
- export * from "./sqlite";
8
- export * from "./better-sqlite";
9
- export * from "./bun-sqlite";
10
- export * from "./d1";
@@ -1,142 +0,0 @@
1
- import { toSnakeCase } from "./field-mapper";
2
-
3
- /**
4
- * Converts a snake_case string to camelCase.
5
- */
6
- export function toCamelCase(str: string): string {
7
- if (str.startsWith("_")) return str; // Keep system prefixes
8
- return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
9
- }
10
-
11
- export function flattenPayload(payload: any, prefix = "", excludeKeys: string[] = []): any {
12
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return payload;
13
- const result: any = {};
14
-
15
- for (const key in payload) {
16
- if (Object.hasOwn(payload, key)) {
17
- const value = payload[key];
18
- if (value === undefined) continue;
19
-
20
- // Do not flatten Date objects or arrays
21
- if (
22
- typeof value === "object" &&
23
- value !== null &&
24
- !Array.isArray(value) &&
25
- !(value instanceof Date) &&
26
- !excludeKeys.includes(key)
27
- ) {
28
- // Only flatten objects that aren't system keys (like _access)
29
- if (key.startsWith("_") && prefix === "") {
30
- result[key] = value;
31
- } else {
32
- // It's a group, flatten it
33
- const flatNested = flattenPayload(value, `${prefix}${key}__`);
34
- Object.assign(result, flatNested);
35
- }
36
- } else {
37
- if (value === undefined) continue;
38
- // IMPORTANT: Convert column name to snake_case when saving
39
- const colName = `${prefix}${toSnakeCase(key)}`;
40
-
41
- // Serialize arrays and objects to JSON strings for SQLite/D1
42
- if (typeof value === "object" && value !== null) {
43
- result[colName] = JSON.stringify(value);
44
- } else {
45
- result[colName] = value;
46
- }
47
- }
48
- }
49
- }
50
- return result;
51
- }
52
-
53
- export function unflattenRow(row: any): any {
54
- if (typeof row !== "object" || row === null || Array.isArray(row)) return row;
55
- const result: any = {};
56
-
57
- for (const key in row) {
58
- if (Object.hasOwn(row, key)) {
59
- let value = row[key];
60
-
61
- // Try to parse JSON strings back to objects/arrays
62
- if (typeof value === "string") {
63
- const trimmed = value.trim();
64
- if (
65
- (trimmed.startsWith("[") && trimmed.endsWith("]")) ||
66
- (trimmed.startsWith("{") && trimmed.endsWith("}"))
67
- ) {
68
- try {
69
- value = JSON.parse(value);
70
- } catch (e) {
71
- // Not valid JSON, keep as string
72
- }
73
- }
74
- }
75
-
76
- // If it's a direct match for timestamps or system fields, keep as is
77
- if (
78
- key === "created_at" ||
79
- key === "updated_at" ||
80
- key === "createdAt" ||
81
- key === "updatedAt"
82
- ) {
83
- if (typeof value === "string" && !value.includes("T") && value.includes(" ")) {
84
- // Normalize SQLite/D1 "YYYY-MM-DD HH:MM:SS" to ISO "YYYY-MM-DDTHH:MM:SSZ"
85
- value = `${value.replace(" ", "T")}Z`;
86
- }
87
- result[toCamelCase(key)] = value;
88
- continue;
89
- }
90
-
91
- if (key.startsWith("_")) {
92
- result[key] = value;
93
- continue;
94
- }
95
-
96
- const parts = key.split("__");
97
- if (parts.length === 1) {
98
- result[toCamelCase(key)] = value;
99
- continue;
100
- }
101
-
102
- // Try to unflatten, but detect collisions (e.g., "email" vs "email_verified")
103
- let current = result;
104
- let collision = false;
105
- const path: any[] = [];
106
-
107
- for (let i = 0; i < parts.length - 1; i++) {
108
- const part = toCamelCase(parts[i]!);
109
- if (
110
- current[part] !== undefined &&
111
- (typeof current[part] !== "object" || current[part] === null)
112
- ) {
113
- collision = true;
114
- break;
115
- }
116
- path.push({ obj: current, key: part });
117
- if (!current[part]) {
118
- current[part] = {};
119
- }
120
- current = current[part];
121
- }
122
-
123
- if (!collision) {
124
- const lastPart = toCamelCase(parts[parts.length - 1]!);
125
- if (current[lastPart] !== undefined && typeof current[lastPart] === "object") {
126
- collision = true;
127
- } else {
128
- current[lastPart] = value;
129
- }
130
- }
131
-
132
- if (collision) {
133
- // If we hit a collision, we must undo any structural changes made for this key
134
- // and just use the full camelCase key at the root.
135
- // Actually, just setting it at the root is mostly safe as long as we don't leave
136
- // empty objects that shouldn't be there. But for simplicity and robustness:
137
- result[toCamelCase(key)] = value;
138
- }
139
- }
140
- }
141
- return result;
142
- }
@@ -1,149 +0,0 @@
1
- import type { Field } from "../../types";
2
-
3
- export function toSnakeCase(str: string): string {
4
- const res = str.replace(/([A-Z])/g, "_$1").toLowerCase();
5
- if (res.startsWith("_") && !str.startsWith("_")) {
6
- return res.slice(1);
7
- }
8
- return res;
9
- }
10
-
11
- /**
12
- * Maps an OpacaCMS FieldType to a Kysely column data type for PostgreSQL.
13
- */
14
- export function mapFieldToPostgresType(field: Field): string {
15
- switch (field.type) {
16
- case "text":
17
- case "richtext":
18
- case "select":
19
- case "radio":
20
- case "relationship":
21
- return "text";
22
- case "number":
23
- return "double precision";
24
- case "boolean":
25
- return "boolean";
26
- case "date":
27
- return "timestamp with time zone";
28
- case "json":
29
- case "file":
30
- return "jsonb";
31
- default:
32
- return "text";
33
- }
34
- }
35
-
36
- /**
37
- * Maps an OpacaCMS FieldType to a Kysely column data type for SQLite/D1.
38
- */
39
- export function mapFieldToSQLiteType(field: Field): string {
40
- switch (field.type) {
41
- case "text":
42
- case "richtext":
43
- case "select":
44
- case "radio":
45
- case "relationship":
46
- case "date": // SQLite stores dates as text
47
- case "json":
48
- case "file":
49
- return "text";
50
- case "number":
51
- return "numeric";
52
- case "boolean":
53
- return "integer"; // 0 or 1
54
- default:
55
- return "text";
56
- }
57
- }
58
-
59
- /**
60
- * Recursively flattens a field list, collecting only fields with a 'name'.
61
- * This skips layout fields like 'row', 'collapsible', 'tabs' while preserving their nested named fields.
62
- * Group and Blocks fields are also flattened, prefixing their children's names to avoid collisions.
63
- * It explicitly excludes virtual fields like 'join' since they are resolved at runtime.
64
- */
65
- export function flattenFields(fields: Field[], prefix = ""): Field[] {
66
- const result: Field[] = [];
67
-
68
- for (const field of fields) {
69
- if (field.type === "join" || field.type === "virtual") continue;
70
-
71
- const currentName = field.name ? `${prefix}${field.name}` : undefined;
72
-
73
- if (field.type === "group") {
74
- if (field.fields && Array.isArray(field.fields)) {
75
- const nextPrefix = currentName ? `${currentName}__` : "";
76
- result.push(...flattenFields(field.fields, nextPrefix));
77
- }
78
- continue;
79
- }
80
-
81
- if (field.type === "blocks") {
82
- continue;
83
- }
84
-
85
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
86
- continue;
87
- }
88
-
89
- if (currentName) {
90
- result.push({ ...field, name: currentName });
91
- }
92
-
93
- if (field.type === "row" || field.type === "collapsible") {
94
- if (field.fields && Array.isArray(field.fields)) {
95
- result.push(...flattenFields(field.fields, prefix));
96
- }
97
- }
98
-
99
- if (field.type === "tabs" && field.tabs && Array.isArray(field.tabs)) {
100
- for (const tab of field.tabs) {
101
- if (tab.fields && Array.isArray(tab.fields)) {
102
- result.push(...flattenFields(tab.fields, prefix));
103
- }
104
- }
105
- }
106
- }
107
-
108
- return result;
109
- }
110
-
111
- /**
112
- * Recursively find all relational fields (relationship with hasMany or blocks).
113
- * This is used by adapters to fetch related data during findOne/find.
114
- */
115
- export function getRelationalFields(fields: Field[], prefix = ""): Field[] {
116
- const result: Field[] = [];
117
-
118
- for (const field of fields) {
119
- const currentName = field.name ? `${prefix}${field.name}` : undefined;
120
-
121
- if (
122
- (field.type === "relationship" && "hasMany" in field && field.hasMany) ||
123
- field.type === "blocks"
124
- ) {
125
- if (currentName) {
126
- result.push({ ...field, name: currentName });
127
- }
128
- continue;
129
- }
130
-
131
- if (field.type === "group" || field.type === "row" || field.type === "collapsible") {
132
- if (field.fields && Array.isArray(field.fields)) {
133
- const nextPrefix = field.type === "group" && field.name ? `${currentName}__` : prefix;
134
- result.push(...getRelationalFields(field.fields, nextPrefix));
135
- }
136
- continue;
137
- }
138
-
139
- if (field.type === "tabs" && field.tabs && Array.isArray(field.tabs)) {
140
- for (const tab of field.tabs) {
141
- if (tab.fields && Array.isArray(tab.fields)) {
142
- result.push(...getRelationalFields(tab.fields, prefix));
143
- }
144
- }
145
- }
146
- }
147
-
148
- return result;
149
- }
@@ -1,223 +0,0 @@
1
- import type { Collection, Global } from "../../types";
2
- import {
3
- flattenFields,
4
- mapFieldToPostgresType,
5
- mapFieldToSQLiteType,
6
- toSnakeCase,
7
- } from "./field-mapper";
8
-
9
- /**
10
- * Generates Kysely migration code for 'up' and 'down' functions based on schema definitions.
11
- */
12
- export function generateMigrationCode(
13
- collections: Collection[],
14
- globals: Global[] = [],
15
- dialect: "postgres" | "sqlite" | "d1",
16
- ): string {
17
- const allSchemas = [...collections, ...globals];
18
- const mapType = dialect === "postgres" ? mapFieldToPostgresType : mapFieldToSQLiteType;
19
- const tsType = dialect === "postgres" ? "timestamp with time zone" : "text";
20
-
21
- let upCode = "";
22
- let downCode = "";
23
-
24
- for (const collection of allSchemas) {
25
- const slug = collection.slug;
26
- const flattenedFields = flattenFields(collection.fields);
27
-
28
- // Main Table
29
- upCode += ` await db.schema.createTable('${slug}')\n`;
30
- upCode += ` .addColumn('id', 'text', (col) => col.primaryKey())\n`;
31
-
32
- for (const field of flattenedFields) {
33
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) continue;
34
- const colName = toSnakeCase(field.name!);
35
- if (colName === "id") continue;
36
-
37
- const colType = mapType(field);
38
- const constraints: string[] = [];
39
- if (field.required) constraints.push("notNull()");
40
- if (field.unique) constraints.push("unique()");
41
-
42
- if (field.defaultValue !== undefined) {
43
- let val = field.defaultValue;
44
- if (typeof val === "string") {
45
- val = `'${val}'`;
46
- } else if (typeof val === "boolean") {
47
- val = dialect === "sqlite" || dialect === "d1" ? (val ? 1 : 0) : val;
48
- }
49
- constraints.push(`defaultTo(${val})`);
50
- }
51
-
52
- const constraintChain = constraints.length > 0 ? `.${constraints.join(".")}` : "";
53
- upCode += ` .addColumn('${colName}', '${colType}', (col) => col${constraintChain})\n`;
54
- }
55
-
56
- // Timestamps
57
- const ts = (collection as any).timestamps !== false;
58
- if (ts) {
59
- const config =
60
- typeof (collection as any).timestamps === "object" ? (collection as any).timestamps : {};
61
- const createdField = toSnakeCase(config.createdAt || "createdAt");
62
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
63
- upCode += ` .addColumn('${createdField}', '${tsType}', (col) => col.defaultTo(sql\`CURRENT_TIMESTAMP\`))\n`;
64
- upCode += ` .addColumn('${updatedField}', '${tsType}', (col) => col.defaultTo(sql\`CURRENT_TIMESTAMP\`))\n`;
65
- }
66
- upCode += ` .execute();\n\n`;
67
-
68
- downCode = ` await db.schema.dropTable('${slug}').execute();\n` + downCode;
69
-
70
- // Join Tables
71
- for (const field of flattenedFields) {
72
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
73
- const colName = toSnakeCase(field.name!);
74
- const joinTableName = `${slug}_${colName}_relations`.toLowerCase();
75
- upCode += ` await db.schema.createTable('${joinTableName}')\n`;
76
- upCode += ` .addColumn('id', 'text', (col) => col.primaryKey())\n`;
77
- upCode += ` .addColumn('source_id', 'text', (col) => col.notNull())\n`;
78
- upCode += ` .addColumn('target_id', 'text', (col) => col.notNull())\n`;
79
- upCode += ` .addColumn('order', 'integer', (col) => col.defaultTo(0))\n`;
80
- upCode += ` .execute();\n\n`;
81
-
82
- downCode = ` await db.schema.dropTable('${joinTableName}').execute();\n` + downCode;
83
- }
84
- }
85
-
86
- // Block Tables
87
- for (const field of collection.fields) {
88
- if (field.type === "blocks" && field.blocks && Array.isArray(field.blocks)) {
89
- for (const block of field.blocks) {
90
- const blockName = toSnakeCase(field.name!);
91
- const blockTableName = `${slug}_${blockName}_${block.slug}`.toLowerCase();
92
-
93
- upCode += ` await db.schema.createTable('${blockTableName}')\n`;
94
- upCode += ` .addColumn('id', 'text', (col) => col.primaryKey())\n`;
95
- upCode += ` .addColumn('_parent_id', 'text', (col) => col.notNull())\n`;
96
- upCode += ` .addColumn('_order', 'integer', (col) => col.defaultTo(0))\n`;
97
- upCode += ` .addColumn('block_type', 'text', (col) => col.notNull())\n`;
98
-
99
- const blockFlattened = flattenFields(block.fields);
100
- for (const bField of blockFlattened) {
101
- const bColName = toSnakeCase(bField.name!);
102
- if (bColName === "id") continue;
103
- const bColType = mapType(bField);
104
-
105
- const bConstraints: string[] = [];
106
- if (bField.required) bConstraints.push("notNull()");
107
- if (bField.unique) bConstraints.push("unique()");
108
- if (bField.defaultValue !== undefined) {
109
- let bVal = bField.defaultValue;
110
- if (typeof bVal === "string") bVal = `'${bVal}'`;
111
- else if (typeof bVal === "boolean")
112
- bVal = dialect === "sqlite" || dialect === "d1" ? (bVal ? 1 : 0) : bVal;
113
- bConstraints.push(`defaultTo(${bVal})`);
114
- }
115
-
116
- const bConstraintChain = bConstraints.length > 0 ? `.${bConstraints.join(".")}` : "";
117
- upCode += ` .addColumn('${bColName}', '${bColType}', (col) => col${bConstraintChain})\n`;
118
- }
119
- upCode += ` .addColumn('created_at', '${tsType}', (col) => col.defaultTo(sql\`CURRENT_TIMESTAMP\`))\n`;
120
- upCode += ` .addColumn('updated_at', '${tsType}', (col) => col.defaultTo(sql\`CURRENT_TIMESTAMP\`))\n`;
121
- upCode += ` .execute();\n\n`;
122
-
123
- downCode = ` await db.schema.dropTable('${blockTableName}').execute();\n` + downCode;
124
- }
125
- }
126
- }
127
- }
128
-
129
- return `import { type OpacaMigrationDb, sql } from 'opacacms/db';
130
-
131
- export async function up(db: OpacaMigrationDb): Promise<void> {
132
- ${upCode}}
133
-
134
- export async function down(db: OpacaMigrationDb): Promise<void> {
135
- ${downCode}}
136
- `;
137
- }
138
-
139
- /**
140
- * Generates raw SQL migration code for Cloudflare D1.
141
- */
142
- export function generateSQLCode(collections: Collection[], globals: Global[] = []): string {
143
- const allSchemas = [...collections, ...globals];
144
- let sql = "-- OpacaCMS Auto-generated SQL Migration\n\n";
145
-
146
- for (const collection of allSchemas) {
147
- const slug = collection.slug;
148
- const flattenedFields = flattenFields(collection.fields);
149
-
150
- sql += `CREATE TABLE IF NOT EXISTS "${slug}" (\n`;
151
- sql += ` "id" TEXT PRIMARY KEY`;
152
-
153
- for (const field of flattenedFields) {
154
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) continue;
155
- const colName = toSnakeCase(field.name!);
156
- if (colName === "id") continue;
157
-
158
- const colType = mapFieldToSQLiteType(field);
159
- sql += `,\n "${colName}" ${colType.toUpperCase()}`;
160
- if (field.required) sql += " NOT NULL";
161
- if (field.unique) sql += " UNIQUE";
162
- if (field.defaultValue !== undefined) {
163
- let val = field.defaultValue;
164
- if (typeof val === "string") val = `'${val}'`;
165
- else if (typeof val === "boolean") val = val ? 1 : 0;
166
- sql += ` DEFAULT ${val}`;
167
- }
168
- }
169
-
170
- const ts = (collection as any).timestamps !== false;
171
- if (ts) {
172
- const config =
173
- typeof (collection as any).timestamps === "object" ? (collection as any).timestamps : {};
174
- const createdField = toSnakeCase(config.createdAt || "createdAt");
175
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
176
- sql += `,\n "${createdField}" TEXT DEFAULT CURRENT_TIMESTAMP`;
177
- sql += `,\n "${updatedField}" TEXT DEFAULT CURRENT_TIMESTAMP`;
178
- }
179
- sql += "\n);\n\n";
180
-
181
- // Join Tables
182
- for (const field of flattenedFields) {
183
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
184
- const colName = toSnakeCase(field.name!);
185
- const joinTableName = `${slug}_${colName}_relations`.toLowerCase();
186
- sql += `CREATE TABLE IF NOT EXISTS "${joinTableName}" (\n`;
187
- sql += ` "id" TEXT PRIMARY KEY,\n`;
188
- sql += ` "source_id" TEXT NOT NULL,\n`;
189
- sql += ` "target_id" TEXT NOT NULL,\n`;
190
- sql += ` "order" INTEGER DEFAULT 0\n`;
191
- sql += `);\n\n`;
192
- }
193
- }
194
-
195
- // Block Tables
196
- for (const field of collection.fields) {
197
- if (field.type === "blocks" && field.blocks && Array.isArray(field.blocks)) {
198
- for (const block of field.blocks) {
199
- const blockName = toSnakeCase(field.name!);
200
- const blockTableName = `${slug}_${blockName}_${block.slug}`.toLowerCase();
201
- sql += `CREATE TABLE IF NOT EXISTS "${blockTableName}" (\n`;
202
- sql += ` "id" TEXT PRIMARY KEY,\n`;
203
- sql += ` "_parent_id" TEXT NOT NULL,\n`;
204
- sql += ` "_order" INTEGER DEFAULT 0,\n`;
205
- sql += ` "block_type" TEXT NOT NULL`;
206
-
207
- const blockFlattened = flattenFields(block.fields);
208
- for (const bField of blockFlattened) {
209
- const bColName = toSnakeCase(bField.name!);
210
- if (bColName === "id") continue;
211
- const bColType = mapFieldToSQLiteType(bField);
212
- sql += `,\n "${bColName}" ${bColType.toUpperCase()}`;
213
- }
214
- sql += `,\n "created_at" TEXT DEFAULT CURRENT_TIMESTAMP,\n`;
215
- sql += ` "updated_at" TEXT DEFAULT CURRENT_TIMESTAMP\n`;
216
- sql += `);\n\n`;
217
- }
218
- }
219
- }
220
- }
221
-
222
- return sql;
223
- }
@@ -1,92 +0,0 @@
1
- import type { ExpressionBuilder } from "kysely";
2
-
3
- /**
4
- * Builds a Kysely expression from a generic query object.
5
- *
6
- * @param eb The Kysely ExpressionBuilder (e.g., from .where((eb) => buildKyselyWhere(eb, query)))
7
- * @param query The query object (e.g., { age: { gt: 18 }, name: 'John' })
8
- * @returns A single Expression combining all conditions with AND, or undefined.
9
- */
10
- export function buildKyselyWhere(
11
- eb: ExpressionBuilder<any, any>,
12
- query: Record<string, any> | undefined,
13
- ): any {
14
- if (!query || Object.keys(query).length === 0) return undefined;
15
-
16
- const conditions: any[] = [];
17
-
18
- for (const [key, value] of Object.entries(query)) {
19
- if (value === undefined) continue;
20
-
21
- if (key === "or" && Array.isArray(value)) {
22
- const orConditions = value.map((v) => buildKyselyWhere(eb, v)).filter((c) => c !== undefined);
23
- if (orConditions.length > 0) {
24
- conditions.push(eb.or(orConditions));
25
- }
26
- continue;
27
- }
28
-
29
- if (key === "and" && Array.isArray(value)) {
30
- const andConditions = value
31
- .map((v) => buildKyselyWhere(eb, v))
32
- .filter((c) => c !== undefined);
33
- if (andConditions.length > 0) {
34
- conditions.push(eb.and(andConditions));
35
- }
36
- continue;
37
- }
38
-
39
- if (
40
- typeof value === "object" &&
41
- value !== null &&
42
- !Array.isArray(value) &&
43
- !(value instanceof Date)
44
- ) {
45
- for (const [op, val] of Object.entries(value)) {
46
- if (val === undefined) continue;
47
- switch (op) {
48
- case "gt":
49
- conditions.push(eb(key, ">", val));
50
- break;
51
- case "gte":
52
- conditions.push(eb(key, ">=", val));
53
- break;
54
- case "lt":
55
- conditions.push(eb(key, "<", val));
56
- break;
57
- case "lte":
58
- conditions.push(eb(key, "<=", val));
59
- break;
60
- case "like":
61
- conditions.push(eb(key, "like", String(val)));
62
- break;
63
- case "ne":
64
- if (val === null) conditions.push(eb(key, "is not", null));
65
- else conditions.push(eb(key, "!=", val));
66
- break;
67
- case "in":
68
- if (Array.isArray(val)) conditions.push(eb(key, "in", val));
69
- break;
70
- case "is":
71
- if (val === null) conditions.push(eb(key, "is", null));
72
- break;
73
- default:
74
- if (val === null) conditions.push(eb(key, "is", null));
75
- else conditions.push(eb(key, "=", val));
76
- break;
77
- }
78
- }
79
- } else {
80
- if (value === null) {
81
- conditions.push(eb(key, "is", null));
82
- } else {
83
- conditions.push(eb(key, "=", value));
84
- }
85
- }
86
- }
87
-
88
- if (conditions.length === 0) return undefined;
89
- if (conditions.length === 1) return conditions[0];
90
-
91
- return eb.and(conditions);
92
- }