@sonicjs-cms/core 1.0.0-alpha.1 → 1.0.0-alpha.3

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 (79) hide show
  1. package/dist/chunk-24PWAFUT.cjs +776 -0
  2. package/dist/chunk-24PWAFUT.cjs.map +1 -0
  3. package/dist/chunk-4URGXJP7.js +3 -0
  4. package/dist/{chunk-PZ5AY32C.js.map → chunk-4URGXJP7.js.map} +1 -1
  5. package/dist/chunk-ALTMI5Y2.cjs +4 -0
  6. package/dist/{chunk-Q7SFCCGT.cjs.map → chunk-ALTMI5Y2.cjs.map} +1 -1
  7. package/dist/chunk-BOLQHE4J.cjs +11 -0
  8. package/dist/chunk-BOLQHE4J.cjs.map +1 -0
  9. package/dist/chunk-BRC3F4CG.cjs +792 -0
  10. package/dist/chunk-BRC3F4CG.cjs.map +1 -0
  11. package/dist/chunk-CXZDAR6S.js +2360 -0
  12. package/dist/chunk-CXZDAR6S.js.map +1 -0
  13. package/dist/chunk-EMMSS5I5.cjs +37 -0
  14. package/dist/chunk-EMMSS5I5.cjs.map +1 -0
  15. package/dist/chunk-G3PMV62Z.js +33 -0
  16. package/dist/chunk-G3PMV62Z.js.map +1 -0
  17. package/dist/chunk-HD7R6T6I.js +9 -0
  18. package/dist/chunk-HD7R6T6I.js.map +1 -0
  19. package/dist/chunk-KRJMGD4E.js +783 -0
  20. package/dist/chunk-KRJMGD4E.js.map +1 -0
  21. package/dist/chunk-L3NXO7Y4.cjs +3093 -0
  22. package/dist/chunk-L3NXO7Y4.cjs.map +1 -0
  23. package/dist/chunk-NRSL6BQI.js +3086 -0
  24. package/dist/chunk-NRSL6BQI.js.map +1 -0
  25. package/dist/chunk-PTQZ5FEI.js +755 -0
  26. package/dist/chunk-PTQZ5FEI.js.map +1 -0
  27. package/dist/chunk-WJ7QYVR2.cjs +2416 -0
  28. package/dist/chunk-WJ7QYVR2.cjs.map +1 -0
  29. package/dist/collection-config-FLlGtsh9.d.cts +107 -0
  30. package/dist/collection-config-FLlGtsh9.d.ts +107 -0
  31. package/dist/index-BlsY5XNH.d.ts +8333 -0
  32. package/dist/index-D45jaIlr.d.cts +8333 -0
  33. package/dist/index.cjs +365 -630
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.cts +16 -7962
  36. package/dist/index.d.ts +16 -7962
  37. package/dist/index.js +10 -592
  38. package/dist/index.js.map +1 -1
  39. package/dist/middleware.cjs +84 -4
  40. package/dist/middleware.cjs.map +1 -1
  41. package/dist/middleware.d.cts +203 -5
  42. package/dist/middleware.d.ts +203 -5
  43. package/dist/middleware.js +3 -6
  44. package/dist/middleware.js.map +1 -1
  45. package/dist/plugin-UzmDImQc.d.cts +357 -0
  46. package/dist/plugin-UzmDImQc.d.ts +357 -0
  47. package/dist/plugins.cjs +28 -4
  48. package/dist/plugins.cjs.map +1 -1
  49. package/dist/plugins.d.cts +326 -4
  50. package/dist/plugins.d.ts +326 -4
  51. package/dist/plugins.js +3 -6
  52. package/dist/plugins.js.map +1 -1
  53. package/dist/routes.cjs +7 -4
  54. package/dist/routes.cjs.map +1 -1
  55. package/dist/routes.d.cts +12 -3
  56. package/dist/routes.d.ts +12 -3
  57. package/dist/routes.js +2 -6
  58. package/dist/routes.js.map +1 -1
  59. package/dist/services.cjs +68 -4
  60. package/dist/services.cjs.map +1 -1
  61. package/dist/services.d.cts +5 -8
  62. package/dist/services.d.ts +5 -8
  63. package/dist/services.js +3 -6
  64. package/dist/services.js.map +1 -1
  65. package/dist/templates.cjs +35 -4
  66. package/dist/templates.cjs.map +1 -1
  67. package/dist/templates.d.cts +137 -5
  68. package/dist/templates.d.ts +137 -5
  69. package/dist/templates.js +2 -6
  70. package/dist/templates.js.map +1 -1
  71. package/dist/types.cjs +1 -1
  72. package/dist/types.d.cts +6 -462
  73. package/dist/types.d.ts +6 -462
  74. package/dist/types.js +1 -1
  75. package/dist/utils.cjs +1 -1
  76. package/dist/utils.js +1 -1
  77. package/package.json +1 -1
  78. package/dist/chunk-PZ5AY32C.js +0 -9
  79. package/dist/chunk-Q7SFCCGT.cjs +0 -11
@@ -0,0 +1,2360 @@
1
+ import { __export } from './chunk-G3PMV62Z.js';
2
+ import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core';
3
+ import { z } from 'zod/v4';
4
+ import { getTableColumns, getViewSelectedFields, isTable, is, Column, SQL, isView, inArray, eq, like, gte, lte, and, count, asc, desc } from 'drizzle-orm';
5
+ import { drizzle } from 'drizzle-orm/d1';
6
+
7
+ // src/services/collection-loader.ts
8
+ async function loadCollectionConfigs() {
9
+ const collections2 = [];
10
+ try {
11
+ const modules = import.meta.glob?.("../collections/*.collection.ts", { eager: true }) || {};
12
+ for (const [path, module] of Object.entries(modules)) {
13
+ try {
14
+ const configModule = module;
15
+ if (!configModule.default) {
16
+ console.warn(`Collection file ${path} does not export a default config`);
17
+ continue;
18
+ }
19
+ const config = configModule.default;
20
+ if (!config.name || !config.displayName || !config.schema) {
21
+ console.error(`Invalid collection config in ${path}: missing required fields`);
22
+ continue;
23
+ }
24
+ const normalizedConfig = {
25
+ ...config,
26
+ managed: config.managed !== void 0 ? config.managed : true,
27
+ isActive: config.isActive !== void 0 ? config.isActive : true
28
+ };
29
+ collections2.push(normalizedConfig);
30
+ console.log(`\u2713 Loaded collection config: ${config.name}`);
31
+ } catch (error) {
32
+ console.error(`Error loading collection from ${path}:`, error);
33
+ }
34
+ }
35
+ console.log(`Loaded ${collections2.length} collection configuration(s)`);
36
+ return collections2;
37
+ } catch (error) {
38
+ console.error("Error loading collection configurations:", error);
39
+ return [];
40
+ }
41
+ }
42
+ async function loadCollectionConfig(name) {
43
+ try {
44
+ console.warn("loadCollectionConfig requires implementation in consuming application");
45
+ return null;
46
+ } catch (error) {
47
+ console.error(`Error loading collection ${name}:`, error);
48
+ return null;
49
+ }
50
+ }
51
+ async function getAvailableCollectionNames() {
52
+ try {
53
+ const modules = import.meta.glob?.("../collections/*.collection.ts") || {};
54
+ const names = [];
55
+ for (const path of Object.keys(modules)) {
56
+ const match = path.match(/\/([^/]+)\.collection\.ts$/);
57
+ if (match && match[1]) {
58
+ names.push(match[1]);
59
+ }
60
+ }
61
+ return names;
62
+ } catch (error) {
63
+ console.error("Error getting collection names:", error);
64
+ return [];
65
+ }
66
+ }
67
+ function validateCollectionConfig(config) {
68
+ const errors = [];
69
+ if (!config.name) {
70
+ errors.push("Collection name is required");
71
+ } else if (!/^[a-z0-9_]+$/.test(config.name)) {
72
+ errors.push("Collection name must contain only lowercase letters, numbers, and underscores");
73
+ }
74
+ if (!config.displayName) {
75
+ errors.push("Display name is required");
76
+ }
77
+ if (!config.schema) {
78
+ errors.push("Schema is required");
79
+ } else {
80
+ if (config.schema.type !== "object") {
81
+ errors.push('Schema type must be "object"');
82
+ }
83
+ if (!config.schema.properties || typeof config.schema.properties !== "object") {
84
+ errors.push("Schema must have properties");
85
+ }
86
+ for (const [fieldName, fieldConfig] of Object.entries(config.schema.properties || {})) {
87
+ if (!fieldConfig.type) {
88
+ errors.push(`Field "${fieldName}" is missing type`);
89
+ }
90
+ if (fieldConfig.type === "reference" && !fieldConfig.collection) {
91
+ errors.push(`Reference field "${fieldName}" is missing collection property`);
92
+ }
93
+ if (["select", "multiselect", "radio"].includes(fieldConfig.type) && !fieldConfig.enum) {
94
+ errors.push(`Select field "${fieldName}" is missing enum options`);
95
+ }
96
+ }
97
+ }
98
+ return {
99
+ valid: errors.length === 0,
100
+ errors
101
+ };
102
+ }
103
+
104
+ // src/services/collection-sync.ts
105
+ async function syncCollections(db) {
106
+ console.log("\u{1F504} Starting collection sync...");
107
+ const results = [];
108
+ const configs = await loadCollectionConfigs();
109
+ if (configs.length === 0) {
110
+ console.log("\u26A0\uFE0F No collection configurations found");
111
+ return results;
112
+ }
113
+ for (const config of configs) {
114
+ const result = await syncCollection(db, config);
115
+ results.push(result);
116
+ }
117
+ const created = results.filter((r) => r.status === "created").length;
118
+ const updated = results.filter((r) => r.status === "updated").length;
119
+ const unchanged = results.filter((r) => r.status === "unchanged").length;
120
+ const errors = results.filter((r) => r.status === "error").length;
121
+ console.log(`\u2705 Collection sync complete: ${created} created, ${updated} updated, ${unchanged} unchanged, ${errors} errors`);
122
+ return results;
123
+ }
124
+ async function syncCollection(db, config) {
125
+ try {
126
+ const validation = validateCollectionConfig(config);
127
+ if (!validation.valid) {
128
+ return {
129
+ name: config.name,
130
+ status: "error",
131
+ error: `Validation failed: ${validation.errors.join(", ")}`
132
+ };
133
+ }
134
+ const existingStmt = db.prepare("SELECT * FROM collections WHERE name = ?");
135
+ const existing = await existingStmt.bind(config.name).first();
136
+ const now = Date.now();
137
+ const collectionId = existing?.id || `col-${config.name}-${crypto.randomUUID().slice(0, 8)}`;
138
+ const schemaJson = JSON.stringify(config.schema);
139
+ const isActive = config.isActive !== false ? 1 : 0;
140
+ const managed = config.managed !== false ? 1 : 0;
141
+ if (!existing) {
142
+ const insertStmt = db.prepare(`
143
+ INSERT INTO collections (id, name, display_name, description, schema, is_active, managed, created_at, updated_at)
144
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
145
+ `);
146
+ await insertStmt.bind(
147
+ collectionId,
148
+ config.name,
149
+ config.displayName,
150
+ config.description || null,
151
+ schemaJson,
152
+ isActive,
153
+ managed,
154
+ now,
155
+ now
156
+ ).run();
157
+ console.log(` \u2713 Created collection: ${config.name}`);
158
+ return {
159
+ name: config.name,
160
+ status: "created",
161
+ message: `Created collection "${config.displayName}"`
162
+ };
163
+ } else {
164
+ const existingSchema = existing.schema ? JSON.stringify(existing.schema) : "{}";
165
+ const existingDisplayName = existing.display_name;
166
+ const existingDescription = existing.description;
167
+ const existingIsActive = existing.is_active;
168
+ const existingManaged = existing.managed;
169
+ const needsUpdate = schemaJson !== existingSchema || config.displayName !== existingDisplayName || (config.description || null) !== existingDescription || isActive !== existingIsActive || managed !== existingManaged;
170
+ if (!needsUpdate) {
171
+ return {
172
+ name: config.name,
173
+ status: "unchanged",
174
+ message: `Collection "${config.displayName}" is up to date`
175
+ };
176
+ }
177
+ const updateStmt = db.prepare(`
178
+ UPDATE collections
179
+ SET display_name = ?, description = ?, schema = ?, is_active = ?, managed = ?, updated_at = ?
180
+ WHERE name = ?
181
+ `);
182
+ await updateStmt.bind(
183
+ config.displayName,
184
+ config.description || null,
185
+ schemaJson,
186
+ isActive,
187
+ managed,
188
+ now,
189
+ config.name
190
+ ).run();
191
+ console.log(` \u2713 Updated collection: ${config.name}`);
192
+ return {
193
+ name: config.name,
194
+ status: "updated",
195
+ message: `Updated collection "${config.displayName}"`
196
+ };
197
+ }
198
+ } catch (error) {
199
+ console.error(` \u2717 Error syncing collection ${config.name}:`, error);
200
+ return {
201
+ name: config.name,
202
+ status: "error",
203
+ error: error instanceof Error ? error.message : "Unknown error"
204
+ };
205
+ }
206
+ }
207
+ async function isCollectionManaged(db, collectionName) {
208
+ try {
209
+ const stmt = db.prepare("SELECT managed FROM collections WHERE name = ?");
210
+ const result = await stmt.bind(collectionName).first();
211
+ return result?.managed === 1;
212
+ } catch (error) {
213
+ console.error(`Error checking if collection is managed:`, error);
214
+ return false;
215
+ }
216
+ }
217
+ async function getManagedCollections(db) {
218
+ try {
219
+ const stmt = db.prepare("SELECT name FROM collections WHERE managed = 1");
220
+ const { results } = await stmt.all();
221
+ return (results || []).map((row) => row.name);
222
+ } catch (error) {
223
+ console.error("Error getting managed collections:", error);
224
+ return [];
225
+ }
226
+ }
227
+ async function cleanupRemovedCollections(db) {
228
+ try {
229
+ const configs = await loadCollectionConfigs();
230
+ const configNames = new Set(configs.map((c) => c.name));
231
+ const managedCollections = await getManagedCollections(db);
232
+ const removed = [];
233
+ for (const managedName of managedCollections) {
234
+ if (!configNames.has(managedName)) {
235
+ const updateStmt = db.prepare(`
236
+ UPDATE collections
237
+ SET is_active = 0, updated_at = ?
238
+ WHERE name = ? AND managed = 1
239
+ `);
240
+ await updateStmt.bind(Date.now(), managedName).run();
241
+ removed.push(managedName);
242
+ console.log(` \u26A0\uFE0F Deactivated removed collection: ${managedName}`);
243
+ }
244
+ }
245
+ return removed;
246
+ } catch (error) {
247
+ console.error("Error cleaning up removed collections:", error);
248
+ return [];
249
+ }
250
+ }
251
+ async function fullCollectionSync(db) {
252
+ const results = await syncCollections(db);
253
+ const removed = await cleanupRemovedCollections(db);
254
+ return { results, removed };
255
+ }
256
+
257
+ // src/services/migrations.ts
258
+ var MigrationService = class {
259
+ constructor(db) {
260
+ this.db = db;
261
+ }
262
+ /**
263
+ * Initialize the migrations tracking table
264
+ */
265
+ async initializeMigrationsTable() {
266
+ const createTableQuery = `
267
+ CREATE TABLE IF NOT EXISTS migrations (
268
+ id TEXT PRIMARY KEY,
269
+ name TEXT NOT NULL,
270
+ filename TEXT NOT NULL,
271
+ applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
272
+ checksum TEXT
273
+ )
274
+ `;
275
+ await this.db.prepare(createTableQuery).run();
276
+ }
277
+ /**
278
+ * Get all available migrations from the migrations directory
279
+ */
280
+ async getAvailableMigrations() {
281
+ const migrations = [];
282
+ const migrationFiles = [
283
+ { id: "001", name: "Initial Schema", filename: "001_initial_schema.sql", description: "Initial database schema with users, content, collections, and media tables" },
284
+ { id: "002", name: "FAQ Plugin", filename: "002_faq_plugin.sql", description: "FAQ plugin tables and initial data" },
285
+ { id: "003", name: "Stage 5 Enhancements", filename: "003_stage5_enhancements.sql", description: "Enhanced content management and media handling" },
286
+ { id: "004", name: "User Management", filename: "004_stage6_user_management.sql", description: "Advanced user management with roles and permissions" },
287
+ { id: "005", name: "Workflow & Automation", filename: "005_stage7_workflow_automation.sql", description: "Workflow states, automation rules, and scheduled content" },
288
+ { id: "006", name: "Plugin System", filename: "006_plugin_system.sql", description: "Plugin registration and configuration system" }
289
+ ];
290
+ const appliedResult = await this.db.prepare(
291
+ "SELECT id, name, filename, applied_at FROM migrations ORDER BY applied_at ASC"
292
+ ).all();
293
+ const appliedMigrations = new Map(
294
+ appliedResult.results?.map((row) => [row.id, row]) || []
295
+ );
296
+ await this.autoDetectAppliedMigrations(appliedMigrations);
297
+ for (const file of migrationFiles) {
298
+ const applied = appliedMigrations.has(file.id);
299
+ const appliedData = appliedMigrations.get(file.id);
300
+ migrations.push({
301
+ id: file.id,
302
+ name: file.name,
303
+ filename: file.filename,
304
+ description: file.description,
305
+ applied,
306
+ appliedAt: applied ? appliedData?.applied_at : void 0,
307
+ size: await this.getMigrationFileSize(file.filename)
308
+ });
309
+ }
310
+ return migrations;
311
+ }
312
+ /**
313
+ * Auto-detect applied migrations by checking if their tables exist
314
+ */
315
+ async autoDetectAppliedMigrations(appliedMigrations) {
316
+ if (!appliedMigrations.has("001")) {
317
+ const hasBasicTables = await this.checkTablesExist(["users", "content", "collections", "media"]);
318
+ if (hasBasicTables) {
319
+ appliedMigrations.set("001", {
320
+ id: "001",
321
+ applied_at: (/* @__PURE__ */ new Date()).toISOString(),
322
+ name: "Initial Schema",
323
+ filename: "001_initial_schema.sql"
324
+ });
325
+ await this.markMigrationApplied("001", "Initial Schema", "001_initial_schema.sql");
326
+ }
327
+ }
328
+ if (!appliedMigrations.has("002")) {
329
+ const hasFaqTables = await this.checkTablesExist(["faqs", "faq_categories"]);
330
+ if (hasFaqTables) {
331
+ appliedMigrations.set("002", {
332
+ id: "002",
333
+ applied_at: (/* @__PURE__ */ new Date()).toISOString(),
334
+ name: "FAQ Plugin",
335
+ filename: "002_faq_plugin.sql"
336
+ });
337
+ await this.markMigrationApplied("002", "FAQ Plugin", "002_faq_plugin.sql");
338
+ }
339
+ }
340
+ if (!appliedMigrations.has("003")) {
341
+ const hasEnhancedTables = await this.checkTablesExist(["content_versions", "email_themes", "email_templates"]);
342
+ if (hasEnhancedTables) {
343
+ appliedMigrations.set("003", {
344
+ id: "003",
345
+ applied_at: (/* @__PURE__ */ new Date()).toISOString(),
346
+ name: "Stage 5 Enhancements",
347
+ filename: "003_stage5_enhancements.sql"
348
+ });
349
+ await this.markMigrationApplied("003", "Stage 5 Enhancements", "003_stage5_enhancements.sql");
350
+ }
351
+ }
352
+ if (!appliedMigrations.has("004")) {
353
+ const hasUserTables = await this.checkTablesExist(["api_tokens", "workflow_history"]);
354
+ if (hasUserTables) {
355
+ appliedMigrations.set("004", {
356
+ id: "004",
357
+ applied_at: (/* @__PURE__ */ new Date()).toISOString(),
358
+ name: "User Management",
359
+ filename: "004_stage6_user_management.sql"
360
+ });
361
+ await this.markMigrationApplied("004", "User Management", "004_stage6_user_management.sql");
362
+ }
363
+ }
364
+ if (!appliedMigrations.has("006")) {
365
+ const hasPluginTables = await this.checkTablesExist(["plugins", "plugin_hooks"]);
366
+ if (hasPluginTables) {
367
+ appliedMigrations.set("006", {
368
+ id: "006",
369
+ applied_at: (/* @__PURE__ */ new Date()).toISOString(),
370
+ name: "Plugin System",
371
+ filename: "006_plugin_system.sql"
372
+ });
373
+ await this.markMigrationApplied("006", "Plugin System", "006_plugin_system.sql");
374
+ }
375
+ }
376
+ }
377
+ /**
378
+ * Check if specific tables exist in the database
379
+ */
380
+ async checkTablesExist(tableNames) {
381
+ try {
382
+ for (const tableName of tableNames) {
383
+ const result = await this.db.prepare(
384
+ `SELECT name FROM sqlite_master WHERE type='table' AND name=?`
385
+ ).bind(tableName).first();
386
+ if (!result) {
387
+ return false;
388
+ }
389
+ }
390
+ return true;
391
+ } catch (error) {
392
+ return false;
393
+ }
394
+ }
395
+ /**
396
+ * Get migration status summary
397
+ */
398
+ async getMigrationStatus() {
399
+ await this.initializeMigrationsTable();
400
+ const migrations = await this.getAvailableMigrations();
401
+ const appliedMigrations = migrations.filter((m) => m.applied);
402
+ const pendingMigrations = migrations.filter((m) => !m.applied);
403
+ const lastApplied = appliedMigrations.length > 0 ? appliedMigrations[appliedMigrations.length - 1]?.appliedAt : void 0;
404
+ return {
405
+ totalMigrations: migrations.length,
406
+ appliedMigrations: appliedMigrations.length,
407
+ pendingMigrations: pendingMigrations.length,
408
+ lastApplied,
409
+ migrations
410
+ };
411
+ }
412
+ /**
413
+ * Mark a migration as applied
414
+ */
415
+ async markMigrationApplied(migrationId, name, filename) {
416
+ await this.initializeMigrationsTable();
417
+ await this.db.prepare(
418
+ "INSERT OR REPLACE INTO migrations (id, name, filename, applied_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)"
419
+ ).bind(migrationId, name, filename).run();
420
+ }
421
+ /**
422
+ * Check if a specific migration has been applied
423
+ */
424
+ async isMigrationApplied(migrationId) {
425
+ await this.initializeMigrationsTable();
426
+ const result = await this.db.prepare(
427
+ "SELECT COUNT(*) as count FROM migrations WHERE id = ?"
428
+ ).bind(migrationId).first();
429
+ return result?.count > 0;
430
+ }
431
+ /**
432
+ * Get the last applied migration
433
+ */
434
+ async getLastAppliedMigration() {
435
+ await this.initializeMigrationsTable();
436
+ const result = await this.db.prepare(
437
+ "SELECT id, name, filename, applied_at FROM migrations ORDER BY applied_at DESC LIMIT 1"
438
+ ).first();
439
+ if (!result) return null;
440
+ return {
441
+ id: result.id,
442
+ name: result.name,
443
+ filename: result.filename,
444
+ applied: true,
445
+ appliedAt: result.applied_at
446
+ };
447
+ }
448
+ /**
449
+ * Get migration file size (simulated)
450
+ */
451
+ async getMigrationFileSize(filename) {
452
+ const sizesMap = {
453
+ "001_initial_schema.sql": 15420,
454
+ "002_faq_plugin.sql": 2340,
455
+ "003_stage5_enhancements.sql": 8920,
456
+ "004_stage6_user_management.sql": 12680,
457
+ "005_stage7_workflow_automation.sql": 18750,
458
+ "006_plugin_system.sql": 5430
459
+ };
460
+ return sizesMap[filename] || 1e3;
461
+ }
462
+ /**
463
+ * Run pending migrations
464
+ */
465
+ async runPendingMigrations() {
466
+ const status = await this.getMigrationStatus();
467
+ const pendingMigrations = status.migrations.filter((m) => !m.applied);
468
+ if (pendingMigrations.length === 0) {
469
+ return {
470
+ success: true,
471
+ message: "All migrations are up to date",
472
+ applied: []
473
+ };
474
+ }
475
+ const applied = [];
476
+ for (const migration of pendingMigrations) {
477
+ try {
478
+ await this.applyMigration(migration);
479
+ await this.markMigrationApplied(migration.id, migration.name, migration.filename);
480
+ applied.push(migration.id);
481
+ } catch (error) {
482
+ console.error(`Failed to apply migration ${migration.id}:`, error);
483
+ break;
484
+ }
485
+ }
486
+ return {
487
+ success: true,
488
+ message: `Applied ${applied.length} migration(s)`,
489
+ applied
490
+ };
491
+ }
492
+ /**
493
+ * Apply a specific migration
494
+ */
495
+ async applyMigration(migration) {
496
+ console.log(`Applying migration ${migration.id}: ${migration.name}`);
497
+ const migrationSQL = await this.getMigrationSQL(migration.id);
498
+ if (migrationSQL === null) {
499
+ throw new Error(`Migration SQL not found for ${migration.id}`);
500
+ }
501
+ if (migrationSQL === "") {
502
+ console.log(`Skipping migration ${migration.id} (empty/obsolete)`);
503
+ return;
504
+ }
505
+ const statements = this.splitSQLStatements(migrationSQL);
506
+ for (const statement of statements) {
507
+ if (statement.trim()) {
508
+ try {
509
+ await this.db.prepare(statement).run();
510
+ } catch (error) {
511
+ console.error(`Error executing statement: ${statement}`, error);
512
+ throw error;
513
+ }
514
+ }
515
+ }
516
+ }
517
+ /**
518
+ * Split SQL into statements, handling CREATE TRIGGER properly
519
+ */
520
+ splitSQLStatements(sql) {
521
+ const statements = [];
522
+ let current = "";
523
+ let inTrigger = false;
524
+ const lines = sql.split("\n");
525
+ for (const line of lines) {
526
+ const trimmed = line.trim();
527
+ if (trimmed.startsWith("--") || trimmed.length === 0) {
528
+ continue;
529
+ }
530
+ if (trimmed.toUpperCase().includes("CREATE TRIGGER")) {
531
+ inTrigger = true;
532
+ }
533
+ current += line + "\n";
534
+ if (inTrigger && trimmed.toUpperCase() === "END;") {
535
+ statements.push(current.trim());
536
+ current = "";
537
+ inTrigger = false;
538
+ } else if (!inTrigger && trimmed.endsWith(";")) {
539
+ statements.push(current.trim());
540
+ current = "";
541
+ }
542
+ }
543
+ if (current.trim()) {
544
+ statements.push(current.trim());
545
+ }
546
+ return statements.filter((s) => s.length > 0);
547
+ }
548
+ /**
549
+ * Get migration SQL by ID
550
+ */
551
+ async getMigrationSQL(migrationId) {
552
+ switch (migrationId) {
553
+ case "001":
554
+ return `
555
+ -- Initial schema for SonicJS AI
556
+ -- Create users table for authentication
557
+ CREATE TABLE IF NOT EXISTS users (
558
+ id TEXT PRIMARY KEY,
559
+ email TEXT NOT NULL UNIQUE,
560
+ username TEXT NOT NULL UNIQUE,
561
+ first_name TEXT NOT NULL,
562
+ last_name TEXT NOT NULL,
563
+ password_hash TEXT,
564
+ role TEXT NOT NULL DEFAULT 'viewer',
565
+ avatar TEXT,
566
+ is_active INTEGER NOT NULL DEFAULT 1,
567
+ last_login_at INTEGER,
568
+ created_at INTEGER NOT NULL,
569
+ updated_at INTEGER NOT NULL
570
+ );
571
+
572
+ -- Create collections table for content schema definitions
573
+ CREATE TABLE IF NOT EXISTS collections (
574
+ id TEXT PRIMARY KEY,
575
+ name TEXT NOT NULL UNIQUE,
576
+ display_name TEXT NOT NULL,
577
+ description TEXT,
578
+ schema TEXT NOT NULL,
579
+ is_active INTEGER NOT NULL DEFAULT 1,
580
+ created_at INTEGER NOT NULL,
581
+ updated_at INTEGER NOT NULL
582
+ );
583
+
584
+ -- Create content table for actual content data
585
+ CREATE TABLE IF NOT EXISTS content (
586
+ id TEXT PRIMARY KEY,
587
+ collection_id TEXT NOT NULL REFERENCES collections(id),
588
+ slug TEXT NOT NULL,
589
+ title TEXT NOT NULL,
590
+ data TEXT NOT NULL,
591
+ status TEXT NOT NULL DEFAULT 'draft',
592
+ published_at INTEGER,
593
+ author_id TEXT NOT NULL REFERENCES users(id),
594
+ created_by TEXT NOT NULL REFERENCES users(id),
595
+ created_at INTEGER NOT NULL,
596
+ updated_at INTEGER NOT NULL
597
+ );
598
+
599
+ -- Create content_versions table for versioning
600
+ CREATE TABLE IF NOT EXISTS content_versions (
601
+ id TEXT PRIMARY KEY,
602
+ content_id TEXT NOT NULL REFERENCES content(id),
603
+ version INTEGER NOT NULL,
604
+ data TEXT NOT NULL,
605
+ author_id TEXT NOT NULL REFERENCES users(id),
606
+ created_at INTEGER NOT NULL
607
+ );
608
+
609
+ -- Create media/files table with comprehensive R2 integration
610
+ CREATE TABLE IF NOT EXISTS media (
611
+ id TEXT PRIMARY KEY,
612
+ filename TEXT NOT NULL,
613
+ original_name TEXT NOT NULL,
614
+ mime_type TEXT NOT NULL,
615
+ size INTEGER NOT NULL,
616
+ width INTEGER,
617
+ height INTEGER,
618
+ folder TEXT NOT NULL DEFAULT 'uploads',
619
+ r2_key TEXT NOT NULL,
620
+ public_url TEXT NOT NULL,
621
+ thumbnail_url TEXT,
622
+ alt TEXT,
623
+ caption TEXT,
624
+ tags TEXT,
625
+ uploaded_by TEXT NOT NULL REFERENCES users(id),
626
+ uploaded_at INTEGER NOT NULL,
627
+ updated_at INTEGER,
628
+ published_at INTEGER,
629
+ scheduled_at INTEGER,
630
+ archived_at INTEGER,
631
+ deleted_at INTEGER
632
+ );
633
+
634
+ -- Create API tokens table for programmatic access
635
+ CREATE TABLE IF NOT EXISTS api_tokens (
636
+ id TEXT PRIMARY KEY,
637
+ name TEXT NOT NULL,
638
+ token TEXT NOT NULL UNIQUE,
639
+ user_id TEXT NOT NULL REFERENCES users(id),
640
+ permissions TEXT NOT NULL,
641
+ expires_at INTEGER,
642
+ last_used_at INTEGER,
643
+ created_at INTEGER NOT NULL
644
+ );
645
+
646
+ -- Create workflow history table for content workflow tracking
647
+ CREATE TABLE IF NOT EXISTS workflow_history (
648
+ id TEXT PRIMARY KEY,
649
+ content_id TEXT NOT NULL REFERENCES content(id),
650
+ action TEXT NOT NULL,
651
+ from_status TEXT NOT NULL,
652
+ to_status TEXT NOT NULL,
653
+ user_id TEXT NOT NULL REFERENCES users(id),
654
+ comment TEXT,
655
+ created_at INTEGER NOT NULL
656
+ );
657
+
658
+ -- Create indexes for better performance
659
+ CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
660
+ CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
661
+ CREATE INDEX IF NOT EXISTS idx_users_role ON users(role);
662
+
663
+ CREATE INDEX IF NOT EXISTS idx_collections_name ON collections(name);
664
+ CREATE INDEX IF NOT EXISTS idx_collections_active ON collections(is_active);
665
+
666
+ CREATE INDEX IF NOT EXISTS idx_content_collection ON content(collection_id);
667
+ CREATE INDEX IF NOT EXISTS idx_content_author ON content(author_id);
668
+ CREATE INDEX IF NOT EXISTS idx_content_status ON content(status);
669
+ CREATE INDEX IF NOT EXISTS idx_content_published ON content(published_at);
670
+ CREATE INDEX IF NOT EXISTS idx_content_slug ON content(slug);
671
+
672
+ CREATE INDEX IF NOT EXISTS idx_content_versions_content ON content_versions(content_id);
673
+ CREATE INDEX IF NOT EXISTS idx_content_versions_version ON content_versions(version);
674
+
675
+ CREATE INDEX IF NOT EXISTS idx_media_folder ON media(folder);
676
+ CREATE INDEX IF NOT EXISTS idx_media_type ON media(mime_type);
677
+ CREATE INDEX IF NOT EXISTS idx_media_uploaded_by ON media(uploaded_by);
678
+ CREATE INDEX IF NOT EXISTS idx_media_uploaded_at ON media(uploaded_at);
679
+ CREATE INDEX IF NOT EXISTS idx_media_deleted ON media(deleted_at);
680
+
681
+ CREATE INDEX IF NOT EXISTS idx_api_tokens_user ON api_tokens(user_id);
682
+ CREATE INDEX IF NOT EXISTS idx_api_tokens_token ON api_tokens(token);
683
+
684
+ CREATE INDEX IF NOT EXISTS idx_workflow_history_content ON workflow_history(content_id);
685
+ CREATE INDEX IF NOT EXISTS idx_workflow_history_user ON workflow_history(user_id);
686
+
687
+ -- Insert default admin user (password: admin123)
688
+ INSERT OR IGNORE INTO users (
689
+ id, email, username, first_name, last_name, password_hash,
690
+ role, is_active, created_at, updated_at
691
+ ) VALUES (
692
+ 'admin-user-id',
693
+ 'admin@sonicjs.com',
694
+ 'admin',
695
+ 'Admin',
696
+ 'User',
697
+ 'd1c379e871838f44e21d5a55841349e50636f06df139bfef11870eec74c381db',
698
+ 'admin',
699
+ 1,
700
+ strftime('%s', 'now') * 1000,
701
+ strftime('%s', 'now') * 1000
702
+ );
703
+
704
+ -- Insert sample collections
705
+ INSERT OR IGNORE INTO collections (
706
+ id, name, display_name, description, schema,
707
+ is_active, created_at, updated_at
708
+ ) VALUES (
709
+ 'blog-posts-collection',
710
+ 'blog_posts',
711
+ 'Blog Posts',
712
+ 'Blog post content collection',
713
+ '{"type":"object","properties":{"title":{"type":"string","title":"Title","required":true},"content":{"type":"string","title":"Content","format":"richtext"},"excerpt":{"type":"string","title":"Excerpt"},"featured_image":{"type":"string","title":"Featured Image","format":"media"},"tags":{"type":"array","title":"Tags","items":{"type":"string"}},"status":{"type":"string","title":"Status","enum":["draft","published","archived"],"default":"draft"}},"required":["title"]}',
714
+ 1,
715
+ strftime('%s', 'now') * 1000,
716
+ strftime('%s', 'now') * 1000
717
+ ),
718
+ (
719
+ 'pages-collection',
720
+ 'pages',
721
+ 'Pages',
722
+ 'Static page content collection',
723
+ '{"type":"object","properties":{"title":{"type":"string","title":"Title","required":true},"content":{"type":"string","title":"Content","format":"richtext"},"slug":{"type":"string","title":"Slug"},"meta_description":{"type":"string","title":"Meta Description"},"featured_image":{"type":"string","title":"Featured Image","format":"media"}},"required":["title"]}',
724
+ 1,
725
+ strftime('%s', 'now') * 1000,
726
+ strftime('%s', 'now') * 1000
727
+ ),
728
+ (
729
+ 'news-collection',
730
+ 'news',
731
+ 'News',
732
+ 'News article content collection',
733
+ '{"type":"object","properties":{"title":{"type":"string","title":"Title","required":true},"content":{"type":"string","title":"Content","format":"richtext"},"publish_date":{"type":"string","title":"Publish Date","format":"date"},"author":{"type":"string","title":"Author"},"category":{"type":"string","title":"Category","enum":["technology","business","general"]}},"required":["title"]}',
734
+ 1,
735
+ strftime('%s', 'now') * 1000,
736
+ strftime('%s', 'now') * 1000
737
+ );
738
+
739
+ -- Insert sample content
740
+ INSERT OR IGNORE INTO content (
741
+ id, collection_id, slug, title, data, status,
742
+ author_id, created_by, created_at, updated_at
743
+ ) VALUES (
744
+ 'welcome-blog-post',
745
+ 'blog-posts-collection',
746
+ 'welcome-to-sonicjs-ai',
747
+ 'Welcome to SonicJS AI',
748
+ '{"title":"Welcome to SonicJS AI","content":"<h1>Welcome to SonicJS AI</h1><p>This is your first blog post created with SonicJS AI, a modern headless CMS built on Cloudflare Workers.</p><h2>Features</h2><ul><li>Cloudflare-native architecture</li><li>TypeScript-first development</li><li>Hono.js framework</li><li>D1 database</li><li>R2 media storage</li><li>Edge computing</li></ul><p>Get started by exploring the admin interface and creating your own content!</p>","excerpt":"Welcome to SonicJS AI, a modern headless CMS built on Cloudflare Workers with TypeScript and Hono.js.","status":"published","tags":["welcome","cms","cloudflare"]}',
749
+ 'published',
750
+ 'admin-user-id',
751
+ 'admin-user-id',
752
+ strftime('%s', 'now') * 1000,
753
+ strftime('%s', 'now') * 1000
754
+ );
755
+ `;
756
+ case "002":
757
+ return `
758
+ CREATE TABLE IF NOT EXISTS faqs (
759
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
760
+ question TEXT NOT NULL,
761
+ answer TEXT NOT NULL,
762
+ category TEXT,
763
+ tags TEXT,
764
+ isPublished INTEGER NOT NULL DEFAULT 1,
765
+ sortOrder INTEGER NOT NULL DEFAULT 0,
766
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
767
+ updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
768
+ );
769
+
770
+ CREATE INDEX IF NOT EXISTS idx_faqs_category ON faqs(category);
771
+ CREATE INDEX IF NOT EXISTS idx_faqs_published ON faqs(isPublished);
772
+ CREATE INDEX IF NOT EXISTS idx_faqs_sort_order ON faqs(sortOrder);
773
+
774
+ CREATE TRIGGER IF NOT EXISTS faqs_updated_at
775
+ AFTER UPDATE ON faqs
776
+ BEGIN
777
+ UPDATE faqs SET updated_at = strftime('%s', 'now') WHERE id = NEW.id;
778
+ END;
779
+ `;
780
+ case "006":
781
+ return `
782
+ -- Plugin System Tables
783
+ CREATE TABLE IF NOT EXISTS plugins (
784
+ id TEXT PRIMARY KEY,
785
+ name TEXT NOT NULL UNIQUE,
786
+ display_name TEXT NOT NULL,
787
+ description TEXT,
788
+ version TEXT NOT NULL,
789
+ author TEXT NOT NULL,
790
+ category TEXT NOT NULL,
791
+ icon TEXT,
792
+ status TEXT DEFAULT 'inactive' CHECK (status IN ('active', 'inactive', 'error')),
793
+ is_core BOOLEAN DEFAULT FALSE,
794
+ settings JSON,
795
+ permissions JSON,
796
+ dependencies JSON,
797
+ download_count INTEGER DEFAULT 0,
798
+ rating REAL DEFAULT 0,
799
+ installed_at INTEGER NOT NULL,
800
+ activated_at INTEGER,
801
+ last_updated INTEGER NOT NULL,
802
+ error_message TEXT,
803
+ created_at INTEGER DEFAULT (unixepoch()),
804
+ updated_at INTEGER DEFAULT (unixepoch())
805
+ );
806
+
807
+ CREATE TABLE IF NOT EXISTS plugin_hooks (
808
+ id TEXT PRIMARY KEY,
809
+ plugin_id TEXT NOT NULL,
810
+ hook_name TEXT NOT NULL,
811
+ handler_name TEXT NOT NULL,
812
+ priority INTEGER DEFAULT 10,
813
+ is_active BOOLEAN DEFAULT TRUE,
814
+ created_at INTEGER DEFAULT (unixepoch()),
815
+ FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE,
816
+ UNIQUE(plugin_id, hook_name, handler_name)
817
+ );
818
+
819
+ CREATE TABLE IF NOT EXISTS plugin_routes (
820
+ id TEXT PRIMARY KEY,
821
+ plugin_id TEXT NOT NULL,
822
+ path TEXT NOT NULL,
823
+ method TEXT NOT NULL,
824
+ handler_name TEXT NOT NULL,
825
+ middleware JSON,
826
+ is_active BOOLEAN DEFAULT TRUE,
827
+ created_at INTEGER DEFAULT (unixepoch()),
828
+ FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE,
829
+ UNIQUE(plugin_id, path, method)
830
+ );
831
+
832
+ CREATE TABLE IF NOT EXISTS plugin_assets (
833
+ id TEXT PRIMARY KEY,
834
+ plugin_id TEXT NOT NULL,
835
+ asset_type TEXT NOT NULL CHECK (asset_type IN ('css', 'js', 'image', 'font')),
836
+ asset_path TEXT NOT NULL,
837
+ load_order INTEGER DEFAULT 100,
838
+ load_location TEXT DEFAULT 'footer' CHECK (load_location IN ('header', 'footer')),
839
+ is_active BOOLEAN DEFAULT TRUE,
840
+ created_at INTEGER DEFAULT (unixepoch()),
841
+ FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE
842
+ );
843
+
844
+ CREATE TABLE IF NOT EXISTS plugin_activity_log (
845
+ id TEXT PRIMARY KEY,
846
+ plugin_id TEXT NOT NULL,
847
+ action TEXT NOT NULL,
848
+ user_id TEXT,
849
+ details JSON,
850
+ timestamp INTEGER DEFAULT (unixepoch()),
851
+ FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE
852
+ );
853
+
854
+ -- Create indexes
855
+ CREATE INDEX IF NOT EXISTS idx_plugins_status ON plugins(status);
856
+ CREATE INDEX IF NOT EXISTS idx_plugins_category ON plugins(category);
857
+ CREATE INDEX IF NOT EXISTS idx_plugin_hooks_plugin ON plugin_hooks(plugin_id);
858
+ CREATE INDEX IF NOT EXISTS idx_plugin_routes_plugin ON plugin_routes(plugin_id);
859
+ CREATE INDEX IF NOT EXISTS idx_plugin_assets_plugin ON plugin_assets(plugin_id);
860
+ CREATE INDEX IF NOT EXISTS idx_plugin_activity_plugin ON plugin_activity_log(plugin_id);
861
+ CREATE INDEX IF NOT EXISTS idx_plugin_activity_timestamp ON plugin_activity_log(timestamp);
862
+
863
+ -- Insert core plugins
864
+ INSERT OR IGNORE INTO plugins (
865
+ id, name, display_name, description, version, author, category, icon,
866
+ status, is_core, permissions, installed_at, last_updated
867
+ ) VALUES
868
+ (
869
+ 'core-auth',
870
+ 'core-auth',
871
+ 'Authentication System',
872
+ 'Core authentication and user management system',
873
+ '1.0.0',
874
+ 'SonicJS Team',
875
+ 'security',
876
+ '\u{1F510}',
877
+ 'active',
878
+ TRUE,
879
+ '["manage:users", "manage:roles", "manage:permissions"]',
880
+ unixepoch(),
881
+ unixepoch()
882
+ ),
883
+ (
884
+ 'core-media',
885
+ 'core-media',
886
+ 'Media Manager',
887
+ 'Core media upload and management system',
888
+ '1.0.0',
889
+ 'SonicJS Team',
890
+ 'media',
891
+ '\u{1F4F8}',
892
+ 'active',
893
+ TRUE,
894
+ '["manage:media", "upload:files"]',
895
+ unixepoch(),
896
+ unixepoch()
897
+ ),
898
+ (
899
+ 'core-workflow',
900
+ 'core-workflow',
901
+ 'Workflow Engine',
902
+ 'Content workflow and approval system',
903
+ '1.0.0',
904
+ 'SonicJS Team',
905
+ 'content',
906
+ '\u{1F504}',
907
+ 'active',
908
+ TRUE,
909
+ '["manage:workflows", "approve:content"]',
910
+ unixepoch(),
911
+ unixepoch()
912
+ ),
913
+ (
914
+ 'cache',
915
+ 'cache',
916
+ 'Cache System',
917
+ 'Three-tiered caching system with memory, KV, and database layers',
918
+ '1.0.0',
919
+ 'SonicJS Team',
920
+ 'performance',
921
+ '\u26A1',
922
+ 'active',
923
+ TRUE,
924
+ '["manage:cache","view:stats"]',
925
+ unixepoch(),
926
+ unixepoch()
927
+ ),
928
+ (
929
+ 'design',
930
+ 'design-plugin',
931
+ 'Design System',
932
+ 'Design system management including themes, components, and UI customization. Provides a visual interface for managing design tokens, typography, colors, and component library.',
933
+ '1.0.0',
934
+ 'SonicJS',
935
+ 'ui',
936
+ '\u{1F3A8}',
937
+ 'active',
938
+ TRUE,
939
+ '["design.view", "design.edit"]',
940
+ unixepoch(),
941
+ unixepoch()
942
+ );
943
+ `;
944
+ case "003":
945
+ case "004":
946
+ case "005":
947
+ case "007":
948
+ case "008":
949
+ case "009":
950
+ case "011":
951
+ case "012":
952
+ case "013":
953
+ return "";
954
+ default:
955
+ return null;
956
+ }
957
+ }
958
+ /**
959
+ * Validate database schema (placeholder)
960
+ */
961
+ async validateSchema() {
962
+ const issues = [];
963
+ const requiredTables = [
964
+ "users",
965
+ "content",
966
+ "collections",
967
+ "media",
968
+ "sessions"
969
+ ];
970
+ for (const table of requiredTables) {
971
+ try {
972
+ await this.db.prepare(`SELECT COUNT(*) FROM ${table} LIMIT 1`).first();
973
+ } catch (error) {
974
+ issues.push(`Missing table: ${table}`);
975
+ }
976
+ }
977
+ return {
978
+ valid: issues.length === 0,
979
+ issues
980
+ };
981
+ }
982
+ };
983
+
984
+ // src/db/schema.ts
985
+ var schema_exports = {};
986
+ __export(schema_exports, {
987
+ apiTokens: () => apiTokens,
988
+ collections: () => collections,
989
+ content: () => content,
990
+ contentVersions: () => contentVersions,
991
+ insertCollectionSchema: () => insertCollectionSchema,
992
+ insertContentSchema: () => insertContentSchema,
993
+ insertLogConfigSchema: () => insertLogConfigSchema,
994
+ insertMediaSchema: () => insertMediaSchema,
995
+ insertPluginActivityLogSchema: () => insertPluginActivityLogSchema,
996
+ insertPluginAssetSchema: () => insertPluginAssetSchema,
997
+ insertPluginHookSchema: () => insertPluginHookSchema,
998
+ insertPluginRouteSchema: () => insertPluginRouteSchema,
999
+ insertPluginSchema: () => insertPluginSchema,
1000
+ insertSystemLogSchema: () => insertSystemLogSchema,
1001
+ insertUserSchema: () => insertUserSchema,
1002
+ insertWorkflowHistorySchema: () => insertWorkflowHistorySchema,
1003
+ logConfig: () => logConfig,
1004
+ media: () => media,
1005
+ pluginActivityLog: () => pluginActivityLog,
1006
+ pluginAssets: () => pluginAssets,
1007
+ pluginHooks: () => pluginHooks,
1008
+ pluginRoutes: () => pluginRoutes,
1009
+ plugins: () => plugins,
1010
+ selectCollectionSchema: () => selectCollectionSchema,
1011
+ selectContentSchema: () => selectContentSchema,
1012
+ selectLogConfigSchema: () => selectLogConfigSchema,
1013
+ selectMediaSchema: () => selectMediaSchema,
1014
+ selectPluginActivityLogSchema: () => selectPluginActivityLogSchema,
1015
+ selectPluginAssetSchema: () => selectPluginAssetSchema,
1016
+ selectPluginHookSchema: () => selectPluginHookSchema,
1017
+ selectPluginRouteSchema: () => selectPluginRouteSchema,
1018
+ selectPluginSchema: () => selectPluginSchema,
1019
+ selectSystemLogSchema: () => selectSystemLogSchema,
1020
+ selectUserSchema: () => selectUserSchema,
1021
+ selectWorkflowHistorySchema: () => selectWorkflowHistorySchema,
1022
+ systemLogs: () => systemLogs,
1023
+ users: () => users,
1024
+ workflowHistory: () => workflowHistory
1025
+ });
1026
+ var CONSTANTS = {
1027
+ INT8_MIN: -128,
1028
+ INT8_MAX: 127,
1029
+ INT8_UNSIGNED_MAX: 255,
1030
+ INT16_MIN: -32768,
1031
+ INT16_MAX: 32767,
1032
+ INT16_UNSIGNED_MAX: 65535,
1033
+ INT24_MIN: -8388608,
1034
+ INT24_MAX: 8388607,
1035
+ INT24_UNSIGNED_MAX: 16777215,
1036
+ INT32_MIN: -2147483648,
1037
+ INT32_MAX: 2147483647,
1038
+ INT32_UNSIGNED_MAX: 4294967295,
1039
+ INT48_MIN: -140737488355328,
1040
+ INT48_MAX: 140737488355327,
1041
+ INT48_UNSIGNED_MAX: 281474976710655,
1042
+ INT64_MIN: -9223372036854775808n,
1043
+ INT64_MAX: 9223372036854775807n,
1044
+ INT64_UNSIGNED_MAX: 18446744073709551615n
1045
+ };
1046
+ function isColumnType(column, columnTypes) {
1047
+ return columnTypes.includes(column.columnType);
1048
+ }
1049
+ function isWithEnum(column) {
1050
+ return "enumValues" in column && Array.isArray(column.enumValues) && column.enumValues.length > 0;
1051
+ }
1052
+ var isPgEnum = isWithEnum;
1053
+ var literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
1054
+ var jsonSchema = z.union([
1055
+ literalSchema,
1056
+ z.record(z.string(), z.any()),
1057
+ z.array(z.any())
1058
+ ]);
1059
+ var bufferSchema = z.custom((v) => v instanceof Buffer);
1060
+ function columnToSchema(column, factory) {
1061
+ const z$1 = z;
1062
+ const coerce = {};
1063
+ let schema;
1064
+ if (isWithEnum(column)) {
1065
+ schema = column.enumValues.length ? z$1.enum(column.enumValues) : z$1.string();
1066
+ }
1067
+ if (!schema) {
1068
+ if (isColumnType(column, ["PgGeometry", "PgPointTuple"])) {
1069
+ schema = z$1.tuple([z$1.number(), z$1.number()]);
1070
+ } else if (isColumnType(column, ["PgGeometryObject", "PgPointObject"])) {
1071
+ schema = z$1.object({ x: z$1.number(), y: z$1.number() });
1072
+ } else if (isColumnType(column, ["PgHalfVector", "PgVector"])) {
1073
+ schema = z$1.array(z$1.number());
1074
+ schema = column.dimensions ? schema.length(column.dimensions) : schema;
1075
+ } else if (isColumnType(column, ["PgLine"])) {
1076
+ schema = z$1.tuple([z$1.number(), z$1.number(), z$1.number()]);
1077
+ } else if (isColumnType(column, ["PgLineABC"])) {
1078
+ schema = z$1.object({
1079
+ a: z$1.number(),
1080
+ b: z$1.number(),
1081
+ c: z$1.number()
1082
+ });
1083
+ } else if (isColumnType(column, ["PgArray"])) {
1084
+ schema = z$1.array(columnToSchema(column.baseColumn));
1085
+ schema = column.size ? schema.length(column.size) : schema;
1086
+ } else if (column.dataType === "array") {
1087
+ schema = z$1.array(z$1.any());
1088
+ } else if (column.dataType === "number") {
1089
+ schema = numberColumnToSchema(column, z$1, coerce);
1090
+ } else if (column.dataType === "bigint") {
1091
+ schema = bigintColumnToSchema(column, z$1, coerce);
1092
+ } else if (column.dataType === "boolean") {
1093
+ schema = coerce === true || coerce.boolean ? z$1.coerce.boolean() : z$1.boolean();
1094
+ } else if (column.dataType === "date") {
1095
+ schema = coerce === true || coerce.date ? z$1.coerce.date() : z$1.date();
1096
+ } else if (column.dataType === "string") {
1097
+ schema = stringColumnToSchema(column, z$1, coerce);
1098
+ } else if (column.dataType === "json") {
1099
+ schema = jsonSchema;
1100
+ } else if (column.dataType === "custom") {
1101
+ schema = z$1.any();
1102
+ } else if (column.dataType === "buffer") {
1103
+ schema = bufferSchema;
1104
+ }
1105
+ }
1106
+ if (!schema) {
1107
+ schema = z$1.any();
1108
+ }
1109
+ return schema;
1110
+ }
1111
+ function numberColumnToSchema(column, z2, coerce) {
1112
+ let unsigned = column.getSQLType().includes("unsigned");
1113
+ let min;
1114
+ let max;
1115
+ let integer2 = false;
1116
+ if (isColumnType(column, ["MySqlTinyInt", "SingleStoreTinyInt"])) {
1117
+ min = unsigned ? 0 : CONSTANTS.INT8_MIN;
1118
+ max = unsigned ? CONSTANTS.INT8_UNSIGNED_MAX : CONSTANTS.INT8_MAX;
1119
+ integer2 = true;
1120
+ } else if (isColumnType(column, [
1121
+ "PgSmallInt",
1122
+ "PgSmallSerial",
1123
+ "MySqlSmallInt",
1124
+ "SingleStoreSmallInt"
1125
+ ])) {
1126
+ min = unsigned ? 0 : CONSTANTS.INT16_MIN;
1127
+ max = unsigned ? CONSTANTS.INT16_UNSIGNED_MAX : CONSTANTS.INT16_MAX;
1128
+ integer2 = true;
1129
+ } else if (isColumnType(column, [
1130
+ "PgReal",
1131
+ "MySqlFloat",
1132
+ "MySqlMediumInt",
1133
+ "SingleStoreMediumInt",
1134
+ "SingleStoreFloat"
1135
+ ])) {
1136
+ min = unsigned ? 0 : CONSTANTS.INT24_MIN;
1137
+ max = unsigned ? CONSTANTS.INT24_UNSIGNED_MAX : CONSTANTS.INT24_MAX;
1138
+ integer2 = isColumnType(column, ["MySqlMediumInt", "SingleStoreMediumInt"]);
1139
+ } else if (isColumnType(column, [
1140
+ "PgInteger",
1141
+ "PgSerial",
1142
+ "MySqlInt",
1143
+ "SingleStoreInt"
1144
+ ])) {
1145
+ min = unsigned ? 0 : CONSTANTS.INT32_MIN;
1146
+ max = unsigned ? CONSTANTS.INT32_UNSIGNED_MAX : CONSTANTS.INT32_MAX;
1147
+ integer2 = true;
1148
+ } else if (isColumnType(column, [
1149
+ "PgDoublePrecision",
1150
+ "MySqlReal",
1151
+ "MySqlDouble",
1152
+ "SingleStoreReal",
1153
+ "SingleStoreDouble",
1154
+ "SQLiteReal"
1155
+ ])) {
1156
+ min = unsigned ? 0 : CONSTANTS.INT48_MIN;
1157
+ max = unsigned ? CONSTANTS.INT48_UNSIGNED_MAX : CONSTANTS.INT48_MAX;
1158
+ } else if (isColumnType(column, [
1159
+ "PgBigInt53",
1160
+ "PgBigSerial53",
1161
+ "MySqlBigInt53",
1162
+ "MySqlSerial",
1163
+ "SingleStoreBigInt53",
1164
+ "SingleStoreSerial",
1165
+ "SQLiteInteger"
1166
+ ])) {
1167
+ unsigned = unsigned || isColumnType(column, ["MySqlSerial", "SingleStoreSerial"]);
1168
+ min = unsigned ? 0 : Number.MIN_SAFE_INTEGER;
1169
+ max = Number.MAX_SAFE_INTEGER;
1170
+ integer2 = true;
1171
+ } else if (isColumnType(column, ["MySqlYear", "SingleStoreYear"])) {
1172
+ min = 1901;
1173
+ max = 2155;
1174
+ integer2 = true;
1175
+ } else {
1176
+ min = Number.MIN_SAFE_INTEGER;
1177
+ max = Number.MAX_SAFE_INTEGER;
1178
+ }
1179
+ let schema = coerce === true || coerce?.number ? integer2 ? z2.coerce.number() : z2.coerce.number().int() : integer2 ? z2.int() : z2.number();
1180
+ schema = schema.gte(min).lte(max);
1181
+ return schema;
1182
+ }
1183
+ function bigintColumnToSchema(column, z2, coerce) {
1184
+ const unsigned = column.getSQLType().includes("unsigned");
1185
+ const min = unsigned ? 0n : CONSTANTS.INT64_MIN;
1186
+ const max = unsigned ? CONSTANTS.INT64_UNSIGNED_MAX : CONSTANTS.INT64_MAX;
1187
+ const schema = coerce === true || coerce?.bigint ? z2.coerce.bigint() : z2.bigint();
1188
+ return schema.gte(min).lte(max);
1189
+ }
1190
+ function stringColumnToSchema(column, z2, coerce) {
1191
+ if (isColumnType(column, ["PgUUID"])) {
1192
+ return z2.uuid();
1193
+ }
1194
+ let max;
1195
+ let regex;
1196
+ let fixed = false;
1197
+ if (isColumnType(column, ["PgVarchar", "SQLiteText"])) {
1198
+ max = column.length;
1199
+ } else if (isColumnType(column, ["MySqlVarChar", "SingleStoreVarChar"])) {
1200
+ max = column.length ?? CONSTANTS.INT16_UNSIGNED_MAX;
1201
+ } else if (isColumnType(column, ["MySqlText", "SingleStoreText"])) {
1202
+ if (column.textType === "longtext") {
1203
+ max = CONSTANTS.INT32_UNSIGNED_MAX;
1204
+ } else if (column.textType === "mediumtext") {
1205
+ max = CONSTANTS.INT24_UNSIGNED_MAX;
1206
+ } else if (column.textType === "text") {
1207
+ max = CONSTANTS.INT16_UNSIGNED_MAX;
1208
+ } else {
1209
+ max = CONSTANTS.INT8_UNSIGNED_MAX;
1210
+ }
1211
+ }
1212
+ if (isColumnType(column, [
1213
+ "PgChar",
1214
+ "MySqlChar",
1215
+ "SingleStoreChar"
1216
+ ])) {
1217
+ max = column.length;
1218
+ fixed = true;
1219
+ }
1220
+ if (isColumnType(column, ["PgBinaryVector"])) {
1221
+ regex = /^[01]+$/;
1222
+ max = column.dimensions;
1223
+ }
1224
+ let schema = coerce === true || coerce?.string ? z2.coerce.string() : z2.string();
1225
+ schema = regex ? schema.regex(regex) : schema;
1226
+ return max && fixed ? schema.length(max) : max ? schema.max(max) : schema;
1227
+ }
1228
+ function getColumns(tableLike) {
1229
+ return isTable(tableLike) ? getTableColumns(tableLike) : getViewSelectedFields(tableLike);
1230
+ }
1231
+ function handleColumns(columns, refinements, conditions, factory) {
1232
+ const columnSchemas = {};
1233
+ for (const [key, selected] of Object.entries(columns)) {
1234
+ if (!is(selected, Column) && !is(selected, SQL) && !is(selected, SQL.Aliased) && typeof selected === "object") {
1235
+ const columns2 = isTable(selected) || isView(selected) ? getColumns(selected) : selected;
1236
+ columnSchemas[key] = handleColumns(columns2, refinements[key] ?? {}, conditions);
1237
+ continue;
1238
+ }
1239
+ const refinement = refinements[key];
1240
+ if (refinement !== void 0 && typeof refinement !== "function") {
1241
+ columnSchemas[key] = refinement;
1242
+ continue;
1243
+ }
1244
+ const column = is(selected, Column) ? selected : void 0;
1245
+ const schema = column ? columnToSchema(column) : z.any();
1246
+ const refined = typeof refinement === "function" ? refinement(schema) : schema;
1247
+ if (conditions.never(column)) {
1248
+ continue;
1249
+ } else {
1250
+ columnSchemas[key] = refined;
1251
+ }
1252
+ if (column) {
1253
+ if (conditions.nullable(column)) {
1254
+ columnSchemas[key] = columnSchemas[key].nullable();
1255
+ }
1256
+ if (conditions.optional(column)) {
1257
+ columnSchemas[key] = columnSchemas[key].optional();
1258
+ }
1259
+ }
1260
+ }
1261
+ return z.object(columnSchemas);
1262
+ }
1263
+ function handleEnum(enum_, factory) {
1264
+ const zod = z;
1265
+ return zod.enum(enum_.enumValues);
1266
+ }
1267
+ var selectConditions = {
1268
+ never: () => false,
1269
+ optional: () => false,
1270
+ nullable: (column) => !column.notNull
1271
+ };
1272
+ var insertConditions = {
1273
+ never: (column) => column?.generated?.type === "always" || column?.generatedIdentity?.type === "always",
1274
+ optional: (column) => !column.notNull || column.notNull && column.hasDefault,
1275
+ nullable: (column) => !column.notNull
1276
+ };
1277
+ var createSelectSchema = (entity, refine) => {
1278
+ if (isPgEnum(entity)) {
1279
+ return handleEnum(entity);
1280
+ }
1281
+ const columns = getColumns(entity);
1282
+ return handleColumns(columns, {}, selectConditions);
1283
+ };
1284
+ var createInsertSchema = (entity, refine) => {
1285
+ const columns = getColumns(entity);
1286
+ return handleColumns(columns, refine ?? {}, insertConditions);
1287
+ };
1288
+
1289
+ // src/db/schema.ts
1290
+ var users = sqliteTable("users", {
1291
+ id: text("id").primaryKey(),
1292
+ email: text("email").notNull().unique(),
1293
+ username: text("username").notNull().unique(),
1294
+ firstName: text("first_name").notNull(),
1295
+ lastName: text("last_name").notNull(),
1296
+ passwordHash: text("password_hash"),
1297
+ // Hashed password, nullable for OAuth users
1298
+ role: text("role").notNull().default("viewer"),
1299
+ // 'admin', 'editor', 'author', 'viewer'
1300
+ avatar: text("avatar"),
1301
+ isActive: integer("is_active", { mode: "boolean" }).notNull().default(true),
1302
+ lastLoginAt: integer("last_login_at"),
1303
+ createdAt: integer("created_at").notNull(),
1304
+ updatedAt: integer("updated_at").notNull()
1305
+ });
1306
+ var collections = sqliteTable("collections", {
1307
+ id: text("id").primaryKey(),
1308
+ name: text("name").notNull().unique(),
1309
+ displayName: text("display_name").notNull(),
1310
+ description: text("description"),
1311
+ schema: text("schema", { mode: "json" }).notNull(),
1312
+ // JSON schema definition
1313
+ isActive: integer("is_active", { mode: "boolean" }).notNull().default(true),
1314
+ managed: integer("managed", { mode: "boolean" }).notNull().default(false),
1315
+ // Config-managed collections cannot be edited in UI
1316
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
1317
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1318
+ });
1319
+ var content = sqliteTable("content", {
1320
+ id: text("id").primaryKey(),
1321
+ collectionId: text("collection_id").notNull().references(() => collections.id),
1322
+ slug: text("slug").notNull(),
1323
+ title: text("title").notNull(),
1324
+ data: text("data", { mode: "json" }).notNull(),
1325
+ // JSON content data
1326
+ status: text("status").notNull().default("draft"),
1327
+ // 'draft', 'published', 'archived'
1328
+ publishedAt: integer("published_at", { mode: "timestamp" }),
1329
+ authorId: text("author_id").notNull().references(() => users.id),
1330
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
1331
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1332
+ });
1333
+ var contentVersions = sqliteTable("content_versions", {
1334
+ id: text("id").primaryKey(),
1335
+ contentId: text("content_id").notNull().references(() => content.id),
1336
+ version: integer("version").notNull(),
1337
+ data: text("data", { mode: "json" }).notNull(),
1338
+ authorId: text("author_id").notNull().references(() => users.id),
1339
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1340
+ });
1341
+ var media = sqliteTable("media", {
1342
+ id: text("id").primaryKey(),
1343
+ filename: text("filename").notNull(),
1344
+ originalName: text("original_name").notNull(),
1345
+ mimeType: text("mime_type").notNull(),
1346
+ size: integer("size").notNull(),
1347
+ width: integer("width"),
1348
+ height: integer("height"),
1349
+ folder: text("folder").notNull().default("uploads"),
1350
+ r2Key: text("r2_key").notNull(),
1351
+ // R2 storage key
1352
+ publicUrl: text("public_url").notNull(),
1353
+ // CDN URL
1354
+ thumbnailUrl: text("thumbnail_url"),
1355
+ alt: text("alt"),
1356
+ caption: text("caption"),
1357
+ tags: text("tags", { mode: "json" }),
1358
+ // JSON array of tags
1359
+ uploadedBy: text("uploaded_by").notNull().references(() => users.id),
1360
+ uploadedAt: integer("uploaded_at").notNull(),
1361
+ updatedAt: integer("updated_at"),
1362
+ publishedAt: integer("published_at"),
1363
+ scheduledAt: integer("scheduled_at"),
1364
+ archivedAt: integer("archived_at"),
1365
+ deletedAt: integer("deleted_at")
1366
+ });
1367
+ var apiTokens = sqliteTable("api_tokens", {
1368
+ id: text("id").primaryKey(),
1369
+ name: text("name").notNull(),
1370
+ token: text("token").notNull().unique(),
1371
+ userId: text("user_id").notNull().references(() => users.id),
1372
+ permissions: text("permissions", { mode: "json" }).notNull(),
1373
+ // Array of permissions
1374
+ expiresAt: integer("expires_at", { mode: "timestamp" }),
1375
+ lastUsedAt: integer("last_used_at", { mode: "timestamp" }),
1376
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1377
+ });
1378
+ var workflowHistory = sqliteTable("workflow_history", {
1379
+ id: text("id").primaryKey(),
1380
+ contentId: text("content_id").notNull().references(() => content.id),
1381
+ action: text("action").notNull(),
1382
+ fromStatus: text("from_status").notNull(),
1383
+ toStatus: text("to_status").notNull(),
1384
+ userId: text("user_id").notNull().references(() => users.id),
1385
+ comment: text("comment"),
1386
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1387
+ });
1388
+ var plugins = sqliteTable("plugins", {
1389
+ id: text("id").primaryKey(),
1390
+ name: text("name").notNull().unique(),
1391
+ displayName: text("display_name").notNull(),
1392
+ description: text("description"),
1393
+ version: text("version").notNull(),
1394
+ author: text("author").notNull(),
1395
+ category: text("category").notNull(),
1396
+ icon: text("icon"),
1397
+ status: text("status").notNull().default("inactive"),
1398
+ // 'active', 'inactive', 'error'
1399
+ isCore: integer("is_core", { mode: "boolean" }).notNull().default(false),
1400
+ settings: text("settings", { mode: "json" }),
1401
+ permissions: text("permissions", { mode: "json" }),
1402
+ dependencies: text("dependencies", { mode: "json" }),
1403
+ downloadCount: integer("download_count").notNull().default(0),
1404
+ rating: integer("rating").notNull().default(0),
1405
+ installedAt: integer("installed_at").notNull(),
1406
+ activatedAt: integer("activated_at"),
1407
+ lastUpdated: integer("last_updated").notNull(),
1408
+ errorMessage: text("error_message"),
1409
+ createdAt: integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3)),
1410
+ updatedAt: integer("updated_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3))
1411
+ });
1412
+ var pluginHooks = sqliteTable("plugin_hooks", {
1413
+ id: text("id").primaryKey(),
1414
+ pluginId: text("plugin_id").notNull().references(() => plugins.id),
1415
+ hookName: text("hook_name").notNull(),
1416
+ handlerName: text("handler_name").notNull(),
1417
+ priority: integer("priority").notNull().default(10),
1418
+ isActive: integer("is_active", { mode: "boolean" }).notNull().default(true),
1419
+ createdAt: integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3))
1420
+ });
1421
+ var pluginRoutes = sqliteTable("plugin_routes", {
1422
+ id: text("id").primaryKey(),
1423
+ pluginId: text("plugin_id").notNull().references(() => plugins.id),
1424
+ path: text("path").notNull(),
1425
+ method: text("method").notNull(),
1426
+ handlerName: text("handler_name").notNull(),
1427
+ middleware: text("middleware", { mode: "json" }),
1428
+ isActive: integer("is_active", { mode: "boolean" }).notNull().default(true),
1429
+ createdAt: integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3))
1430
+ });
1431
+ var pluginAssets = sqliteTable("plugin_assets", {
1432
+ id: text("id").primaryKey(),
1433
+ pluginId: text("plugin_id").notNull().references(() => plugins.id),
1434
+ assetType: text("asset_type").notNull(),
1435
+ // 'css', 'js', 'image', 'font'
1436
+ assetPath: text("asset_path").notNull(),
1437
+ loadOrder: integer("load_order").notNull().default(100),
1438
+ loadLocation: text("load_location").notNull().default("footer"),
1439
+ // 'header', 'footer'
1440
+ isActive: integer("is_active", { mode: "boolean" }).notNull().default(true),
1441
+ createdAt: integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3))
1442
+ });
1443
+ var pluginActivityLog = sqliteTable("plugin_activity_log", {
1444
+ id: text("id").primaryKey(),
1445
+ pluginId: text("plugin_id").notNull().references(() => plugins.id),
1446
+ action: text("action").notNull(),
1447
+ userId: text("user_id"),
1448
+ details: text("details", { mode: "json" }),
1449
+ timestamp: integer("timestamp").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3))
1450
+ });
1451
+ var insertUserSchema = createInsertSchema(users, {
1452
+ email: (schema) => schema.email(),
1453
+ firstName: (schema) => schema.min(1),
1454
+ lastName: (schema) => schema.min(1),
1455
+ username: (schema) => schema.min(3)
1456
+ });
1457
+ var selectUserSchema = createSelectSchema(users);
1458
+ var insertCollectionSchema = createInsertSchema(collections, {
1459
+ name: (schema) => schema.min(1).regex(/^[a-z0-9_]+$/, "Collection name must be lowercase with underscores"),
1460
+ displayName: (schema) => schema.min(1)
1461
+ });
1462
+ var selectCollectionSchema = createSelectSchema(collections);
1463
+ var insertContentSchema = createInsertSchema(content, {
1464
+ slug: (schema) => schema.min(1).regex(/^[a-zA-Z0-9_-]+$/, "Slug must contain only letters, numbers, underscores, and hyphens"),
1465
+ title: (schema) => schema.min(1),
1466
+ status: (schema) => schema
1467
+ });
1468
+ var selectContentSchema = createSelectSchema(content);
1469
+ var insertMediaSchema = createInsertSchema(media, {
1470
+ filename: (schema) => schema.min(1),
1471
+ originalName: (schema) => schema.min(1),
1472
+ mimeType: (schema) => schema.min(1),
1473
+ size: (schema) => schema.positive(),
1474
+ r2Key: (schema) => schema.min(1),
1475
+ publicUrl: (schema) => schema.url(),
1476
+ folder: (schema) => schema.min(1)
1477
+ });
1478
+ var selectMediaSchema = createSelectSchema(media);
1479
+ var insertWorkflowHistorySchema = createInsertSchema(workflowHistory, {
1480
+ action: (schema) => schema.min(1),
1481
+ fromStatus: (schema) => schema.min(1),
1482
+ toStatus: (schema) => schema.min(1)
1483
+ });
1484
+ var selectWorkflowHistorySchema = createSelectSchema(workflowHistory);
1485
+ var insertPluginSchema = createInsertSchema(plugins, {
1486
+ name: (schema) => schema.min(1),
1487
+ displayName: (schema) => schema.min(1),
1488
+ version: (schema) => schema.min(1),
1489
+ author: (schema) => schema.min(1),
1490
+ category: (schema) => schema.min(1)
1491
+ });
1492
+ var selectPluginSchema = createSelectSchema(plugins);
1493
+ var insertPluginHookSchema = createInsertSchema(pluginHooks, {
1494
+ hookName: (schema) => schema.min(1),
1495
+ handlerName: (schema) => schema.min(1)
1496
+ });
1497
+ var selectPluginHookSchema = createSelectSchema(pluginHooks);
1498
+ var insertPluginRouteSchema = createInsertSchema(pluginRoutes, {
1499
+ path: (schema) => schema.min(1),
1500
+ method: (schema) => schema.min(1),
1501
+ handlerName: (schema) => schema.min(1)
1502
+ });
1503
+ var selectPluginRouteSchema = createSelectSchema(pluginRoutes);
1504
+ var insertPluginAssetSchema = createInsertSchema(pluginAssets, {
1505
+ assetType: (schema) => schema.min(1),
1506
+ assetPath: (schema) => schema.min(1)
1507
+ });
1508
+ var selectPluginAssetSchema = createSelectSchema(pluginAssets);
1509
+ var insertPluginActivityLogSchema = createInsertSchema(pluginActivityLog, {
1510
+ action: (schema) => schema.min(1)
1511
+ });
1512
+ var selectPluginActivityLogSchema = createSelectSchema(pluginActivityLog);
1513
+ var systemLogs = sqliteTable("system_logs", {
1514
+ id: text("id").primaryKey(),
1515
+ level: text("level").notNull(),
1516
+ // 'debug', 'info', 'warn', 'error', 'fatal'
1517
+ category: text("category").notNull(),
1518
+ // 'auth', 'api', 'workflow', 'plugin', 'media', 'system', etc.
1519
+ message: text("message").notNull(),
1520
+ data: text("data", { mode: "json" }),
1521
+ // Additional structured data
1522
+ userId: text("user_id").references(() => users.id),
1523
+ sessionId: text("session_id"),
1524
+ requestId: text("request_id"),
1525
+ ipAddress: text("ip_address"),
1526
+ userAgent: text("user_agent"),
1527
+ method: text("method"),
1528
+ // HTTP method for API logs
1529
+ url: text("url"),
1530
+ // Request URL for API logs
1531
+ statusCode: integer("status_code"),
1532
+ // HTTP status code for API logs
1533
+ duration: integer("duration"),
1534
+ // Request duration in milliseconds
1535
+ stackTrace: text("stack_trace"),
1536
+ // Error stack trace for error logs
1537
+ tags: text("tags", { mode: "json" }),
1538
+ // Array of tags for categorization
1539
+ source: text("source"),
1540
+ // Source component/module that generated the log
1541
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1542
+ });
1543
+ var logConfig = sqliteTable("log_config", {
1544
+ id: text("id").primaryKey(),
1545
+ category: text("category").notNull().unique(),
1546
+ enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
1547
+ level: text("level").notNull().default("info"),
1548
+ // minimum log level to store
1549
+ retention: integer("retention").notNull().default(30),
1550
+ // days to keep logs
1551
+ maxSize: integer("max_size").default(1e4),
1552
+ // max number of logs per category
1553
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
1554
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
1555
+ });
1556
+ var insertSystemLogSchema = createInsertSchema(systemLogs, {
1557
+ level: (schema) => schema.min(1),
1558
+ category: (schema) => schema.min(1),
1559
+ message: (schema) => schema.min(1)
1560
+ });
1561
+ var selectSystemLogSchema = createSelectSchema(systemLogs);
1562
+ var insertLogConfigSchema = createInsertSchema(logConfig, {
1563
+ category: (schema) => schema.min(1),
1564
+ level: (schema) => schema.min(1)
1565
+ });
1566
+ var selectLogConfigSchema = createSelectSchema(logConfig);
1567
+ var Logger = class {
1568
+ db;
1569
+ enabled = true;
1570
+ configCache = /* @__PURE__ */ new Map();
1571
+ lastConfigRefresh = 0;
1572
+ configRefreshInterval = 6e4;
1573
+ // 1 minute
1574
+ constructor(database) {
1575
+ this.db = drizzle(database);
1576
+ }
1577
+ /**
1578
+ * Log a debug message
1579
+ */
1580
+ async debug(category, message, data, context) {
1581
+ return this.log("debug", category, message, data, context);
1582
+ }
1583
+ /**
1584
+ * Log an info message
1585
+ */
1586
+ async info(category, message, data, context) {
1587
+ return this.log("info", category, message, data, context);
1588
+ }
1589
+ /**
1590
+ * Log a warning message
1591
+ */
1592
+ async warn(category, message, data, context) {
1593
+ return this.log("warn", category, message, data, context);
1594
+ }
1595
+ /**
1596
+ * Log an error message
1597
+ */
1598
+ async error(category, message, error, context) {
1599
+ const errorData = error instanceof Error ? {
1600
+ name: error.name,
1601
+ message: error.message,
1602
+ stack: error.stack
1603
+ } : error;
1604
+ return this.log("error", category, message, errorData, {
1605
+ ...context,
1606
+ stackTrace: error instanceof Error ? error.stack : void 0
1607
+ });
1608
+ }
1609
+ /**
1610
+ * Log a fatal message
1611
+ */
1612
+ async fatal(category, message, error, context) {
1613
+ const errorData = error instanceof Error ? {
1614
+ name: error.name,
1615
+ message: error.message,
1616
+ stack: error.stack
1617
+ } : error;
1618
+ return this.log("fatal", category, message, errorData, {
1619
+ ...context,
1620
+ stackTrace: error instanceof Error ? error.stack : void 0
1621
+ });
1622
+ }
1623
+ /**
1624
+ * Log an API request
1625
+ */
1626
+ async logRequest(method, url, statusCode, duration, context) {
1627
+ const level = statusCode >= 500 ? "error" : statusCode >= 400 ? "warn" : "info";
1628
+ return this.log(level, "api", `${method} ${url} - ${statusCode}`, {
1629
+ method,
1630
+ url,
1631
+ statusCode,
1632
+ duration
1633
+ }, {
1634
+ ...context,
1635
+ method,
1636
+ url,
1637
+ statusCode,
1638
+ duration
1639
+ });
1640
+ }
1641
+ /**
1642
+ * Log an authentication event
1643
+ */
1644
+ async logAuth(action, userId, success = true, context) {
1645
+ const level = success ? "info" : "warn";
1646
+ return this.log(level, "auth", `Authentication ${action}: ${success ? "success" : "failed"}`, {
1647
+ action,
1648
+ success,
1649
+ userId
1650
+ }, {
1651
+ ...context,
1652
+ userId,
1653
+ tags: ["authentication", action]
1654
+ });
1655
+ }
1656
+ /**
1657
+ * Log a security event
1658
+ */
1659
+ async logSecurity(event, severity, context) {
1660
+ const level = severity === "critical" ? "fatal" : severity === "high" ? "error" : "warn";
1661
+ return this.log(level, "security", `Security event: ${event}`, {
1662
+ event,
1663
+ severity
1664
+ }, {
1665
+ ...context,
1666
+ tags: ["security", severity]
1667
+ });
1668
+ }
1669
+ /**
1670
+ * Core logging method
1671
+ */
1672
+ async log(level, category, message, data, context) {
1673
+ if (!this.enabled) return;
1674
+ try {
1675
+ const config = await this.getConfig(category);
1676
+ if (!config || !config.enabled || !this.shouldLog(level, config.level)) {
1677
+ return;
1678
+ }
1679
+ const logEntry = {
1680
+ id: crypto.randomUUID(),
1681
+ level,
1682
+ category,
1683
+ message,
1684
+ data: data ? JSON.stringify(data) : null,
1685
+ userId: context?.userId || null,
1686
+ sessionId: context?.sessionId || null,
1687
+ requestId: context?.requestId || null,
1688
+ ipAddress: context?.ipAddress || null,
1689
+ userAgent: context?.userAgent || null,
1690
+ method: context?.method || null,
1691
+ url: context?.url || null,
1692
+ statusCode: context?.statusCode || null,
1693
+ duration: context?.duration || null,
1694
+ stackTrace: context?.stackTrace || null,
1695
+ tags: context?.tags ? JSON.stringify(context.tags) : null,
1696
+ source: context?.source || null,
1697
+ createdAt: /* @__PURE__ */ new Date()
1698
+ };
1699
+ await this.db.insert(systemLogs).values(logEntry);
1700
+ if (config.maxSize) {
1701
+ await this.cleanupCategory(category, config.maxSize);
1702
+ }
1703
+ } catch (error) {
1704
+ console.error("Logger error:", error);
1705
+ }
1706
+ }
1707
+ /**
1708
+ * Get logs with filtering and pagination
1709
+ */
1710
+ async getLogs(filter = {}) {
1711
+ try {
1712
+ const conditions = [];
1713
+ if (filter.level && filter.level.length > 0) {
1714
+ conditions.push(inArray(systemLogs.level, filter.level));
1715
+ }
1716
+ if (filter.category && filter.category.length > 0) {
1717
+ conditions.push(inArray(systemLogs.category, filter.category));
1718
+ }
1719
+ if (filter.userId) {
1720
+ conditions.push(eq(systemLogs.userId, filter.userId));
1721
+ }
1722
+ if (filter.source) {
1723
+ conditions.push(eq(systemLogs.source, filter.source));
1724
+ }
1725
+ if (filter.search) {
1726
+ conditions.push(
1727
+ like(systemLogs.message, `%${filter.search}%`)
1728
+ );
1729
+ }
1730
+ if (filter.startDate) {
1731
+ conditions.push(gte(systemLogs.createdAt, filter.startDate));
1732
+ }
1733
+ if (filter.endDate) {
1734
+ conditions.push(lte(systemLogs.createdAt, filter.endDate));
1735
+ }
1736
+ const whereClause = conditions.length > 0 ? and(...conditions) : void 0;
1737
+ const totalResult = await this.db.select({ count: count() }).from(systemLogs).where(whereClause);
1738
+ const total = totalResult[0]?.count || 0;
1739
+ const sortColumn = filter.sortBy === "level" ? systemLogs.level : filter.sortBy === "category" ? systemLogs.category : systemLogs.createdAt;
1740
+ const sortFn = filter.sortOrder === "asc" ? asc : desc;
1741
+ const logs = await this.db.select().from(systemLogs).where(whereClause).orderBy(sortFn(sortColumn)).limit(filter.limit || 50).offset(filter.offset || 0);
1742
+ return { logs, total };
1743
+ } catch (error) {
1744
+ console.error("Error getting logs:", error);
1745
+ return { logs: [], total: 0 };
1746
+ }
1747
+ }
1748
+ /**
1749
+ * Get log configuration for a category
1750
+ */
1751
+ async getConfig(category) {
1752
+ try {
1753
+ const now = Date.now();
1754
+ if (this.configCache.has(category) && now - this.lastConfigRefresh < this.configRefreshInterval) {
1755
+ return this.configCache.get(category) || null;
1756
+ }
1757
+ const configs = await this.db.select().from(logConfig).where(eq(logConfig.category, category));
1758
+ const config = configs[0] || null;
1759
+ if (config) {
1760
+ this.configCache.set(category, config);
1761
+ this.lastConfigRefresh = now;
1762
+ }
1763
+ return config;
1764
+ } catch (error) {
1765
+ console.error("Error getting log config:", error);
1766
+ return null;
1767
+ }
1768
+ }
1769
+ /**
1770
+ * Update log configuration
1771
+ */
1772
+ async updateConfig(category, updates) {
1773
+ try {
1774
+ await this.db.update(logConfig).set({
1775
+ ...updates,
1776
+ updatedAt: /* @__PURE__ */ new Date()
1777
+ }).where(eq(logConfig.category, category));
1778
+ this.configCache.delete(category);
1779
+ } catch (error) {
1780
+ console.error("Error updating log config:", error);
1781
+ }
1782
+ }
1783
+ /**
1784
+ * Get all log configurations
1785
+ */
1786
+ async getAllConfigs() {
1787
+ try {
1788
+ return await this.db.select().from(logConfig);
1789
+ } catch (error) {
1790
+ console.error("Error getting log configs:", error);
1791
+ return [];
1792
+ }
1793
+ }
1794
+ /**
1795
+ * Clean up old logs for a category
1796
+ */
1797
+ async cleanupCategory(category, maxSize) {
1798
+ try {
1799
+ const countResult = await this.db.select({ count: count() }).from(systemLogs).where(eq(systemLogs.category, category));
1800
+ const currentCount = countResult[0]?.count || 0;
1801
+ if (currentCount > maxSize) {
1802
+ const cutoffLogs = await this.db.select({ createdAt: systemLogs.createdAt }).from(systemLogs).where(eq(systemLogs.category, category)).orderBy(desc(systemLogs.createdAt)).limit(1).offset(maxSize - 1);
1803
+ if (cutoffLogs[0]) {
1804
+ await this.db.delete(systemLogs).where(
1805
+ and(
1806
+ eq(systemLogs.category, category),
1807
+ lte(systemLogs.createdAt, cutoffLogs[0].createdAt)
1808
+ )
1809
+ );
1810
+ }
1811
+ }
1812
+ } catch (error) {
1813
+ console.error("Error cleaning up logs:", error);
1814
+ }
1815
+ }
1816
+ /**
1817
+ * Clean up logs based on retention policy
1818
+ */
1819
+ async cleanupByRetention() {
1820
+ try {
1821
+ const configs = await this.getAllConfigs();
1822
+ for (const config of configs) {
1823
+ if (config.retention > 0) {
1824
+ const cutoffDate = /* @__PURE__ */ new Date();
1825
+ cutoffDate.setDate(cutoffDate.getDate() - config.retention);
1826
+ await this.db.delete(systemLogs).where(
1827
+ and(
1828
+ eq(systemLogs.category, config.category),
1829
+ lte(systemLogs.createdAt, cutoffDate)
1830
+ )
1831
+ );
1832
+ }
1833
+ }
1834
+ } catch (error) {
1835
+ console.error("Error cleaning up logs by retention:", error);
1836
+ }
1837
+ }
1838
+ /**
1839
+ * Check if a log level should be recorded based on configuration
1840
+ */
1841
+ shouldLog(level, configLevel) {
1842
+ const levels = ["debug", "info", "warn", "error", "fatal"];
1843
+ const levelIndex = levels.indexOf(level);
1844
+ const configLevelIndex = levels.indexOf(configLevel);
1845
+ return levelIndex >= configLevelIndex;
1846
+ }
1847
+ /**
1848
+ * Enable or disable logging
1849
+ */
1850
+ setEnabled(enabled) {
1851
+ this.enabled = enabled;
1852
+ }
1853
+ /**
1854
+ * Check if logging is enabled
1855
+ */
1856
+ isEnabled() {
1857
+ return this.enabled;
1858
+ }
1859
+ };
1860
+ var loggerInstance = null;
1861
+ function getLogger(database) {
1862
+ if (!loggerInstance && database) {
1863
+ loggerInstance = new Logger(database);
1864
+ }
1865
+ if (!loggerInstance) {
1866
+ throw new Error("Logger not initialized. Call getLogger with a database instance first.");
1867
+ }
1868
+ return loggerInstance;
1869
+ }
1870
+ function initLogger(database) {
1871
+ loggerInstance = new Logger(database);
1872
+ return loggerInstance;
1873
+ }
1874
+
1875
+ // src/services/plugin-service.ts
1876
+ var PluginService = class {
1877
+ constructor(db) {
1878
+ this.db = db;
1879
+ }
1880
+ async getAllPlugins() {
1881
+ await this.ensureAllPluginsExist();
1882
+ const stmt = this.db.prepare(`
1883
+ SELECT * FROM plugins
1884
+ ORDER BY is_core DESC, display_name ASC
1885
+ `);
1886
+ const { results } = await stmt.all();
1887
+ return (results || []).map(this.mapPluginFromDb);
1888
+ }
1889
+ /**
1890
+ * Ensure all plugins from the registry exist in the database
1891
+ * Auto-installs any newly detected plugins with inactive status
1892
+ *
1893
+ * Note: This method should be overridden or configured with a plugin registry
1894
+ * in the consuming application
1895
+ */
1896
+ async ensureAllPluginsExist() {
1897
+ console.log("[PluginService] ensureAllPluginsExist - requires PLUGIN_REGISTRY configuration");
1898
+ }
1899
+ async getPlugin(pluginId) {
1900
+ const stmt = this.db.prepare("SELECT * FROM plugins WHERE id = ?");
1901
+ const plugin = await stmt.bind(pluginId).first();
1902
+ if (!plugin) return null;
1903
+ return this.mapPluginFromDb(plugin);
1904
+ }
1905
+ async getPluginByName(name) {
1906
+ const stmt = this.db.prepare("SELECT * FROM plugins WHERE name = ?");
1907
+ const plugin = await stmt.bind(name).first();
1908
+ if (!plugin) return null;
1909
+ return this.mapPluginFromDb(plugin);
1910
+ }
1911
+ async getPluginStats() {
1912
+ const stmt = this.db.prepare(`
1913
+ SELECT
1914
+ COUNT(*) as total,
1915
+ COUNT(CASE WHEN status = 'active' THEN 1 END) as active,
1916
+ COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive,
1917
+ COUNT(CASE WHEN status = 'error' THEN 1 END) as errors
1918
+ FROM plugins
1919
+ `);
1920
+ const stats = await stmt.first();
1921
+ return {
1922
+ total: stats.total || 0,
1923
+ active: stats.active || 0,
1924
+ inactive: stats.inactive || 0,
1925
+ errors: stats.errors || 0
1926
+ };
1927
+ }
1928
+ async installPlugin(pluginData) {
1929
+ const id = pluginData.id || `plugin-${Date.now()}`;
1930
+ const now = Math.floor(Date.now() / 1e3);
1931
+ const stmt = this.db.prepare(`
1932
+ INSERT INTO plugins (
1933
+ id, name, display_name, description, version, author, category, icon,
1934
+ status, is_core, settings, permissions, dependencies, download_count,
1935
+ rating, installed_at, last_updated
1936
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1937
+ `);
1938
+ await stmt.bind(
1939
+ id,
1940
+ pluginData.name || id,
1941
+ pluginData.display_name || "Unnamed Plugin",
1942
+ pluginData.description || "",
1943
+ pluginData.version || "1.0.0",
1944
+ pluginData.author || "Unknown",
1945
+ pluginData.category || "utilities",
1946
+ pluginData.icon || "\u{1F50C}",
1947
+ "inactive",
1948
+ pluginData.is_core || false,
1949
+ JSON.stringify(pluginData.settings || {}),
1950
+ JSON.stringify(pluginData.permissions || []),
1951
+ JSON.stringify(pluginData.dependencies || []),
1952
+ pluginData.download_count || 0,
1953
+ pluginData.rating || 0,
1954
+ now,
1955
+ now
1956
+ ).run();
1957
+ await this.logActivity(id, "installed", null, { version: pluginData.version });
1958
+ const installed = await this.getPlugin(id);
1959
+ if (!installed) throw new Error("Failed to install plugin");
1960
+ return installed;
1961
+ }
1962
+ async uninstallPlugin(pluginId) {
1963
+ const plugin = await this.getPlugin(pluginId);
1964
+ if (!plugin) throw new Error("Plugin not found");
1965
+ if (plugin.is_core) throw new Error("Cannot uninstall core plugins");
1966
+ if (plugin.status === "active") {
1967
+ await this.deactivatePlugin(pluginId);
1968
+ }
1969
+ const stmt = this.db.prepare("DELETE FROM plugins WHERE id = ?");
1970
+ await stmt.bind(pluginId).run();
1971
+ await this.logActivity(pluginId, "uninstalled", null, { name: plugin.name });
1972
+ }
1973
+ async activatePlugin(pluginId) {
1974
+ const plugin = await this.getPlugin(pluginId);
1975
+ if (!plugin) throw new Error("Plugin not found");
1976
+ if (plugin.dependencies && plugin.dependencies.length > 0) {
1977
+ await this.checkDependencies(plugin.dependencies);
1978
+ }
1979
+ const now = Math.floor(Date.now() / 1e3);
1980
+ const stmt = this.db.prepare(`
1981
+ UPDATE plugins
1982
+ SET status = 'active', activated_at = ?, error_message = NULL
1983
+ WHERE id = ?
1984
+ `);
1985
+ await stmt.bind(now, pluginId).run();
1986
+ await this.logActivity(pluginId, "activated", null);
1987
+ }
1988
+ async deactivatePlugin(pluginId) {
1989
+ const plugin = await this.getPlugin(pluginId);
1990
+ if (!plugin) throw new Error("Plugin not found");
1991
+ await this.checkDependents(plugin.name);
1992
+ const stmt = this.db.prepare(`
1993
+ UPDATE plugins
1994
+ SET status = 'inactive', activated_at = NULL
1995
+ WHERE id = ?
1996
+ `);
1997
+ await stmt.bind(pluginId).run();
1998
+ await this.logActivity(pluginId, "deactivated", null);
1999
+ }
2000
+ async updatePluginSettings(pluginId, settings) {
2001
+ const plugin = await this.getPlugin(pluginId);
2002
+ if (!plugin) throw new Error("Plugin not found");
2003
+ const stmt = this.db.prepare(`
2004
+ UPDATE plugins
2005
+ SET settings = ?, updated_at = unixepoch()
2006
+ WHERE id = ?
2007
+ `);
2008
+ await stmt.bind(JSON.stringify(settings), pluginId).run();
2009
+ await this.logActivity(pluginId, "settings_updated", null);
2010
+ }
2011
+ async setPluginError(pluginId, error) {
2012
+ const stmt = this.db.prepare(`
2013
+ UPDATE plugins
2014
+ SET status = 'error', error_message = ?
2015
+ WHERE id = ?
2016
+ `);
2017
+ await stmt.bind(error, pluginId).run();
2018
+ await this.logActivity(pluginId, "error", null, { error });
2019
+ }
2020
+ async getPluginActivity(pluginId, limit = 10) {
2021
+ const stmt = this.db.prepare(`
2022
+ SELECT * FROM plugin_activity_log
2023
+ WHERE plugin_id = ?
2024
+ ORDER BY timestamp DESC
2025
+ LIMIT ?
2026
+ `);
2027
+ const { results } = await stmt.bind(pluginId, limit).all();
2028
+ return (results || []).map((row) => ({
2029
+ id: row.id,
2030
+ action: row.action,
2031
+ userId: row.user_id,
2032
+ details: row.details ? JSON.parse(row.details) : null,
2033
+ timestamp: row.timestamp
2034
+ }));
2035
+ }
2036
+ async registerHook(pluginId, hookName, handlerName, priority = 10) {
2037
+ const id = `hook-${Date.now()}`;
2038
+ const stmt = this.db.prepare(`
2039
+ INSERT INTO plugin_hooks (id, plugin_id, hook_name, handler_name, priority)
2040
+ VALUES (?, ?, ?, ?, ?)
2041
+ `);
2042
+ await stmt.bind(id, pluginId, hookName, handlerName, priority).run();
2043
+ }
2044
+ async registerRoute(pluginId, path, method, handlerName, middleware) {
2045
+ const id = `route-${Date.now()}`;
2046
+ const stmt = this.db.prepare(`
2047
+ INSERT INTO plugin_routes (id, plugin_id, path, method, handler_name, middleware)
2048
+ VALUES (?, ?, ?, ?, ?, ?)
2049
+ `);
2050
+ await stmt.bind(
2051
+ id,
2052
+ pluginId,
2053
+ path,
2054
+ method,
2055
+ handlerName,
2056
+ JSON.stringify(middleware || [])
2057
+ ).run();
2058
+ }
2059
+ async getPluginHooks(pluginId) {
2060
+ const stmt = this.db.prepare(`
2061
+ SELECT * FROM plugin_hooks
2062
+ WHERE plugin_id = ? AND is_active = TRUE
2063
+ ORDER BY priority ASC
2064
+ `);
2065
+ const { results } = await stmt.bind(pluginId).all();
2066
+ return results || [];
2067
+ }
2068
+ async getPluginRoutes(pluginId) {
2069
+ const stmt = this.db.prepare(`
2070
+ SELECT * FROM plugin_routes
2071
+ WHERE plugin_id = ? AND is_active = TRUE
2072
+ `);
2073
+ const { results } = await stmt.bind(pluginId).all();
2074
+ return results || [];
2075
+ }
2076
+ async checkDependencies(dependencies) {
2077
+ for (const dep of dependencies) {
2078
+ const plugin = await this.getPluginByName(dep);
2079
+ if (!plugin || plugin.status !== "active") {
2080
+ throw new Error(`Required dependency '${dep}' is not active`);
2081
+ }
2082
+ }
2083
+ }
2084
+ async checkDependents(pluginName) {
2085
+ const stmt = this.db.prepare(`
2086
+ SELECT id, display_name FROM plugins
2087
+ WHERE status = 'active'
2088
+ AND dependencies LIKE ?
2089
+ `);
2090
+ const { results } = await stmt.bind(`%"${pluginName}"%`).all();
2091
+ if (results && results.length > 0) {
2092
+ const names = results.map((p) => p.display_name).join(", ");
2093
+ throw new Error(`Cannot deactivate. The following plugins depend on this one: ${names}`);
2094
+ }
2095
+ }
2096
+ async logActivity(pluginId, action, userId, details) {
2097
+ const id = `activity-${Date.now()}`;
2098
+ const stmt = this.db.prepare(`
2099
+ INSERT INTO plugin_activity_log (id, plugin_id, action, user_id, details)
2100
+ VALUES (?, ?, ?, ?, ?)
2101
+ `);
2102
+ await stmt.bind(
2103
+ id,
2104
+ pluginId,
2105
+ action,
2106
+ userId,
2107
+ details ? JSON.stringify(details) : null
2108
+ ).run();
2109
+ }
2110
+ mapPluginFromDb(row) {
2111
+ return {
2112
+ id: row.id,
2113
+ name: row.name,
2114
+ display_name: row.display_name,
2115
+ description: row.description,
2116
+ version: row.version,
2117
+ author: row.author,
2118
+ category: row.category,
2119
+ icon: row.icon,
2120
+ status: row.status,
2121
+ is_core: row.is_core === 1,
2122
+ settings: row.settings ? JSON.parse(row.settings) : void 0,
2123
+ permissions: row.permissions ? JSON.parse(row.permissions) : void 0,
2124
+ dependencies: row.dependencies ? JSON.parse(row.dependencies) : void 0,
2125
+ download_count: row.download_count || 0,
2126
+ rating: row.rating || 0,
2127
+ installed_at: row.installed_at,
2128
+ activated_at: row.activated_at,
2129
+ last_updated: row.last_updated,
2130
+ error_message: row.error_message
2131
+ };
2132
+ }
2133
+ };
2134
+
2135
+ // src/services/plugin-bootstrap.ts
2136
+ var PluginBootstrapService = class {
2137
+ constructor(db) {
2138
+ this.db = db;
2139
+ this.pluginService = new PluginService(db);
2140
+ }
2141
+ pluginService;
2142
+ /**
2143
+ * Core plugins that should always be available in the system
2144
+ */
2145
+ CORE_PLUGINS = [
2146
+ {
2147
+ id: "core-auth",
2148
+ name: "core-auth",
2149
+ display_name: "Authentication System",
2150
+ description: "Core authentication and user management system",
2151
+ version: "1.0.0",
2152
+ author: "SonicJS Team",
2153
+ category: "security",
2154
+ icon: "\u{1F510}",
2155
+ permissions: ["manage:users", "manage:roles", "manage:permissions"],
2156
+ dependencies: [],
2157
+ settings: {
2158
+ requiredFields: {
2159
+ email: { required: true, minLength: 5, label: "Email", type: "email" },
2160
+ password: { required: true, minLength: 8, label: "Password", type: "password" },
2161
+ username: { required: true, minLength: 3, label: "Username", type: "text" },
2162
+ firstName: { required: true, minLength: 1, label: "First Name", type: "text" },
2163
+ lastName: { required: true, minLength: 1, label: "Last Name", type: "text" }
2164
+ },
2165
+ validation: {
2166
+ emailFormat: true,
2167
+ allowDuplicateUsernames: false,
2168
+ passwordRequirements: {
2169
+ requireUppercase: false,
2170
+ requireLowercase: false,
2171
+ requireNumbers: false,
2172
+ requireSpecialChars: false
2173
+ }
2174
+ },
2175
+ registration: {
2176
+ enabled: true,
2177
+ requireEmailVerification: false,
2178
+ defaultRole: "viewer"
2179
+ }
2180
+ }
2181
+ },
2182
+ {
2183
+ id: "core-media",
2184
+ name: "core-media",
2185
+ display_name: "Media Manager",
2186
+ description: "Core media upload and management system",
2187
+ version: "1.0.0",
2188
+ author: "SonicJS Team",
2189
+ category: "media",
2190
+ icon: "\u{1F4F8}",
2191
+ permissions: ["manage:media", "upload:files"],
2192
+ dependencies: [],
2193
+ settings: {}
2194
+ },
2195
+ {
2196
+ id: "database-tools",
2197
+ name: "database-tools",
2198
+ display_name: "Database Tools",
2199
+ description: "Database management tools including truncate, backup, and validation",
2200
+ version: "1.0.0",
2201
+ author: "SonicJS Team",
2202
+ category: "system",
2203
+ icon: "\u{1F5C4}\uFE0F",
2204
+ permissions: ["manage:database", "admin"],
2205
+ dependencies: [],
2206
+ settings: {
2207
+ enableTruncate: true,
2208
+ enableBackup: true,
2209
+ enableValidation: true,
2210
+ requireConfirmation: true
2211
+ }
2212
+ },
2213
+ {
2214
+ id: "seed-data",
2215
+ name: "seed-data",
2216
+ display_name: "Seed Data",
2217
+ description: "Generate realistic example users and content for testing and development",
2218
+ version: "1.0.0",
2219
+ author: "SonicJS Team",
2220
+ category: "development",
2221
+ icon: "\u{1F331}",
2222
+ permissions: ["admin"],
2223
+ dependencies: [],
2224
+ settings: {
2225
+ userCount: 20,
2226
+ contentCount: 200,
2227
+ defaultPassword: "password123"
2228
+ }
2229
+ },
2230
+ {
2231
+ id: "core-cache",
2232
+ name: "core-cache",
2233
+ display_name: "Cache System",
2234
+ description: "Three-tiered caching system with memory, KV, and database layers",
2235
+ version: "1.0.0",
2236
+ author: "SonicJS Team",
2237
+ category: "performance",
2238
+ icon: "\u26A1",
2239
+ permissions: ["manage:cache", "view:stats"],
2240
+ dependencies: [],
2241
+ settings: {
2242
+ enableMemoryCache: true,
2243
+ enableKVCache: true,
2244
+ enableDatabaseCache: true,
2245
+ defaultTTL: 3600
2246
+ }
2247
+ }
2248
+ ];
2249
+ /**
2250
+ * Bootstrap all core plugins - install them if they don't exist
2251
+ */
2252
+ async bootstrapCorePlugins() {
2253
+ console.log("[PluginBootstrap] Starting core plugin bootstrap process...");
2254
+ try {
2255
+ for (const corePlugin of this.CORE_PLUGINS) {
2256
+ await this.ensurePluginInstalled(corePlugin);
2257
+ }
2258
+ console.log(
2259
+ "[PluginBootstrap] Core plugin bootstrap completed successfully"
2260
+ );
2261
+ } catch (error) {
2262
+ console.error("[PluginBootstrap] Error during plugin bootstrap:", error);
2263
+ throw error;
2264
+ }
2265
+ }
2266
+ /**
2267
+ * Ensure a specific plugin is installed
2268
+ */
2269
+ async ensurePluginInstalled(plugin) {
2270
+ try {
2271
+ const existingPlugin = await this.pluginService.getPlugin(plugin.id);
2272
+ if (existingPlugin) {
2273
+ console.log(
2274
+ `[PluginBootstrap] Plugin already installed: ${plugin.display_name} (status: ${existingPlugin.status})`
2275
+ );
2276
+ if (existingPlugin.version !== plugin.version) {
2277
+ console.log(
2278
+ `[PluginBootstrap] Updating plugin version: ${plugin.display_name} from ${existingPlugin.version} to ${plugin.version}`
2279
+ );
2280
+ await this.updatePlugin(plugin);
2281
+ }
2282
+ if (plugin.id === "core-auth" && existingPlugin.status !== "active") {
2283
+ console.log(
2284
+ `[PluginBootstrap] Core-auth plugin is inactive, activating it now...`
2285
+ );
2286
+ await this.pluginService.activatePlugin(plugin.id);
2287
+ }
2288
+ } else {
2289
+ console.log(
2290
+ `[PluginBootstrap] Installing plugin: ${plugin.display_name}`
2291
+ );
2292
+ await this.pluginService.installPlugin({
2293
+ ...plugin,
2294
+ is_core: plugin.name.startsWith("core-")
2295
+ });
2296
+ if (plugin.name.startsWith("core-")) {
2297
+ console.log(
2298
+ `[PluginBootstrap] Activating newly installed core plugin: ${plugin.display_name}`
2299
+ );
2300
+ await this.pluginService.activatePlugin(plugin.id);
2301
+ }
2302
+ }
2303
+ } catch (error) {
2304
+ console.error(
2305
+ `[PluginBootstrap] Error ensuring plugin ${plugin.display_name}:`,
2306
+ error
2307
+ );
2308
+ }
2309
+ }
2310
+ /**
2311
+ * Update an existing plugin
2312
+ */
2313
+ async updatePlugin(plugin) {
2314
+ const now = Math.floor(Date.now() / 1e3);
2315
+ const stmt = this.db.prepare(`
2316
+ UPDATE plugins
2317
+ SET
2318
+ version = ?,
2319
+ description = ?,
2320
+ permissions = ?,
2321
+ settings = ?,
2322
+ last_updated = ?
2323
+ WHERE id = ?
2324
+ `);
2325
+ await stmt.bind(
2326
+ plugin.version,
2327
+ plugin.description,
2328
+ JSON.stringify(plugin.permissions),
2329
+ JSON.stringify(plugin.settings || {}),
2330
+ now,
2331
+ plugin.id
2332
+ ).run();
2333
+ }
2334
+ /**
2335
+ * Check if bootstrap is needed (first run detection)
2336
+ */
2337
+ async isBootstrapNeeded() {
2338
+ try {
2339
+ for (const corePlugin of this.CORE_PLUGINS.filter(
2340
+ (p) => p.name.startsWith("core-")
2341
+ )) {
2342
+ const exists = await this.pluginService.getPlugin(corePlugin.id);
2343
+ if (!exists) {
2344
+ return true;
2345
+ }
2346
+ }
2347
+ return false;
2348
+ } catch (error) {
2349
+ console.error(
2350
+ "[PluginBootstrap] Error checking bootstrap status:",
2351
+ error
2352
+ );
2353
+ return true;
2354
+ }
2355
+ }
2356
+ };
2357
+
2358
+ export { Logger, MigrationService, PluginBootstrapService, PluginService, apiTokens, cleanupRemovedCollections, collections, content, contentVersions, fullCollectionSync, getAvailableCollectionNames, getLogger, getManagedCollections, initLogger, insertCollectionSchema, insertContentSchema, insertLogConfigSchema, insertMediaSchema, insertPluginActivityLogSchema, insertPluginAssetSchema, insertPluginHookSchema, insertPluginRouteSchema, insertPluginSchema, insertSystemLogSchema, insertUserSchema, insertWorkflowHistorySchema, isCollectionManaged, loadCollectionConfig, loadCollectionConfigs, logConfig, media, pluginActivityLog, pluginAssets, pluginHooks, pluginRoutes, plugins, schema_exports, selectCollectionSchema, selectContentSchema, selectLogConfigSchema, selectMediaSchema, selectPluginActivityLogSchema, selectPluginAssetSchema, selectPluginHookSchema, selectPluginRouteSchema, selectPluginSchema, selectSystemLogSchema, selectUserSchema, selectWorkflowHistorySchema, syncCollection, syncCollections, systemLogs, users, validateCollectionConfig, workflowHistory };
2359
+ //# sourceMappingURL=chunk-CXZDAR6S.js.map
2360
+ //# sourceMappingURL=chunk-CXZDAR6S.js.map