opacacms 0.1.0 → 0.1.2

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 (247) hide show
  1. package/dist/admin/index.js +49 -0
  2. package/dist/{chunk-2zm8cy1w.js → admin/webcomponent.js} +116 -168
  3. package/dist/{chunk-6dhs73zq.js → chunk-2yz1nsxs.js} +1 -1
  4. package/dist/chunk-fa5mg0hr.js +96 -0
  5. package/dist/{chunk-kwp83w8b.js → chunk-m09hahe2.js} +7 -7
  6. package/dist/{chunk-hmhcense.js → chunk-ry15hke8.js} +253 -4
  7. package/dist/chunk-vtvqfhgy.js +2442 -0
  8. package/dist/{chunk-f3nvxn63.js → chunk-y8hc6nm4.js} +1 -1
  9. package/dist/{src/cli → cli}/index.js +10 -10
  10. package/dist/{src/client.js → client.js} +2 -2
  11. package/dist/{src/db → db}/bun-sqlite.js +10 -10
  12. package/dist/{src/db → db}/d1.js +8 -8
  13. package/dist/db/index.d.ts +2 -0
  14. package/dist/db/index.js +7 -0
  15. package/dist/db/migration.d.ts +39 -0
  16. package/dist/{src/db → db}/postgres.js +10 -10
  17. package/dist/{src/db → db}/sqlite.js +8 -8
  18. package/dist/index.d.ts +0 -2
  19. package/dist/index.js +13 -0
  20. package/dist/{src/runtimes → runtimes}/bun.js +5 -6
  21. package/dist/{src/runtimes → runtimes}/cloudflare-workers.js +5 -6
  22. package/dist/{src/runtimes → runtimes}/next.js +5 -6
  23. package/dist/{src/runtimes → runtimes}/node.js +5 -6
  24. package/dist/{src/server.js → server.js} +7 -8
  25. package/dist/storage/index.d.ts +0 -3
  26. package/dist/storage/index.js +35 -0
  27. package/dist/types.d.ts +5 -2
  28. package/package.json +161 -39
  29. package/bun.lock +0 -34
  30. package/dist/api.d.ts +0 -6
  31. package/dist/chunk-8gkhn1d4.js +0 -309
  32. package/dist/chunk-dy5t83hr.js +0 -261
  33. package/dist/src/admin/index.js +0 -176
  34. package/dist/src/admin/webcomponent.js +0 -19
  35. package/dist/src/api.js +0 -27
  36. package/dist/src/index.js +0 -20
  37. package/dist/src/storage/index.js +0 -355
  38. package/global.d.ts +0 -11
  39. package/src/admin/api-client.ts +0 -63
  40. package/src/admin/auth-client.ts +0 -40
  41. package/src/admin/custom-field.ts +0 -179
  42. package/src/admin/index.ts +0 -15
  43. package/src/admin/react.tsx +0 -72
  44. package/src/admin/router.ts +0 -9
  45. package/src/admin/stores/admin-queries.ts +0 -121
  46. package/src/admin/stores/auth.ts +0 -61
  47. package/src/admin/stores/column-visibility.ts +0 -67
  48. package/src/admin/stores/config.ts +0 -15
  49. package/src/admin/stores/media.ts +0 -95
  50. package/src/admin/stores/query.ts +0 -13
  51. package/src/admin/stores/ui.ts +0 -29
  52. package/src/admin/ui/admin-client.tsx +0 -283
  53. package/src/admin/ui/admin-layout.tsx +0 -276
  54. package/src/admin/ui/components/ColumnVisibilityToggle.tsx +0 -141
  55. package/src/admin/ui/components/DataDetailSheet.tsx +0 -141
  56. package/src/admin/ui/components/DataDetailView.tsx +0 -175
  57. package/src/admin/ui/components/Table.tsx +0 -67
  58. package/src/admin/ui/components/fields/ArrayField.tsx +0 -166
  59. package/src/admin/ui/components/fields/BlocksField.tsx +0 -202
  60. package/src/admin/ui/components/fields/BooleanField.tsx +0 -50
  61. package/src/admin/ui/components/fields/CollapsibleField.tsx +0 -75
  62. package/src/admin/ui/components/fields/DateField.tsx +0 -45
  63. package/src/admin/ui/components/fields/FileField.tsx +0 -322
  64. package/src/admin/ui/components/fields/GroupField.tsx +0 -50
  65. package/src/admin/ui/components/fields/JoinField.tsx +0 -23
  66. package/src/admin/ui/components/fields/NumberField.tsx +0 -46
  67. package/src/admin/ui/components/fields/RadioField.tsx +0 -62
  68. package/src/admin/ui/components/fields/RelationshipField.tsx +0 -278
  69. package/src/admin/ui/components/fields/RowField.tsx +0 -40
  70. package/src/admin/ui/components/fields/SelectField.tsx +0 -59
  71. package/src/admin/ui/components/fields/TabsField.tsx +0 -101
  72. package/src/admin/ui/components/fields/TextAreaField.tsx +0 -54
  73. package/src/admin/ui/components/fields/TextField.tsx +0 -49
  74. package/src/admin/ui/components/fields/VirtualField.tsx +0 -53
  75. package/src/admin/ui/components/fields/index.tsx +0 -371
  76. package/src/admin/ui/components/fields/richtext-editor/index.tsx +0 -211
  77. package/src/admin/ui/components/fields/richtext-editor/nodes/ImageComponent.tsx +0 -142
  78. package/src/admin/ui/components/fields/richtext-editor/nodes/ImageNode.tsx +0 -95
  79. package/src/admin/ui/components/fields/richtext-editor/plugins/ComponentPickerPlugin.tsx +0 -226
  80. package/src/admin/ui/components/fields/richtext-editor/plugins/EditableSyncPlugin.tsx +0 -16
  81. package/src/admin/ui/components/fields/richtext-editor/plugins/NotionToolbarPlugin.tsx +0 -184
  82. package/src/admin/ui/components/fields/richtext-editor/plugins/SimpleToolbarPlugin.tsx +0 -240
  83. package/src/admin/ui/components/fields/richtext-editor/plugins/ValueSyncPlugin.tsx +0 -40
  84. package/src/admin/ui/components/fields/utils.ts +0 -1
  85. package/src/admin/ui/components/link.tsx +0 -41
  86. package/src/admin/ui/components/media/AssetManagerModal.tsx +0 -334
  87. package/src/admin/ui/components/toast.tsx +0 -72
  88. package/src/admin/ui/components/ui/accordion.tsx +0 -51
  89. package/src/admin/ui/components/ui/alert-dialog.tsx +0 -98
  90. package/src/admin/ui/components/ui/blocks.tsx +0 -32
  91. package/src/admin/ui/components/ui/breadcrumbs.tsx +0 -59
  92. package/src/admin/ui/components/ui/button.tsx +0 -26
  93. package/src/admin/ui/components/ui/collapsible.tsx +0 -124
  94. package/src/admin/ui/components/ui/dialog.tsx +0 -79
  95. package/src/admin/ui/components/ui/group.tsx +0 -20
  96. package/src/admin/ui/components/ui/index.ts +0 -17
  97. package/src/admin/ui/components/ui/input.tsx +0 -12
  98. package/src/admin/ui/components/ui/join.tsx +0 -53
  99. package/src/admin/ui/components/ui/label.tsx +0 -11
  100. package/src/admin/ui/components/ui/radio-group.tsx +0 -75
  101. package/src/admin/ui/components/ui/relationship-detail-sheet.tsx +0 -122
  102. package/src/admin/ui/components/ui/relationship.tsx +0 -58
  103. package/src/admin/ui/components/ui/scroll-area.tsx +0 -19
  104. package/src/admin/ui/components/ui/select.tsx +0 -187
  105. package/src/admin/ui/components/ui/separator.tsx +0 -21
  106. package/src/admin/ui/components/ui/sheet.tsx +0 -106
  107. package/src/admin/ui/components/ui/tabs.tsx +0 -116
  108. package/src/admin/ui/components/ui/utils.ts +0 -3
  109. package/src/admin/ui/hooks/use-debounce.ts +0 -15
  110. package/src/admin/ui/styles/_locale-switcher.scss +0 -33
  111. package/src/admin/ui/styles/accordion.scss +0 -60
  112. package/src/admin/ui/styles/animations.scss +0 -41
  113. package/src/admin/ui/styles/asset-manager.scss +0 -547
  114. package/src/admin/ui/styles/badge.scss +0 -13
  115. package/src/admin/ui/styles/base.scss +0 -22
  116. package/src/admin/ui/styles/button.scss +0 -161
  117. package/src/admin/ui/styles/card.scss +0 -13
  118. package/src/admin/ui/styles/collapsible.scss +0 -75
  119. package/src/admin/ui/styles/data-detail.scss +0 -92
  120. package/src/admin/ui/styles/dialog.scss +0 -102
  121. package/src/admin/ui/styles/empty-state.scss +0 -22
  122. package/src/admin/ui/styles/group.scss +0 -19
  123. package/src/admin/ui/styles/index.scss +0 -33
  124. package/src/admin/ui/styles/input.scss +0 -80
  125. package/src/admin/ui/styles/label.scss +0 -12
  126. package/src/admin/ui/styles/layout.scss +0 -56
  127. package/src/admin/ui/styles/lexical.scss +0 -469
  128. package/src/admin/ui/styles/loading.scss +0 -102
  129. package/src/admin/ui/styles/media-registry.scss +0 -597
  130. package/src/admin/ui/styles/pagination.scss +0 -20
  131. package/src/admin/ui/styles/radio-group.scss +0 -66
  132. package/src/admin/ui/styles/row.scss +0 -17
  133. package/src/admin/ui/styles/scrollbar.scss +0 -36
  134. package/src/admin/ui/styles/select.scss +0 -121
  135. package/src/admin/ui/styles/separator.scss +0 -14
  136. package/src/admin/ui/styles/sheet.scss +0 -152
  137. package/src/admin/ui/styles/sidebar.scss +0 -148
  138. package/src/admin/ui/styles/switch.scss +0 -59
  139. package/src/admin/ui/styles/table.scss +0 -207
  140. package/src/admin/ui/styles/tabs.scss +0 -62
  141. package/src/admin/ui/styles/toast.scss +0 -45
  142. package/src/admin/ui/styles/variables.scss +0 -24
  143. package/src/admin/ui/views/collection-list-view.tsx +0 -720
  144. package/src/admin/ui/views/dashboard-view.tsx +0 -263
  145. package/src/admin/ui/views/document-edit-view.tsx +0 -384
  146. package/src/admin/ui/views/global-edit-view.tsx +0 -226
  147. package/src/admin/ui/views/init-view.tsx +0 -182
  148. package/src/admin/ui/views/login-view.tsx +0 -123
  149. package/src/admin/ui/views/media-registry-view.tsx +0 -1104
  150. package/src/admin/ui/views/settings-view.tsx +0 -729
  151. package/src/admin/webcomponent.tsx +0 -15
  152. package/src/api.ts +0 -9
  153. package/src/auth/index.ts +0 -194
  154. package/src/auth/migrations.ts +0 -87
  155. package/src/auth/premissions.ts +0 -46
  156. package/src/cli/commands/generate-types.ts +0 -116
  157. package/src/cli/commands/init.ts +0 -95
  158. package/src/cli/commands/migrate-commands.ts +0 -160
  159. package/src/cli/commands/seed-command.ts +0 -11
  160. package/src/cli/d1-mock.ts +0 -101
  161. package/src/cli/index.test.ts +0 -84
  162. package/src/cli/index.ts +0 -183
  163. package/src/cli/r2-mock.ts +0 -217
  164. package/src/cli/seeding.ts +0 -405
  165. package/src/client.ts +0 -181
  166. package/src/config-utils.ts +0 -102
  167. package/src/config.ts +0 -49
  168. package/src/db/adapter.ts +0 -53
  169. package/src/db/better-sqlite.ts +0 -630
  170. package/src/db/bun-sqlite.ts +0 -646
  171. package/src/db/d1.ts +0 -711
  172. package/src/db/kysely/data-mapper.ts +0 -142
  173. package/src/db/kysely/field-mapper.ts +0 -148
  174. package/src/db/kysely/migration-generator.ts +0 -223
  175. package/src/db/kysely/query-builder.ts +0 -92
  176. package/src/db/kysely/schema-builder.ts +0 -439
  177. package/src/db/kysely/sql-utils.ts +0 -13
  178. package/src/db/postgres.ts +0 -621
  179. package/src/db/sqlite.ts +0 -658
  180. package/src/db/system-schema.ts +0 -121
  181. package/src/index.ts +0 -13
  182. package/src/runtimes/README.md +0 -59
  183. package/src/runtimes/bun.ts +0 -49
  184. package/src/runtimes/cloudflare-workers.ts +0 -38
  185. package/src/runtimes/next.ts +0 -26
  186. package/src/runtimes/node.ts +0 -52
  187. package/src/schema/collection.ts +0 -184
  188. package/src/schema/fields/base.ts +0 -164
  189. package/src/schema/fields/index.ts +0 -427
  190. package/src/schema/global.ts +0 -145
  191. package/src/schema/index.ts +0 -4
  192. package/src/schema/infer.ts +0 -72
  193. package/src/server/admin-router.ts +0 -20
  194. package/src/server/admin.ts +0 -142
  195. package/src/server/assets.ts +0 -306
  196. package/src/server/collection-router.ts +0 -55
  197. package/src/server/handlers.ts +0 -722
  198. package/src/server/middlewares/admin.ts +0 -27
  199. package/src/server/middlewares/auth.ts +0 -89
  200. package/src/server/middlewares/context.ts +0 -17
  201. package/src/server/middlewares/cors.ts +0 -24
  202. package/src/server/middlewares/database-init.ts +0 -74
  203. package/src/server/middlewares/rate-limit.ts +0 -71
  204. package/src/server/router.ts +0 -47
  205. package/src/server/setup-middlewares.ts +0 -58
  206. package/src/server/system-router.ts +0 -35
  207. package/src/server.ts +0 -9
  208. package/src/storage/adapters/cloudflare-r2.ts +0 -136
  209. package/src/storage/adapters/local.ts +0 -146
  210. package/src/storage/adapters/s3.ts +0 -186
  211. package/src/storage/errors.ts +0 -46
  212. package/src/storage/index.ts +0 -5
  213. package/src/storage/types.ts +0 -39
  214. package/src/types.ts +0 -577
  215. package/src/utils/lexical.ts +0 -37
  216. package/src/utils/logger.ts +0 -73
  217. package/src/validation.ts +0 -429
  218. package/src/validator.ts +0 -179
  219. package/test/admin-custom-field.test.ts +0 -162
  220. package/test/admin-react-field.test.tsx +0 -134
  221. package/test/api-features.test.ts +0 -78
  222. package/test/api.test.ts +0 -178
  223. package/test/auth.test.ts +0 -62
  224. package/test/cli-integration.test.ts +0 -146
  225. package/test/cli.test.ts +0 -25
  226. package/test/db/postgres.test.ts +0 -95
  227. package/test/db/sqlite-filter.test.ts +0 -53
  228. package/test/db/sqlite.test.ts +0 -82
  229. package/test/engine-features.test.ts +0 -79
  230. package/test/globals.test.ts +0 -74
  231. package/test/integration-tmp/db-app/opacacms.config.ts +0 -15
  232. package/test/integration-tmp/my-sqlite-app/opacacms.config.ts +0 -25
  233. package/test/integration-tmp/my-test-app/index.ts +0 -8
  234. package/test/integration-tmp/my-test-app/opacacms.config.ts +0 -16
  235. package/test/integration-tmp/my-test-app/package.json +0 -12
  236. package/test/populate.test.ts +0 -79
  237. package/test/runtimes.test.ts +0 -43
  238. package/test/schema-builder.test.ts +0 -107
  239. package/test/schema-features.test.ts +0 -63
  240. package/test/seeding.test.ts +0 -68
  241. package/test/storage/local.test.ts +0 -72
  242. package/test/storage/s3.test.ts +0 -60
  243. package/test/structural-data.test.ts +0 -100
  244. package/test/test-setup.ts +0 -11
  245. package/test/validation.test.ts +0 -162
  246. package/tsconfig.json +0 -42
  247. /package/dist/{src/admin/index.css → admin/webcomponent.css} +0 -0
@@ -1,646 +0,0 @@
1
- import { Database } from "bun:sqlite";
2
- import fs from "node:fs/promises";
3
- import path from "node:path";
4
- import { FileMigrationProvider, Kysely, Migrator, sql } from "kysely";
5
- import { BunSqliteDialect } from "kysely-bun-sqlite";
6
- import type { Collection, FindOptions, Global, PaginatedResult } from "../types";
7
- import { logger } from "../utils/logger";
8
- import { BaseDatabaseAdapter } from "./adapter";
9
- import { flattenPayload, unflattenRow } from "./kysely/data-mapper";
10
- import { flattenFields, getRelationalFields, toSnakeCase } from "./kysely/field-mapper";
11
- import { buildKyselyWhere } from "./kysely/query-builder";
12
- import { pushSchema } from "./kysely/schema-builder";
13
-
14
- export class BunSQLiteAdapter extends BaseDatabaseAdapter {
15
- override name = "bun-sqlite";
16
- private _rawDb: any;
17
- private _db: Kysely<any>;
18
- private _collections: Collection[] = [];
19
- override push: boolean;
20
- override migrationDir: string;
21
- override pushDestructive: boolean;
22
-
23
- override get raw() {
24
- return this._rawDb;
25
- }
26
-
27
- override get db() {
28
- return this._db;
29
- }
30
-
31
- constructor(
32
- path: string,
33
- options?: { push?: boolean; pushDestructive?: boolean; migrationDir?: string },
34
- ) {
35
- super();
36
- this._rawDb = new Database(path);
37
- this._db = new Kysely<any>({
38
- dialect: new BunSqliteDialect({
39
- database: this._rawDb,
40
- }),
41
- });
42
- this.push = options?.push ?? process.env.NODE_ENV !== "production";
43
- this.pushDestructive = options?.pushDestructive ?? false;
44
- this.migrationDir = options?.migrationDir ?? "./migrations";
45
- }
46
-
47
- override async connect() {
48
- // Synchronous internally
49
- }
50
-
51
- override async disconnect() {
52
- await this._db.destroy();
53
- }
54
-
55
- override async unsafe(query: string, params?: any[]): Promise<unknown> {
56
- const compiled = sql.raw(query);
57
- const result = await compiled.execute(this._db);
58
- return result.rows;
59
- }
60
-
61
- private async coerceData(collection: string, data: any): Promise<any> {
62
- const colDef = this._collections.find((c) => c.slug === collection);
63
- if (!colDef) return data;
64
-
65
- const result = { ...data };
66
- const allFields = flattenFields(colDef.fields);
67
-
68
- for (const field of allFields) {
69
- const colName = toSnakeCase(field.name!);
70
- if (!(colName in result)) continue;
71
-
72
- const value = result[colName];
73
- if (value === undefined || value === null) continue;
74
-
75
- switch (field.type) {
76
- case "boolean":
77
- result[colName] = value ? 1 : 0;
78
- break;
79
- case "number":
80
- result[colName] = Number(value);
81
- break;
82
- case "date":
83
- if (value instanceof Date) {
84
- result[colName] = value.toISOString();
85
- } else if (typeof value === "string") {
86
- result[colName] = new Date(value).toISOString();
87
- }
88
- break;
89
- case "richtext":
90
- case "json":
91
- case "file":
92
- if (typeof value === "object") {
93
- result[colName] = JSON.stringify(value);
94
- }
95
- break;
96
- }
97
- }
98
-
99
- return result;
100
- }
101
-
102
- override async count(collection: string, query?: Record<string, unknown>): Promise<number> {
103
- const tableName = toSnakeCase(collection);
104
- let qb = this._db.selectFrom(tableName).select((eb) => eb.fn.count("id").as("count"));
105
- if (query && Object.keys(query).length > 0) {
106
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
107
- }
108
- const result = await qb.executeTakeFirst();
109
- return Number(result?.count || 0);
110
- }
111
-
112
- override async create<T extends object>(collection: string, data: Partial<T>): Promise<T> {
113
- const tableName = toSnakeCase(collection);
114
- const colDef = this._collections.find((c) => c.slug === collection);
115
- const jsonFields =
116
- colDef?.fields
117
- .filter((f) => f.name && ["richtext", "json", "file"].includes(f.type))
118
- .map((f) => toSnakeCase(f.name!)) || [];
119
-
120
- const flatData = flattenPayload(data, "", jsonFields);
121
-
122
- // Stringify JSON fields for SQLite
123
- for (const field of jsonFields) {
124
- if (flatData[field] && typeof flatData[field] === "object") {
125
- flatData[field] = JSON.stringify(flatData[field]);
126
- }
127
- }
128
-
129
- const relationalFields = getRelationalFields(colDef?.fields || []);
130
- const hasManyData: Record<string, unknown[]> = {};
131
- const blocksData: Record<string, unknown[]> = {};
132
-
133
- for (const field of relationalFields) {
134
- const key = field.name!;
135
- if (Array.isArray(flatData[key])) {
136
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
137
- hasManyData[key] = flatData[key];
138
- } else if (field.type === "blocks") {
139
- blocksData[key] = flatData[key];
140
- }
141
- delete flatData[key];
142
- }
143
- }
144
-
145
- if (!flatData.id) flatData.id = crypto.randomUUID();
146
-
147
- // Whitelist only fields that exist in the database
148
- const dbFields = flattenFields(colDef?.fields || []);
149
- const validCols = new Set(dbFields.map((f: any) => toSnakeCase(f.name!)));
150
- validCols.add("id");
151
-
152
- const ts = colDef?.timestamps !== false;
153
- if (ts) {
154
- const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
155
- validCols.add(toSnakeCase(config.createdAt || "createdAt"));
156
- validCols.add(toSnakeCase(config.updatedAt || "updatedAt"));
157
- }
158
-
159
- const filteredData: Record<string, any> = {};
160
- for (const col of Object.keys(flatData)) {
161
- if (validCols.has(col)) {
162
- filteredData[col] = flatData[col];
163
- }
164
- }
165
-
166
- const coercedData = await this.coerceData(collection, filteredData);
167
- await this._db.insertInto(tableName).values(coercedData).execute();
168
-
169
- // hasMany relations
170
- for (const [key, values] of Object.entries(hasManyData)) {
171
- const joinTableName = `${tableName}_${toSnakeCase(key)}_relations`.toLowerCase();
172
- if (values.length > 0) {
173
- const joinData = values.map((val: any, idx: number) => {
174
- const tId = typeof val === "object" ? val.id : val;
175
- return { id: crypto.randomUUID(), source_id: flatData.id, target_id: tId, order: idx };
176
- });
177
- await this._db.insertInto(joinTableName).values(joinData).execute();
178
- }
179
- }
180
-
181
- // Blocks
182
- for (const [key, blocks] of Object.entries(blocksData)) {
183
- for (let i = 0; i < (blocks as any[]).length; i++) {
184
- const block = blocks[i] as any;
185
- if (!block.blockType) continue;
186
- const blockTableName = `${tableName}_${toSnakeCase(key)}_${toSnakeCase(
187
- block.blockType,
188
- )}`.toLowerCase();
189
- const bId = block.id || crypto.randomUUID();
190
-
191
- // Block fields also need same logic
192
- const blockDef = relationalFields.find((f) => f.name === key && f.type === "blocks");
193
- const blockConfig = (blockDef as any)?.blocks?.find((b: any) => b.slug === block.blockType);
194
- const blockJsonFields =
195
- blockConfig?.fields
196
- .filter((f: any) => ["richtext", "json", "file"].includes(f.type))
197
- .map((f: any) => f.name!) || [];
198
-
199
- const blockFlatData = flattenPayload({ ...block, id: bId }, "", blockJsonFields);
200
-
201
- for (const f of blockJsonFields) {
202
- if (blockFlatData[f] && typeof blockFlatData[f] === "object") {
203
- blockFlatData[f] = JSON.stringify(blockFlatData[f]);
204
- }
205
- }
206
-
207
- delete blockFlatData.blockType;
208
- const coercedBlockData = await this.coerceData(blockTableName, {
209
- ...blockFlatData,
210
- _parent_id: flatData.id,
211
- _order: i,
212
- block_type: block.blockType,
213
- });
214
- await this._db.insertInto(blockTableName).values(coercedBlockData).execute();
215
- }
216
- }
217
-
218
- return this.findOne<T>(collection, { id: flatData.id }, this._db) as Promise<T>;
219
- }
220
-
221
- override async findOne<T extends object>(
222
- collection: string,
223
- query: Record<string, unknown>,
224
- tx?: any,
225
- ): Promise<T | null> {
226
- const tableName = toSnakeCase(collection);
227
- const executor = tx || this._db;
228
- let qb = executor.selectFrom(tableName).selectAll();
229
- if (query && Object.keys(query).length > 0) {
230
- qb = qb.where((eb: any) => buildKyselyWhere(eb, query) || eb.val(true));
231
- }
232
-
233
- const row = await qb.executeTakeFirst();
234
- if (!row) return null;
235
-
236
- const unflattened = unflattenRow(row);
237
- const colDef = this._collections.find((c) => c.slug === collection);
238
-
239
- if (colDef) {
240
- const relationalFields = getRelationalFields(colDef.fields);
241
- for (const field of relationalFields) {
242
- if (!field.name) continue;
243
- const snakeName = toSnakeCase(field.name);
244
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
245
- const joinTableName = `${toSnakeCase(collection)}_${snakeName}_relations`.toLowerCase();
246
- try {
247
- const relations = await executor
248
- .selectFrom(joinTableName)
249
- .selectAll()
250
- .where("source_id", "=", row.id)
251
- .orderBy("order", "asc")
252
- .execute();
253
- const parts = field.name.split("__");
254
- let current = unflattened;
255
- for (let i = 0; i < parts.length - 1; i++) {
256
- if (!current[parts[i]!]) current[parts[i]!] = {};
257
- current = current[parts[i]!];
258
- }
259
- current[parts[parts.length - 1]!] = relations.map((r: any) => r.target_id);
260
- } catch (e) { }
261
- } else if (field.type === "blocks" && field.blocks) {
262
- const blockData: any[] = [];
263
- for (const b of field.blocks) {
264
- const blockTableName =
265
- `${collection}_${snakeName}_${toSnakeCase(b.slug)}`.toLowerCase();
266
- try {
267
- const blocks = await executor
268
- .selectFrom(blockTableName)
269
- .selectAll()
270
- .where("_parent_id", "=", row.id)
271
- .execute();
272
-
273
- for (const blk of blocks) {
274
- const uf = unflattenRow(blk);
275
- uf.blockType = blk.block_type;
276
- blockData.push(uf);
277
- }
278
- } catch (e) { }
279
- }
280
- blockData.sort((a, b) => a._order - b._order);
281
- blockData.forEach((b) => {
282
- delete b._order;
283
- delete b._parentId;
284
- });
285
- const parts = field.name.split("__");
286
- let current = unflattened;
287
- for (let i = 0; i < parts.length - 1; i++) {
288
- if (!current[parts[i]!]) current[parts[i]!] = {};
289
- current = current[parts[i]!];
290
- }
291
- current[parts[parts.length - 1]!] = blockData;
292
- }
293
- }
294
- }
295
-
296
- return unflattened as T;
297
- }
298
-
299
- override async find<T extends object>(
300
- collection: string,
301
- query?: Record<string, unknown>,
302
- options?: FindOptions,
303
- ): Promise<PaginatedResult<T>> {
304
- const page = options?.page || 1;
305
- const limit = options?.limit || 10;
306
- const offset = (page - 1) * limit;
307
-
308
- const total = await this.count(collection, query);
309
- const tableName = toSnakeCase(collection);
310
-
311
- let qb = this._db.selectFrom(tableName).selectAll().limit(limit).offset(offset);
312
- if (query && Object.keys(query).length > 0) {
313
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
314
- }
315
- if (options?.sort) {
316
- const [col, dir] = (options.sort ?? "").split(":");
317
-
318
- if (col) {
319
- qb = qb.orderBy(col as any, dir === "desc" ? "desc" : "asc");
320
- }
321
- } else {
322
- qb = qb.orderBy("created_at", "desc");
323
- }
324
-
325
- const rows = await qb.execute();
326
-
327
- // N+1 resolve for joins/blocks
328
- const docs = await Promise.all(rows.map((row) => this.findOne<T>(collection, { id: row.id })));
329
-
330
- const totalPages = Math.ceil(total / limit);
331
-
332
- return {
333
- docs: docs.filter(Boolean) as T[],
334
- totalDocs: total,
335
- limit,
336
- totalPages,
337
- page,
338
- pagingCounter: offset + 1,
339
- hasNextPage: page * limit < total,
340
- hasPrevPage: page > 1,
341
- prevPage: page > 1 ? page - 1 : null,
342
- nextPage: page < totalPages ? page + 1 : null,
343
- };
344
- }
345
-
346
- override async update<T extends object>(
347
- collection: string,
348
- query: Record<string, unknown> | string | number,
349
- data: Partial<T>,
350
- ): Promise<T> {
351
- return this._db.transaction().execute(async (tx) => {
352
- let normalizedQuery = query;
353
- if (typeof query !== "object" || query === null) {
354
- normalizedQuery = { id: query };
355
- }
356
-
357
- const current = await this.findOne<any>(
358
- collection,
359
- normalizedQuery as Record<string, unknown>,
360
- tx,
361
- );
362
- if (!current) throw new Error("Document not found");
363
-
364
- const colDef = this._collections.find((c) => c.slug === collection);
365
- const jsonFields =
366
- colDef?.fields
367
- .filter((f) => ["richtext", "json", "file"].includes(f.type))
368
- .map((f) => f.name!) || [];
369
-
370
- const flatData = flattenPayload(data, "", jsonFields);
371
-
372
- for (const field of jsonFields) {
373
- if (flatData[field] && typeof flatData[field] === "object") {
374
- flatData[field] = JSON.stringify(flatData[field]);
375
- }
376
- }
377
-
378
- const relationalFields = getRelationalFields(colDef?.fields || []);
379
- const hasManyData: Record<string, unknown[]> = {};
380
- const blocksData: Record<string, unknown[]> = {};
381
-
382
- for (const field of relationalFields) {
383
- const key = field.name!;
384
- if (Array.isArray(flatData[key])) {
385
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
386
- hasManyData[key] = flatData[key];
387
- } else if (field.type === "blocks") {
388
- blocksData[key] = flatData[key];
389
- }
390
- delete flatData[key];
391
- }
392
- }
393
-
394
- flatData.updated_at = new Date().toISOString();
395
-
396
- if (Object.keys(flatData).length > 0) {
397
- const coercedData = await this.coerceData(collection, flatData);
398
- await tx.updateTable(toSnakeCase(collection)).set(coercedData).where("id", "=", current.id).execute();
399
- }
400
-
401
- for (const [key, values] of Object.entries(hasManyData)) {
402
- const joinTableName = `${toSnakeCase(collection)}_${toSnakeCase(key)}_relations`.toLowerCase();
403
- await tx.deleteFrom(joinTableName).where("source_id", "=", current.id).execute();
404
- if (values.length > 0) {
405
- const joinData = values.map((val: any, idx: number) => {
406
- const tId = typeof val === "object" ? val.id : val;
407
- return { id: crypto.randomUUID(), source_id: current.id, target_id: tId, order: idx };
408
- });
409
- await tx.insertInto(joinTableName).values(joinData).execute();
410
- }
411
- }
412
-
413
- for (const [key, blocks] of Object.entries(blocksData)) {
414
- const blockDef = relationalFields.find((f) => f.name === key && f.type === "blocks");
415
- if (blockDef && "blocks" in blockDef && blockDef.blocks) {
416
- for (const b of blockDef.blocks) {
417
- const blockTableName =
418
- `${toSnakeCase(collection)}_${toSnakeCase(key)}_${toSnakeCase(b.slug)}`.toLowerCase();
419
- try {
420
- await tx.deleteFrom(blockTableName).where("_parent_id", "=", current.id).execute();
421
- } catch (e) { }
422
- }
423
- }
424
-
425
- for (let i = 0; i < (blocks as any[]).length; i++) {
426
- const block = blocks[i] as any;
427
- if (!block.blockType) continue;
428
- const blockTableName =
429
- `${collection}_${toSnakeCase(key)}_${toSnakeCase(block.blockType)}`.toLowerCase();
430
- const bId = block.id || crypto.randomUUID();
431
-
432
- const blockConfig = (blockDef as any)?.blocks?.find(
433
- (b: any) => b.slug === block.blockType,
434
- );
435
- const blockJsonFields =
436
- blockConfig?.fields
437
- .filter((f: any) => ["richtext", "json", "file"].includes(f.type))
438
- .map((f: any) => f.name!) || [];
439
-
440
- const blockFlatData = flattenPayload({ ...block, id: bId }, "", blockJsonFields);
441
-
442
- for (const f of blockJsonFields) {
443
- if (blockFlatData[f] && typeof blockFlatData[f] === "object") {
444
- blockFlatData[f] = JSON.stringify(blockFlatData[f]);
445
- }
446
- }
447
-
448
- delete blockFlatData.blockType;
449
- const coercedBlockData = await this.coerceData(blockTableName, {
450
- ...blockFlatData,
451
- _parent_id: current.id,
452
- _order: i,
453
- block_type: block.blockType,
454
- });
455
- await this._db.insertInto(blockTableName).values(coercedBlockData).execute();
456
- }
457
- }
458
-
459
- return this.findOne<T>(collection, { id: current.id }, tx) as Promise<T>;
460
- });
461
- }
462
-
463
- override async updateMany<T extends object>(
464
- collection: string,
465
- query: Record<string, unknown>,
466
- data: Partial<T>,
467
- ): Promise<number> {
468
- return this._db.transaction().execute(async (tx) => {
469
- let qb = tx.updateTable(toSnakeCase(collection));
470
- if (query && Object.keys(query).length > 0) {
471
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
472
- }
473
-
474
- const colDef = this._collections.find((c) => c.slug === collection);
475
- const jsonFields =
476
- colDef?.fields
477
- .filter((f) => ["richtext", "json", "file"].includes(f.type))
478
- .map((f) => f.name!) || [];
479
-
480
- const flatData = flattenPayload(data, "", jsonFields);
481
-
482
- for (const field of jsonFields) {
483
- if (flatData[field] && typeof flatData[field] === "object") {
484
- flatData[field] = JSON.stringify(flatData[field]);
485
- }
486
- }
487
-
488
- for (const key in flatData) {
489
- if (Array.isArray(flatData[key])) {
490
- delete flatData[key]; // Arrays not supported in bulk update via this API yet
491
- }
492
- }
493
-
494
- flatData.updated_at = new Date().toISOString();
495
-
496
- if (Object.keys(flatData).length > 0) {
497
- const coercedData = await this.coerceData(collection, flatData);
498
- const result = await qb.set(coercedData).executeTakeFirst();
499
- return Number(result.numUpdatedRows || 0);
500
- }
501
- return 0;
502
- });
503
- }
504
-
505
- override async delete(
506
- collection: string,
507
- query: Record<string, unknown> | string | number,
508
- ): Promise<boolean> {
509
- let normalizedQuery = query;
510
- if (typeof query !== "object" || query === null) {
511
- normalizedQuery = { id: query };
512
- }
513
-
514
- const current = await this.findOne<any>(collection, normalizedQuery as Record<string, unknown>);
515
- if (!current) return false;
516
-
517
- await this._db.transaction().execute(async (tx) => {
518
- const colDef = this._collections.find((c) => c.slug === collection);
519
- if (colDef) {
520
- const relationalFields = getRelationalFields(colDef.fields);
521
- for (const field of relationalFields) {
522
- if (!field.name) continue;
523
- const snakeName = toSnakeCase(field.name);
524
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
525
- const joinTableName = `${collection}_${snakeName}_relations`.toLowerCase();
526
- try {
527
- await tx.deleteFrom(joinTableName).where("source_id", "=", current.id).execute();
528
- } catch (e) { }
529
- } else if (field.type === "blocks" && field.blocks) {
530
- for (const b of field.blocks) {
531
- const blockTableName =
532
- `${collection}_${snakeName}_${toSnakeCase(b.slug)}`.toLowerCase();
533
- try {
534
- await tx.deleteFrom(blockTableName).where("_parent_id", "=", current.id).execute();
535
- } catch (e) { }
536
- }
537
- }
538
- }
539
- }
540
- await tx.deleteFrom(toSnakeCase(collection)).where("id", "=", current.id).execute();
541
- });
542
-
543
- return true;
544
- }
545
-
546
- override async deleteMany(collection: string, query: Record<string, unknown>): Promise<number> {
547
- return this._db.transaction().execute(async (tx) => {
548
- // Get IDs first to delete relations properly
549
- let selectQb = tx.selectFrom(toSnakeCase(collection)).select("id");
550
- if (query && Object.keys(query).length > 0) {
551
- selectQb = selectQb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
552
- }
553
- const docs = await selectQb.execute();
554
- if (docs.length === 0) return 0;
555
-
556
- const ids = docs.map((d) => d.id);
557
- const colDef = this._collections.find((c) => c.slug === collection);
558
-
559
- if (colDef) {
560
- const relationalFields = getRelationalFields(colDef.fields);
561
- for (const field of relationalFields) {
562
- if (!field.name) continue;
563
- const snakeName = toSnakeCase(field.name);
564
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
565
- const joinTableName = `${toSnakeCase(collection)}_${snakeName}_relations`.toLowerCase();
566
- try {
567
- await tx.deleteFrom(joinTableName).where("source_id", "in", ids).execute();
568
- } catch (e) { }
569
- } else if (field.type === "blocks" && (field as any).blocks) {
570
- for (const b of (field as any).blocks) {
571
- const blockTableName =
572
- `${toSnakeCase(collection)}_${snakeName}_${toSnakeCase(b.slug)}`.toLowerCase();
573
- try {
574
- await tx.deleteFrom(blockTableName).where("_parent_id", "in", ids).execute();
575
- } catch (e) { }
576
- }
577
- }
578
- }
579
- }
580
-
581
- const result = await tx.deleteFrom(toSnakeCase(collection)).where("id", "in", ids).executeTakeFirst();
582
- return Number(result.numDeletedRows || 0);
583
- });
584
- }
585
-
586
- override async findGlobal<T extends object>(slug: string): Promise<T | null> {
587
- const tableName = toSnakeCase(slug);
588
- const row = await this._db.selectFrom(tableName).selectAll().limit(1).executeTakeFirst();
589
- return row ? (unflattenRow(row) as T) : null;
590
- }
591
-
592
- override async updateGlobal<T extends object>(slug: string, data: Partial<T>): Promise<T> {
593
- const existing = await this.findGlobal<any>(slug);
594
- const flatData = flattenPayload(data);
595
- flatData.updated_at = new Date().toISOString();
596
-
597
- if (!existing) {
598
- if (!flatData.id) flatData.id = "global";
599
- await this._db.insertInto(toSnakeCase(slug)).values(flatData).execute();
600
- } else {
601
- await this._db.updateTable(toSnakeCase(slug)).set(flatData).where("id", "=", existing.id).execute();
602
- }
603
- return this.findGlobal<T>(slug) as Promise<T>;
604
- }
605
-
606
- override async runMigrations(): Promise<void> {
607
- const migrator = new Migrator({
608
- db: this._db,
609
- provider: new FileMigrationProvider({
610
- fs,
611
- path,
612
- migrationFolder: path.resolve(process.cwd(), this.migrationDir),
613
- }),
614
- });
615
-
616
- const { error, results } = await migrator.migrateToLatest();
617
-
618
- results?.forEach((it) => {
619
- if (it.status === "Success") {
620
- logger.success(`🚀 Migration "${it.migrationName}" was executed successfully`);
621
- } else if (it.status === "Error") {
622
- logger.error(`❌ Migration "${it.migrationName}" failed`);
623
- }
624
- });
625
-
626
- if (error) {
627
- throw error;
628
- }
629
- }
630
-
631
- override async migrate(collections: Collection[], globals: Global[] = []): Promise<void> {
632
- this._collections = collections;
633
- if (this.push) {
634
- await pushSchema(this._db, "sqlite", collections, globals, {
635
- pushDestructive: this.pushDestructive,
636
- });
637
- }
638
- }
639
- }
640
-
641
- export function createBunSQLiteAdapter(
642
- path: string,
643
- options?: { push?: boolean; pushDestructive?: boolean; migrationDir?: string },
644
- ): BunSQLiteAdapter {
645
- return new BunSQLiteAdapter(path, options);
646
- }