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
@@ -1,631 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import {
4
- CompiledQuery,
5
- FileMigrationProvider,
6
- Kysely,
7
- Migrator,
8
- PostgresDialect,
9
- sql,
10
- } from "kysely";
11
- import postgres from "postgres";
12
- import type { Collection, FindOptions, Global, PaginatedResult } from "../types";
13
- import { logger } from "../utils/logger";
14
- import { BaseDatabaseAdapter } from "./adapter";
15
- import { flattenPayload, unflattenRow } from "./kysely/data-mapper";
16
- import { toSnakeCase } from "./kysely/field-mapper";
17
- import { buildKyselyWhere } from "./kysely/query-builder";
18
- import { pushSchema } from "./kysely/schema-builder";
19
-
20
- export interface PostgresConfig {
21
- url?: string;
22
- host?: string;
23
- port?: number;
24
- database?: string;
25
- username?: string;
26
- password?: string;
27
- ssl?: boolean | "require" | "allow" | "prefer" | "verify-full" | Record<string, unknown>;
28
- }
29
-
30
- export class PostgresAdapter extends BaseDatabaseAdapter {
31
- override name = "postgres";
32
- private _rawDb: postgres.Sql | null = null;
33
- private _db: Kysely<any> | null = null;
34
- private _collections: Collection[] = [];
35
- private _globals: Global[] = [];
36
- private config: PostgresConfig | string;
37
- override push: boolean;
38
- override migrationDir: string;
39
- override pushDestructive: boolean;
40
-
41
- override get raw() {
42
- return this._rawDb;
43
- }
44
-
45
- override get db() {
46
- return this._db;
47
- }
48
-
49
- constructor(
50
- config: PostgresConfig | string,
51
- options?: { push?: boolean; pushDestructive?: boolean; migrationDir?: string },
52
- ) {
53
- super();
54
- this.config = config;
55
- this.push = options?.push ?? process.env.NODE_ENV !== "production";
56
- this.pushDestructive = options?.pushDestructive ?? false;
57
- this.migrationDir = options?.migrationDir ?? "./migrations";
58
- }
59
-
60
- override async connect(): Promise<void> {
61
- if (this._rawDb) return;
62
-
63
- if (typeof this.config === "string") {
64
- this._rawDb = postgres(this.config);
65
- } else {
66
- this._rawDb = postgres({
67
- host: this.config.host,
68
- port: this.config.port,
69
- database: this.config.database,
70
- username: this.config.username,
71
- password: this.config.password,
72
- ssl: this.config.ssl,
73
- });
74
- }
75
-
76
- this._db = new Kysely<any>({
77
- dialect: new PostgresDialect({
78
- pool: {
79
- connect: async () => {
80
- const query = async (sqlStr: string, parameters?: any[]) => {
81
- const res = await (this._rawDb as any).unsafe(sqlStr, parameters || []);
82
- return { rows: res };
83
- };
84
- return { query, release: () => { } };
85
- },
86
- end: async () => { },
87
- on: () => { },
88
- } as any,
89
- }),
90
- });
91
- }
92
-
93
- override async disconnect(): Promise<void> {
94
- if (this._db) await this._db.destroy();
95
- if (this._rawDb) await this._rawDb.end();
96
- this._db = null;
97
- this._rawDb = null;
98
- }
99
-
100
- override async unsafe(query: string, params?: unknown[]): Promise<unknown> {
101
- if (!this._db) throw new Error("DB not connected");
102
- const compiled = CompiledQuery.raw(query, (params || []) as any);
103
- const result = await this._db.executeQuery(compiled);
104
- return result.rows;
105
- }
106
-
107
- override async count(collection: string, query?: Record<string, unknown>): Promise<number> {
108
- if (!this._db) throw new Error("DB not connected");
109
- const tableName = toSnakeCase(collection);
110
- let qb = this._db.selectFrom(tableName).select((eb) => eb.fn.count("id").as("count"));
111
- if (query && Object.keys(query).length > 0) {
112
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
113
- }
114
- const result = await qb.executeTakeFirst();
115
- return Number(result?.count || 0);
116
- }
117
-
118
- override async create<T extends object>(collection: string, data: Partial<T>): Promise<T> {
119
- if (!this._db) throw new Error("DB not connected");
120
- const tableName = toSnakeCase(collection);
121
- return this._db.transaction().execute(async (tx) => {
122
- const colDef = this._collections.find((c) => c.slug === collection);
123
- const jsonFields =
124
- colDef?.fields
125
- .filter((f) => f.name && (["richtext", "json", "file"].includes(f.type) || f.localized))
126
- .map((f) => f.name!) || [];
127
- const flatData = flattenPayload(data, "", jsonFields);
128
- const hasManyData: Record<string, unknown[]> = {};
129
- const blocksData: Record<string, unknown[]> = {};
130
-
131
- for (const key in flatData) {
132
- if (Array.isArray(flatData[key])) {
133
- const isHasMany = colDef?.fields.some(
134
- (f) => f.type === "relationship" && "hasMany" in f && f.hasMany && f.name === key,
135
- );
136
-
137
- if (isHasMany) {
138
- hasManyData[key] = flatData[key];
139
- } else {
140
- blocksData[key] = flatData[key];
141
- }
142
- delete flatData[key];
143
- }
144
- }
145
-
146
- if (!flatData.id) flatData.id = crypto.randomUUID();
147
-
148
- const ts = colDef?.timestamps !== false;
149
- if (ts) {
150
- const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
151
- const createdField = toSnakeCase(config.createdAt || "createdAt");
152
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
153
- if (!flatData[createdField]) flatData[createdField] = new Date().toISOString();
154
- if (!flatData[updatedField]) flatData[updatedField] = new Date().toISOString();
155
- }
156
-
157
- await tx.insertInto(tableName).values(flatData).execute();
158
-
159
- // hasMany relations
160
- for (const [key, values] of Object.entries(hasManyData)) {
161
- const joinTableName = `${tableName}_${toSnakeCase(key)}_relations`.toLowerCase();
162
- if (values.length > 0) {
163
- const joinData = values.map((val: any, idx: number) => {
164
- const tId = typeof val === "object" ? val.id : val;
165
- return { id: crypto.randomUUID(), source_id: flatData.id, target_id: tId, order: idx };
166
- });
167
- await tx.insertInto(joinTableName).values(joinData).execute();
168
- }
169
- }
170
-
171
- // Blocks
172
- for (const [key, blocks] of Object.entries(blocksData)) {
173
- for (let i = 0; i < (blocks as any[]).length; i++) {
174
- const block = blocks[i] as any;
175
- if (!block.blockType) continue;
176
- const blockTableName =
177
- `${tableName}_${toSnakeCase(key)}_${block.blockType}`.toLowerCase();
178
- const bId = block.id || crypto.randomUUID();
179
- const blockFlatData = flattenPayload({ ...block, id: bId });
180
- delete blockFlatData.blockType;
181
- await tx
182
- .insertInto(blockTableName)
183
- .values({
184
- ...blockFlatData,
185
- _parent_id: flatData.id,
186
- _order: i,
187
- block_type: block.blockType,
188
- })
189
- .execute();
190
- }
191
- }
192
-
193
- return this.findOne<T>(collection, { id: flatData.id }, tx) as Promise<T>;
194
- });
195
- }
196
-
197
- override async findOne<T extends object>(
198
- collection: string,
199
- query: Record<string, unknown>,
200
- tx?: any,
201
- ): Promise<T | null> {
202
- const tableName = toSnakeCase(collection);
203
- const executor = tx || this._db;
204
- if (!executor) throw new Error("DB not connected");
205
- let qb = executor.selectFrom(tableName).selectAll();
206
- if (query && Object.keys(query).length > 0) {
207
- qb = qb.where((eb: any) => buildKyselyWhere(eb, query) || eb.val(true));
208
- }
209
-
210
- const row = await qb.executeTakeFirst();
211
- if (!row) return null;
212
-
213
- const unflattened = unflattenRow(row);
214
- const colDef = this._collections.find((c) => c.slug === collection);
215
-
216
- if (colDef) {
217
- const { getRelationalFields, toSnakeCase } = await import("./kysely/field-mapper.js");
218
- const relationalFields = getRelationalFields(colDef.fields);
219
-
220
- for (const field of relationalFields) {
221
- if (!field.name) continue;
222
- const snakeName = toSnakeCase(field.name);
223
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
224
- const joinTableName = `${collection}_${snakeName}_relations`.toLowerCase();
225
- try {
226
- const relations = await executor
227
- .selectFrom(joinTableName)
228
- .selectAll()
229
- .where("source_id", "=", row.id)
230
- .orderBy("order", "asc")
231
- .execute();
232
- const parts = field.name!.split("__");
233
- let current = unflattened;
234
- for (let i = 0; i < parts.length - 1; i++) {
235
- if (!current[parts[i]!]) current[parts[i]!] = {};
236
- current = current[parts[i]!];
237
- }
238
- current[parts[parts.length - 1]!] = relations.map((r: any) => r.target_id);
239
- } catch (e) { }
240
- } else if (field.type === "blocks" && "blocks" in field && field.blocks) {
241
- const blockData: any[] = [];
242
- for (const b of field.blocks) {
243
- const blockTableName = `${collection}_${snakeName}_${b.slug}`.toLowerCase();
244
- try {
245
- const blocks = await executor
246
- .selectFrom(blockTableName)
247
- .selectAll()
248
- .where("_parent_id", "=", row.id)
249
- .execute();
250
-
251
- for (const blk of blocks) {
252
- const uf = unflattenRow(blk);
253
- uf.blockType = blk.block_type;
254
- blockData.push(uf);
255
- }
256
- } catch (e) { }
257
- }
258
- blockData.sort((a, b) => a._order - b._order);
259
- blockData.forEach((b) => {
260
- delete b._order;
261
- delete b._parent_id;
262
- });
263
- const parts = field.name!.split("__");
264
- let current = unflattened;
265
- for (let i = 0; i < parts.length - 1; i++) {
266
- if (!current[parts[i]!]) current[parts[i]!] = {};
267
- current = current[parts[i]!];
268
- }
269
- current[parts[parts.length - 1]!] = blockData;
270
- }
271
- }
272
- }
273
-
274
- return unflattened as T;
275
- }
276
-
277
- override async find<T extends object>(
278
- collection: string,
279
- query?: Record<string, unknown>,
280
- options?: FindOptions,
281
- ): Promise<PaginatedResult<T>> {
282
- if (!this._db) throw new Error("DB not connected");
283
- const page = options?.page || 1;
284
- const limit = options?.limit || 10;
285
- const offset = (page - 1) * limit;
286
-
287
- const total = await this.count(collection, query);
288
-
289
- const tableName = toSnakeCase(collection);
290
- let qb = this._db.selectFrom(tableName).selectAll().limit(limit).offset(offset);
291
- if (query && Object.keys(query).length > 0) {
292
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
293
- }
294
- if (options?.sort) {
295
- const [col, dir] = (options.sort ?? "").split(":");
296
- if (col) {
297
- qb = qb.orderBy(col as any, dir === "desc" ? "desc" : "asc");
298
- }
299
- } else {
300
- qb = qb.orderBy("created_at" as any, "desc");
301
- }
302
-
303
- const rows = await qb.execute();
304
-
305
- const docs = await Promise.all(rows.map((row) => this.findOne<T>(collection, { id: row.id })));
306
-
307
- const totalPages = Math.ceil(total / limit);
308
- return {
309
- docs: docs.filter(Boolean) as T[],
310
- totalDocs: total,
311
- limit,
312
- totalPages,
313
- page,
314
- pagingCounter: offset + 1,
315
- hasNextPage: page * limit < total,
316
- hasPrevPage: page > 1,
317
- prevPage: page > 1 ? page - 1 : null,
318
- nextPage: page < totalPages ? page + 1 : null,
319
- };
320
- }
321
-
322
- override async update<T extends object>(
323
- collection: string,
324
- query: Record<string, unknown> | string | number,
325
- data: Partial<T>,
326
- ): Promise<T> {
327
- if (!this._db) throw new Error("DB not connected");
328
- return this._db.transaction().execute(async (tx) => {
329
- let normalizedQuery = query;
330
- if (typeof query !== "object" || query === null) {
331
- normalizedQuery = { id: query };
332
- }
333
-
334
- const current = await this.findOne<any>(
335
- collection,
336
- normalizedQuery as Record<string, unknown>,
337
- tx,
338
- );
339
- if (!current) throw new Error("Document not found");
340
-
341
- const colDef = this._collections.find((c) => c.slug === collection);
342
- const jsonFields =
343
- colDef?.fields
344
- .filter((f) => f.name && (["richtext", "json", "file"].includes(f.type) || f.localized))
345
- .map((f) => f.name!) || [];
346
- const flatData = flattenPayload(data, "", jsonFields);
347
- const hasManyData: Record<string, unknown[]> = {};
348
- const blocksData: Record<string, unknown[]> = {};
349
-
350
- for (const key in flatData) {
351
- if (Array.isArray(flatData[key])) {
352
- const isHasMany = colDef?.fields.some(
353
- (f) => f.type === "relationship" && "hasMany" in f && f.hasMany && f.name === key,
354
- );
355
- if (isHasMany) {
356
- hasManyData[key] = flatData[key];
357
- } else {
358
- blocksData[key] = flatData[key];
359
- }
360
- delete flatData[key];
361
- }
362
- }
363
-
364
- const ts = colDef?.timestamps !== false;
365
- if (ts) {
366
- const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
367
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
368
- flatData[updatedField] = new Date().toISOString();
369
- }
370
-
371
- const tableName = toSnakeCase(collection);
372
- if (Object.keys(flatData).length > 0) {
373
- await tx.updateTable(tableName).set(flatData).where("id", "=", current.id).execute();
374
- }
375
-
376
- for (const [key, values] of Object.entries(hasManyData)) {
377
- const joinTableName = `${tableName}_${toSnakeCase(key)}_relations`.toLowerCase();
378
- await tx.deleteFrom(joinTableName).where("source_id", "=", current.id).execute();
379
- if (values.length > 0) {
380
- const joinData = values.map((val: any, idx: number) => {
381
- const tId = typeof val === "object" ? val.id : val;
382
- return { id: crypto.randomUUID(), source_id: current.id, target_id: tId, order: idx };
383
- });
384
- await tx.insertInto(joinTableName).values(joinData).execute();
385
- }
386
- }
387
-
388
- for (const [key, blocks] of Object.entries(blocksData)) {
389
- const fieldDef = colDef?.fields.find((f) => f.name === key);
390
- if (fieldDef && "blocks" in fieldDef && fieldDef.blocks) {
391
- for (const b of fieldDef.blocks) {
392
- const blockTableName = `${tableName}_${toSnakeCase(key)}_${b.slug}`.toLowerCase();
393
- try {
394
- await tx.deleteFrom(blockTableName).where("_parent_id", "=", current.id).execute();
395
- } catch (e) { }
396
- }
397
- }
398
-
399
- for (let i = 0; i < (blocks as any[]).length; i++) {
400
- const block = blocks[i] as any;
401
- if (!block.blockType) continue;
402
- const blockTableName =
403
- `${tableName}_${toSnakeCase(key)}_${block.blockType}`.toLowerCase();
404
- const bId = block.id || crypto.randomUUID();
405
- const blockFlatData = flattenPayload({ ...block, id: bId });
406
- delete blockFlatData.blockType;
407
- await tx
408
- .insertInto(blockTableName)
409
- .values({
410
- ...blockFlatData,
411
- _parent_id: current.id,
412
- _order: i,
413
- block_type: block.blockType,
414
- })
415
- .execute();
416
- }
417
- }
418
-
419
- return this.findOne<T>(collection, { id: current.id }, tx) as Promise<T>;
420
- });
421
- }
422
-
423
- override async updateMany<T extends object>(
424
- collection: string,
425
- query: Record<string, unknown>,
426
- data: Partial<T>,
427
- ): Promise<number> {
428
- if (!this._db) throw new Error("DB not connected");
429
- const tableName = toSnakeCase(collection);
430
- return this._db.transaction().execute(async (tx) => {
431
- let qb = tx.updateTable(tableName);
432
- if (query && Object.keys(query).length > 0) {
433
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
434
- }
435
-
436
- const flatData = flattenPayload(data);
437
- for (const key in flatData) {
438
- if (Array.isArray(flatData[key])) {
439
- delete flatData[key];
440
- }
441
- }
442
-
443
- const colDef = this._collections.find((c) => c.slug === collection);
444
-
445
- const ts = colDef?.timestamps !== false;
446
- if (ts) {
447
- const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
448
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
449
- flatData[updatedField] = new Date().toISOString();
450
- }
451
-
452
- if (Object.keys(flatData).length > 0) {
453
- const result = await qb.set(flatData).executeTakeFirst();
454
- return Number(result.numUpdatedRows || 0);
455
- }
456
- return 0;
457
- });
458
- }
459
-
460
- override async delete(
461
- collection: string,
462
- query: Record<string, unknown> | string | number,
463
- ): Promise<boolean> {
464
- if (!this._db) throw new Error("DB not connected");
465
- let normalizedQuery = query;
466
- if (typeof query !== "object" || query === null) {
467
- normalizedQuery = { id: query };
468
- }
469
-
470
- const current = await this.findOne<any>(collection, normalizedQuery as Record<string, unknown>);
471
- if (!current) return false;
472
-
473
- const tableName = toSnakeCase(collection);
474
- await this._db.transaction().execute(async (tx) => {
475
- const colDef = this._collections.find((c) => c.slug === collection);
476
- if (colDef) {
477
- for (const field of colDef.fields) {
478
- const snakeName = toSnakeCase(field.name!);
479
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
480
- const joinTableName = `${tableName}_${snakeName}_relations`.toLowerCase();
481
- try {
482
- await tx.deleteFrom(joinTableName).where("source_id", "=", current.id).execute();
483
- } catch (e) { }
484
- } else if (field.type === "blocks" && "blocks" in field && field.blocks) {
485
- for (const b of field.blocks) {
486
- const blockTableName = `${tableName}_${snakeName}_${b.slug}`.toLowerCase();
487
- try {
488
- await tx.deleteFrom(blockTableName).where("_parent_id", "=", current.id).execute();
489
- } catch (e) { }
490
- }
491
- }
492
- }
493
- }
494
- await tx.deleteFrom(tableName).where("id", "=", current.id).execute();
495
- });
496
-
497
- return true;
498
- }
499
-
500
- override async deleteMany(collection: string, query: Record<string, unknown>): Promise<number> {
501
- if (!this._db) throw new Error("DB not connected");
502
- const tableName = toSnakeCase(collection);
503
- return this._db.transaction().execute(async (tx) => {
504
- let selectQb = tx.selectFrom(tableName).select("id");
505
- if (query && Object.keys(query).length > 0) {
506
- selectQb = selectQb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
507
- }
508
- const docs = await selectQb.execute();
509
- if (docs.length === 0) return 0;
510
-
511
- const ids = docs.map((d) => d.id as string);
512
- const colDef = this._collections.find((c) => c.slug === collection);
513
-
514
- if (colDef) {
515
- for (const field of colDef.fields) {
516
- const snakeName = toSnakeCase(field.name!);
517
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
518
- const joinTableName = `${tableName}_${snakeName}_relations`.toLowerCase();
519
- try {
520
- await tx.deleteFrom(joinTableName).where("source_id", "in", ids).execute();
521
- } catch (e) { }
522
- } else if (field.type === "blocks" && "blocks" in field && field.blocks) {
523
- for (const b of field.blocks) {
524
- const blockTableName = `${tableName}_${snakeName}_${b.slug}`.toLowerCase();
525
- try {
526
- await tx.deleteFrom(blockTableName).where("_parent_id", "in", ids).execute();
527
- } catch (e) { }
528
- }
529
- }
530
- }
531
- }
532
-
533
- const result = await tx.deleteFrom(tableName).where("id", "in", ids).executeTakeFirst();
534
- return Number(result.numDeletedRows || 0);
535
- });
536
- }
537
-
538
- override async findGlobal<T extends object>(slug: string): Promise<T | null> {
539
- if (!this._db) throw new Error("DB not connected");
540
- const tableName = toSnakeCase(slug);
541
- const row = await this._db
542
- .selectFrom(tableName as any)
543
- .selectAll()
544
- .limit(1)
545
- .executeTakeFirst();
546
- return row ? (unflattenRow(row) as T) : null;
547
- }
548
-
549
- override async updateGlobal<T extends object>(slug: string, data: Partial<T>): Promise<T> {
550
- if (!this._db) throw new Error("DB not connected");
551
- const tableName = toSnakeCase(slug);
552
- const existing = await this.findGlobal<any>(slug);
553
- const globalDef = this._globals.find((g) => g.slug === slug);
554
- const jsonFields =
555
- globalDef?.fields
556
- .filter((f) => f.name && (["richtext", "json", "file"].includes(f.type) || f.localized))
557
- .map((f) => f.name!) || [];
558
- const flatData = flattenPayload(data, "", jsonFields);
559
- const ts = globalDef?.timestamps !== false;
560
- if (ts) {
561
- const config = typeof globalDef?.timestamps === "object" ? globalDef.timestamps : {};
562
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
563
- flatData[updatedField] = new Date().toISOString();
564
- }
565
-
566
- if (!existing) {
567
- if (!flatData.id) flatData.id = "global";
568
- if (ts) {
569
- const config = typeof globalDef?.timestamps === "object" ? globalDef.timestamps : {};
570
- const createdField = toSnakeCase(config.createdAt || "createdAt");
571
- if (!flatData[createdField]) flatData[createdField] = new Date().toISOString();
572
- }
573
- await this._db
574
- .insertInto(tableName as any)
575
- .values(flatData)
576
- .execute();
577
- } else {
578
- await this._db
579
- .updateTable(tableName as any)
580
- .set(flatData)
581
- .where("id", "=", existing.id)
582
- .execute();
583
- }
584
- return this.findGlobal<T>(slug) as Promise<T>;
585
- }
586
-
587
- override async runMigrations(): Promise<void> {
588
- if (!this._db) throw new Error("DB not connected");
589
-
590
- const migrator = new Migrator({
591
- db: this._db,
592
- provider: new FileMigrationProvider({
593
- fs,
594
- path,
595
- migrationFolder: path.resolve(process.cwd(), this.migrationDir),
596
- }),
597
- });
598
-
599
- const { error, results } = await migrator.migrateToLatest();
600
-
601
- results?.forEach((it) => {
602
- if (it.status === "Success") {
603
- logger.success(`🚀 Migration "${it.migrationName}" was executed successfully`);
604
- } else if (it.status === "Error") {
605
- logger.error(`❌ Migration "${it.migrationName}" failed`);
606
- }
607
- });
608
-
609
- if (error) {
610
- throw error;
611
- }
612
- }
613
-
614
- override async migrate(collections: Collection[], globals: Global[] = []): Promise<void> {
615
- const { getSystemCollections } = await import("./system-schema");
616
- this._collections = [...getSystemCollections(), ...collections];
617
- this._globals = globals;
618
- if (this.push && this._db) {
619
- await pushSchema(this._db, "postgres", collections, globals, {
620
- pushDestructive: this.pushDestructive,
621
- });
622
- }
623
- }
624
- }
625
-
626
- export function createPostgresAdapter(
627
- config: PostgresConfig | string,
628
- options?: { push?: boolean; pushDestructive?: boolean; migrationDir?: string },
629
- ): PostgresAdapter {
630
- return new PostgresAdapter(config, options);
631
- }