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