@sonicjs-cms/core 2.0.10 → 2.0.12

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 (87) hide show
  1. package/README.md +75 -1
  2. package/dist/chunk-22EFGHAX.cjs +801 -0
  3. package/dist/chunk-22EFGHAX.cjs.map +1 -0
  4. package/dist/{chunk-3PHG75W4.cjs → chunk-2HRF65VF.cjs} +9 -5
  5. package/dist/chunk-2HRF65VF.cjs.map +1 -0
  6. package/dist/{chunk-DOR2IU73.cjs → chunk-3F4LF7LW.cjs} +249 -2
  7. package/dist/chunk-3F4LF7LW.cjs.map +1 -0
  8. package/dist/chunk-3OKKNBPD.cjs +70 -0
  9. package/dist/chunk-3OKKNBPD.cjs.map +1 -0
  10. package/dist/{chunk-LW33AOBF.js → chunk-5RKQB2JG.js} +6 -222
  11. package/dist/chunk-5RKQB2JG.js.map +1 -0
  12. package/dist/{chunk-Z4H6DBVF.js → chunk-6B4ENDQM.js} +12006 -10745
  13. package/dist/chunk-6B4ENDQM.js.map +1 -0
  14. package/dist/chunk-AUVW4I3D.js +1550 -0
  15. package/dist/chunk-AUVW4I3D.js.map +1 -0
  16. package/dist/{chunk-HKEK7UNV.js → chunk-CPXAVWCU.js} +3 -3
  17. package/dist/{chunk-HKEK7UNV.js.map → chunk-CPXAVWCU.js.map} +1 -1
  18. package/dist/{chunk-MXJJN4IA.js → chunk-DSDHGJ4F.js} +9 -5
  19. package/dist/chunk-DSDHGJ4F.js.map +1 -0
  20. package/dist/{chunk-F5ESJXI2.cjs → chunk-DTLB6UIH.cjs} +3 -3
  21. package/dist/{chunk-F5ESJXI2.cjs.map → chunk-DTLB6UIH.cjs.map} +1 -1
  22. package/dist/{chunk-HXA5QSI3.cjs → chunk-F4IGVB2V.cjs} +22 -6
  23. package/dist/chunk-F4IGVB2V.cjs.map +1 -0
  24. package/dist/{chunk-Q7SL7U43.cjs → chunk-K5WUGEXH.cjs} +12014 -10752
  25. package/dist/chunk-K5WUGEXH.cjs.map +1 -0
  26. package/dist/{chunk-YHG45LMU.js → chunk-LBSKQKYL.js} +20 -4
  27. package/dist/chunk-LBSKQKYL.js.map +1 -0
  28. package/dist/chunk-LWMMMW43.js +787 -0
  29. package/dist/chunk-LWMMMW43.js.map +1 -0
  30. package/dist/{chunk-6FR25MPC.js → chunk-M2YDOOBC.js} +246 -3
  31. package/dist/chunk-M2YDOOBC.js.map +1 -0
  32. package/dist/{chunk-FTMKKKNH.js → chunk-QNWYQZ55.js} +3 -3
  33. package/dist/{chunk-FTMKKKNH.js.map → chunk-QNWYQZ55.js.map} +1 -1
  34. package/dist/chunk-RDJ2QLA2.cjs +1552 -0
  35. package/dist/chunk-RDJ2QLA2.cjs.map +1 -0
  36. package/dist/chunk-RKNHW6QU.js +61 -0
  37. package/dist/chunk-RKNHW6QU.js.map +1 -0
  38. package/dist/{chunk-MU3MR2QR.cjs → chunk-YU6QFFI4.cjs} +5 -222
  39. package/dist/chunk-YU6QFFI4.cjs.map +1 -0
  40. package/dist/{chunk-CAP6QQR2.cjs → chunk-ZMSYKV62.cjs} +5 -5
  41. package/dist/{chunk-CAP6QQR2.cjs.map → chunk-ZMSYKV62.cjs.map} +1 -1
  42. package/dist/index.cjs +527 -154
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.js +390 -13
  45. package/dist/index.js.map +1 -1
  46. package/dist/middleware.cjs +24 -23
  47. package/dist/middleware.js +3 -2
  48. package/dist/migrations-DURR3GZX.js +4 -0
  49. package/dist/migrations-DURR3GZX.js.map +1 -0
  50. package/dist/migrations-P5BD7WQK.cjs +13 -0
  51. package/dist/migrations-P5BD7WQK.cjs.map +1 -0
  52. package/dist/plugins.cjs +7 -7
  53. package/dist/plugins.js +1 -1
  54. package/dist/routes.cjs +31 -29
  55. package/dist/routes.js +8 -6
  56. package/dist/services.cjs +42 -24
  57. package/dist/services.js +4 -2
  58. package/dist/templates.cjs +17 -21
  59. package/dist/templates.js +2 -2
  60. package/dist/utils.cjs +44 -11
  61. package/dist/utils.js +2 -1
  62. package/migrations/001_initial_schema.sql +2 -2
  63. package/migrations/007_demo_login_plugin.sql +1 -1
  64. package/migrations/020_add_email_plugin.sql +22 -0
  65. package/migrations/021_add_magic_link_auth_plugin.sql +42 -0
  66. package/migrations/022_add_tinymce_plugin.sql +25 -0
  67. package/migrations/023_add_easy_mdx_plugin.sql +25 -0
  68. package/migrations/024_add_quill_editor_plugin.sql +25 -0
  69. package/migrations/025_rename_mdxeditor_to_easy_mdx.sql +22 -0
  70. package/migrations/026_add_otp_login.sql +42 -0
  71. package/package.json +7 -3
  72. package/dist/chunk-3PHG75W4.cjs.map +0 -1
  73. package/dist/chunk-6FR25MPC.js.map +0 -1
  74. package/dist/chunk-COBUPOMD.js +0 -1511
  75. package/dist/chunk-COBUPOMD.js.map +0 -1
  76. package/dist/chunk-DOR2IU73.cjs.map +0 -1
  77. package/dist/chunk-HXA5QSI3.cjs.map +0 -1
  78. package/dist/chunk-LW33AOBF.js.map +0 -1
  79. package/dist/chunk-MU3MR2QR.cjs.map +0 -1
  80. package/dist/chunk-MXJJN4IA.js.map +0 -1
  81. package/dist/chunk-NBDPIRQS.cjs +0 -1526
  82. package/dist/chunk-NBDPIRQS.cjs.map +0 -1
  83. package/dist/chunk-Q7SL7U43.cjs.map +0 -1
  84. package/dist/chunk-YHG45LMU.js.map +0 -1
  85. package/dist/chunk-Z4H6DBVF.js.map +0 -1
  86. package/migrations/002_faq_plugin.sql +0 -86
  87. package/migrations/013_code_examples_plugin.sql +0 -177
@@ -0,0 +1,787 @@
1
+ // src/services/collection-loader.ts
2
+ var registeredCollections = [];
3
+ function registerCollections(collections) {
4
+ for (const config of collections) {
5
+ if (!config.name || !config.displayName || !config.schema) {
6
+ console.error(`Invalid collection config: missing required fields`, config);
7
+ continue;
8
+ }
9
+ const normalizedConfig = {
10
+ ...config,
11
+ managed: config.managed !== void 0 ? config.managed : true,
12
+ isActive: config.isActive !== void 0 ? config.isActive : true
13
+ };
14
+ registeredCollections.push(normalizedConfig);
15
+ console.log(`\u2713 Registered collection: ${config.name}`);
16
+ }
17
+ }
18
+ async function loadCollectionConfigs() {
19
+ const collections = [...registeredCollections];
20
+ try {
21
+ const modules = import.meta.glob?.("../collections/*.collection.ts", { eager: true }) || {};
22
+ for (const [path, module] of Object.entries(modules)) {
23
+ try {
24
+ const configModule = module;
25
+ if (!configModule.default) {
26
+ console.warn(`Collection file ${path} does not export a default config`);
27
+ continue;
28
+ }
29
+ const config = configModule.default;
30
+ if (!config.name || !config.displayName || !config.schema) {
31
+ console.error(`Invalid collection config in ${path}: missing required fields`);
32
+ continue;
33
+ }
34
+ const normalizedConfig = {
35
+ ...config,
36
+ managed: config.managed !== void 0 ? config.managed : true,
37
+ isActive: config.isActive !== void 0 ? config.isActive : true
38
+ };
39
+ collections.push(normalizedConfig);
40
+ console.log(`\u2713 Loaded collection config: ${config.name}`);
41
+ } catch (error) {
42
+ console.error(`Error loading collection from ${path}:`, error);
43
+ }
44
+ }
45
+ console.log(`Loaded ${collections.length} total collection configuration(s) (${registeredCollections.length} registered, ${collections.length - registeredCollections.length} from core)`);
46
+ return collections;
47
+ } catch (error) {
48
+ console.error("Error loading collection configurations:", error);
49
+ return collections;
50
+ }
51
+ }
52
+ async function loadCollectionConfig(name) {
53
+ try {
54
+ console.warn("loadCollectionConfig requires implementation in consuming application");
55
+ return null;
56
+ } catch (error) {
57
+ console.error(`Error loading collection ${name}:`, error);
58
+ return null;
59
+ }
60
+ }
61
+ async function getAvailableCollectionNames() {
62
+ try {
63
+ const modules = import.meta.glob?.("../collections/*.collection.ts") || {};
64
+ const names = [];
65
+ for (const path of Object.keys(modules)) {
66
+ const match = path.match(/\/([^/]+)\.collection\.ts$/);
67
+ if (match && match[1]) {
68
+ names.push(match[1]);
69
+ }
70
+ }
71
+ return names;
72
+ } catch (error) {
73
+ console.error("Error getting collection names:", error);
74
+ return [];
75
+ }
76
+ }
77
+ function validateCollectionConfig(config) {
78
+ const errors = [];
79
+ if (!config.name) {
80
+ errors.push("Collection name is required");
81
+ } else if (!/^[a-z0-9_]+$/.test(config.name)) {
82
+ errors.push("Collection name must contain only lowercase letters, numbers, and underscores");
83
+ }
84
+ if (!config.displayName) {
85
+ errors.push("Display name is required");
86
+ }
87
+ if (!config.schema) {
88
+ errors.push("Schema is required");
89
+ } else {
90
+ if (config.schema.type !== "object") {
91
+ errors.push('Schema type must be "object"');
92
+ }
93
+ if (!config.schema.properties || typeof config.schema.properties !== "object") {
94
+ errors.push("Schema must have properties");
95
+ }
96
+ for (const [fieldName, fieldConfig] of Object.entries(config.schema.properties || {})) {
97
+ if (!fieldConfig.type) {
98
+ errors.push(`Field "${fieldName}" is missing type`);
99
+ }
100
+ if (fieldConfig.type === "reference" && !fieldConfig.collection) {
101
+ errors.push(`Reference field "${fieldName}" is missing collection property`);
102
+ }
103
+ if (["select", "multiselect", "radio"].includes(fieldConfig.type) && !fieldConfig.enum) {
104
+ errors.push(`Select field "${fieldName}" is missing enum options`);
105
+ }
106
+ }
107
+ }
108
+ return {
109
+ valid: errors.length === 0,
110
+ errors
111
+ };
112
+ }
113
+
114
+ // src/services/collection-sync.ts
115
+ async function syncCollections(db) {
116
+ console.log("\u{1F504} Starting collection sync...");
117
+ const results = [];
118
+ const configs = await loadCollectionConfigs();
119
+ if (configs.length === 0) {
120
+ console.log("\u26A0\uFE0F No collection configurations found");
121
+ return results;
122
+ }
123
+ for (const config of configs) {
124
+ const result = await syncCollection(db, config);
125
+ results.push(result);
126
+ }
127
+ const created = results.filter((r) => r.status === "created").length;
128
+ const updated = results.filter((r) => r.status === "updated").length;
129
+ const unchanged = results.filter((r) => r.status === "unchanged").length;
130
+ const errors = results.filter((r) => r.status === "error").length;
131
+ console.log(`\u2705 Collection sync complete: ${created} created, ${updated} updated, ${unchanged} unchanged, ${errors} errors`);
132
+ return results;
133
+ }
134
+ async function syncCollection(db, config) {
135
+ try {
136
+ const validation = validateCollectionConfig(config);
137
+ if (!validation.valid) {
138
+ return {
139
+ name: config.name,
140
+ status: "error",
141
+ error: `Validation failed: ${validation.errors.join(", ")}`
142
+ };
143
+ }
144
+ const existingStmt = db.prepare("SELECT * FROM collections WHERE name = ?");
145
+ const existing = await existingStmt.bind(config.name).first();
146
+ const now = Date.now();
147
+ const collectionId = existing?.id || `col-${config.name}-${crypto.randomUUID().slice(0, 8)}`;
148
+ const schemaJson = JSON.stringify(config.schema);
149
+ const isActive = config.isActive !== false ? 1 : 0;
150
+ const managed = config.managed !== false ? 1 : 0;
151
+ if (!existing) {
152
+ const insertStmt = db.prepare(`
153
+ INSERT INTO collections (id, name, display_name, description, schema, is_active, managed, created_at, updated_at)
154
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
155
+ `);
156
+ await insertStmt.bind(
157
+ collectionId,
158
+ config.name,
159
+ config.displayName,
160
+ config.description || null,
161
+ schemaJson,
162
+ isActive,
163
+ managed,
164
+ now,
165
+ now
166
+ ).run();
167
+ console.log(` \u2713 Created collection: ${config.name}`);
168
+ return {
169
+ name: config.name,
170
+ status: "created",
171
+ message: `Created collection "${config.displayName}"`
172
+ };
173
+ } else {
174
+ const existingSchema = existing.schema ? JSON.stringify(existing.schema) : "{}";
175
+ const existingDisplayName = existing.display_name;
176
+ const existingDescription = existing.description;
177
+ const existingIsActive = existing.is_active;
178
+ const existingManaged = existing.managed;
179
+ const needsUpdate = schemaJson !== existingSchema || config.displayName !== existingDisplayName || (config.description || null) !== existingDescription || isActive !== existingIsActive || managed !== existingManaged;
180
+ if (!needsUpdate) {
181
+ return {
182
+ name: config.name,
183
+ status: "unchanged",
184
+ message: `Collection "${config.displayName}" is up to date`
185
+ };
186
+ }
187
+ const updateStmt = db.prepare(`
188
+ UPDATE collections
189
+ SET display_name = ?, description = ?, schema = ?, is_active = ?, managed = ?, updated_at = ?
190
+ WHERE name = ?
191
+ `);
192
+ await updateStmt.bind(
193
+ config.displayName,
194
+ config.description || null,
195
+ schemaJson,
196
+ isActive,
197
+ managed,
198
+ now,
199
+ config.name
200
+ ).run();
201
+ console.log(` \u2713 Updated collection: ${config.name}`);
202
+ return {
203
+ name: config.name,
204
+ status: "updated",
205
+ message: `Updated collection "${config.displayName}"`
206
+ };
207
+ }
208
+ } catch (error) {
209
+ console.error(` \u2717 Error syncing collection ${config.name}:`, error);
210
+ return {
211
+ name: config.name,
212
+ status: "error",
213
+ error: error instanceof Error ? error.message : "Unknown error"
214
+ };
215
+ }
216
+ }
217
+ async function isCollectionManaged(db, collectionName) {
218
+ try {
219
+ const stmt = db.prepare("SELECT managed FROM collections WHERE name = ?");
220
+ const result = await stmt.bind(collectionName).first();
221
+ return result?.managed === 1;
222
+ } catch (error) {
223
+ console.error(`Error checking if collection is managed:`, error);
224
+ return false;
225
+ }
226
+ }
227
+ async function getManagedCollections(db) {
228
+ try {
229
+ const stmt = db.prepare("SELECT name FROM collections WHERE managed = 1");
230
+ const { results } = await stmt.all();
231
+ return (results || []).map((row) => row.name);
232
+ } catch (error) {
233
+ console.error("Error getting managed collections:", error);
234
+ return [];
235
+ }
236
+ }
237
+ async function cleanupRemovedCollections(db) {
238
+ try {
239
+ const configs = await loadCollectionConfigs();
240
+ const configNames = new Set(configs.map((c) => c.name));
241
+ const managedCollections = await getManagedCollections(db);
242
+ const removed = [];
243
+ for (const managedName of managedCollections) {
244
+ if (!configNames.has(managedName)) {
245
+ const updateStmt = db.prepare(`
246
+ UPDATE collections
247
+ SET is_active = 0, updated_at = ?
248
+ WHERE name = ? AND managed = 1
249
+ `);
250
+ await updateStmt.bind(Date.now(), managedName).run();
251
+ removed.push(managedName);
252
+ console.log(` \u26A0\uFE0F Deactivated removed collection: ${managedName}`);
253
+ }
254
+ }
255
+ return removed;
256
+ } catch (error) {
257
+ console.error("Error cleaning up removed collections:", error);
258
+ return [];
259
+ }
260
+ }
261
+ async function fullCollectionSync(db) {
262
+ const results = await syncCollections(db);
263
+ const removed = await cleanupRemovedCollections(db);
264
+ return { results, removed };
265
+ }
266
+
267
+ // src/services/plugin-service.ts
268
+ var PluginService = class {
269
+ constructor(db) {
270
+ this.db = db;
271
+ }
272
+ async getAllPlugins() {
273
+ await this.ensureAllPluginsExist();
274
+ const stmt = this.db.prepare(`
275
+ SELECT * FROM plugins
276
+ ORDER BY is_core DESC, display_name ASC
277
+ `);
278
+ const { results } = await stmt.all();
279
+ return (results || []).map(this.mapPluginFromDb);
280
+ }
281
+ /**
282
+ * Ensure all plugins from the registry exist in the database
283
+ * Auto-installs any newly detected plugins with inactive status
284
+ *
285
+ * Note: This method should be overridden or configured with a plugin registry
286
+ * in the consuming application
287
+ */
288
+ async ensureAllPluginsExist() {
289
+ console.log("[PluginService] ensureAllPluginsExist - requires PLUGIN_REGISTRY configuration");
290
+ }
291
+ async getPlugin(pluginId) {
292
+ const stmt = this.db.prepare("SELECT * FROM plugins WHERE id = ?");
293
+ const plugin = await stmt.bind(pluginId).first();
294
+ if (!plugin) return null;
295
+ return this.mapPluginFromDb(plugin);
296
+ }
297
+ async getPluginByName(name) {
298
+ const stmt = this.db.prepare("SELECT * FROM plugins WHERE name = ?");
299
+ const plugin = await stmt.bind(name).first();
300
+ if (!plugin) return null;
301
+ return this.mapPluginFromDb(plugin);
302
+ }
303
+ async getPluginStats() {
304
+ const stmt = this.db.prepare(`
305
+ SELECT
306
+ COUNT(*) as total,
307
+ COUNT(CASE WHEN status = 'active' THEN 1 END) as active,
308
+ COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive,
309
+ COUNT(CASE WHEN status = 'error' THEN 1 END) as errors
310
+ FROM plugins
311
+ `);
312
+ const stats = await stmt.first();
313
+ return {
314
+ total: stats.total || 0,
315
+ active: stats.active || 0,
316
+ inactive: stats.inactive || 0,
317
+ errors: stats.errors || 0
318
+ };
319
+ }
320
+ async installPlugin(pluginData) {
321
+ const id = pluginData.id || `plugin-${Date.now()}`;
322
+ const now = Math.floor(Date.now() / 1e3);
323
+ const stmt = this.db.prepare(`
324
+ INSERT INTO plugins (
325
+ id, name, display_name, description, version, author, category, icon,
326
+ status, is_core, settings, permissions, dependencies, download_count,
327
+ rating, installed_at, last_updated
328
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
329
+ `);
330
+ await stmt.bind(
331
+ id,
332
+ pluginData.name || id,
333
+ pluginData.display_name || "Unnamed Plugin",
334
+ pluginData.description || "",
335
+ pluginData.version || "1.0.0",
336
+ pluginData.author || "Unknown",
337
+ pluginData.category || "utilities",
338
+ pluginData.icon || "\u{1F50C}",
339
+ "inactive",
340
+ pluginData.is_core || false,
341
+ JSON.stringify(pluginData.settings || {}),
342
+ JSON.stringify(pluginData.permissions || []),
343
+ JSON.stringify(pluginData.dependencies || []),
344
+ pluginData.download_count || 0,
345
+ pluginData.rating || 0,
346
+ now,
347
+ now
348
+ ).run();
349
+ await this.logActivity(id, "installed", null, { version: pluginData.version });
350
+ const installed = await this.getPlugin(id);
351
+ if (!installed) throw new Error("Failed to install plugin");
352
+ return installed;
353
+ }
354
+ async uninstallPlugin(pluginId) {
355
+ const plugin = await this.getPlugin(pluginId);
356
+ if (!plugin) throw new Error("Plugin not found");
357
+ if (plugin.is_core) throw new Error("Cannot uninstall core plugins");
358
+ if (plugin.status === "active") {
359
+ await this.deactivatePlugin(pluginId);
360
+ }
361
+ const stmt = this.db.prepare("DELETE FROM plugins WHERE id = ?");
362
+ await stmt.bind(pluginId).run();
363
+ await this.logActivity(pluginId, "uninstalled", null, { name: plugin.name });
364
+ }
365
+ async activatePlugin(pluginId) {
366
+ const plugin = await this.getPlugin(pluginId);
367
+ if (!plugin) throw new Error("Plugin not found");
368
+ if (plugin.dependencies && plugin.dependencies.length > 0) {
369
+ await this.checkDependencies(plugin.dependencies);
370
+ }
371
+ const now = Math.floor(Date.now() / 1e3);
372
+ const stmt = this.db.prepare(`
373
+ UPDATE plugins
374
+ SET status = 'active', activated_at = ?, error_message = NULL
375
+ WHERE id = ?
376
+ `);
377
+ await stmt.bind(now, pluginId).run();
378
+ await this.logActivity(pluginId, "activated", null);
379
+ }
380
+ async deactivatePlugin(pluginId) {
381
+ const plugin = await this.getPlugin(pluginId);
382
+ if (!plugin) throw new Error("Plugin not found");
383
+ await this.checkDependents(plugin.name);
384
+ const stmt = this.db.prepare(`
385
+ UPDATE plugins
386
+ SET status = 'inactive', activated_at = NULL
387
+ WHERE id = ?
388
+ `);
389
+ await stmt.bind(pluginId).run();
390
+ await this.logActivity(pluginId, "deactivated", null);
391
+ }
392
+ async updatePluginSettings(pluginId, settings) {
393
+ const plugin = await this.getPlugin(pluginId);
394
+ if (!plugin) throw new Error("Plugin not found");
395
+ const stmt = this.db.prepare(`
396
+ UPDATE plugins
397
+ SET settings = ?, updated_at = unixepoch()
398
+ WHERE id = ?
399
+ `);
400
+ await stmt.bind(JSON.stringify(settings), pluginId).run();
401
+ await this.logActivity(pluginId, "settings_updated", null);
402
+ }
403
+ async setPluginError(pluginId, error) {
404
+ const stmt = this.db.prepare(`
405
+ UPDATE plugins
406
+ SET status = 'error', error_message = ?
407
+ WHERE id = ?
408
+ `);
409
+ await stmt.bind(error, pluginId).run();
410
+ await this.logActivity(pluginId, "error", null, { error });
411
+ }
412
+ async getPluginActivity(pluginId, limit = 10) {
413
+ const stmt = this.db.prepare(`
414
+ SELECT * FROM plugin_activity_log
415
+ WHERE plugin_id = ?
416
+ ORDER BY timestamp DESC
417
+ LIMIT ?
418
+ `);
419
+ const { results } = await stmt.bind(pluginId, limit).all();
420
+ return (results || []).map((row) => ({
421
+ id: row.id,
422
+ action: row.action,
423
+ userId: row.user_id,
424
+ details: row.details ? JSON.parse(row.details) : null,
425
+ timestamp: row.timestamp
426
+ }));
427
+ }
428
+ async registerHook(pluginId, hookName, handlerName, priority = 10) {
429
+ const id = `hook-${Date.now()}`;
430
+ const stmt = this.db.prepare(`
431
+ INSERT INTO plugin_hooks (id, plugin_id, hook_name, handler_name, priority)
432
+ VALUES (?, ?, ?, ?, ?)
433
+ `);
434
+ await stmt.bind(id, pluginId, hookName, handlerName, priority).run();
435
+ }
436
+ async registerRoute(pluginId, path, method, handlerName, middleware) {
437
+ const id = `route-${Date.now()}`;
438
+ const stmt = this.db.prepare(`
439
+ INSERT INTO plugin_routes (id, plugin_id, path, method, handler_name, middleware)
440
+ VALUES (?, ?, ?, ?, ?, ?)
441
+ `);
442
+ await stmt.bind(
443
+ id,
444
+ pluginId,
445
+ path,
446
+ method,
447
+ handlerName,
448
+ JSON.stringify(middleware || [])
449
+ ).run();
450
+ }
451
+ async getPluginHooks(pluginId) {
452
+ const stmt = this.db.prepare(`
453
+ SELECT * FROM plugin_hooks
454
+ WHERE plugin_id = ? AND is_active = TRUE
455
+ ORDER BY priority ASC
456
+ `);
457
+ const { results } = await stmt.bind(pluginId).all();
458
+ return results || [];
459
+ }
460
+ async getPluginRoutes(pluginId) {
461
+ const stmt = this.db.prepare(`
462
+ SELECT * FROM plugin_routes
463
+ WHERE plugin_id = ? AND is_active = TRUE
464
+ `);
465
+ const { results } = await stmt.bind(pluginId).all();
466
+ return results || [];
467
+ }
468
+ async checkDependencies(dependencies) {
469
+ for (const dep of dependencies) {
470
+ const plugin = await this.getPluginByName(dep);
471
+ if (!plugin || plugin.status !== "active") {
472
+ throw new Error(`Required dependency '${dep}' is not active`);
473
+ }
474
+ }
475
+ }
476
+ async checkDependents(pluginName) {
477
+ const stmt = this.db.prepare(`
478
+ SELECT id, display_name FROM plugins
479
+ WHERE status = 'active'
480
+ AND dependencies LIKE ?
481
+ `);
482
+ const { results } = await stmt.bind(`%"${pluginName}"%`).all();
483
+ if (results && results.length > 0) {
484
+ const names = results.map((p) => p.display_name).join(", ");
485
+ throw new Error(`Cannot deactivate. The following plugins depend on this one: ${names}`);
486
+ }
487
+ }
488
+ async logActivity(pluginId, action, userId, details) {
489
+ const id = `activity-${Date.now()}`;
490
+ const stmt = this.db.prepare(`
491
+ INSERT INTO plugin_activity_log (id, plugin_id, action, user_id, details)
492
+ VALUES (?, ?, ?, ?, ?)
493
+ `);
494
+ await stmt.bind(
495
+ id,
496
+ pluginId,
497
+ action,
498
+ userId,
499
+ details ? JSON.stringify(details) : null
500
+ ).run();
501
+ }
502
+ mapPluginFromDb(row) {
503
+ return {
504
+ id: row.id,
505
+ name: row.name,
506
+ display_name: row.display_name,
507
+ description: row.description,
508
+ version: row.version,
509
+ author: row.author,
510
+ category: row.category,
511
+ icon: row.icon,
512
+ status: row.status,
513
+ is_core: row.is_core === 1,
514
+ settings: row.settings ? JSON.parse(row.settings) : void 0,
515
+ permissions: row.permissions ? JSON.parse(row.permissions) : void 0,
516
+ dependencies: row.dependencies ? JSON.parse(row.dependencies) : void 0,
517
+ download_count: row.download_count || 0,
518
+ rating: row.rating || 0,
519
+ installed_at: row.installed_at,
520
+ activated_at: row.activated_at,
521
+ last_updated: row.last_updated,
522
+ error_message: row.error_message
523
+ };
524
+ }
525
+ };
526
+
527
+ // src/services/plugin-bootstrap.ts
528
+ var PluginBootstrapService = class {
529
+ constructor(db) {
530
+ this.db = db;
531
+ this.pluginService = new PluginService(db);
532
+ }
533
+ pluginService;
534
+ /**
535
+ * Core plugins that should always be available in the system
536
+ */
537
+ CORE_PLUGINS = [
538
+ {
539
+ id: "core-auth",
540
+ name: "core-auth",
541
+ display_name: "Authentication System",
542
+ description: "Core authentication and user management system",
543
+ version: "1.0.0",
544
+ author: "SonicJS Team",
545
+ category: "security",
546
+ icon: "\u{1F510}",
547
+ permissions: ["manage:users", "manage:roles", "manage:permissions"],
548
+ dependencies: [],
549
+ settings: {
550
+ requiredFields: {
551
+ email: { required: true, minLength: 5, label: "Email", type: "email" },
552
+ password: { required: true, minLength: 8, label: "Password", type: "password" },
553
+ username: { required: true, minLength: 3, label: "Username", type: "text" },
554
+ firstName: { required: true, minLength: 1, label: "First Name", type: "text" },
555
+ lastName: { required: true, minLength: 1, label: "Last Name", type: "text" }
556
+ },
557
+ validation: {
558
+ emailFormat: true,
559
+ allowDuplicateUsernames: false,
560
+ passwordRequirements: {
561
+ requireUppercase: false,
562
+ requireLowercase: false,
563
+ requireNumbers: false,
564
+ requireSpecialChars: false
565
+ }
566
+ },
567
+ registration: {
568
+ enabled: true,
569
+ requireEmailVerification: false,
570
+ defaultRole: "viewer"
571
+ }
572
+ }
573
+ },
574
+ {
575
+ id: "core-media",
576
+ name: "core-media",
577
+ display_name: "Media Manager",
578
+ description: "Core media upload and management system",
579
+ version: "1.0.0",
580
+ author: "SonicJS Team",
581
+ category: "media",
582
+ icon: "\u{1F4F8}",
583
+ permissions: ["manage:media", "upload:files"],
584
+ dependencies: [],
585
+ settings: {}
586
+ },
587
+ {
588
+ id: "database-tools",
589
+ name: "database-tools",
590
+ display_name: "Database Tools",
591
+ description: "Database management tools including truncate, backup, and validation",
592
+ version: "1.0.0",
593
+ author: "SonicJS Team",
594
+ category: "system",
595
+ icon: "\u{1F5C4}\uFE0F",
596
+ permissions: ["manage:database", "admin"],
597
+ dependencies: [],
598
+ settings: {
599
+ enableTruncate: true,
600
+ enableBackup: true,
601
+ enableValidation: true,
602
+ requireConfirmation: true
603
+ }
604
+ },
605
+ {
606
+ id: "seed-data",
607
+ name: "seed-data",
608
+ display_name: "Seed Data",
609
+ description: "Generate realistic example users and content for testing and development",
610
+ version: "1.0.0",
611
+ author: "SonicJS Team",
612
+ category: "development",
613
+ icon: "\u{1F331}",
614
+ permissions: ["admin"],
615
+ dependencies: [],
616
+ settings: {
617
+ userCount: 20,
618
+ contentCount: 200,
619
+ defaultPassword: "password123"
620
+ }
621
+ },
622
+ {
623
+ id: "core-cache",
624
+ name: "core-cache",
625
+ display_name: "Cache System",
626
+ description: "Three-tiered caching system with memory, KV, and database layers",
627
+ version: "1.0.0",
628
+ author: "SonicJS Team",
629
+ category: "performance",
630
+ icon: "\u26A1",
631
+ permissions: ["manage:cache", "view:stats"],
632
+ dependencies: [],
633
+ settings: {
634
+ enableMemoryCache: true,
635
+ enableKVCache: true,
636
+ enableDatabaseCache: true,
637
+ defaultTTL: 3600
638
+ }
639
+ },
640
+ {
641
+ id: "workflow-plugin",
642
+ name: "workflow-plugin",
643
+ display_name: "Workflow Management",
644
+ description: "Content workflow management with approval chains, scheduling, and automation",
645
+ version: "1.0.0-beta.1",
646
+ author: "SonicJS Team",
647
+ category: "content",
648
+ icon: "\u{1F504}",
649
+ permissions: ["manage:workflows", "view:workflows", "transition:content"],
650
+ dependencies: ["content-plugin"],
651
+ settings: {
652
+ enableApprovalChains: true,
653
+ enableScheduling: true,
654
+ enableAutomation: true,
655
+ enableNotifications: true
656
+ }
657
+ },
658
+ {
659
+ id: "easy-mdx",
660
+ name: "easy-mdx",
661
+ display_name: "EasyMDE Editor",
662
+ description: "Lightweight markdown editor with live preview for richtext fields",
663
+ version: "1.0.0",
664
+ author: "SonicJS Team",
665
+ category: "editor",
666
+ icon: "\u270D\uFE0F",
667
+ permissions: [],
668
+ dependencies: [],
669
+ settings: {
670
+ defaultHeight: 400,
671
+ toolbar: "full",
672
+ placeholder: "Start writing your content..."
673
+ }
674
+ }
675
+ ];
676
+ /**
677
+ * Bootstrap all core plugins - install them if they don't exist
678
+ */
679
+ async bootstrapCorePlugins() {
680
+ console.log("[PluginBootstrap] Starting core plugin bootstrap process...");
681
+ try {
682
+ for (const corePlugin of this.CORE_PLUGINS) {
683
+ await this.ensurePluginInstalled(corePlugin);
684
+ }
685
+ console.log(
686
+ "[PluginBootstrap] Core plugin bootstrap completed successfully"
687
+ );
688
+ } catch (error) {
689
+ console.error("[PluginBootstrap] Error during plugin bootstrap:", error);
690
+ throw error;
691
+ }
692
+ }
693
+ /**
694
+ * Ensure a specific plugin is installed
695
+ */
696
+ async ensurePluginInstalled(plugin) {
697
+ try {
698
+ const existingPlugin = await this.pluginService.getPlugin(plugin.id);
699
+ if (existingPlugin) {
700
+ console.log(
701
+ `[PluginBootstrap] Plugin already installed: ${plugin.display_name} (status: ${existingPlugin.status})`
702
+ );
703
+ if (existingPlugin.version !== plugin.version) {
704
+ console.log(
705
+ `[PluginBootstrap] Updating plugin version: ${plugin.display_name} from ${existingPlugin.version} to ${plugin.version}`
706
+ );
707
+ await this.updatePlugin(plugin);
708
+ }
709
+ if (plugin.id === "core-auth" && existingPlugin.status !== "active") {
710
+ console.log(
711
+ `[PluginBootstrap] Core-auth plugin is inactive, activating it now...`
712
+ );
713
+ await this.pluginService.activatePlugin(plugin.id);
714
+ }
715
+ } else {
716
+ console.log(
717
+ `[PluginBootstrap] Installing plugin: ${plugin.display_name}`
718
+ );
719
+ await this.pluginService.installPlugin({
720
+ ...plugin,
721
+ is_core: plugin.name.startsWith("core-")
722
+ });
723
+ if (plugin.name.startsWith("core-")) {
724
+ console.log(
725
+ `[PluginBootstrap] Activating newly installed core plugin: ${plugin.display_name}`
726
+ );
727
+ await this.pluginService.activatePlugin(plugin.id);
728
+ }
729
+ }
730
+ } catch (error) {
731
+ console.error(
732
+ `[PluginBootstrap] Error ensuring plugin ${plugin.display_name}:`,
733
+ error
734
+ );
735
+ }
736
+ }
737
+ /**
738
+ * Update an existing plugin
739
+ */
740
+ async updatePlugin(plugin) {
741
+ const now = Math.floor(Date.now() / 1e3);
742
+ const stmt = this.db.prepare(`
743
+ UPDATE plugins
744
+ SET
745
+ version = ?,
746
+ description = ?,
747
+ permissions = ?,
748
+ settings = ?,
749
+ last_updated = ?
750
+ WHERE id = ?
751
+ `);
752
+ await stmt.bind(
753
+ plugin.version,
754
+ plugin.description,
755
+ JSON.stringify(plugin.permissions),
756
+ JSON.stringify(plugin.settings || {}),
757
+ now,
758
+ plugin.id
759
+ ).run();
760
+ }
761
+ /**
762
+ * Check if bootstrap is needed (first run detection)
763
+ */
764
+ async isBootstrapNeeded() {
765
+ try {
766
+ for (const corePlugin of this.CORE_PLUGINS.filter(
767
+ (p) => p.name.startsWith("core-")
768
+ )) {
769
+ const exists = await this.pluginService.getPlugin(corePlugin.id);
770
+ if (!exists) {
771
+ return true;
772
+ }
773
+ }
774
+ return false;
775
+ } catch (error) {
776
+ console.error(
777
+ "[PluginBootstrap] Error checking bootstrap status:",
778
+ error
779
+ );
780
+ return true;
781
+ }
782
+ }
783
+ };
784
+
785
+ export { PluginBootstrapService, PluginService, cleanupRemovedCollections, fullCollectionSync, getAvailableCollectionNames, getManagedCollections, isCollectionManaged, loadCollectionConfig, loadCollectionConfigs, registerCollections, syncCollection, syncCollections, validateCollectionConfig };
786
+ //# sourceMappingURL=chunk-LWMMMW43.js.map
787
+ //# sourceMappingURL=chunk-LWMMMW43.js.map