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
@@ -17,7 +17,7 @@ async function migrateCreateCommand(opaca, migrationName = "migration", outDir)
17
17
  fs.mkdirSync(fullMigrationDir, { recursive: true });
18
18
  }
19
19
  const timestamp = new Date().toISOString().replace(/[-:T]/g, "").split(".")[0];
20
- const { generateMigrationCode, generateSQLCode } = await import("./chunk-kwp83w8b.js");
20
+ const { generateMigrationCode, generateSQLCode } = await import("./chunk-m09hahe2.js");
21
21
  const { getSystemCollections } = await import("./chunk-v521d72w.js");
22
22
  let dialect = "sqlite";
23
23
  if (db.name === "postgres")
@@ -0,0 +1,96 @@
1
+ import {
2
+ __require
3
+ } from "./chunk-8sqjbsgt.js";
4
+
5
+ // src/admin/router.ts
6
+ import { createRouter } from "@nanostores/router";
7
+ var $router = createRouter({
8
+ dashboard: "/admin",
9
+ collections: "/admin/collections/:slug",
10
+ document: "/admin/collections/:slug/:id",
11
+ globals: "/admin/globals/:slug",
12
+ settings: "/admin/settings"
13
+ });
14
+
15
+ // src/admin/stores/config.ts
16
+ import { atom } from "nanostores";
17
+ var $config = atom(null);
18
+ var $needsInit = atom(false);
19
+ var $isFetchingConfig = atom(false);
20
+ var $hasMetadataError = atom(false);
21
+ function setConfig(config) {
22
+ $config.set(config);
23
+ }
24
+ function setNeedsInit(needs) {
25
+ $needsInit.set(needs);
26
+ }
27
+
28
+ // src/admin/stores/query.ts
29
+ import { nanoquery } from "@nanostores/query";
30
+
31
+ // src/admin/api-client.ts
32
+ import ky from "ky";
33
+ var client = null;
34
+ var currentBaseURL = null;
35
+ var configureAPI = (serverUrl) => {
36
+ if (!serverUrl || !serverUrl.startsWith("http"))
37
+ return;
38
+ const url = serverUrl;
39
+ const baseURL = url.replace(/\/$/, "");
40
+ if (client && currentBaseURL === baseURL)
41
+ return;
42
+ currentBaseURL = baseURL;
43
+ client = ky.create({
44
+ prefixUrl: baseURL,
45
+ credentials: "include",
46
+ retry: 0,
47
+ hooks: {
48
+ afterResponse: [
49
+ async (_request, _options, response) => {
50
+ if (response.status === 401 || response.status === 403) {
51
+ try {
52
+ const { $session } = await import("./chunk-xa7rjsn2.js");
53
+ const { notify } = await import("./chunk-jwjk85ze.js");
54
+ $session.set(null);
55
+ notify("Session expired. Please log in again.", "error");
56
+ } catch (e) {}
57
+ }
58
+ }
59
+ ]
60
+ }
61
+ });
62
+ };
63
+ var getCurrentBaseURL = () => {
64
+ if (!currentBaseURL) {
65
+ throw new Error("API client not configured. Did you provide a valid serverUrl?");
66
+ }
67
+ return currentBaseURL;
68
+ };
69
+ var api = new Proxy({}, {
70
+ get(_, prop) {
71
+ if (!client) {
72
+ throw new Error("API client not configured. Did you provide a valid serverUrl?");
73
+ }
74
+ if (!client)
75
+ throw new Error("API client not configured");
76
+ const c = client;
77
+ if (c) {
78
+ return c[prop];
79
+ }
80
+ return;
81
+ }
82
+ });
83
+
84
+ // src/admin/stores/query.ts
85
+ var [
86
+ createFetcherStore,
87
+ createMutatorStore,
88
+ { invalidateKeys, revalidateKeys, mutateCache }
89
+ ] = nanoquery({
90
+ fetcher: (...keys) => {
91
+ const url = keys.join("");
92
+ return api.get(url).json();
93
+ }
94
+ });
95
+
96
+ export { $router, $config, $needsInit, $isFetchingConfig, $hasMetadataError, setConfig, setNeedsInit, configureAPI, getCurrentBaseURL, api, createFetcherStore, createMutatorStore, invalidateKeys, revalidateKeys, mutateCache };
@@ -50,9 +50,9 @@ function generateMigrationCode(collections, globals = [], dialect) {
50
50
  const config = typeof collection.timestamps === "object" ? collection.timestamps : {};
51
51
  const createdField = toSnakeCase(config.createdAt || "createdAt");
52
52
  const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
53
- upCode += ` .addColumn('${createdField}', '${tsType}', (col) => col.defaultTo(sql\`CURRENT_TIMESTAMP\`))
53
+ upCode += ` .addColumn('${createdField}', '${tsType}', (col) => col.defaultTo('CURRENT_TIMESTAMP'))
54
54
  `;
55
- upCode += ` .addColumn('${updatedField}', '${tsType}', (col) => col.defaultTo(sql\`CURRENT_TIMESTAMP\`))
55
+ upCode += ` .addColumn('${updatedField}', '${tsType}', (col) => col.defaultTo('CURRENT_TIMESTAMP'))
56
56
  `;
57
57
  }
58
58
  upCode += ` .execute();
@@ -119,9 +119,9 @@ function generateMigrationCode(collections, globals = [], dialect) {
119
119
  upCode += ` .addColumn('${bColName}', '${bColType}', (col) => col${bConstraintChain})
120
120
  `;
121
121
  }
122
- upCode += ` .addColumn('created_at', '${tsType}', (col) => col.defaultTo(sql\`CURRENT_TIMESTAMP\`))
122
+ upCode += ` .addColumn('created_at', '${tsType}', (col) => col.defaultTo('CURRENT_TIMESTAMP'))
123
123
  `;
124
- upCode += ` .addColumn('updated_at', '${tsType}', (col) => col.defaultTo(sql\`CURRENT_TIMESTAMP\`))
124
+ upCode += ` .addColumn('updated_at', '${tsType}', (col) => col.defaultTo('CURRENT_TIMESTAMP'))
125
125
  `;
126
126
  upCode += ` .execute();
127
127
 
@@ -132,12 +132,12 @@ function generateMigrationCode(collections, globals = [], dialect) {
132
132
  }
133
133
  }
134
134
  }
135
- return `import { Kysely, sql } from 'kysely';
135
+ return `import type { OpacaMigrationDb } from 'opacacms/db';
136
136
 
137
- export async function up(db: Kysely<any>): Promise<void> {
137
+ export async function up(db: OpacaMigrationDb): Promise<void> {
138
138
  ${upCode}}
139
139
 
140
- export async function down(db: Kysely<any>): Promise<void> {
140
+ export async function down(db: OpacaMigrationDb): Promise<void> {
141
141
  ${downCode}}
142
142
  `;
143
143
  }
@@ -1,7 +1,3 @@
1
- import {
2
- createAuth,
3
- sanitizeConfig
4
- } from "./chunk-dy5t83hr.js";
5
1
  import {
6
2
  logger
7
3
  } from "./chunk-62ev8gnc.js";
@@ -14,9 +10,87 @@ import {
14
10
  init_system_schema
15
11
  } from "./chunk-ybbbqj63.js";
16
12
  import {
13
+ __require,
17
14
  __toCommonJS
18
15
  } from "./chunk-8sqjbsgt.js";
19
16
 
17
+ // src/config-utils.ts
18
+ init_system_schema();
19
+ function sanitizeConfig(config) {
20
+ const collections = [...config.collections];
21
+ const supportsAuth = config.db.name === "sqlite" || config.db.name === "postgres" || config.db.name === "d1";
22
+ const systemCollections = getSystemCollections();
23
+ for (const systemCol of systemCollections) {
24
+ const isAsset = systemCol.slug === "_opaca_assets";
25
+ const isAuth = ["_users", "_sessions", "_accounts", "_verifications", "_api_keys"].includes(systemCol.slug);
26
+ if (isAsset && config.storages || isAuth && supportsAuth) {
27
+ if (!collections.find((col) => col.slug === systemCol.slug)) {
28
+ collections.push({
29
+ ...systemCol,
30
+ admin: true
31
+ });
32
+ }
33
+ }
34
+ }
35
+ const sanitizeField = (f) => ({
36
+ name: f.name,
37
+ type: f.type,
38
+ label: f.label,
39
+ required: f.required,
40
+ unique: f.unique,
41
+ defaultValue: f.defaultValue,
42
+ localized: f.localized,
43
+ admin: f.admin ? {
44
+ description: f.admin.description,
45
+ hidden: f.admin.hidden,
46
+ readOnly: f.admin.readOnly,
47
+ components: f.admin.components
48
+ } : undefined,
49
+ options: f.options,
50
+ fields: f.fields ? f.fields.map(sanitizeField) : undefined,
51
+ relationTo: f.relationTo,
52
+ displayField: f.displayField,
53
+ collection: f.collection,
54
+ on: f.on,
55
+ blocks: f.blocks ? f.blocks.map((b) => ({
56
+ slug: b.slug,
57
+ label: b.label,
58
+ fields: b.fields.map(sanitizeField)
59
+ })) : undefined,
60
+ tabs: f.tabs ? f.tabs.map((t) => ({
61
+ label: t.label,
62
+ fields: t.fields.map(sanitizeField)
63
+ })) : undefined
64
+ });
65
+ return {
66
+ appName: config.appName,
67
+ serverURL: config.serverURL,
68
+ collections: collections.map((col) => ({
69
+ slug: col.slug,
70
+ apiPath: col.apiPath,
71
+ label: col.label,
72
+ icon: col.icon,
73
+ admin: col.admin,
74
+ hidden: col.hidden,
75
+ fields: col.fields.map(sanitizeField),
76
+ timestamps: col.timestamps,
77
+ auth: col.auth,
78
+ versions: col.versions
79
+ })),
80
+ globals: config.globals?.map((g) => ({
81
+ slug: g.slug,
82
+ label: g.label,
83
+ icon: g.icon,
84
+ fields: g.fields.map(sanitizeField)
85
+ })),
86
+ storages: config.storages ? Object.keys(config.storages).reduce((acc, key) => {
87
+ acc[key] = {};
88
+ return acc;
89
+ }, {}) : {},
90
+ i18n: config.i18n
91
+ };
92
+ }
93
+
20
94
  // src/server/admin.ts
21
95
  function createAdminHandlers(config, getAuth) {
22
96
  const getMetadata = (c) => {
@@ -891,6 +965,181 @@ function createCorsMiddleware(config) {
891
965
  });
892
966
  }
893
967
 
968
+ // src/auth/index.ts
969
+ import { apiKey } from "@better-auth/api-key";
970
+ import { betterAuth } from "better-auth";
971
+ import { admin } from "better-auth/plugins";
972
+ import { CamelCasePlugin } from "kysely";
973
+
974
+ // src/auth/premissions.ts
975
+ import { createAccessControl } from "better-auth/plugins/access";
976
+ function createPermissions(config) {
977
+ const resources = {
978
+ user: ["create", "read", "update", "delete", "ban", "impersonate"],
979
+ session: ["read", "revoke", "delete"]
980
+ };
981
+ for (const collection of config.collections) {
982
+ resources[collection.slug] = ["create", "read", "update", "delete"];
983
+ }
984
+ const ac = createAccessControl(resources);
985
+ const adminRole = ac.newRole({
986
+ user: ["create", "read", "update", "delete", "ban", "impersonate"],
987
+ session: ["read", "revoke", "delete"]
988
+ });
989
+ for (const collection of config.collections) {
990
+ adminRole[collection.slug] = ["create", "read", "update", "delete"];
991
+ }
992
+ const userRole = ac.newRole({});
993
+ const roles = {
994
+ admin: adminRole,
995
+ user: userRole
996
+ };
997
+ if (config.access?.roles) {
998
+ for (const [roleName, permissions] of Object.entries(config.access.roles)) {
999
+ roles[roleName] = ac.newRole(permissions);
1000
+ }
1001
+ }
1002
+ return {
1003
+ ac,
1004
+ roles
1005
+ };
1006
+ }
1007
+
1008
+ // src/auth/index.ts
1009
+ async function createAuth(config) {
1010
+ const userAuth = config.auth || {};
1011
+ const trustedOrigins = config.trustedOrigins;
1012
+ const { ac, roles } = createPermissions(config);
1013
+ const rawDb = config.db.raw;
1014
+ const env = typeof process !== "undefined" ? process.env : {};
1015
+ const baseURL = String(config.serverURL || env.BETTER_AUTH_URL || "").replace(/\/$/, "");
1016
+ if (!baseURL) {
1017
+ throw new Error("[OpacaAuth] baseURL could not be determined. Please provide 'serverURL' in your config or 'BETTER_AUTH_URL' in your environment.");
1018
+ }
1019
+ const authURL = `${baseURL}/api/auth`;
1020
+ const secret = env.OPACA_SECRET || env.BETTER_AUTH_SECRET || config.secret;
1021
+ if (!secret) {
1022
+ throw new Error("[OpacaAuth] No secret found for authentication. Please provide 'OPACA_SECRET' or 'BETTER_AUTH_SECRET'.");
1023
+ }
1024
+ if (typeof process !== "undefined" && !env.BETTER_AUTH_URL) {
1025
+ process.env.BETTER_AUTH_URL = authURL;
1026
+ }
1027
+ let databaseConfig;
1028
+ if (config.db.name === "postgres" && rawDb) {
1029
+ const { PostgresJSDialect } = await import("kysely-postgres-js");
1030
+ const { Kysely } = await import("kysely");
1031
+ const kysely = new Kysely({
1032
+ dialect: new PostgresJSDialect({ postgres: rawDb }),
1033
+ plugins: [new CamelCasePlugin]
1034
+ });
1035
+ databaseConfig = {
1036
+ db: kysely,
1037
+ type: "pg"
1038
+ };
1039
+ } else if (config.db.name === "d1" && rawDb) {
1040
+ const { D1Dialect } = await import("kysely-d1");
1041
+ const { Kysely } = await import("kysely");
1042
+ const kysely = new Kysely({
1043
+ dialect: new D1Dialect({ database: rawDb }),
1044
+ plugins: [new CamelCasePlugin]
1045
+ });
1046
+ databaseConfig = {
1047
+ db: kysely,
1048
+ type: "sqlite"
1049
+ };
1050
+ } else {
1051
+ databaseConfig = {
1052
+ db: rawDb,
1053
+ type: "sqlite"
1054
+ };
1055
+ }
1056
+ const isSecure = baseURL.startsWith("https");
1057
+ const plugins = [
1058
+ admin({
1059
+ ac,
1060
+ roles
1061
+ }),
1062
+ ...userAuth.features?.apiKeys?.enabled ? [
1063
+ apiKey({
1064
+ defaultPrefix: "opaca_",
1065
+ schema: {
1066
+ apikey: {
1067
+ modelName: "_api_keys"
1068
+ }
1069
+ }
1070
+ })
1071
+ ] : []
1072
+ ];
1073
+ const socialProviders = {};
1074
+ if (userAuth.socialProviders?.github) {
1075
+ socialProviders.github = userAuth.socialProviders.github;
1076
+ }
1077
+ if (userAuth.socialProviders?.google) {
1078
+ socialProviders.google = userAuth.socialProviders.google;
1079
+ }
1080
+ return betterAuth({
1081
+ database: databaseConfig,
1082
+ baseURL,
1083
+ basePath: "/api/auth",
1084
+ secret,
1085
+ trustedOrigins,
1086
+ emailAndPassword: {
1087
+ enabled: userAuth.strategies?.emailPassword !== false
1088
+ },
1089
+ socialProviders,
1090
+ user: {
1091
+ modelName: "_users"
1092
+ },
1093
+ session: {
1094
+ modelName: "_sessions",
1095
+ expiresIn: (userAuth.session?.expiresInDays || 30) * 86400,
1096
+ updateAge: userAuth.session?.updateAgeSeconds || 86400
1097
+ },
1098
+ account: {
1099
+ modelName: "_accounts"
1100
+ },
1101
+ verification: {
1102
+ modelName: "_verifications"
1103
+ },
1104
+ advanced: {
1105
+ useSecureCookies: isSecure,
1106
+ defaultCookieAttributes: {
1107
+ sameSite: isSecure ? "none" : "lax",
1108
+ secure: isSecure
1109
+ }
1110
+ },
1111
+ databaseHooks: {
1112
+ user: {
1113
+ create: {
1114
+ before: async (user) => {
1115
+ try {
1116
+ let userCount = 0;
1117
+ try {
1118
+ userCount = await config.db.count("_users");
1119
+ } catch (e) {
1120
+ const result = await config.db.unsafe("SELECT COUNT(*) as count FROM _users");
1121
+ const rows = result?.results || result || [];
1122
+ userCount = Number(rows[0]?.count || rows[0]?.["count(*)"] || 0);
1123
+ }
1124
+ if (userCount === 0) {
1125
+ return {
1126
+ data: {
1127
+ ...user,
1128
+ role: "admin"
1129
+ }
1130
+ };
1131
+ }
1132
+ } catch (e) {
1133
+ console.error("[OpacaAuth] Failed to check user count in hook:", e);
1134
+ }
1135
+ }
1136
+ }
1137
+ }
1138
+ },
1139
+ plugins
1140
+ });
1141
+ }
1142
+
894
1143
  // src/auth/migrations.ts
895
1144
  init_system_schema();
896
1145
  async function runAuthMigrations(db) {