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,160 +0,0 @@
1
- import fs from "node:fs";
2
- import { relative, resolve } from "node:path";
3
- import { spawnSync } from "node:child_process";
4
- import { logger } from "../../utils/logger.js";
5
- import type { DatabaseAdapter, OpacaConfig } from "../../types";
6
-
7
- export async function migrateCreateCommand(
8
- opaca: OpacaConfig,
9
- migrationName: string = "migration",
10
- outDir?: string,
11
- ) {
12
- const db = opaca.db;
13
- const migrationDir = outDir || db.migrationDir || "./migrations";
14
- const fullMigrationDir = resolve(process.cwd(), migrationDir);
15
-
16
- if (!fs.existsSync(fullMigrationDir)) {
17
- fs.mkdirSync(fullMigrationDir, { recursive: true });
18
- }
19
-
20
- const timestamp = new Date().toISOString().replace(/[-:T]/g, "").split(".")[0];
21
- const { generateMigrationCode, generateSQLCode } = await import(
22
- "../../db/kysely/migration-generator.js"
23
- );
24
- const { getSystemCollections } = await import("../../db/system-schema.js");
25
-
26
- let dialect: "sqlite" | "postgres" | "d1" = "sqlite";
27
- if (db.name === "postgres") dialect = "postgres";
28
- if (db.name === "d1") dialect = "d1";
29
-
30
- const isD1 = dialect === "d1";
31
- const fileName = `${timestamp}_${migrationName}.${isD1 ? "sql" : "ts"}`;
32
- const filePath = resolve(fullMigrationDir, fileName);
33
-
34
- const allCollections = [...getSystemCollections(), ...(opaca.collections || [])];
35
-
36
- const template = isD1
37
- ? generateSQLCode(allCollections, opaca.globals || [])
38
- : generateMigrationCode(allCollections, opaca.globals || [], dialect);
39
-
40
- fs.writeFileSync(filePath, template);
41
- logger.success(`🚀 Migration created successfully at ${relative(process.cwd(), filePath)}`);
42
- }
43
-
44
- export async function migrateRunCommand(db: DatabaseAdapter) {
45
- logger.info("🎬 Running migrations...");
46
- if (db.runMigrations) {
47
- await db.connect();
48
- try {
49
- await db.runMigrations();
50
- logger.success("✅ Migrations applied successfully!");
51
- } catch (error: any) {
52
- logger.error(`❌ Failed to run migrations: ${error.message}`);
53
- throw error;
54
- } finally {
55
- // We don't disconnect here because in CLI the process will exit,
56
- // and in tests we might want to reuse the same adapter instance.
57
- }
58
- } else {
59
- throw new Error(`Adapter ${db.name} does not support running migrations.`);
60
- }
61
- }
62
-
63
- export async function migrateStatusCommand(opaca: OpacaConfig) {
64
- logger.info("📊 Checking migration status...");
65
- const db = opaca.db;
66
- const migrationDir = db.migrationDir || "./migrations";
67
- const fullMigrationDir = resolve(process.cwd(), migrationDir);
68
-
69
- if (!fs.existsSync(fullMigrationDir)) {
70
- logger.info("No migrations directory found.");
71
- return;
72
- }
73
-
74
- const migrationFiles = fs
75
- .readdirSync(fullMigrationDir)
76
- .filter((f) => f.endsWith(".ts") || f.endsWith(".sql"))
77
- .sort();
78
-
79
- let appliedMigrations: string[] = [];
80
- try {
81
- await db.connect();
82
- // Try both kysely_migration (default) and _opaca_migrations if we ever change it
83
- const rows = (await db.unsafe("SELECT name FROM kysely_migration").catch(() => [])) as any[];
84
- appliedMigrations = rows.map((r) => r.name);
85
- } catch (e) {
86
- // Database or table might not exist yet
87
- } finally {
88
- // Keep connection alive for potential reuse in tests
89
- }
90
-
91
- console.log(`\nFound ${migrationFiles.length} migration files in ${migrationDir}:`);
92
- for (const file of migrationFiles) {
93
- const name = file.replace(/\.(ts|sql)$/, "");
94
- const isApplied = appliedMigrations.includes(name);
95
- console.log(` ${isApplied ? "✅ [Applied] " : "❌ [Pending] "} ${file}`);
96
- }
97
-
98
- const pending = migrationFiles.filter((f) => !appliedMigrations.includes(f.replace(/\.(ts|sql)$/, "")));
99
- if (pending.length > 0) {
100
- console.log(`\n💡 You have ${pending.length} pending migrations. Run 'opacacms migrate' to apply them.`);
101
- } else {
102
- console.log("\n✨ All migrations are up to date.");
103
- }
104
- }
105
-
106
- export async function migrateD1Command(
107
- migrationDir: string,
108
- isRemote: boolean,
109
- binding: string = "DB",
110
- ) {
111
- const fullMigrationDir = resolve(process.cwd(), migrationDir);
112
-
113
- if (!fs.existsSync(fullMigrationDir)) {
114
- throw new Error(`[OpacaCMS] Migration directory not found: ${fullMigrationDir}`);
115
- }
116
-
117
- const migrations = fs
118
- .readdirSync(fullMigrationDir)
119
- .filter((file) => file.endsWith(".sql"))
120
- .sort();
121
-
122
- if (migrations.length === 0) {
123
- console.log(`[OpacaCMS] No SQL migrations found in ${fullMigrationDir}`);
124
- return;
125
- }
126
-
127
- console.log(
128
- `[OpacaCMS] Found ${migrations.length} migrations. Applying to ${isRemote ? "🌊 REMOTE (Cloudflare D1)" : "💻 LOCAL (SQLite)"}...`,
129
- );
130
-
131
- for (const migration of migrations) {
132
- const filePath = resolve(fullMigrationDir, migration);
133
- console.log(`\n[OpacaCMS] 📦 Applying: ${migration}...`);
134
-
135
- const wranglerArgs = [
136
- "wrangler",
137
- "d1",
138
- "execute",
139
- binding,
140
- "--file",
141
- filePath,
142
- isRemote ? "--remote" : "--local",
143
- "--yes",
144
- ];
145
-
146
- const result = spawnSync("bunx", wranglerArgs, {
147
- stdio: "inherit",
148
- shell: true,
149
- cwd: process.cwd(),
150
- });
151
-
152
- if (result.status !== 0) {
153
- console.error(`[OpacaCMS] ❌ Failed to apply migration: ${migration}`);
154
- } else {
155
- console.log(`[OpacaCMS] ✅ Success: ${migration}`);
156
- }
157
- }
158
-
159
- console.log("\n[OpacaCMS] ✨ Database migration process completed!");
160
- }
@@ -1,11 +0,0 @@
1
- import type { OpacaConfig } from "../../types";
2
-
3
- export async function seedCommand(opaca: OpacaConfig, count: number, reset: boolean, type: "assets" | "collections") {
4
- const { autoSeed } = await import("../seeding.js");
5
- try {
6
- await autoSeed(opaca, count, reset, type);
7
- } catch (error: any) {
8
- console.error(`[OpacaCMS] Seeding failed: ${error.message}`);
9
- throw error;
10
- }
11
- }
@@ -1,101 +0,0 @@
1
- import { Database } from "bun:sqlite";
2
- import fs from "node:fs";
3
- import path from "node:path";
4
-
5
- /**
6
- * A minimal D1Database mock that wraps bun:sqlite to allow OpacaCMS CLI
7
- * to run D1-based configurations locally.
8
- *
9
- * It prioritizes Wrangler's local state if found.
10
- */
11
- export function createD1Mock(dbPath: string = ".opaca/local-d1.db") {
12
- // 1. Try to find Wrangler's local D1 state
13
- const wranglerD1Dir = path.resolve(
14
- process.cwd(),
15
- ".wrangler/state/v3/d1/miniflare-D1DatabaseObject",
16
- );
17
-
18
- if (fs.existsSync(wranglerD1Dir)) {
19
- const files = fs.readdirSync(wranglerD1Dir);
20
- const sqliteFile = files.find((f) => f.endsWith(".sqlite"));
21
- if (sqliteFile) {
22
- const wranglerPath = path.join(wranglerD1Dir, sqliteFile);
23
- try {
24
- const sqlite = new Database(wranglerPath);
25
- console.log(`[OpacaCMS] Using Wrangler D1 local state: ${sqliteFile}`);
26
- return wrapSqlite(sqlite);
27
- } catch (e) {
28
- console.warn(
29
- `[OpacaCMS] Failed to open Wrangler D1 state at ${wranglerPath}. Falling back...`,
30
- );
31
- }
32
- }
33
- }
34
-
35
- // 2. Default to provided path (useful for manual testing or CI)
36
- const absolutePath = path.isAbsolute(dbPath) ? dbPath : path.resolve(process.cwd(), dbPath);
37
- const dir = path.dirname(absolutePath);
38
-
39
- try {
40
- if (!fs.existsSync(dir)) {
41
- fs.mkdirSync(dir, { recursive: true });
42
- }
43
- const sqlite = new Database(absolutePath);
44
- console.log(`[OpacaCMS] Using local CLI database: ${absolutePath}`);
45
- return wrapSqlite(sqlite);
46
- } catch (err) {
47
- console.warn(
48
- `[OpacaCMS] Warning: Could not open database at ${absolutePath}. Using memory database.`,
49
- );
50
- return wrapSqlite(new Database(":memory:"));
51
- }
52
- }
53
-
54
- function wrapSqlite(sqlite: Database) {
55
- return {
56
- prepare(query: string) {
57
- const stmt = sqlite.prepare(query);
58
-
59
- const bridge = {
60
- bind(...params: any[]) {
61
- (bridge as any)._params = params;
62
- return bridge;
63
- },
64
- async first() {
65
- const params = (bridge as any)._params || [];
66
- return stmt.get(...params);
67
- },
68
- async all() {
69
- const params = (bridge as any)._params || [];
70
- const results = stmt.all(...params);
71
- return { results, success: true, meta: {} };
72
- },
73
- async run() {
74
- const params = (bridge as any)._params || [];
75
- const result = stmt.run(...params);
76
- return {
77
- success: true,
78
- meta: { changes: result.changes, last_row_id: result.lastInsertRowid },
79
- };
80
- },
81
- async raw() {
82
- const params = (bridge as any)._params || [];
83
- return stmt.all(...params);
84
- },
85
- };
86
-
87
- return bridge;
88
- },
89
- async batch(statements: any[]) {
90
- const results = [];
91
- for (const stmt of statements) {
92
- results.push(await stmt.all());
93
- }
94
- return results;
95
- },
96
- async exec(query: string) {
97
- sqlite.exec(query);
98
- return { count: 0, duration: 0 };
99
- },
100
- };
101
- }
@@ -1,84 +0,0 @@
1
- import { afterAll, describe, expect, it } from "bun:test";
2
- import fs from "fs";
3
- import { resolve } from "path";
4
- import { loadConfig } from "./index";
5
-
6
- const TMP_DIR = resolve("/tmp/opacacms-cli-test");
7
- if (!fs.existsSync(TMP_DIR)) fs.mkdirSync(TMP_DIR);
8
-
9
- describe("CLI loadConfig", () => {
10
- afterAll(() => {
11
- fs.rmSync(TMP_DIR, { recursive: true, force: true });
12
- });
13
-
14
- const createTempConfig = (name: string, content: string) => {
15
- const path = resolve(TMP_DIR, name);
16
- fs.writeFileSync(path, content);
17
- return path;
18
- };
19
-
20
- it("should load a valid config with only default export", async () => {
21
- const path = createTempConfig(
22
- "valid.ts",
23
- `
24
- export default {
25
- db: { name: 'postgres' },
26
- collections: []
27
- };
28
- `,
29
- );
30
- const config = await loadConfig(path);
31
- expect(config.db.name).toBe("postgres");
32
- });
33
-
34
- it("should fail if default export is missing", async () => {
35
- const path = createTempConfig(
36
- "no-default.ts",
37
- `
38
- export const config = {
39
- db: { name: 'postgres' },
40
- collections: []
41
- };
42
- `,
43
- );
44
- expect(loadConfig(path)).rejects.toThrow(/must have a 'default' export/);
45
- });
46
-
47
- it("should fail if named exports are present", async () => {
48
- const path = createTempConfig(
49
- "named-exports.ts",
50
- `
51
- export const foo = "bar";
52
- export default {
53
- db: { name: 'postgres' },
54
- collections: []
55
- };
56
- `,
57
- );
58
- expect(loadConfig(path)).rejects.toThrow(/Named exports are not allowed/);
59
- });
60
-
61
- it("should fail if default export is a Hono app", async () => {
62
- const path = createTempConfig(
63
- "hono-app.ts",
64
- `
65
- export default {
66
- fetch: () => {}
67
- };
68
- `,
69
- );
70
- expect(loadConfig(path)).rejects.toThrow(/Default export is a Hono application/);
71
- });
72
-
73
- it("should fail if no db adapter is found", async () => {
74
- const path = createTempConfig(
75
- "no-db.ts",
76
- `
77
- export default {
78
- collections: []
79
- };
80
- `,
81
- );
82
- expect(loadConfig(path)).rejects.toThrow(/No database adapter found/);
83
- });
84
- });
package/src/cli/index.ts DELETED
@@ -1,183 +0,0 @@
1
- #!/usr/bin/env bun
2
- import fs from "node:fs";
3
- import { resolve } from "node:path";
4
- import { parseArgs } from "node:util";
5
- import { pathToFileURL } from "node:url";
6
-
7
- /**
8
- * Loads and validates the OpacaCMS configuration from a file.
9
- */
10
- export async function loadConfig(configPath: string) {
11
- if (!fs.existsSync(configPath)) {
12
- throw new Error(`Config file not found at ${configPath}`);
13
- }
14
-
15
- try {
16
- const configUrl = pathToFileURL(configPath).href;
17
- const mod = await import(configUrl);
18
-
19
- if (!mod.default) {
20
- throw new Error(
21
- `The configuration file at ${configPath} must have a 'default' export.`,
22
- );
23
- }
24
-
25
- const namedExports = Object.keys(mod).filter((k) => k !== "default" && k !== "__esModule");
26
- if (namedExports.length > 0) {
27
- throw new Error(
28
- `Named exports are not allowed in the configuration file. Found: ${namedExports.join(", ")}.`,
29
- );
30
- }
31
-
32
- let opaca = mod.default;
33
-
34
- if (typeof opaca === "function") {
35
- const { createD1Mock } = await import("./d1-mock.js");
36
- const { createR2Mock } = await import("./r2-mock.js");
37
-
38
- const mockDb = createD1Mock();
39
- const mockBucket = createR2Mock();
40
- const mockSecureBucket = createR2Mock(".opaca/local-r2/secure");
41
-
42
- opaca = await opaca(
43
- {
44
- DB: mockDb,
45
- BUCKET: mockBucket,
46
- SECURE_BUCKET: mockSecureBucket,
47
- OPACA_SECRET: "cli-secret",
48
- },
49
- { url: "http://localhost:3000" },
50
- );
51
- }
52
-
53
- if (opaca?.fetch) {
54
- throw new Error(
55
- "Default export is a Hono application. The CLI requires the configuration object.",
56
- );
57
- }
58
-
59
- if (!opaca.db) {
60
- throw new Error("No database adapter found in config");
61
- }
62
-
63
- return opaca;
64
- } catch (error: any) {
65
- throw error;
66
- }
67
- }
68
-
69
- async function main() {
70
- const { values, positionals } = parseArgs({
71
- args: process.argv.slice(2),
72
- options: {
73
- config: { type: "string", short: "c" },
74
- example: { type: "string", short: "e" },
75
- help: { type: "boolean", short: "h" },
76
- version: { type: "boolean", short: "v" },
77
- out: { type: "string", short: "o" },
78
- remote: { type: "boolean" },
79
- local: { type: "boolean" },
80
- binding: { type: "string", short: "b" },
81
- url: { type: "string" },
82
- token: { type: "string" },
83
- count: { type: "string" },
84
- reset: { type: "boolean" },
85
- },
86
- allowPositionals: true,
87
- });
88
-
89
- if (values.help) {
90
- console.log("Usage: opacacms <command> [options]");
91
- console.log("\nCommands:");
92
- console.log(" init [target] Initialize a new project");
93
- console.log(" migrate:create Generate migrations from your schema");
94
- console.log(" migrate Run pending migrations");
95
- console.log(" migrate:status Show migration status");
96
- console.log(" migrate:d1 Apply SQL migrations to D1");
97
- console.log(" seed Seed database with mock data");
98
- console.log(" seed:assets Seed only assets");
99
- console.log(" generate:types Generate TS definitions from instance");
100
- process.exit(0);
101
- }
102
-
103
- if (values.version) {
104
- console.log("OpacaCMS v0.1.0");
105
- process.exit(0);
106
- }
107
-
108
- const command = positionals[0];
109
- if (!command) {
110
- console.log("Usage: opacacms <command> [options]. Use --help for more info.");
111
- process.exit(1);
112
- }
113
-
114
- if (command === "init") {
115
- const { initCommand } = await import("./commands/init.js");
116
- await initCommand(positionals[1] || "my-opaca-app", values.example as string);
117
- return;
118
- }
119
-
120
- if (command === "generate:types") {
121
- const { generateTypesCommand } = await import("./commands/generate-types.js");
122
- await generateTypesCommand(values.url as string, values.token as string, (values.out as string) || "opaca-types.d.ts");
123
- return;
124
- }
125
-
126
- // Common commands requiring config
127
- let configPath = values.config ? resolve(process.cwd(), values.config as string) : "";
128
- if (!configPath) {
129
- const defaults = ["opacacms.config.ts", "opacacms.config.js", "src/opacacms.config.ts", "src/opacacms.config.js", "opaca.config.ts", "opaca.config.js"];
130
- for (const d of defaults) {
131
- if (fs.existsSync(resolve(process.cwd(), d))) {
132
- configPath = resolve(process.cwd(), d);
133
- break;
134
- }
135
- }
136
- }
137
-
138
- if (!configPath || !fs.existsSync(configPath)) {
139
- console.error("Config file not found. Use -c or --config to specify path.");
140
- process.exit(1);
141
- }
142
-
143
- const opaca = await loadConfig(configPath);
144
-
145
- switch (command) {
146
- case "migrate:create": {
147
- const { migrateCreateCommand } = await import("./commands/migrate-commands.js");
148
- await migrateCreateCommand(opaca, positionals[1], values.out as string);
149
- break;
150
- }
151
- case "migrate": {
152
- const { migrateRunCommand } = await import("./commands/migrate-commands.js");
153
- await migrateRunCommand(opaca.db);
154
- break;
155
- }
156
- case "migrate:status": {
157
- const { migrateStatusCommand } = await import("./commands/migrate-commands.js");
158
- await migrateStatusCommand(opaca);
159
- break;
160
- }
161
- case "migrate:d1": {
162
- const { migrateD1Command } = await import("./commands/migrate-commands.js");
163
- await migrateD1Command((values.out as string) || "./migrations", !!values.remote, (values.binding as string) || "DB");
164
- break;
165
- }
166
- case "seed":
167
- case "seed:assets": {
168
- const { seedCommand } = await import("./commands/seed-command.js");
169
- await seedCommand(opaca, parseInt(values.count as string) || 10, !!values.reset, command === "seed:assets" ? "assets" : "collections");
170
- break;
171
- }
172
- default:
173
- console.error(`Unknown command: ${command}`);
174
- process.exit(1);
175
- }
176
- }
177
-
178
- if (import.meta.main) {
179
- main().catch((err) => {
180
- console.error(err);
181
- process.exit(1);
182
- });
183
- }