@sonicjs-cms/core 2.0.10 → 2.2.0

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 (75) hide show
  1. package/dist/{chunk-Q7SL7U43.cjs → chunk-2DIWLDCA.cjs} +12001 -10740
  2. package/dist/chunk-2DIWLDCA.cjs.map +1 -0
  3. package/dist/{chunk-LW33AOBF.js → chunk-5RKQB2JG.js} +6 -222
  4. package/dist/chunk-5RKQB2JG.js.map +1 -0
  5. package/dist/{chunk-DOR2IU73.cjs → chunk-AINTFRTC.cjs} +2 -2
  6. package/dist/{chunk-DOR2IU73.cjs.map → chunk-AINTFRTC.cjs.map} +1 -1
  7. package/dist/chunk-HV2I6API.cjs +1049 -0
  8. package/dist/chunk-HV2I6API.cjs.map +1 -0
  9. package/dist/chunk-K4Z3IHOK.js +1031 -0
  10. package/dist/chunk-K4Z3IHOK.js.map +1 -0
  11. package/dist/{chunk-6FR25MPC.js → chunk-L232U757.js} +2 -2
  12. package/dist/{chunk-6FR25MPC.js.map → chunk-L232U757.js.map} +1 -1
  13. package/dist/chunk-NMVOTNSL.js +61 -0
  14. package/dist/chunk-NMVOTNSL.js.map +1 -0
  15. package/dist/{chunk-YHG45LMU.js → chunk-OORGXYDA.js} +48 -5
  16. package/dist/chunk-OORGXYDA.js.map +1 -0
  17. package/dist/{chunk-FTMKKKNH.js → chunk-QNWYQZ55.js} +3 -3
  18. package/dist/{chunk-FTMKKKNH.js.map → chunk-QNWYQZ55.js.map} +1 -1
  19. package/dist/{chunk-Z4H6DBVF.js → chunk-R57VFNP3.js} +11991 -10731
  20. package/dist/chunk-R57VFNP3.js.map +1 -0
  21. package/dist/{chunk-COBUPOMD.js → chunk-T7IYBGGO.cjs} +5 -770
  22. package/dist/chunk-T7IYBGGO.cjs.map +1 -0
  23. package/dist/{chunk-HXA5QSI3.cjs → chunk-UEYMFNBN.cjs} +51 -6
  24. package/dist/chunk-UEYMFNBN.cjs.map +1 -0
  25. package/dist/chunk-WBX5YMTB.cjs +70 -0
  26. package/dist/chunk-WBX5YMTB.cjs.map +1 -0
  27. package/dist/{chunk-3PHG75W4.cjs → chunk-YTMFJLJZ.cjs} +7 -5
  28. package/dist/chunk-YTMFJLJZ.cjs.map +1 -0
  29. package/dist/{chunk-MU3MR2QR.cjs → chunk-YU6QFFI4.cjs} +5 -222
  30. package/dist/chunk-YU6QFFI4.cjs.map +1 -0
  31. package/dist/{chunk-CAP6QQR2.cjs → chunk-ZMSYKV62.cjs} +5 -5
  32. package/dist/{chunk-CAP6QQR2.cjs.map → chunk-ZMSYKV62.cjs.map} +1 -1
  33. package/dist/{chunk-NBDPIRQS.cjs → chunk-ZPMFT2JW.js} +4 -786
  34. package/dist/chunk-ZPMFT2JW.js.map +1 -0
  35. package/dist/{chunk-MXJJN4IA.js → chunk-ZUK55KZB.js} +7 -5
  36. package/dist/chunk-ZUK55KZB.js.map +1 -0
  37. package/dist/index.cjs +542 -145
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.js +389 -12
  40. package/dist/index.js.map +1 -1
  41. package/dist/middleware.cjs +33 -23
  42. package/dist/middleware.js +4 -2
  43. package/dist/migrations-IHERIQVD.js +4 -0
  44. package/dist/migrations-IHERIQVD.js.map +1 -0
  45. package/dist/migrations-POFD5KNG.cjs +13 -0
  46. package/dist/migrations-POFD5KNG.cjs.map +1 -0
  47. package/dist/routes.cjs +31 -29
  48. package/dist/routes.js +8 -6
  49. package/dist/services.cjs +44 -26
  50. package/dist/services.js +4 -2
  51. package/dist/templates.cjs +17 -21
  52. package/dist/templates.js +2 -2
  53. package/dist/utils.cjs +44 -11
  54. package/dist/utils.js +2 -1
  55. package/migrations/001_initial_schema.sql +2 -2
  56. package/migrations/007_demo_login_plugin.sql +1 -1
  57. package/migrations/020_add_email_plugin.sql +22 -0
  58. package/migrations/021_add_magic_link_auth_plugin.sql +42 -0
  59. package/migrations/021_add_otp_login.sql +42 -0
  60. package/migrations/022_add_tinymce_plugin.sql +25 -0
  61. package/migrations/023_add_easy_mdx_plugin.sql +25 -0
  62. package/migrations/024_add_quill_editor_plugin.sql +25 -0
  63. package/migrations/025_rename_mdxeditor_to_easy_mdx.sql +22 -0
  64. package/package.json +5 -3
  65. package/dist/chunk-3PHG75W4.cjs.map +0 -1
  66. package/dist/chunk-COBUPOMD.js.map +0 -1
  67. package/dist/chunk-HXA5QSI3.cjs.map +0 -1
  68. package/dist/chunk-LW33AOBF.js.map +0 -1
  69. package/dist/chunk-MU3MR2QR.cjs.map +0 -1
  70. package/dist/chunk-MXJJN4IA.js.map +0 -1
  71. package/dist/chunk-NBDPIRQS.cjs.map +0 -1
  72. package/dist/chunk-Q7SL7U43.cjs.map +0 -1
  73. package/dist/chunk-YHG45LMU.js.map +0 -1
  74. package/dist/chunk-Z4H6DBVF.js.map +0 -1
  75. package/migrations/002_faq_plugin.sql +0 -86
@@ -0,0 +1,1049 @@
1
+ 'use strict';
2
+
3
+ var chunkWBX5YMTB_cjs = require('./chunk-WBX5YMTB.cjs');
4
+
5
+ // src/services/collection-loader.ts
6
+ var registeredCollections = [];
7
+ function registerCollections(collections) {
8
+ for (const config of collections) {
9
+ if (!config.name || !config.displayName || !config.schema) {
10
+ console.error(`Invalid collection config: missing required fields`, config);
11
+ continue;
12
+ }
13
+ const normalizedConfig = {
14
+ ...config,
15
+ managed: config.managed !== void 0 ? config.managed : true,
16
+ isActive: config.isActive !== void 0 ? config.isActive : true
17
+ };
18
+ registeredCollections.push(normalizedConfig);
19
+ console.log(`\u2713 Registered collection: ${config.name}`);
20
+ }
21
+ }
22
+ async function loadCollectionConfigs() {
23
+ const collections = [...registeredCollections];
24
+ try {
25
+ const modules = undefined?.("../collections/*.collection.ts", { eager: true }) || {};
26
+ for (const [path, module] of Object.entries(modules)) {
27
+ try {
28
+ const configModule = module;
29
+ if (!configModule.default) {
30
+ console.warn(`Collection file ${path} does not export a default config`);
31
+ continue;
32
+ }
33
+ const config = configModule.default;
34
+ if (!config.name || !config.displayName || !config.schema) {
35
+ console.error(`Invalid collection config in ${path}: missing required fields`);
36
+ continue;
37
+ }
38
+ const normalizedConfig = {
39
+ ...config,
40
+ managed: config.managed !== void 0 ? config.managed : true,
41
+ isActive: config.isActive !== void 0 ? config.isActive : true
42
+ };
43
+ collections.push(normalizedConfig);
44
+ console.log(`\u2713 Loaded collection config: ${config.name}`);
45
+ } catch (error) {
46
+ console.error(`Error loading collection from ${path}:`, error);
47
+ }
48
+ }
49
+ console.log(`Loaded ${collections.length} total collection configuration(s) (${registeredCollections.length} registered, ${collections.length - registeredCollections.length} from core)`);
50
+ return collections;
51
+ } catch (error) {
52
+ console.error("Error loading collection configurations:", error);
53
+ return collections;
54
+ }
55
+ }
56
+ async function loadCollectionConfig(name) {
57
+ try {
58
+ console.warn("loadCollectionConfig requires implementation in consuming application");
59
+ return null;
60
+ } catch (error) {
61
+ console.error(`Error loading collection ${name}:`, error);
62
+ return null;
63
+ }
64
+ }
65
+ async function getAvailableCollectionNames() {
66
+ try {
67
+ const modules = undefined?.("../collections/*.collection.ts") || {};
68
+ const names = [];
69
+ for (const path of Object.keys(modules)) {
70
+ const match = path.match(/\/([^/]+)\.collection\.ts$/);
71
+ if (match && match[1]) {
72
+ names.push(match[1]);
73
+ }
74
+ }
75
+ return names;
76
+ } catch (error) {
77
+ console.error("Error getting collection names:", error);
78
+ return [];
79
+ }
80
+ }
81
+ function validateCollectionConfig(config) {
82
+ const errors = [];
83
+ if (!config.name) {
84
+ errors.push("Collection name is required");
85
+ } else if (!/^[a-z0-9_]+$/.test(config.name)) {
86
+ errors.push("Collection name must contain only lowercase letters, numbers, and underscores");
87
+ }
88
+ if (!config.displayName) {
89
+ errors.push("Display name is required");
90
+ }
91
+ if (!config.schema) {
92
+ errors.push("Schema is required");
93
+ } else {
94
+ if (config.schema.type !== "object") {
95
+ errors.push('Schema type must be "object"');
96
+ }
97
+ if (!config.schema.properties || typeof config.schema.properties !== "object") {
98
+ errors.push("Schema must have properties");
99
+ }
100
+ for (const [fieldName, fieldConfig] of Object.entries(config.schema.properties || {})) {
101
+ if (!fieldConfig.type) {
102
+ errors.push(`Field "${fieldName}" is missing type`);
103
+ }
104
+ if (fieldConfig.type === "reference" && !fieldConfig.collection) {
105
+ errors.push(`Reference field "${fieldName}" is missing collection property`);
106
+ }
107
+ if (["select", "multiselect", "radio"].includes(fieldConfig.type) && !fieldConfig.enum) {
108
+ errors.push(`Select field "${fieldName}" is missing enum options`);
109
+ }
110
+ }
111
+ }
112
+ return {
113
+ valid: errors.length === 0,
114
+ errors
115
+ };
116
+ }
117
+
118
+ // src/services/collection-sync.ts
119
+ async function syncCollections(db) {
120
+ console.log("\u{1F504} Starting collection sync...");
121
+ const results = [];
122
+ const configs = await loadCollectionConfigs();
123
+ if (configs.length === 0) {
124
+ console.log("\u26A0\uFE0F No collection configurations found");
125
+ return results;
126
+ }
127
+ for (const config of configs) {
128
+ const result = await syncCollection(db, config);
129
+ results.push(result);
130
+ }
131
+ const created = results.filter((r) => r.status === "created").length;
132
+ const updated = results.filter((r) => r.status === "updated").length;
133
+ const unchanged = results.filter((r) => r.status === "unchanged").length;
134
+ const errors = results.filter((r) => r.status === "error").length;
135
+ console.log(`\u2705 Collection sync complete: ${created} created, ${updated} updated, ${unchanged} unchanged, ${errors} errors`);
136
+ return results;
137
+ }
138
+ async function syncCollection(db, config) {
139
+ try {
140
+ const validation = validateCollectionConfig(config);
141
+ if (!validation.valid) {
142
+ return {
143
+ name: config.name,
144
+ status: "error",
145
+ error: `Validation failed: ${validation.errors.join(", ")}`
146
+ };
147
+ }
148
+ const existingStmt = db.prepare("SELECT * FROM collections WHERE name = ?");
149
+ const existing = await existingStmt.bind(config.name).first();
150
+ const now = Date.now();
151
+ const collectionId = existing?.id || `col-${config.name}-${crypto.randomUUID().slice(0, 8)}`;
152
+ const schemaJson = JSON.stringify(config.schema);
153
+ const isActive = config.isActive !== false ? 1 : 0;
154
+ const managed = config.managed !== false ? 1 : 0;
155
+ if (!existing) {
156
+ const insertStmt = db.prepare(`
157
+ INSERT INTO collections (id, name, display_name, description, schema, is_active, managed, created_at, updated_at)
158
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
159
+ `);
160
+ await insertStmt.bind(
161
+ collectionId,
162
+ config.name,
163
+ config.displayName,
164
+ config.description || null,
165
+ schemaJson,
166
+ isActive,
167
+ managed,
168
+ now,
169
+ now
170
+ ).run();
171
+ console.log(` \u2713 Created collection: ${config.name}`);
172
+ return {
173
+ name: config.name,
174
+ status: "created",
175
+ message: `Created collection "${config.displayName}"`
176
+ };
177
+ } else {
178
+ const existingSchema = existing.schema ? JSON.stringify(existing.schema) : "{}";
179
+ const existingDisplayName = existing.display_name;
180
+ const existingDescription = existing.description;
181
+ const existingIsActive = existing.is_active;
182
+ const existingManaged = existing.managed;
183
+ const needsUpdate = schemaJson !== existingSchema || config.displayName !== existingDisplayName || (config.description || null) !== existingDescription || isActive !== existingIsActive || managed !== existingManaged;
184
+ if (!needsUpdate) {
185
+ return {
186
+ name: config.name,
187
+ status: "unchanged",
188
+ message: `Collection "${config.displayName}" is up to date`
189
+ };
190
+ }
191
+ const updateStmt = db.prepare(`
192
+ UPDATE collections
193
+ SET display_name = ?, description = ?, schema = ?, is_active = ?, managed = ?, updated_at = ?
194
+ WHERE name = ?
195
+ `);
196
+ await updateStmt.bind(
197
+ config.displayName,
198
+ config.description || null,
199
+ schemaJson,
200
+ isActive,
201
+ managed,
202
+ now,
203
+ config.name
204
+ ).run();
205
+ console.log(` \u2713 Updated collection: ${config.name}`);
206
+ return {
207
+ name: config.name,
208
+ status: "updated",
209
+ message: `Updated collection "${config.displayName}"`
210
+ };
211
+ }
212
+ } catch (error) {
213
+ console.error(` \u2717 Error syncing collection ${config.name}:`, error);
214
+ return {
215
+ name: config.name,
216
+ status: "error",
217
+ error: error instanceof Error ? error.message : "Unknown error"
218
+ };
219
+ }
220
+ }
221
+ async function isCollectionManaged(db, collectionName) {
222
+ try {
223
+ const stmt = db.prepare("SELECT managed FROM collections WHERE name = ?");
224
+ const result = await stmt.bind(collectionName).first();
225
+ return result?.managed === 1;
226
+ } catch (error) {
227
+ console.error(`Error checking if collection is managed:`, error);
228
+ return false;
229
+ }
230
+ }
231
+ async function getManagedCollections(db) {
232
+ try {
233
+ const stmt = db.prepare("SELECT name FROM collections WHERE managed = 1");
234
+ const { results } = await stmt.all();
235
+ return (results || []).map((row) => row.name);
236
+ } catch (error) {
237
+ console.error("Error getting managed collections:", error);
238
+ return [];
239
+ }
240
+ }
241
+ async function cleanupRemovedCollections(db) {
242
+ try {
243
+ const configs = await loadCollectionConfigs();
244
+ const configNames = new Set(configs.map((c) => c.name));
245
+ const managedCollections = await getManagedCollections(db);
246
+ const removed = [];
247
+ for (const managedName of managedCollections) {
248
+ if (!configNames.has(managedName)) {
249
+ const updateStmt = db.prepare(`
250
+ UPDATE collections
251
+ SET is_active = 0, updated_at = ?
252
+ WHERE name = ? AND managed = 1
253
+ `);
254
+ await updateStmt.bind(Date.now(), managedName).run();
255
+ removed.push(managedName);
256
+ console.log(` \u26A0\uFE0F Deactivated removed collection: ${managedName}`);
257
+ }
258
+ }
259
+ return removed;
260
+ } catch (error) {
261
+ console.error("Error cleaning up removed collections:", error);
262
+ return [];
263
+ }
264
+ }
265
+ async function fullCollectionSync(db) {
266
+ const results = await syncCollections(db);
267
+ const removed = await cleanupRemovedCollections(db);
268
+ return { results, removed };
269
+ }
270
+
271
+ // src/services/plugin-service.ts
272
+ var PluginService = class {
273
+ constructor(db) {
274
+ this.db = db;
275
+ }
276
+ async getAllPlugins() {
277
+ await this.ensureAllPluginsExist();
278
+ const stmt = this.db.prepare(`
279
+ SELECT * FROM plugins
280
+ ORDER BY is_core DESC, display_name ASC
281
+ `);
282
+ const { results } = await stmt.all();
283
+ return (results || []).map(this.mapPluginFromDb);
284
+ }
285
+ /**
286
+ * Ensure all plugins from the registry exist in the database
287
+ * Auto-installs any newly detected plugins with inactive status
288
+ *
289
+ * Note: This method should be overridden or configured with a plugin registry
290
+ * in the consuming application
291
+ */
292
+ async ensureAllPluginsExist() {
293
+ console.log("[PluginService] ensureAllPluginsExist - requires PLUGIN_REGISTRY configuration");
294
+ }
295
+ async getPlugin(pluginId) {
296
+ const stmt = this.db.prepare("SELECT * FROM plugins WHERE id = ?");
297
+ const plugin = await stmt.bind(pluginId).first();
298
+ if (!plugin) return null;
299
+ return this.mapPluginFromDb(plugin);
300
+ }
301
+ async getPluginByName(name) {
302
+ const stmt = this.db.prepare("SELECT * FROM plugins WHERE name = ?");
303
+ const plugin = await stmt.bind(name).first();
304
+ if (!plugin) return null;
305
+ return this.mapPluginFromDb(plugin);
306
+ }
307
+ async getPluginStats() {
308
+ const stmt = this.db.prepare(`
309
+ SELECT
310
+ COUNT(*) as total,
311
+ COUNT(CASE WHEN status = 'active' THEN 1 END) as active,
312
+ COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive,
313
+ COUNT(CASE WHEN status = 'error' THEN 1 END) as errors
314
+ FROM plugins
315
+ `);
316
+ const stats = await stmt.first();
317
+ return {
318
+ total: stats.total || 0,
319
+ active: stats.active || 0,
320
+ inactive: stats.inactive || 0,
321
+ errors: stats.errors || 0
322
+ };
323
+ }
324
+ async installPlugin(pluginData) {
325
+ const id = pluginData.id || `plugin-${Date.now()}`;
326
+ const now = Math.floor(Date.now() / 1e3);
327
+ const stmt = this.db.prepare(`
328
+ INSERT INTO plugins (
329
+ id, name, display_name, description, version, author, category, icon,
330
+ status, is_core, settings, permissions, dependencies, download_count,
331
+ rating, installed_at, last_updated
332
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
333
+ `);
334
+ await stmt.bind(
335
+ id,
336
+ pluginData.name || id,
337
+ pluginData.display_name || "Unnamed Plugin",
338
+ pluginData.description || "",
339
+ pluginData.version || "1.0.0",
340
+ pluginData.author || "Unknown",
341
+ pluginData.category || "utilities",
342
+ pluginData.icon || "\u{1F50C}",
343
+ "inactive",
344
+ pluginData.is_core || false,
345
+ JSON.stringify(pluginData.settings || {}),
346
+ JSON.stringify(pluginData.permissions || []),
347
+ JSON.stringify(pluginData.dependencies || []),
348
+ pluginData.download_count || 0,
349
+ pluginData.rating || 0,
350
+ now,
351
+ now
352
+ ).run();
353
+ await this.logActivity(id, "installed", null, { version: pluginData.version });
354
+ const installed = await this.getPlugin(id);
355
+ if (!installed) throw new Error("Failed to install plugin");
356
+ return installed;
357
+ }
358
+ async uninstallPlugin(pluginId) {
359
+ const plugin = await this.getPlugin(pluginId);
360
+ if (!plugin) throw new Error("Plugin not found");
361
+ if (plugin.is_core) throw new Error("Cannot uninstall core plugins");
362
+ if (plugin.status === "active") {
363
+ await this.deactivatePlugin(pluginId);
364
+ }
365
+ const stmt = this.db.prepare("DELETE FROM plugins WHERE id = ?");
366
+ await stmt.bind(pluginId).run();
367
+ await this.logActivity(pluginId, "uninstalled", null, { name: plugin.name });
368
+ }
369
+ async activatePlugin(pluginId) {
370
+ const plugin = await this.getPlugin(pluginId);
371
+ if (!plugin) throw new Error("Plugin not found");
372
+ if (plugin.dependencies && plugin.dependencies.length > 0) {
373
+ await this.checkDependencies(plugin.dependencies);
374
+ }
375
+ const now = Math.floor(Date.now() / 1e3);
376
+ const stmt = this.db.prepare(`
377
+ UPDATE plugins
378
+ SET status = 'active', activated_at = ?, error_message = NULL
379
+ WHERE id = ?
380
+ `);
381
+ await stmt.bind(now, pluginId).run();
382
+ await this.logActivity(pluginId, "activated", null);
383
+ }
384
+ async deactivatePlugin(pluginId) {
385
+ const plugin = await this.getPlugin(pluginId);
386
+ if (!plugin) throw new Error("Plugin not found");
387
+ await this.checkDependents(plugin.name);
388
+ const stmt = this.db.prepare(`
389
+ UPDATE plugins
390
+ SET status = 'inactive', activated_at = NULL
391
+ WHERE id = ?
392
+ `);
393
+ await stmt.bind(pluginId).run();
394
+ await this.logActivity(pluginId, "deactivated", null);
395
+ }
396
+ async updatePluginSettings(pluginId, settings) {
397
+ const plugin = await this.getPlugin(pluginId);
398
+ if (!plugin) throw new Error("Plugin not found");
399
+ const stmt = this.db.prepare(`
400
+ UPDATE plugins
401
+ SET settings = ?, updated_at = unixepoch()
402
+ WHERE id = ?
403
+ `);
404
+ await stmt.bind(JSON.stringify(settings), pluginId).run();
405
+ await this.logActivity(pluginId, "settings_updated", null);
406
+ }
407
+ async setPluginError(pluginId, error) {
408
+ const stmt = this.db.prepare(`
409
+ UPDATE plugins
410
+ SET status = 'error', error_message = ?
411
+ WHERE id = ?
412
+ `);
413
+ await stmt.bind(error, pluginId).run();
414
+ await this.logActivity(pluginId, "error", null, { error });
415
+ }
416
+ async getPluginActivity(pluginId, limit = 10) {
417
+ const stmt = this.db.prepare(`
418
+ SELECT * FROM plugin_activity_log
419
+ WHERE plugin_id = ?
420
+ ORDER BY timestamp DESC
421
+ LIMIT ?
422
+ `);
423
+ const { results } = await stmt.bind(pluginId, limit).all();
424
+ return (results || []).map((row) => ({
425
+ id: row.id,
426
+ action: row.action,
427
+ userId: row.user_id,
428
+ details: row.details ? JSON.parse(row.details) : null,
429
+ timestamp: row.timestamp
430
+ }));
431
+ }
432
+ async registerHook(pluginId, hookName, handlerName, priority = 10) {
433
+ const id = `hook-${Date.now()}`;
434
+ const stmt = this.db.prepare(`
435
+ INSERT INTO plugin_hooks (id, plugin_id, hook_name, handler_name, priority)
436
+ VALUES (?, ?, ?, ?, ?)
437
+ `);
438
+ await stmt.bind(id, pluginId, hookName, handlerName, priority).run();
439
+ }
440
+ async registerRoute(pluginId, path, method, handlerName, middleware) {
441
+ const id = `route-${Date.now()}`;
442
+ const stmt = this.db.prepare(`
443
+ INSERT INTO plugin_routes (id, plugin_id, path, method, handler_name, middleware)
444
+ VALUES (?, ?, ?, ?, ?, ?)
445
+ `);
446
+ await stmt.bind(
447
+ id,
448
+ pluginId,
449
+ path,
450
+ method,
451
+ handlerName,
452
+ JSON.stringify(middleware || [])
453
+ ).run();
454
+ }
455
+ async getPluginHooks(pluginId) {
456
+ const stmt = this.db.prepare(`
457
+ SELECT * FROM plugin_hooks
458
+ WHERE plugin_id = ? AND is_active = TRUE
459
+ ORDER BY priority ASC
460
+ `);
461
+ const { results } = await stmt.bind(pluginId).all();
462
+ return results || [];
463
+ }
464
+ async getPluginRoutes(pluginId) {
465
+ const stmt = this.db.prepare(`
466
+ SELECT * FROM plugin_routes
467
+ WHERE plugin_id = ? AND is_active = TRUE
468
+ `);
469
+ const { results } = await stmt.bind(pluginId).all();
470
+ return results || [];
471
+ }
472
+ async checkDependencies(dependencies) {
473
+ for (const dep of dependencies) {
474
+ const plugin = await this.getPluginByName(dep);
475
+ if (!plugin || plugin.status !== "active") {
476
+ throw new Error(`Required dependency '${dep}' is not active`);
477
+ }
478
+ }
479
+ }
480
+ async checkDependents(pluginName) {
481
+ const stmt = this.db.prepare(`
482
+ SELECT id, display_name FROM plugins
483
+ WHERE status = 'active'
484
+ AND dependencies LIKE ?
485
+ `);
486
+ const { results } = await stmt.bind(`%"${pluginName}"%`).all();
487
+ if (results && results.length > 0) {
488
+ const names = results.map((p) => p.display_name).join(", ");
489
+ throw new Error(`Cannot deactivate. The following plugins depend on this one: ${names}`);
490
+ }
491
+ }
492
+ async logActivity(pluginId, action, userId, details) {
493
+ const id = `activity-${Date.now()}`;
494
+ const stmt = this.db.prepare(`
495
+ INSERT INTO plugin_activity_log (id, plugin_id, action, user_id, details)
496
+ VALUES (?, ?, ?, ?, ?)
497
+ `);
498
+ await stmt.bind(
499
+ id,
500
+ pluginId,
501
+ action,
502
+ userId,
503
+ details ? JSON.stringify(details) : null
504
+ ).run();
505
+ }
506
+ mapPluginFromDb(row) {
507
+ return {
508
+ id: row.id,
509
+ name: row.name,
510
+ display_name: row.display_name,
511
+ description: row.description,
512
+ version: row.version,
513
+ author: row.author,
514
+ category: row.category,
515
+ icon: row.icon,
516
+ status: row.status,
517
+ is_core: row.is_core === 1,
518
+ settings: row.settings ? JSON.parse(row.settings) : void 0,
519
+ permissions: row.permissions ? JSON.parse(row.permissions) : void 0,
520
+ dependencies: row.dependencies ? JSON.parse(row.dependencies) : void 0,
521
+ download_count: row.download_count || 0,
522
+ rating: row.rating || 0,
523
+ installed_at: row.installed_at,
524
+ activated_at: row.activated_at,
525
+ last_updated: row.last_updated,
526
+ error_message: row.error_message
527
+ };
528
+ }
529
+ };
530
+
531
+ // src/services/plugin-bootstrap.ts
532
+ var PluginBootstrapService = class {
533
+ constructor(db) {
534
+ this.db = db;
535
+ this.pluginService = new PluginService(db);
536
+ }
537
+ pluginService;
538
+ /**
539
+ * Core plugins that should always be available in the system
540
+ */
541
+ CORE_PLUGINS = [
542
+ {
543
+ id: "core-auth",
544
+ name: "core-auth",
545
+ display_name: "Authentication System",
546
+ description: "Core authentication and user management system",
547
+ version: "1.0.0",
548
+ author: "SonicJS Team",
549
+ category: "security",
550
+ icon: "\u{1F510}",
551
+ permissions: ["manage:users", "manage:roles", "manage:permissions"],
552
+ dependencies: [],
553
+ settings: {
554
+ requiredFields: {
555
+ email: { required: true, minLength: 5, label: "Email", type: "email" },
556
+ password: { required: true, minLength: 8, label: "Password", type: "password" },
557
+ username: { required: true, minLength: 3, label: "Username", type: "text" },
558
+ firstName: { required: true, minLength: 1, label: "First Name", type: "text" },
559
+ lastName: { required: true, minLength: 1, label: "Last Name", type: "text" }
560
+ },
561
+ validation: {
562
+ emailFormat: true,
563
+ allowDuplicateUsernames: false,
564
+ passwordRequirements: {
565
+ requireUppercase: false,
566
+ requireLowercase: false,
567
+ requireNumbers: false,
568
+ requireSpecialChars: false
569
+ }
570
+ },
571
+ registration: {
572
+ enabled: true,
573
+ requireEmailVerification: false,
574
+ defaultRole: "viewer"
575
+ }
576
+ }
577
+ },
578
+ {
579
+ id: "core-media",
580
+ name: "core-media",
581
+ display_name: "Media Manager",
582
+ description: "Core media upload and management system",
583
+ version: "1.0.0",
584
+ author: "SonicJS Team",
585
+ category: "media",
586
+ icon: "\u{1F4F8}",
587
+ permissions: ["manage:media", "upload:files"],
588
+ dependencies: [],
589
+ settings: {}
590
+ },
591
+ {
592
+ id: "database-tools",
593
+ name: "database-tools",
594
+ display_name: "Database Tools",
595
+ description: "Database management tools including truncate, backup, and validation",
596
+ version: "1.0.0",
597
+ author: "SonicJS Team",
598
+ category: "system",
599
+ icon: "\u{1F5C4}\uFE0F",
600
+ permissions: ["manage:database", "admin"],
601
+ dependencies: [],
602
+ settings: {
603
+ enableTruncate: true,
604
+ enableBackup: true,
605
+ enableValidation: true,
606
+ requireConfirmation: true
607
+ }
608
+ },
609
+ {
610
+ id: "seed-data",
611
+ name: "seed-data",
612
+ display_name: "Seed Data",
613
+ description: "Generate realistic example users and content for testing and development",
614
+ version: "1.0.0",
615
+ author: "SonicJS Team",
616
+ category: "development",
617
+ icon: "\u{1F331}",
618
+ permissions: ["admin"],
619
+ dependencies: [],
620
+ settings: {
621
+ userCount: 20,
622
+ contentCount: 200,
623
+ defaultPassword: "password123"
624
+ }
625
+ },
626
+ {
627
+ id: "core-cache",
628
+ name: "core-cache",
629
+ display_name: "Cache System",
630
+ description: "Three-tiered caching system with memory, KV, and database layers",
631
+ version: "1.0.0",
632
+ author: "SonicJS Team",
633
+ category: "performance",
634
+ icon: "\u26A1",
635
+ permissions: ["manage:cache", "view:stats"],
636
+ dependencies: [],
637
+ settings: {
638
+ enableMemoryCache: true,
639
+ enableKVCache: true,
640
+ enableDatabaseCache: true,
641
+ defaultTTL: 3600
642
+ }
643
+ },
644
+ {
645
+ id: "workflow-plugin",
646
+ name: "workflow-plugin",
647
+ display_name: "Workflow Management",
648
+ description: "Content workflow management with approval chains, scheduling, and automation",
649
+ version: "1.0.0-beta.1",
650
+ author: "SonicJS Team",
651
+ category: "content",
652
+ icon: "\u{1F504}",
653
+ permissions: ["manage:workflows", "view:workflows", "transition:content"],
654
+ dependencies: ["content-plugin"],
655
+ settings: {
656
+ enableApprovalChains: true,
657
+ enableScheduling: true,
658
+ enableAutomation: true,
659
+ enableNotifications: true
660
+ }
661
+ },
662
+ {
663
+ id: "easy-mdx",
664
+ name: "easy-mdx",
665
+ display_name: "EasyMDE Editor",
666
+ description: "Lightweight markdown editor with live preview for richtext fields",
667
+ version: "1.0.0",
668
+ author: "SonicJS Team",
669
+ category: "editor",
670
+ icon: "\u270D\uFE0F",
671
+ permissions: [],
672
+ dependencies: [],
673
+ settings: {
674
+ defaultHeight: 400,
675
+ toolbar: "full",
676
+ placeholder: "Start writing your content..."
677
+ }
678
+ }
679
+ ];
680
+ /**
681
+ * Bootstrap all core plugins - install them if they don't exist
682
+ */
683
+ async bootstrapCorePlugins() {
684
+ console.log("[PluginBootstrap] Starting core plugin bootstrap process...");
685
+ try {
686
+ for (const corePlugin of this.CORE_PLUGINS) {
687
+ await this.ensurePluginInstalled(corePlugin);
688
+ }
689
+ console.log(
690
+ "[PluginBootstrap] Core plugin bootstrap completed successfully"
691
+ );
692
+ } catch (error) {
693
+ console.error("[PluginBootstrap] Error during plugin bootstrap:", error);
694
+ throw error;
695
+ }
696
+ }
697
+ /**
698
+ * Ensure a specific plugin is installed
699
+ */
700
+ async ensurePluginInstalled(plugin) {
701
+ try {
702
+ const existingPlugin = await this.pluginService.getPlugin(plugin.id);
703
+ if (existingPlugin) {
704
+ console.log(
705
+ `[PluginBootstrap] Plugin already installed: ${plugin.display_name} (status: ${existingPlugin.status})`
706
+ );
707
+ if (existingPlugin.version !== plugin.version) {
708
+ console.log(
709
+ `[PluginBootstrap] Updating plugin version: ${plugin.display_name} from ${existingPlugin.version} to ${plugin.version}`
710
+ );
711
+ await this.updatePlugin(plugin);
712
+ }
713
+ if (plugin.id === "core-auth" && existingPlugin.status !== "active") {
714
+ console.log(
715
+ `[PluginBootstrap] Core-auth plugin is inactive, activating it now...`
716
+ );
717
+ await this.pluginService.activatePlugin(plugin.id);
718
+ }
719
+ } else {
720
+ console.log(
721
+ `[PluginBootstrap] Installing plugin: ${plugin.display_name}`
722
+ );
723
+ await this.pluginService.installPlugin({
724
+ ...plugin,
725
+ is_core: plugin.name.startsWith("core-")
726
+ });
727
+ if (plugin.name.startsWith("core-")) {
728
+ console.log(
729
+ `[PluginBootstrap] Activating newly installed core plugin: ${plugin.display_name}`
730
+ );
731
+ await this.pluginService.activatePlugin(plugin.id);
732
+ }
733
+ }
734
+ } catch (error) {
735
+ console.error(
736
+ `[PluginBootstrap] Error ensuring plugin ${plugin.display_name}:`,
737
+ error
738
+ );
739
+ }
740
+ }
741
+ /**
742
+ * Update an existing plugin
743
+ */
744
+ async updatePlugin(plugin) {
745
+ const now = Math.floor(Date.now() / 1e3);
746
+ const stmt = this.db.prepare(`
747
+ UPDATE plugins
748
+ SET
749
+ version = ?,
750
+ description = ?,
751
+ permissions = ?,
752
+ settings = ?,
753
+ last_updated = ?
754
+ WHERE id = ?
755
+ `);
756
+ await stmt.bind(
757
+ plugin.version,
758
+ plugin.description,
759
+ JSON.stringify(plugin.permissions),
760
+ JSON.stringify(plugin.settings || {}),
761
+ now,
762
+ plugin.id
763
+ ).run();
764
+ }
765
+ /**
766
+ * Check if bootstrap is needed (first run detection)
767
+ */
768
+ async isBootstrapNeeded() {
769
+ try {
770
+ for (const corePlugin of this.CORE_PLUGINS.filter(
771
+ (p) => p.name.startsWith("core-")
772
+ )) {
773
+ const exists = await this.pluginService.getPlugin(corePlugin.id);
774
+ if (!exists) {
775
+ return true;
776
+ }
777
+ }
778
+ return false;
779
+ } catch (error) {
780
+ console.error(
781
+ "[PluginBootstrap] Error checking bootstrap status:",
782
+ error
783
+ );
784
+ return true;
785
+ }
786
+ }
787
+ };
788
+
789
+ // src/services/telemetry-service.ts
790
+ var TelemetryService = class {
791
+ config;
792
+ identity = null;
793
+ client = null;
794
+ enabled = true;
795
+ eventQueue = [];
796
+ isInitialized = false;
797
+ constructor(config) {
798
+ this.config = {
799
+ ...chunkWBX5YMTB_cjs.getTelemetryConfig(),
800
+ ...config
801
+ };
802
+ this.enabled = this.config.enabled;
803
+ }
804
+ /**
805
+ * Initialize the telemetry service
806
+ */
807
+ async initialize(identity) {
808
+ if (!this.enabled) {
809
+ if (this.config.debug) {
810
+ console.log("[Telemetry] Disabled via configuration");
811
+ }
812
+ return;
813
+ }
814
+ try {
815
+ this.identity = identity;
816
+ if (this.config.apiKey) {
817
+ const { PostHog } = await import('posthog-node');
818
+ this.client = new PostHog(this.config.apiKey, {
819
+ host: this.config.host,
820
+ flushAt: 20,
821
+ // Batch events
822
+ flushInterval: 1e4
823
+ // Flush every 10 seconds
824
+ });
825
+ if (this.config.debug) {
826
+ console.log("[Telemetry] Initialized with installation ID:", identity.installationId);
827
+ }
828
+ } else if (this.config.debug) {
829
+ console.log("[Telemetry] No API key provided, tracking will be logged only");
830
+ }
831
+ this.isInitialized = true;
832
+ await this.flushQueue();
833
+ } catch (error) {
834
+ if (this.config.debug) {
835
+ console.error("[Telemetry] Initialization failed:", error);
836
+ }
837
+ this.enabled = false;
838
+ }
839
+ }
840
+ /**
841
+ * Track a telemetry event
842
+ */
843
+ async track(event, properties) {
844
+ if (!this.enabled) return;
845
+ try {
846
+ const sanitizedProps = this.sanitizeProperties(properties);
847
+ const enrichedProps = {
848
+ ...sanitizedProps,
849
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
850
+ version: this.getVersion()
851
+ };
852
+ if (!this.isInitialized) {
853
+ this.eventQueue.push({ event, properties: enrichedProps });
854
+ if (this.config.debug) {
855
+ console.log("[Telemetry] Queued event:", event, enrichedProps);
856
+ }
857
+ return;
858
+ }
859
+ if (this.client && this.identity) {
860
+ this.client.capture({
861
+ distinctId: this.identity.installationId,
862
+ event,
863
+ properties: enrichedProps
864
+ });
865
+ if (this.config.debug) {
866
+ console.log("[Telemetry] Tracked event:", event, enrichedProps);
867
+ }
868
+ } else if (this.config.debug) {
869
+ console.log("[Telemetry] Event (no client):", event, enrichedProps);
870
+ }
871
+ } catch (error) {
872
+ if (this.config.debug) {
873
+ console.error("[Telemetry] Failed to track event:", error);
874
+ }
875
+ }
876
+ }
877
+ /**
878
+ * Track installation started
879
+ */
880
+ async trackInstallationStarted(properties) {
881
+ await this.track("installation_started", properties);
882
+ }
883
+ /**
884
+ * Track installation completed
885
+ */
886
+ async trackInstallationCompleted(properties) {
887
+ await this.track("installation_completed", properties);
888
+ }
889
+ /**
890
+ * Track installation failed
891
+ */
892
+ async trackInstallationFailed(error, properties) {
893
+ await this.track("installation_failed", {
894
+ ...properties,
895
+ errorType: chunkWBX5YMTB_cjs.sanitizeErrorMessage(error)
896
+ });
897
+ }
898
+ /**
899
+ * Track dev server started
900
+ */
901
+ async trackDevServerStarted(properties) {
902
+ await this.track("dev_server_started", properties);
903
+ }
904
+ /**
905
+ * Track page view in admin UI
906
+ */
907
+ async trackPageView(route, properties) {
908
+ await this.track("page_viewed", {
909
+ ...properties,
910
+ route: chunkWBX5YMTB_cjs.sanitizeRoute(route)
911
+ });
912
+ }
913
+ /**
914
+ * Track error (sanitized)
915
+ */
916
+ async trackError(error, properties) {
917
+ await this.track("error_occurred", {
918
+ ...properties,
919
+ errorType: chunkWBX5YMTB_cjs.sanitizeErrorMessage(error)
920
+ });
921
+ }
922
+ /**
923
+ * Track plugin activation
924
+ */
925
+ async trackPluginActivated(properties) {
926
+ await this.track("plugin_activated", properties);
927
+ }
928
+ /**
929
+ * Track migration run
930
+ */
931
+ async trackMigrationRun(properties) {
932
+ await this.track("migration_run", properties);
933
+ }
934
+ /**
935
+ * Flush queued events
936
+ */
937
+ async flushQueue() {
938
+ if (this.eventQueue.length === 0) return;
939
+ const queue = [...this.eventQueue];
940
+ this.eventQueue = [];
941
+ for (const { event, properties } of queue) {
942
+ await this.track(event, properties);
943
+ }
944
+ }
945
+ /**
946
+ * Sanitize properties to ensure no PII
947
+ */
948
+ sanitizeProperties(properties) {
949
+ if (!properties) return {};
950
+ const sanitized = {};
951
+ for (const [key, value] of Object.entries(properties)) {
952
+ if (value === void 0) continue;
953
+ if (key === "route" && typeof value === "string") {
954
+ sanitized[key] = chunkWBX5YMTB_cjs.sanitizeRoute(value);
955
+ continue;
956
+ }
957
+ if (key.toLowerCase().includes("error") && typeof value === "string") {
958
+ sanitized[key] = chunkWBX5YMTB_cjs.sanitizeErrorMessage(value);
959
+ continue;
960
+ }
961
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
962
+ sanitized[key] = value;
963
+ }
964
+ }
965
+ return sanitized;
966
+ }
967
+ /**
968
+ * Get SonicJS version
969
+ */
970
+ getVersion() {
971
+ try {
972
+ return process.env.SONICJS_VERSION || "2.0.0";
973
+ } catch {
974
+ return "unknown";
975
+ }
976
+ }
977
+ /**
978
+ * Shutdown the telemetry service
979
+ */
980
+ async shutdown() {
981
+ try {
982
+ if (this.client) {
983
+ await this.client.shutdown();
984
+ }
985
+ } catch (error) {
986
+ if (this.config.debug) {
987
+ console.error("[Telemetry] Shutdown failed:", error);
988
+ }
989
+ }
990
+ }
991
+ /**
992
+ * Enable telemetry
993
+ */
994
+ enable() {
995
+ this.enabled = true;
996
+ }
997
+ /**
998
+ * Disable telemetry
999
+ */
1000
+ disable() {
1001
+ this.enabled = false;
1002
+ }
1003
+ /**
1004
+ * Check if telemetry is enabled
1005
+ */
1006
+ isEnabled() {
1007
+ return this.enabled;
1008
+ }
1009
+ };
1010
+ var telemetryInstance = null;
1011
+ function getTelemetryService(config) {
1012
+ if (!telemetryInstance) {
1013
+ telemetryInstance = new TelemetryService(config);
1014
+ }
1015
+ return telemetryInstance;
1016
+ }
1017
+ async function initTelemetry(identity, config) {
1018
+ const service = getTelemetryService(config);
1019
+ await service.initialize(identity);
1020
+ return service;
1021
+ }
1022
+ function createInstallationIdentity(projectName) {
1023
+ const installationId = chunkWBX5YMTB_cjs.generateInstallationId();
1024
+ const identity = { installationId };
1025
+ if (projectName) {
1026
+ identity.projectId = chunkWBX5YMTB_cjs.generateProjectId(projectName);
1027
+ }
1028
+ return identity;
1029
+ }
1030
+
1031
+ exports.PluginBootstrapService = PluginBootstrapService;
1032
+ exports.PluginService = PluginService;
1033
+ exports.TelemetryService = TelemetryService;
1034
+ exports.cleanupRemovedCollections = cleanupRemovedCollections;
1035
+ exports.createInstallationIdentity = createInstallationIdentity;
1036
+ exports.fullCollectionSync = fullCollectionSync;
1037
+ exports.getAvailableCollectionNames = getAvailableCollectionNames;
1038
+ exports.getManagedCollections = getManagedCollections;
1039
+ exports.getTelemetryService = getTelemetryService;
1040
+ exports.initTelemetry = initTelemetry;
1041
+ exports.isCollectionManaged = isCollectionManaged;
1042
+ exports.loadCollectionConfig = loadCollectionConfig;
1043
+ exports.loadCollectionConfigs = loadCollectionConfigs;
1044
+ exports.registerCollections = registerCollections;
1045
+ exports.syncCollection = syncCollection;
1046
+ exports.syncCollections = syncCollections;
1047
+ exports.validateCollectionConfig = validateCollectionConfig;
1048
+ //# sourceMappingURL=chunk-HV2I6API.cjs.map
1049
+ //# sourceMappingURL=chunk-HV2I6API.cjs.map