@nodestackapp/server 0.0.0-stage → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +181 -2
- package/bin/nodebase.js +4 -0
- package/bin/nodestack.js +21 -0
- package/dist/NodeBase.d.ts +2 -0
- package/dist/NodeBase.d.ts.map +1 -0
- package/dist/NodeBase.js +8 -0
- package/dist/NodeBase.js.map +1 -0
- package/dist/NodeStack.d.ts +106 -0
- package/dist/NodeStack.d.ts.map +1 -0
- package/dist/NodeStack.js +298 -0
- package/dist/NodeStack.js.map +1 -0
- package/dist/admin/AdminUIBundler.d.ts +8 -0
- package/dist/admin/AdminUIBundler.d.ts.map +1 -0
- package/dist/admin/AdminUIBundler.js +103 -0
- package/dist/admin/AdminUIBundler.js.map +1 -0
- package/dist/admin/AdminUIService.d.ts +30 -0
- package/dist/admin/AdminUIService.d.ts.map +1 -0
- package/dist/admin/AdminUIService.js +210 -0
- package/dist/admin/AdminUIService.js.map +1 -0
- package/dist/admin/DocsService.d.ts +29 -0
- package/dist/admin/DocsService.d.ts.map +1 -0
- package/dist/admin/DocsService.js +564 -0
- package/dist/admin/DocsService.js.map +1 -0
- package/dist/admin/ui/css/analytics.css +325 -0
- package/dist/admin/ui/css/main.css +2015 -0
- package/dist/admin/ui/css/rules.css +264 -0
- package/dist/admin/ui/css/webhooks.css +336 -0
- package/dist/admin/ui/favicon.svg +17 -0
- package/dist/admin/ui/icon.svg +17 -0
- package/dist/admin/ui/index.html +14584 -0
- package/dist/admin/ui/js/analytics.js +624 -0
- package/dist/admin/ui/js/api.js +353 -0
- package/dist/admin/ui/js/app.js +263 -0
- package/dist/admin/ui/js/apps.js +436 -0
- package/dist/admin/ui/js/collections.js +436 -0
- package/dist/admin/ui/js/command-palette.js +600 -0
- package/dist/admin/ui/js/demo.js +559 -0
- package/dist/admin/ui/js/modals.js +2379 -0
- package/dist/admin/ui/js/plugin-tester.js +559 -0
- package/dist/admin/ui/js/plugins.js +768 -0
- package/dist/admin/ui/js/records.js +1270 -0
- package/dist/admin/ui/js/rules.js +775 -0
- package/dist/admin/ui/js/schema.js +290 -0
- package/dist/admin/ui/js/state.js +140 -0
- package/dist/admin/ui/js/views.js +714 -0
- package/dist/admin/ui/js/webhooks.js +1086 -0
- package/dist/analytics/AnalyticsService.d.ts +62 -0
- package/dist/analytics/AnalyticsService.d.ts.map +1 -0
- package/dist/analytics/AnalyticsService.js +196 -0
- package/dist/analytics/AnalyticsService.js.map +1 -0
- package/dist/apps/AppManager.d.ts +28 -0
- package/dist/apps/AppManager.d.ts.map +1 -0
- package/dist/apps/AppManager.js +211 -0
- package/dist/apps/AppManager.js.map +1 -0
- package/dist/apps/AppRegistry.d.ts +27 -0
- package/dist/apps/AppRegistry.d.ts.map +1 -0
- package/dist/apps/AppRegistry.js +220 -0
- package/dist/apps/AppRegistry.js.map +1 -0
- package/dist/apps/AppScope.d.ts +55 -0
- package/dist/apps/AppScope.d.ts.map +1 -0
- package/dist/apps/AppScope.js +295 -0
- package/dist/apps/AppScope.js.map +1 -0
- package/dist/apps/index.d.ts +5 -0
- package/dist/apps/index.d.ts.map +1 -0
- package/dist/apps/index.js +21 -0
- package/dist/apps/index.js.map +1 -0
- package/dist/apps/models/App.d.ts +29 -0
- package/dist/apps/models/App.d.ts.map +1 -0
- package/dist/apps/models/App.js +3 -0
- package/dist/apps/models/App.js.map +1 -0
- package/dist/audit/AuditLogService.d.ts +68 -0
- package/dist/audit/AuditLogService.d.ts.map +1 -0
- package/dist/audit/AuditLogService.js +243 -0
- package/dist/audit/AuditLogService.js.map +1 -0
- package/dist/auth/AuthService.d.ts +35 -0
- package/dist/auth/AuthService.d.ts.map +1 -0
- package/dist/auth/AuthService.js +276 -0
- package/dist/auth/AuthService.js.map +1 -0
- package/dist/cli/cli.d.ts +3 -0
- package/dist/cli/cli.d.ts.map +1 -0
- package/dist/cli/cli.js +477 -0
- package/dist/cli/cli.js.map +1 -0
- package/dist/core/config/ConfigService.d.ts +41 -0
- package/dist/core/config/ConfigService.d.ts.map +1 -0
- package/dist/core/config/ConfigService.js +139 -0
- package/dist/core/config/ConfigService.js.map +1 -0
- package/dist/core/config/EnvLoader.d.ts +7 -0
- package/dist/core/config/EnvLoader.d.ts.map +1 -0
- package/dist/core/config/EnvLoader.js +84 -0
- package/dist/core/config/EnvLoader.js.map +1 -0
- package/dist/core/container/Container.d.ts +34 -0
- package/dist/core/container/Container.d.ts.map +1 -0
- package/dist/core/container/Container.js +98 -0
- package/dist/core/container/Container.js.map +1 -0
- package/dist/core/container/Tokens.d.ts +40 -0
- package/dist/core/container/Tokens.d.ts.map +1 -0
- package/dist/core/container/Tokens.js +40 -0
- package/dist/core/container/Tokens.js.map +1 -0
- package/dist/core/errors/AppError.d.ts +24 -0
- package/dist/core/errors/AppError.d.ts.map +1 -0
- package/dist/core/errors/AppError.js +52 -0
- package/dist/core/errors/AppError.js.map +1 -0
- package/dist/core/events/EventBus.d.ts +45 -0
- package/dist/core/events/EventBus.d.ts.map +1 -0
- package/dist/core/events/EventBus.js +360 -0
- package/dist/core/events/EventBus.js.map +1 -0
- package/dist/core/events/types.d.ts +35 -0
- package/dist/core/events/types.d.ts.map +1 -0
- package/dist/core/events/types.js +3 -0
- package/dist/core/events/types.js.map +1 -0
- package/dist/core/maintenance/MaintenanceGate.d.ts +65 -0
- package/dist/core/maintenance/MaintenanceGate.d.ts.map +1 -0
- package/dist/core/maintenance/MaintenanceGate.js +162 -0
- package/dist/core/maintenance/MaintenanceGate.js.map +1 -0
- package/dist/core/plugins/PluginManager.d.ts +150 -0
- package/dist/core/plugins/PluginManager.d.ts.map +1 -0
- package/dist/core/plugins/PluginManager.js +1592 -0
- package/dist/core/plugins/PluginManager.js.map +1 -0
- package/dist/core/plugins/types.d.ts +170 -0
- package/dist/core/plugins/types.d.ts.map +1 -0
- package/dist/core/plugins/types.js +3 -0
- package/dist/core/plugins/types.js.map +1 -0
- package/dist/database/DatabaseService.d.ts +27 -0
- package/dist/database/DatabaseService.d.ts.map +1 -0
- package/dist/database/DatabaseService.js +97 -0
- package/dist/database/DatabaseService.js.map +1 -0
- package/dist/database/drivers/IDatabaseDriver.d.ts +17 -0
- package/dist/database/drivers/IDatabaseDriver.d.ts.map +1 -0
- package/dist/database/drivers/IDatabaseDriver.js +3 -0
- package/dist/database/drivers/IDatabaseDriver.js.map +1 -0
- package/dist/database/drivers/NodeSqliteDriver.d.ts +16 -0
- package/dist/database/drivers/NodeSqliteDriver.d.ts.map +1 -0
- package/dist/database/drivers/NodeSqliteDriver.js +115 -0
- package/dist/database/drivers/NodeSqliteDriver.js.map +1 -0
- package/dist/database/migrations/SystemMigrations.d.ts +5 -0
- package/dist/database/migrations/SystemMigrations.d.ts.map +1 -0
- package/dist/database/migrations/SystemMigrations.js +164 -0
- package/dist/database/migrations/SystemMigrations.js.map +1 -0
- package/dist/demo/DemoService.d.ts +115 -0
- package/dist/demo/DemoService.d.ts.map +1 -0
- package/dist/demo/DemoService.js +427 -0
- package/dist/demo/DemoService.js.map +1 -0
- package/dist/files/FileStorageService.d.ts +35 -0
- package/dist/files/FileStorageService.d.ts.map +1 -0
- package/dist/files/FileStorageService.js +126 -0
- package/dist/files/FileStorageService.js.map +1 -0
- package/dist/http/HttpServer.d.ts +61 -0
- package/dist/http/HttpServer.d.ts.map +1 -0
- package/dist/http/HttpServer.js +478 -0
- package/dist/http/HttpServer.js.map +1 -0
- package/dist/http/controllers/AnalyticsController.d.ts +9 -0
- package/dist/http/controllers/AnalyticsController.d.ts.map +1 -0
- package/dist/http/controllers/AnalyticsController.js +18 -0
- package/dist/http/controllers/AnalyticsController.js.map +1 -0
- package/dist/http/controllers/AppController.d.ts +29 -0
- package/dist/http/controllers/AppController.d.ts.map +1 -0
- package/dist/http/controllers/AppController.js +36 -0
- package/dist/http/controllers/AppController.js.map +1 -0
- package/dist/http/controllers/AuditLogController.d.ts +26 -0
- package/dist/http/controllers/AuditLogController.d.ts.map +1 -0
- package/dist/http/controllers/AuditLogController.js +32 -0
- package/dist/http/controllers/AuditLogController.js.map +1 -0
- package/dist/http/controllers/AuthController.d.ts +18 -0
- package/dist/http/controllers/AuthController.d.ts.map +1 -0
- package/dist/http/controllers/AuthController.js +84 -0
- package/dist/http/controllers/AuthController.js.map +1 -0
- package/dist/http/controllers/BaseController.d.ts +7 -0
- package/dist/http/controllers/BaseController.d.ts.map +1 -0
- package/dist/http/controllers/BaseController.js +20 -0
- package/dist/http/controllers/BaseController.js.map +1 -0
- package/dist/http/controllers/CollectionController.d.ts +44 -0
- package/dist/http/controllers/CollectionController.d.ts.map +1 -0
- package/dist/http/controllers/CollectionController.js +89 -0
- package/dist/http/controllers/CollectionController.js.map +1 -0
- package/dist/http/controllers/DemoController.d.ts +34 -0
- package/dist/http/controllers/DemoController.d.ts.map +1 -0
- package/dist/http/controllers/DemoController.js +55 -0
- package/dist/http/controllers/DemoController.js.map +1 -0
- package/dist/http/controllers/FileController.d.ts +29 -0
- package/dist/http/controllers/FileController.d.ts.map +1 -0
- package/dist/http/controllers/FileController.js +172 -0
- package/dist/http/controllers/FileController.js.map +1 -0
- package/dist/http/controllers/HealthController.d.ts +10 -0
- package/dist/http/controllers/HealthController.d.ts.map +1 -0
- package/dist/http/controllers/HealthController.js +28 -0
- package/dist/http/controllers/HealthController.js.map +1 -0
- package/dist/http/controllers/LogController.d.ts +15 -0
- package/dist/http/controllers/LogController.d.ts.map +1 -0
- package/dist/http/controllers/LogController.js +25 -0
- package/dist/http/controllers/LogController.js.map +1 -0
- package/dist/http/controllers/RealtimeController.d.ts +13 -0
- package/dist/http/controllers/RealtimeController.d.ts.map +1 -0
- package/dist/http/controllers/RealtimeController.js +54 -0
- package/dist/http/controllers/RealtimeController.js.map +1 -0
- package/dist/http/controllers/RecordController.d.ts +74 -0
- package/dist/http/controllers/RecordController.d.ts.map +1 -0
- package/dist/http/controllers/RecordController.js +202 -0
- package/dist/http/controllers/RecordController.js.map +1 -0
- package/dist/http/controllers/TemplateController.d.ts +29 -0
- package/dist/http/controllers/TemplateController.d.ts.map +1 -0
- package/dist/http/controllers/TemplateController.js +63 -0
- package/dist/http/controllers/TemplateController.js.map +1 -0
- package/dist/http/controllers/WebhookController.d.ts +78 -0
- package/dist/http/controllers/WebhookController.d.ts.map +1 -0
- package/dist/http/controllers/WebhookController.js +113 -0
- package/dist/http/controllers/WebhookController.js.map +1 -0
- package/dist/http/middleware/AppResolutionMiddleware.d.ts +8 -0
- package/dist/http/middleware/AppResolutionMiddleware.d.ts.map +1 -0
- package/dist/http/middleware/AppResolutionMiddleware.js +98 -0
- package/dist/http/middleware/AppResolutionMiddleware.js.map +1 -0
- package/dist/http/middleware/AuthMiddleware.d.ts +17 -0
- package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -0
- package/dist/http/middleware/AuthMiddleware.js +97 -0
- package/dist/http/middleware/AuthMiddleware.js.map +1 -0
- package/dist/http/middleware/ChaosMiddleware.d.ts +130 -0
- package/dist/http/middleware/ChaosMiddleware.d.ts.map +1 -0
- package/dist/http/middleware/ChaosMiddleware.js +434 -0
- package/dist/http/middleware/ChaosMiddleware.js.map +1 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +141 -0
- package/dist/index.js.map +1 -0
- package/dist/logger/LogService.d.ts +31 -0
- package/dist/logger/LogService.d.ts.map +1 -0
- package/dist/logger/LogService.js +104 -0
- package/dist/logger/LogService.js.map +1 -0
- package/dist/plugins/algolia.d.ts +76 -0
- package/dist/plugins/algolia.d.ts.map +1 -0
- package/dist/plugins/algolia.js +532 -0
- package/dist/plugins/algolia.js.map +1 -0
- package/dist/plugins/index.d.ts +6 -0
- package/dist/plugins/index.d.ts.map +1 -0
- package/dist/plugins/index.js +22 -0
- package/dist/plugins/index.js.map +1 -0
- package/dist/plugins/resend.d.ts +42 -0
- package/dist/plugins/resend.d.ts.map +1 -0
- package/dist/plugins/resend.js +335 -0
- package/dist/plugins/resend.js.map +1 -0
- package/dist/plugins/s3.d.ts +35 -0
- package/dist/plugins/s3.d.ts.map +1 -0
- package/dist/plugins/s3.js +425 -0
- package/dist/plugins/s3.js.map +1 -0
- package/dist/plugins/stripe.d.ts +45 -0
- package/dist/plugins/stripe.d.ts.map +1 -0
- package/dist/plugins/stripe.js +470 -0
- package/dist/plugins/stripe.js.map +1 -0
- package/dist/plugins/webhooks.d.ts +35 -0
- package/dist/plugins/webhooks.d.ts.map +1 -0
- package/dist/plugins/webhooks.js +415 -0
- package/dist/plugins/webhooks.js.map +1 -0
- package/dist/realtime/RealtimeService.d.ts +26 -0
- package/dist/realtime/RealtimeService.d.ts.map +1 -0
- package/dist/realtime/RealtimeService.js +165 -0
- package/dist/realtime/RealtimeService.js.map +1 -0
- package/dist/records/CsvHelper.d.ts +27 -0
- package/dist/records/CsvHelper.d.ts.map +1 -0
- package/dist/records/CsvHelper.js +195 -0
- package/dist/records/CsvHelper.js.map +1 -0
- package/dist/records/FakerEngine.d.ts +73 -0
- package/dist/records/FakerEngine.d.ts.map +1 -0
- package/dist/records/FakerEngine.js +644 -0
- package/dist/records/FakerEngine.js.map +1 -0
- package/dist/records/FilterCodec.d.ts +22 -0
- package/dist/records/FilterCodec.d.ts.map +1 -0
- package/dist/records/FilterCodec.js +57 -0
- package/dist/records/FilterCodec.js.map +1 -0
- package/dist/records/FtsService.d.ts +63 -0
- package/dist/records/FtsService.d.ts.map +1 -0
- package/dist/records/FtsService.js +310 -0
- package/dist/records/FtsService.js.map +1 -0
- package/dist/records/MockDataService.d.ts +31 -0
- package/dist/records/MockDataService.d.ts.map +1 -0
- package/dist/records/MockDataService.js +222 -0
- package/dist/records/MockDataService.js.map +1 -0
- package/dist/records/QueryFilterParser.d.ts +35 -0
- package/dist/records/QueryFilterParser.d.ts.map +1 -0
- package/dist/records/QueryFilterParser.js +262 -0
- package/dist/records/QueryFilterParser.js.map +1 -0
- package/dist/records/RecordService.d.ts +77 -0
- package/dist/records/RecordService.d.ts.map +1 -0
- package/dist/records/RecordService.js +686 -0
- package/dist/records/RecordService.js.map +1 -0
- package/dist/rules/RuleBuilder.d.ts +72 -0
- package/dist/rules/RuleBuilder.d.ts.map +1 -0
- package/dist/rules/RuleBuilder.js +383 -0
- package/dist/rules/RuleBuilder.js.map +1 -0
- package/dist/rules/RuleEngine.d.ts +28 -0
- package/dist/rules/RuleEngine.d.ts.map +1 -0
- package/dist/rules/RuleEngine.js +204 -0
- package/dist/rules/RuleEngine.js.map +1 -0
- package/dist/schema/OpenApiGenerator.d.ts +32 -0
- package/dist/schema/OpenApiGenerator.d.ts.map +1 -0
- package/dist/schema/OpenApiGenerator.js +1836 -0
- package/dist/schema/OpenApiGenerator.js.map +1 -0
- package/dist/schema/SchemaInferenceService.d.ts +82 -0
- package/dist/schema/SchemaInferenceService.d.ts.map +1 -0
- package/dist/schema/SchemaInferenceService.js +622 -0
- package/dist/schema/SchemaInferenceService.js.map +1 -0
- package/dist/schema/SchemaService.d.ts +33 -0
- package/dist/schema/SchemaService.d.ts.map +1 -0
- package/dist/schema/SchemaService.js +338 -0
- package/dist/schema/SchemaService.js.map +1 -0
- package/dist/schema/TypeGenerator.d.ts +19 -0
- package/dist/schema/TypeGenerator.d.ts.map +1 -0
- package/dist/schema/TypeGenerator.js +173 -0
- package/dist/schema/TypeGenerator.js.map +1 -0
- package/dist/schema/models/Collection.d.ts +44 -0
- package/dist/schema/models/Collection.d.ts.map +1 -0
- package/dist/schema/models/Collection.js +3 -0
- package/dist/schema/models/Collection.js.map +1 -0
- package/dist/schema/models/Field.d.ts +25 -0
- package/dist/schema/models/Field.d.ts.map +1 -0
- package/dist/schema/models/Field.js +3 -0
- package/dist/schema/models/Field.js.map +1 -0
- package/dist/templates/TemplateImageGenerator.d.ts +43 -0
- package/dist/templates/TemplateImageGenerator.d.ts.map +1 -0
- package/dist/templates/TemplateImageGenerator.js +350 -0
- package/dist/templates/TemplateImageGenerator.js.map +1 -0
- package/dist/templates/TemplateService.d.ts +31 -0
- package/dist/templates/TemplateService.d.ts.map +1 -0
- package/dist/templates/TemplateService.js +209 -0
- package/dist/templates/TemplateService.js.map +1 -0
- package/dist/templates/definitions/blog.d.ts +3 -0
- package/dist/templates/definitions/blog.d.ts.map +1 -0
- package/dist/templates/definitions/blog.js +386 -0
- package/dist/templates/definitions/blog.js.map +1 -0
- package/dist/templates/definitions/crm.d.ts +3 -0
- package/dist/templates/definitions/crm.d.ts.map +1 -0
- package/dist/templates/definitions/crm.js +456 -0
- package/dist/templates/definitions/crm.js.map +1 -0
- package/dist/templates/definitions/ecommerce.d.ts +3 -0
- package/dist/templates/definitions/ecommerce.d.ts.map +1 -0
- package/dist/templates/definitions/ecommerce.js +781 -0
- package/dist/templates/definitions/ecommerce.js.map +1 -0
- package/dist/templates/definitions/index.d.ts +7 -0
- package/dist/templates/definitions/index.d.ts.map +1 -0
- package/dist/templates/definitions/index.js +15 -0
- package/dist/templates/definitions/index.js.map +1 -0
- package/dist/templates/types.d.ts +65 -0
- package/dist/templates/types.d.ts.map +1 -0
- package/dist/templates/types.js +3 -0
- package/dist/templates/types.js.map +1 -0
- package/dist/webhooks/WebhookService.d.ts +149 -0
- package/dist/webhooks/WebhookService.d.ts.map +1 -0
- package/dist/webhooks/WebhookService.js +781 -0
- package/dist/webhooks/WebhookService.js.map +1 -0
- package/package.json +86 -4
|
@@ -0,0 +1,1592 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.PluginManager = exports.OFFICIAL_PLUGINS = void 0;
|
|
7
|
+
const find_my_way_1 = __importDefault(require("find-my-way"));
|
|
8
|
+
const Tokens_1 = require("../container/Tokens");
|
|
9
|
+
const AppError_1 = require("../errors/AppError");
|
|
10
|
+
const stripe_1 = require("../../plugins/stripe");
|
|
11
|
+
const s3_1 = require("../../plugins/s3");
|
|
12
|
+
const resend_1 = require("../../plugins/resend");
|
|
13
|
+
const webhooks_1 = require("../../plugins/webhooks");
|
|
14
|
+
const algolia_1 = require("../../plugins/algolia");
|
|
15
|
+
exports.OFFICIAL_PLUGINS = [
|
|
16
|
+
{
|
|
17
|
+
id: 'stripe',
|
|
18
|
+
name: 'stripe',
|
|
19
|
+
packageName: '@nodestackapp/plugin-stripe',
|
|
20
|
+
title: 'Stripe Payments',
|
|
21
|
+
category: 'Payments & Checkout',
|
|
22
|
+
description: 'Process checkout sessions, customer billing portals, and verify webhook signatures with audit logs.',
|
|
23
|
+
icon: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg>`,
|
|
24
|
+
badge: 'PAYMENTS',
|
|
25
|
+
collections: ['_stripe_payments'],
|
|
26
|
+
factory: () => (0, stripe_1.stripePlugin)(),
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
id: 's3-storage',
|
|
30
|
+
name: 's3-storage',
|
|
31
|
+
packageName: '@nodestackapp/plugin-s3',
|
|
32
|
+
title: 'S3 Cloud Storage',
|
|
33
|
+
category: 'Object Storage & CDN',
|
|
34
|
+
description: 'AWS S3, MinIO, and Cloudflare R2 object storage with SigV4 presigned upload URLs and file tracking.',
|
|
35
|
+
icon: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>`,
|
|
36
|
+
badge: 'STORAGE',
|
|
37
|
+
collections: ['_s3_uploads'],
|
|
38
|
+
factory: () => (0, s3_1.s3StoragePlugin)(),
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
id: 'resend',
|
|
42
|
+
name: 'resend',
|
|
43
|
+
packageName: '@nodestackapp/plugin-resend',
|
|
44
|
+
title: 'Resend Transactional Email',
|
|
45
|
+
category: 'Communications',
|
|
46
|
+
description: 'Transactional email delivery via Resend API with safe dry-run mode and delivery logs in SQLite.',
|
|
47
|
+
icon: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>`,
|
|
48
|
+
badge: 'EMAIL',
|
|
49
|
+
collections: ['_email_logs'],
|
|
50
|
+
factory: () => (0, resend_1.resendPlugin)(),
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
id: 'webhooks',
|
|
54
|
+
name: 'webhooks',
|
|
55
|
+
packageName: '@nodestackapp/plugin-webhooks',
|
|
56
|
+
title: 'Discord & Slack Webhooks',
|
|
57
|
+
category: 'Automation & Alerts',
|
|
58
|
+
description: 'Real-time outbound notifications to Discord and Slack channels on database mutations with payload logs.',
|
|
59
|
+
icon: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,
|
|
60
|
+
badge: 'WEBHOOKS',
|
|
61
|
+
collections: ['_webhook_logs'],
|
|
62
|
+
factory: () => (0, webhooks_1.webhookPlugin)(),
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
id: 'algolia',
|
|
66
|
+
name: 'algolia',
|
|
67
|
+
packageName: '@nodestackapp/plugin-algolia',
|
|
68
|
+
title: 'Algolia Search Sync',
|
|
69
|
+
category: 'Search & Discovery',
|
|
70
|
+
description: 'Realtime search indexing on record mutations, background sync queues, and batch re-indexing.',
|
|
71
|
+
icon: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>`,
|
|
72
|
+
badge: 'SEARCH',
|
|
73
|
+
collections: ['_algolia_sync_queue'],
|
|
74
|
+
factory: () => (0, algolia_1.algoliaPlugin)(),
|
|
75
|
+
},
|
|
76
|
+
];
|
|
77
|
+
class PluginManager {
|
|
78
|
+
app;
|
|
79
|
+
container;
|
|
80
|
+
plugins = new Map();
|
|
81
|
+
pendingInits = [];
|
|
82
|
+
anonymousCounter = 1;
|
|
83
|
+
registeredFunctions = new Set();
|
|
84
|
+
dynamicRouter = (0, find_my_way_1.default)({ defaultRoute: (_req, res) => res.end() });
|
|
85
|
+
dynamicRoutesMap = new Map();
|
|
86
|
+
pluginHookUnsubscribers = new Map();
|
|
87
|
+
scopedHookUnsubscribers = new Map();
|
|
88
|
+
scopedPlugins = new Map();
|
|
89
|
+
provisionedScopes = new Set();
|
|
90
|
+
runtimeLoadedOfficialPlugins = new Set();
|
|
91
|
+
constructor(app, container) {
|
|
92
|
+
this.app = app;
|
|
93
|
+
this.container = container;
|
|
94
|
+
this.initSettingsTable();
|
|
95
|
+
this.registerConfigRoutes();
|
|
96
|
+
if (this.app.adminUi && typeof this.app.adminUi.setCatalogGetter === 'function') {
|
|
97
|
+
this.app.adminUi.setCatalogGetter((db) => this.getOfficialCatalog(db));
|
|
98
|
+
}
|
|
99
|
+
if (this.app.adminUi && typeof this.app.adminUi.setNavItemsGetter === 'function') {
|
|
100
|
+
this.app.adminUi.setNavItemsGetter((db) => this.getScopedNavItems(db));
|
|
101
|
+
}
|
|
102
|
+
if (this.app.server && typeof this.app.server.setDynamicRouteHandler === 'function') {
|
|
103
|
+
this.app.server.setDynamicRouteHandler((req, reply) => this.handleDynamicRoute(req, reply));
|
|
104
|
+
}
|
|
105
|
+
if (this.app.server && typeof this.app.server.setDynamicRouteMatcher === 'function') {
|
|
106
|
+
this.app.server.setDynamicRouteMatcher((method, path) => this.findDynamicRoute(method, path));
|
|
107
|
+
}
|
|
108
|
+
if (this.app.apps && typeof this.app.apps.onScopeInit === 'function') {
|
|
109
|
+
this.app.apps.onScopeInit((scope) => {
|
|
110
|
+
this.provisionScope(scope);
|
|
111
|
+
if (typeof scope.onClose === 'function') {
|
|
112
|
+
scope.onClose(() => {
|
|
113
|
+
this.disposeScope(scope.app.slug);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
this.loadAutoEnabledPlugins();
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Install/use a plugin on the NodeStack instance
|
|
122
|
+
*/
|
|
123
|
+
use(pluginOrFn, targetScope) {
|
|
124
|
+
// 1. Normalize plugin
|
|
125
|
+
let plugin;
|
|
126
|
+
if (typeof pluginOrFn === 'function') {
|
|
127
|
+
if (this.registeredFunctions.has(pluginOrFn)) {
|
|
128
|
+
throw new Error('[PluginManager] This plugin function is already registered.');
|
|
129
|
+
}
|
|
130
|
+
const fnName = pluginOrFn.name || `plugin_${this.anonymousCounter++}`;
|
|
131
|
+
plugin = {
|
|
132
|
+
name: fnName,
|
|
133
|
+
register: pluginOrFn,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
plugin = pluginOrFn;
|
|
138
|
+
}
|
|
139
|
+
if (!plugin || typeof plugin !== 'object' || !plugin.name) {
|
|
140
|
+
throw new Error('[PluginManager] Invalid plugin provided: must have a valid name');
|
|
141
|
+
}
|
|
142
|
+
// 2. Check duplicate registration
|
|
143
|
+
if (this.plugins.has(plugin.name)) {
|
|
144
|
+
throw new Error(`[PluginManager] Plugin "${plugin.name}" is already registered. Duplicate plugin registrations are not permitted.`);
|
|
145
|
+
}
|
|
146
|
+
if (typeof pluginOrFn === 'function') {
|
|
147
|
+
this.registeredFunctions.add(pluginOrFn);
|
|
148
|
+
}
|
|
149
|
+
// 3. Validate dependencies
|
|
150
|
+
if (plugin.dependencies && plugin.dependencies.length > 0) {
|
|
151
|
+
for (const dep of plugin.dependencies) {
|
|
152
|
+
if (!this.plugins.has(dep)) {
|
|
153
|
+
throw new Error(`[PluginManager] Plugin "${plugin.name}" requires dependent plugin "${dep}" which has not been registered.`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// 4. Build Plugin Context
|
|
158
|
+
const context = {
|
|
159
|
+
app: this.app,
|
|
160
|
+
container: this.container,
|
|
161
|
+
tokens: Tokens_1.TOKENS,
|
|
162
|
+
config: this.app.config,
|
|
163
|
+
db: this.app.db,
|
|
164
|
+
schema: this.app.schema,
|
|
165
|
+
eventBus: this.app.eventBus,
|
|
166
|
+
adminUi: this.app.adminUi,
|
|
167
|
+
auth: {
|
|
168
|
+
requireAdmin: () => this.app.authMiddleware.requireAdmin(),
|
|
169
|
+
requireAdminOrInitial: () => this.app.authMiddleware.requireAdminOrInitialSetup(),
|
|
170
|
+
requireAuth: () => this.app.authMiddleware.requireAuth(),
|
|
171
|
+
},
|
|
172
|
+
router: {
|
|
173
|
+
get: (path, handler, options) => context.registerRoute('GET', path, handler, options),
|
|
174
|
+
post: (path, handler, options) => context.registerRoute('POST', path, handler, options),
|
|
175
|
+
patch: (path, handler, options) => context.registerRoute('PATCH', path, handler, options),
|
|
176
|
+
delete: (path, handler, options) => context.registerRoute('DELETE', path, handler, options),
|
|
177
|
+
put: (path, handler, options) => context.registerRoute('PUT', path, handler, options),
|
|
178
|
+
raw: this.app.server.app,
|
|
179
|
+
},
|
|
180
|
+
registerRoute: (method, path, handler, options = {}) => {
|
|
181
|
+
const fastify = this.app.server.app;
|
|
182
|
+
const resolvedOptions = this.resolveRouteOptions(options);
|
|
183
|
+
const routeHandler = async (req, reply) => {
|
|
184
|
+
if (!this.plugins.has(plugin.name)) {
|
|
185
|
+
return reply.status(404).send({
|
|
186
|
+
statusCode: 404,
|
|
187
|
+
error: 'Not Found',
|
|
188
|
+
message: `Route ${req.method}:${req.url} not found (plugin disabled)`,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
return handler.call(this.app.server.app, req, reply);
|
|
192
|
+
};
|
|
193
|
+
const registerBoth = (p) => {
|
|
194
|
+
this.registerDynamicRoute(method, p, routeHandler, resolvedOptions, plugin.name);
|
|
195
|
+
const isBooted = this.isFastifyBooted(fastify);
|
|
196
|
+
if (!isBooted) {
|
|
197
|
+
try {
|
|
198
|
+
const m = method.toLowerCase();
|
|
199
|
+
if (typeof fastify[m] === 'function') {
|
|
200
|
+
fastify[m](p, resolvedOptions, routeHandler);
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
fastify.route({
|
|
204
|
+
method: method,
|
|
205
|
+
url: p,
|
|
206
|
+
handler: routeHandler,
|
|
207
|
+
...resolvedOptions,
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
// Already booted fallback to dynamicRouter
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
registerBoth(path);
|
|
217
|
+
if (path.startsWith('/api/') && !path.startsWith('/api/apps/')) {
|
|
218
|
+
registerBoth(path.replace(/^\/api\//, '/api/apps/:appId/'));
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
registerHook: (event, handler, collection) => {
|
|
222
|
+
// Guard handler with the plugin's active status
|
|
223
|
+
const guardedHandler = async (...args) => {
|
|
224
|
+
if (!this.plugins.has(plugin.name)) {
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
return handler(...args);
|
|
228
|
+
};
|
|
229
|
+
let unsubscribe;
|
|
230
|
+
switch (event) {
|
|
231
|
+
case 'beforeCreate':
|
|
232
|
+
unsubscribe = this.app.eventBus.onRecordBeforeCreate(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
233
|
+
break;
|
|
234
|
+
case 'afterCreate':
|
|
235
|
+
unsubscribe = this.app.eventBus.onRecordAfterCreate(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
236
|
+
break;
|
|
237
|
+
case 'beforeUpdate':
|
|
238
|
+
unsubscribe = this.app.eventBus.onRecordBeforeUpdate(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
239
|
+
break;
|
|
240
|
+
case 'afterUpdate':
|
|
241
|
+
unsubscribe = this.app.eventBus.onRecordAfterUpdate(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
242
|
+
break;
|
|
243
|
+
case 'beforeDelete':
|
|
244
|
+
unsubscribe = this.app.eventBus.onRecordBeforeDelete(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
245
|
+
break;
|
|
246
|
+
case 'afterDelete':
|
|
247
|
+
unsubscribe = this.app.eventBus.onRecordAfterDelete(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
248
|
+
break;
|
|
249
|
+
case 'beforeServe':
|
|
250
|
+
unsubscribe = this.app.eventBus.onBeforeServe(guardedHandler);
|
|
251
|
+
break;
|
|
252
|
+
case 'afterServe':
|
|
253
|
+
unsubscribe = this.app.eventBus.onAfterServe(guardedHandler);
|
|
254
|
+
break;
|
|
255
|
+
default:
|
|
256
|
+
unsubscribe = this.app.eventBus.on(event, guardedHandler);
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
if (!this.pluginHookUnsubscribers.has(plugin.name)) {
|
|
260
|
+
this.pluginHookUnsubscribers.set(plugin.name, []);
|
|
261
|
+
}
|
|
262
|
+
this.pluginHookUnsubscribers.get(plugin.name).push(unsubscribe);
|
|
263
|
+
},
|
|
264
|
+
registerSystemCollection: (dto) => {
|
|
265
|
+
return this.app.schema.registerSystemCollection(dto);
|
|
266
|
+
},
|
|
267
|
+
registerAdminNav: (item) => {
|
|
268
|
+
this.app.adminUi.registerNavItem(item);
|
|
269
|
+
},
|
|
270
|
+
getService: (token) => {
|
|
271
|
+
return this.container.get(token);
|
|
272
|
+
},
|
|
273
|
+
bindService: (token, instance) => {
|
|
274
|
+
this.container.bindInstance(token, instance);
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
// 5. Execute Declarative Registrations
|
|
278
|
+
const scopeToProvision = targetScope || this.app.defaultApp;
|
|
279
|
+
if (scopeToProvision) {
|
|
280
|
+
this.provisionPluginForScope(plugin, scopeToProvision);
|
|
281
|
+
}
|
|
282
|
+
if (plugin.routes && Array.isArray(plugin.routes)) {
|
|
283
|
+
for (const route of plugin.routes) {
|
|
284
|
+
const routeOpts = { ...(route.options || {}) };
|
|
285
|
+
if (route.auth && !routeOpts.auth) {
|
|
286
|
+
routeOpts.auth = route.auth;
|
|
287
|
+
}
|
|
288
|
+
context.registerRoute(route.method, route.path, route.handler, routeOpts);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
if (plugin.adminNavItems && Array.isArray(plugin.adminNavItems)) {
|
|
292
|
+
for (const navItem of plugin.adminNavItems) {
|
|
293
|
+
context.registerAdminNav(navItem);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
// 6. Execute Lifecycle Hooks
|
|
297
|
+
if (typeof plugin.register === 'function') {
|
|
298
|
+
const regRes = plugin.register(context);
|
|
299
|
+
if (regRes instanceof Promise) {
|
|
300
|
+
this.pendingInits.push(regRes.catch((err) => {
|
|
301
|
+
const record = this.plugins.get(plugin.name);
|
|
302
|
+
if (record) {
|
|
303
|
+
record.status = 'error';
|
|
304
|
+
record.error = err;
|
|
305
|
+
}
|
|
306
|
+
console.error(`[PluginManager] Error in register hook for "${plugin.name}":`, err);
|
|
307
|
+
}));
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
if (typeof plugin.init === 'function') {
|
|
311
|
+
const initPromise = (async () => {
|
|
312
|
+
try {
|
|
313
|
+
await plugin.init(context);
|
|
314
|
+
const record = this.plugins.get(plugin.name);
|
|
315
|
+
if (record) {
|
|
316
|
+
record.status = 'initialized';
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
catch (err) {
|
|
320
|
+
const record = this.plugins.get(plugin.name);
|
|
321
|
+
if (record) {
|
|
322
|
+
record.status = 'error';
|
|
323
|
+
record.error = err instanceof Error ? err : new Error(String(err));
|
|
324
|
+
}
|
|
325
|
+
console.error(`[PluginManager] Error initializing plugin "${plugin.name}":`, err);
|
|
326
|
+
}
|
|
327
|
+
})();
|
|
328
|
+
this.pendingInits.push(initPromise);
|
|
329
|
+
}
|
|
330
|
+
else {
|
|
331
|
+
const record = this.plugins.get(plugin.name);
|
|
332
|
+
if (record) {
|
|
333
|
+
record.status = 'initialized';
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
// 7. Register Serve Hooks if present
|
|
337
|
+
if (typeof plugin.onBeforeServe === 'function') {
|
|
338
|
+
const unsub = this.app.eventBus.onBeforeServe(async (ctx) => {
|
|
339
|
+
if (!this.plugins.has(plugin.name))
|
|
340
|
+
return;
|
|
341
|
+
return plugin.onBeforeServe(ctx);
|
|
342
|
+
});
|
|
343
|
+
if (!this.pluginHookUnsubscribers.has(plugin.name)) {
|
|
344
|
+
this.pluginHookUnsubscribers.set(plugin.name, []);
|
|
345
|
+
}
|
|
346
|
+
this.pluginHookUnsubscribers.get(plugin.name).push(unsub);
|
|
347
|
+
}
|
|
348
|
+
if (typeof plugin.onAfterServe === 'function') {
|
|
349
|
+
const unsub = this.app.eventBus.onAfterServe(async (ctx) => {
|
|
350
|
+
if (!this.plugins.has(plugin.name))
|
|
351
|
+
return;
|
|
352
|
+
return plugin.onAfterServe(ctx);
|
|
353
|
+
});
|
|
354
|
+
if (!this.pluginHookUnsubscribers.has(plugin.name)) {
|
|
355
|
+
this.pluginHookUnsubscribers.set(plugin.name, []);
|
|
356
|
+
}
|
|
357
|
+
this.pluginHookUnsubscribers.get(plugin.name).push(unsub);
|
|
358
|
+
}
|
|
359
|
+
// 8. Register Admin UI Plugin Metadata
|
|
360
|
+
this.app.adminUi.registerPluginMeta({
|
|
361
|
+
name: plugin.name,
|
|
362
|
+
version: plugin.version,
|
|
363
|
+
description: plugin.description,
|
|
364
|
+
hasConfig: Boolean(plugin.configSchema?.fields && plugin.configSchema.fields.length > 0),
|
|
365
|
+
});
|
|
366
|
+
// 9. Store plugin record
|
|
367
|
+
this.plugins.set(plugin.name, {
|
|
368
|
+
name: plugin.name,
|
|
369
|
+
plugin,
|
|
370
|
+
context,
|
|
371
|
+
status: 'registered',
|
|
372
|
+
});
|
|
373
|
+
// 10. If plugin defines configSchema and onConfigUpdate, hydrate with effective initial settings
|
|
374
|
+
if (plugin.configSchema?.fields && typeof plugin.onConfigUpdate === 'function') {
|
|
375
|
+
try {
|
|
376
|
+
const effective = this.getEffectiveConfig(plugin.name);
|
|
377
|
+
const initialSync = plugin.onConfigUpdate(effective);
|
|
378
|
+
if (initialSync instanceof Promise) {
|
|
379
|
+
this.pendingInits.push(initialSync.catch(() => { }));
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
catch { }
|
|
383
|
+
}
|
|
384
|
+
return this;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Ensures that all asynchronous plugin initialization is resolved.
|
|
388
|
+
* Invoked automatically by `app.start()` before the server binds and listens.
|
|
389
|
+
*/
|
|
390
|
+
async ensureInitialized() {
|
|
391
|
+
if (this.pendingInits.length > 0) {
|
|
392
|
+
const inits = [...this.pendingInits];
|
|
393
|
+
this.pendingInits = [];
|
|
394
|
+
await Promise.all(inits);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Check if a plugin is registered
|
|
399
|
+
*/
|
|
400
|
+
hasPlugin(name, db) {
|
|
401
|
+
if (!db || db === this.app.db) {
|
|
402
|
+
return this.plugins.has(name);
|
|
403
|
+
}
|
|
404
|
+
return this.isPluginEnabledInDb(name, db);
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Get a registered plugin by name
|
|
408
|
+
*/
|
|
409
|
+
getPlugin(name) {
|
|
410
|
+
return this.plugins.get(name)?.plugin;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Get all registered plugins
|
|
414
|
+
*/
|
|
415
|
+
getAllPlugins() {
|
|
416
|
+
return Array.from(this.plugins.values()).map((r) => r.plugin);
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Get plugin metadata for UI and telemetry
|
|
420
|
+
*/
|
|
421
|
+
getPluginsMetadata() {
|
|
422
|
+
return Array.from(this.plugins.values()).map((r) => ({
|
|
423
|
+
name: r.plugin.name,
|
|
424
|
+
version: r.plugin.version,
|
|
425
|
+
description: r.plugin.description,
|
|
426
|
+
}));
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Resolve authentication policy into Fastify preHandler middleware
|
|
430
|
+
*/
|
|
431
|
+
resolveRouteOptions(rawOptions) {
|
|
432
|
+
const options = { ...(rawOptions || {}) };
|
|
433
|
+
const authPolicy = options.auth || (options.requireAdmin ? 'admin' : undefined);
|
|
434
|
+
let authPreHandler = null;
|
|
435
|
+
if (authPolicy === 'admin') {
|
|
436
|
+
authPreHandler = this.app.authMiddleware.requireAdmin();
|
|
437
|
+
}
|
|
438
|
+
else if (authPolicy === 'adminOrInitial') {
|
|
439
|
+
authPreHandler = this.app.authMiddleware.requireAdminOrInitialSetup();
|
|
440
|
+
}
|
|
441
|
+
else if (authPolicy === 'auth' || authPolicy === 'user') {
|
|
442
|
+
authPreHandler = this.app.authMiddleware.requireAuth();
|
|
443
|
+
}
|
|
444
|
+
if (authPreHandler) {
|
|
445
|
+
if (options.preHandler) {
|
|
446
|
+
const existing = Array.isArray(options.preHandler) ? options.preHandler : [options.preHandler];
|
|
447
|
+
options.preHandler = [authPreHandler, ...existing];
|
|
448
|
+
}
|
|
449
|
+
else {
|
|
450
|
+
options.preHandler = authPreHandler;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
delete options.auth;
|
|
454
|
+
delete options.requireAdmin;
|
|
455
|
+
return options;
|
|
456
|
+
}
|
|
457
|
+
isFastifyBooted(fastify) {
|
|
458
|
+
if (!fastify)
|
|
459
|
+
return false;
|
|
460
|
+
if (fastify.server && fastify.server.listening)
|
|
461
|
+
return true;
|
|
462
|
+
for (const sym of Object.getOwnPropertySymbols(fastify)) {
|
|
463
|
+
if (sym.description === 'fastify.state') {
|
|
464
|
+
const state = fastify[sym];
|
|
465
|
+
if (state && (state.ready || state.started || state.listening || state.booting)) {
|
|
466
|
+
return true;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return false;
|
|
471
|
+
}
|
|
472
|
+
findDynamicRoute(method, path) {
|
|
473
|
+
const match = this.dynamicRouter.find(method.toUpperCase(), path);
|
|
474
|
+
if (!match)
|
|
475
|
+
return null;
|
|
476
|
+
return (match.store || match.handler?.routeData || match.handler);
|
|
477
|
+
}
|
|
478
|
+
registerDynamicRoute(method, path, handler, options = {}, pluginName) {
|
|
479
|
+
// If route options contain unsupported Fastify options that cannot be honored at runtime,
|
|
480
|
+
// explicitly reject them so developers get fast, clear feedback
|
|
481
|
+
const isBooted = this.isFastifyBooted(this.app?.server?.app);
|
|
482
|
+
if (isBooted) {
|
|
483
|
+
const unsupportedOptions = ['constraints'].filter((key) => key in options);
|
|
484
|
+
if (unsupportedOptions.length > 0) {
|
|
485
|
+
throw new Error(`[PluginManager] Unsupported route option(s) [${unsupportedOptions.join(', ')}] for runtime route "${method} ${path}". Runtime routes cannot use these options.`);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
const m = method.toUpperCase();
|
|
489
|
+
const routeKey = `${m}:${path}`;
|
|
490
|
+
const item = {
|
|
491
|
+
method: m,
|
|
492
|
+
path,
|
|
493
|
+
handler,
|
|
494
|
+
options,
|
|
495
|
+
preParsing: options.preParsing,
|
|
496
|
+
preValidation: options.preValidation,
|
|
497
|
+
preHandler: options.preHandler,
|
|
498
|
+
preSerialization: options.preSerialization,
|
|
499
|
+
onSend: options.onSend,
|
|
500
|
+
onResponse: options.onResponse,
|
|
501
|
+
onError: options.onError,
|
|
502
|
+
schema: options.schema,
|
|
503
|
+
pluginName,
|
|
504
|
+
};
|
|
505
|
+
handler.routeData = item;
|
|
506
|
+
this.dynamicRoutesMap.set(routeKey, item);
|
|
507
|
+
try {
|
|
508
|
+
this.dynamicRouter.on(m, path, { store: item }, handler, item);
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
// route may already be registered
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
async handleDynamicRoute(req, reply) {
|
|
515
|
+
const urlPath = req.url.split('?')[0];
|
|
516
|
+
const match = this.dynamicRouter.find(req.method, urlPath);
|
|
517
|
+
if (!match)
|
|
518
|
+
return false;
|
|
519
|
+
const routeData = (match.store || match.handler?.routeData || match.handler);
|
|
520
|
+
const handler = typeof routeData?.handler === 'function'
|
|
521
|
+
? routeData.handler
|
|
522
|
+
: (typeof match.handler === 'function' ? match.handler : null);
|
|
523
|
+
if (!handler)
|
|
524
|
+
return false;
|
|
525
|
+
req.params = { ...(req.params || {}), ...match.params };
|
|
526
|
+
try {
|
|
527
|
+
// 1. preValidation lifecycle hooks
|
|
528
|
+
if (routeData.preValidation) {
|
|
529
|
+
const preValidators = Array.isArray(routeData.preValidation) ? routeData.preValidation : [routeData.preValidation];
|
|
530
|
+
for (const pv of preValidators) {
|
|
531
|
+
await pv.call(this.app.server.app, req, reply);
|
|
532
|
+
if (reply.sent)
|
|
533
|
+
return true;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
// 2. preHandler lifecycle hooks
|
|
537
|
+
if (routeData.preHandler) {
|
|
538
|
+
const handlers = Array.isArray(routeData.preHandler) ? routeData.preHandler : [routeData.preHandler];
|
|
539
|
+
for (const ph of handlers) {
|
|
540
|
+
await ph.call(this.app.server.app, req, reply);
|
|
541
|
+
if (reply.sent)
|
|
542
|
+
return true;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
// 3. Route Handler
|
|
546
|
+
let result = await handler.call(this.app.server.app, req, reply);
|
|
547
|
+
// 4. preSerialization lifecycle hooks
|
|
548
|
+
if (!reply.sent && result !== undefined && routeData.preSerialization) {
|
|
549
|
+
const preSerializers = Array.isArray(routeData.preSerialization) ? routeData.preSerialization : [routeData.preSerialization];
|
|
550
|
+
for (const ps of preSerializers) {
|
|
551
|
+
result = await ps.call(this.app.server.app, req, reply, result);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
// 5. onSend lifecycle hooks
|
|
555
|
+
if (!reply.sent && result !== undefined && routeData.onSend) {
|
|
556
|
+
const onSends = Array.isArray(routeData.onSend) ? routeData.onSend : [routeData.onSend];
|
|
557
|
+
for (const os of onSends) {
|
|
558
|
+
result = await os.call(this.app.server.app, req, reply, result);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
if (!reply.sent && result !== undefined) {
|
|
562
|
+
reply.send(result);
|
|
563
|
+
}
|
|
564
|
+
// 6. onResponse lifecycle hooks
|
|
565
|
+
if (routeData.onResponse) {
|
|
566
|
+
const onResponses = Array.isArray(routeData.onResponse) ? routeData.onResponse : [routeData.onResponse];
|
|
567
|
+
for (const or of onResponses) {
|
|
568
|
+
await or.call(this.app.server.app, req, reply);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
return true;
|
|
572
|
+
}
|
|
573
|
+
catch (err) {
|
|
574
|
+
if (routeData.onError) {
|
|
575
|
+
const onErrors = Array.isArray(routeData.onError) ? routeData.onError : [routeData.onError];
|
|
576
|
+
for (const oe of onErrors) {
|
|
577
|
+
await oe.call(this.app.server.app, req, reply, err);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
throw err;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
removeDynamicRoutesForPlugin(pluginName) {
|
|
584
|
+
for (const [key, item] of Array.from(this.dynamicRoutesMap.entries())) {
|
|
585
|
+
if (item.pluginName === pluginName) {
|
|
586
|
+
this.dynamicRoutesMap.delete(key);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
this.dynamicRouter.reset();
|
|
590
|
+
for (const item of this.dynamicRoutesMap.values()) {
|
|
591
|
+
try {
|
|
592
|
+
item.handler.routeData = item;
|
|
593
|
+
this.dynamicRouter.on(item.method, item.path, { store: item }, item.handler, item);
|
|
594
|
+
}
|
|
595
|
+
catch { }
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
removeHooksForPlugin(pluginName) {
|
|
599
|
+
const unsubs = this.pluginHookUnsubscribers.get(pluginName);
|
|
600
|
+
if (unsubs) {
|
|
601
|
+
for (const unsub of unsubs) {
|
|
602
|
+
try {
|
|
603
|
+
unsub();
|
|
604
|
+
}
|
|
605
|
+
catch { }
|
|
606
|
+
}
|
|
607
|
+
this.pluginHookUnsubscribers.delete(pluginName);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Return application-scoped navigation items for installed plugins and active configurations
|
|
612
|
+
*/
|
|
613
|
+
getScopedNavItems(db) {
|
|
614
|
+
const targetDb = db || this.app.db;
|
|
615
|
+
const catalog = this.getOfficialCatalog(targetDb);
|
|
616
|
+
const navItems = [];
|
|
617
|
+
for (const record of this.plugins.values()) {
|
|
618
|
+
const plugin = record.plugin;
|
|
619
|
+
const official = catalog.find((c) => c.name === plugin.name || c.id === plugin.name);
|
|
620
|
+
// If it is an official catalog plugin and NOT installed in targetDb, omit from sidebar nav
|
|
621
|
+
if (official && !official.isInstalled) {
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
let effectiveConfig = {};
|
|
625
|
+
try {
|
|
626
|
+
effectiveConfig = this.getEffectiveConfig(plugin.name, targetDb);
|
|
627
|
+
}
|
|
628
|
+
catch {
|
|
629
|
+
effectiveConfig = {};
|
|
630
|
+
}
|
|
631
|
+
if (typeof plugin.buildAdminNavItems === 'function') {
|
|
632
|
+
const items = plugin.buildAdminNavItems(effectiveConfig, record.context);
|
|
633
|
+
if (Array.isArray(items)) {
|
|
634
|
+
navItems.push(...items);
|
|
635
|
+
continue;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
if (plugin.adminNavItems) {
|
|
639
|
+
navItems.push(...plugin.adminNavItems);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
return navItems;
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* Return catalog of official first-party extensions and their installation status
|
|
646
|
+
*/
|
|
647
|
+
getOfficialCatalog(db) {
|
|
648
|
+
const targetDb = db || this.app.db;
|
|
649
|
+
const enabledMap = new Map();
|
|
650
|
+
try {
|
|
651
|
+
this.initSettingsTable(targetDb);
|
|
652
|
+
if (targetDb && typeof targetDb.all === 'function') {
|
|
653
|
+
const rows = targetDb.all('SELECT pluginName, settings FROM _plugin_settings');
|
|
654
|
+
for (const r of rows) {
|
|
655
|
+
try {
|
|
656
|
+
const s = JSON.parse(r.settings);
|
|
657
|
+
if (s && s._enabled !== undefined) {
|
|
658
|
+
enabledMap.set(r.pluginName, Boolean(s._enabled));
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
catch { }
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
catch { }
|
|
666
|
+
return exports.OFFICIAL_PLUGINS.map((def) => {
|
|
667
|
+
const isEnabledInDb = enabledMap.get(def.name);
|
|
668
|
+
let isInstalled;
|
|
669
|
+
if (isEnabledInDb !== undefined) {
|
|
670
|
+
isInstalled = isEnabledInDb;
|
|
671
|
+
}
|
|
672
|
+
else if (this.runtimeLoadedOfficialPlugins.has(def.name)) {
|
|
673
|
+
isInstalled = false;
|
|
674
|
+
}
|
|
675
|
+
else if (targetDb !== this.app.db) {
|
|
676
|
+
isInstalled = false;
|
|
677
|
+
}
|
|
678
|
+
else {
|
|
679
|
+
isInstalled = this.plugins.has(def.name);
|
|
680
|
+
}
|
|
681
|
+
return {
|
|
682
|
+
id: def.id,
|
|
683
|
+
name: def.name,
|
|
684
|
+
packageName: def.packageName,
|
|
685
|
+
title: def.title,
|
|
686
|
+
category: def.category,
|
|
687
|
+
description: def.description,
|
|
688
|
+
icon: def.icon,
|
|
689
|
+
badge: def.badge,
|
|
690
|
+
isInstalled,
|
|
691
|
+
hasConfig: isInstalled ? Boolean(this.plugins.get(def.name)?.plugin.configSchema?.fields?.length) : true,
|
|
692
|
+
collections: def.collections,
|
|
693
|
+
};
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* 1-Click enable official first-party plugin at runtime
|
|
698
|
+
*/
|
|
699
|
+
async enableOfficialPlugin(id, scopeOrDb) {
|
|
700
|
+
let targetScope;
|
|
701
|
+
let targetDb;
|
|
702
|
+
if (scopeOrDb && 'schema' in scopeOrDb && 'db' in scopeOrDb && 'app' in scopeOrDb) {
|
|
703
|
+
targetScope = scopeOrDb;
|
|
704
|
+
targetDb = targetScope.db;
|
|
705
|
+
}
|
|
706
|
+
else if (scopeOrDb && 'get' in scopeOrDb && 'run' in scopeOrDb) {
|
|
707
|
+
targetDb = scopeOrDb;
|
|
708
|
+
targetScope = this.findScopeForDb(targetDb);
|
|
709
|
+
}
|
|
710
|
+
else {
|
|
711
|
+
targetScope = this.app.defaultApp;
|
|
712
|
+
targetDb = this.app.db;
|
|
713
|
+
}
|
|
714
|
+
const def = exports.OFFICIAL_PLUGINS.find((p) => p.id === id || p.name === id);
|
|
715
|
+
if (!def) {
|
|
716
|
+
throw new AppError_1.NotFoundError(`Official plugin "${id}" not found in catalog`);
|
|
717
|
+
}
|
|
718
|
+
this.runtimeLoadedOfficialPlugins.add(def.name);
|
|
719
|
+
let plugin;
|
|
720
|
+
if (!this.plugins.has(def.name)) {
|
|
721
|
+
plugin = def.factory();
|
|
722
|
+
this.use(plugin, targetScope || this.app.defaultApp);
|
|
723
|
+
await this.ensureInitialized();
|
|
724
|
+
}
|
|
725
|
+
else {
|
|
726
|
+
plugin = this.plugins.get(def.name).plugin;
|
|
727
|
+
if (targetScope) {
|
|
728
|
+
this.provisionPluginForScope(plugin, targetScope);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
this.initSettingsTable(targetDb);
|
|
732
|
+
let dbSettings = {};
|
|
733
|
+
try {
|
|
734
|
+
const row = targetDb.get('SELECT settings FROM _plugin_settings WHERE pluginName = ?', [def.name]);
|
|
735
|
+
if (row?.settings) {
|
|
736
|
+
dbSettings = JSON.parse(row.settings);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
catch { }
|
|
740
|
+
dbSettings._enabled = true;
|
|
741
|
+
const now = new Date().toISOString();
|
|
742
|
+
targetDb.prepare(`
|
|
743
|
+
INSERT INTO _plugin_settings (pluginName, settings, updatedAt)
|
|
744
|
+
VALUES (?, ?, ?)
|
|
745
|
+
ON CONFLICT(pluginName) DO UPDATE SET settings=excluded.settings, updatedAt=excluded.updatedAt
|
|
746
|
+
`).run(def.name, JSON.stringify(dbSettings), now);
|
|
747
|
+
return this.getPluginConfig(def.name, targetDb);
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Deactivate official first-party plugin
|
|
751
|
+
*/
|
|
752
|
+
async disableOfficialPlugin(id, scopeOrDb) {
|
|
753
|
+
let targetScope;
|
|
754
|
+
let targetDb;
|
|
755
|
+
if (scopeOrDb && 'schema' in scopeOrDb && 'db' in scopeOrDb && 'app' in scopeOrDb) {
|
|
756
|
+
targetScope = scopeOrDb;
|
|
757
|
+
targetDb = targetScope.db;
|
|
758
|
+
}
|
|
759
|
+
else if (scopeOrDb && 'get' in scopeOrDb && 'run' in scopeOrDb) {
|
|
760
|
+
targetDb = scopeOrDb;
|
|
761
|
+
targetScope = this.findScopeForDb(targetDb);
|
|
762
|
+
}
|
|
763
|
+
else {
|
|
764
|
+
targetScope = this.app.defaultApp;
|
|
765
|
+
targetDb = this.app.db;
|
|
766
|
+
}
|
|
767
|
+
const def = exports.OFFICIAL_PLUGINS.find((p) => p.id === id || p.name === id);
|
|
768
|
+
const name = def ? def.name : id;
|
|
769
|
+
this.initSettingsTable(targetDb);
|
|
770
|
+
let dbSettings = {};
|
|
771
|
+
try {
|
|
772
|
+
const row = targetDb.get('SELECT settings FROM _plugin_settings WHERE pluginName = ?', [name]);
|
|
773
|
+
if (row?.settings) {
|
|
774
|
+
dbSettings = JSON.parse(row.settings);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
catch { }
|
|
778
|
+
dbSettings._enabled = false;
|
|
779
|
+
const now = new Date().toISOString();
|
|
780
|
+
targetDb.prepare(`
|
|
781
|
+
INSERT INTO _plugin_settings (pluginName, settings, updatedAt)
|
|
782
|
+
VALUES (?, ?, ?)
|
|
783
|
+
ON CONFLICT(pluginName) DO UPDATE SET settings=excluded.settings, updatedAt=excluded.updatedAt
|
|
784
|
+
`).run(name, JSON.stringify(dbSettings), now);
|
|
785
|
+
if (targetScope) {
|
|
786
|
+
this.removeScopedHooks(targetScope.app.slug, name);
|
|
787
|
+
this.provisionedScopes.delete(`${targetScope.app.slug}:${name}`);
|
|
788
|
+
}
|
|
789
|
+
const isEnabledInAnyOtherApp = this.isPluginEnabledInAnyApp(name, targetDb);
|
|
790
|
+
if (!isEnabledInAnyOtherApp) {
|
|
791
|
+
const record = this.plugins.get(name);
|
|
792
|
+
if (record) {
|
|
793
|
+
if (typeof record.plugin.onDestroy === 'function') {
|
|
794
|
+
try {
|
|
795
|
+
await record.plugin.onDestroy(record.context);
|
|
796
|
+
}
|
|
797
|
+
catch (e) {
|
|
798
|
+
console.error(`[PluginManager] Error destroying plugin "${name}":`, e);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
if (record.plugin.adminNavItems) {
|
|
802
|
+
for (const item of record.plugin.adminNavItems) {
|
|
803
|
+
this.app.adminUi.removeNavItem(item.id);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
this.app.adminUi.removePluginMeta(name);
|
|
807
|
+
this.removeHooksForPlugin(name);
|
|
808
|
+
this.removeDynamicRoutesForPlugin(name);
|
|
809
|
+
this.plugins.delete(name);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
findScopeForDb(db) {
|
|
814
|
+
if (!db || db === this.app.db) {
|
|
815
|
+
return this.app.defaultApp;
|
|
816
|
+
}
|
|
817
|
+
if (this.app.apps) {
|
|
818
|
+
if (typeof this.app.apps.findScopeByDb === 'function') {
|
|
819
|
+
const found = this.app.apps.findScopeByDb(db);
|
|
820
|
+
if (found)
|
|
821
|
+
return found;
|
|
822
|
+
}
|
|
823
|
+
for (const app of this.app.apps.registry.getAllApps()) {
|
|
824
|
+
try {
|
|
825
|
+
const scope = this.app.apps.get(app.slug);
|
|
826
|
+
if (scope && (scope.db === db || scope.db?.driver === db?.driver)) {
|
|
827
|
+
return scope;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
catch { }
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
return undefined;
|
|
834
|
+
}
|
|
835
|
+
isPluginEnabledInDb(pluginName, db) {
|
|
836
|
+
const targetDb = db || this.app.db;
|
|
837
|
+
try {
|
|
838
|
+
this.initSettingsTable(targetDb);
|
|
839
|
+
const row = targetDb.get('SELECT settings FROM _plugin_settings WHERE pluginName = ?', [pluginName]);
|
|
840
|
+
if (!row || !row.settings) {
|
|
841
|
+
if (targetDb === this.app.db) {
|
|
842
|
+
return this.plugins.has(pluginName) && !this.runtimeLoadedOfficialPlugins.has(pluginName);
|
|
843
|
+
}
|
|
844
|
+
return false;
|
|
845
|
+
}
|
|
846
|
+
const settings = JSON.parse(row.settings);
|
|
847
|
+
if (settings && settings._enabled !== undefined) {
|
|
848
|
+
return Boolean(settings._enabled);
|
|
849
|
+
}
|
|
850
|
+
if (targetDb === this.app.db) {
|
|
851
|
+
return this.plugins.has(pluginName) && !this.runtimeLoadedOfficialPlugins.has(pluginName);
|
|
852
|
+
}
|
|
853
|
+
return false;
|
|
854
|
+
}
|
|
855
|
+
catch {
|
|
856
|
+
return targetDb === this.app.db && this.plugins.has(pluginName);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
isPluginEnabledInAnyApp(pluginName, excludeDb) {
|
|
860
|
+
if (this.app.db !== excludeDb && this.isPluginEnabledInDb(pluginName, this.app.db)) {
|
|
861
|
+
return true;
|
|
862
|
+
}
|
|
863
|
+
if (this.app.apps) {
|
|
864
|
+
for (const app of this.app.apps.registry.getAllApps()) {
|
|
865
|
+
try {
|
|
866
|
+
const scope = this.app.apps.get(app.slug);
|
|
867
|
+
if (scope && scope.db !== excludeDb && this.isPluginEnabledInDb(pluginName, scope.db)) {
|
|
868
|
+
return true;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
catch { }
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return false;
|
|
875
|
+
}
|
|
876
|
+
getScopedHookKey(appSlug, pluginName) {
|
|
877
|
+
return `${appSlug}:${pluginName}`;
|
|
878
|
+
}
|
|
879
|
+
addScopedHookUnsubscriber(appSlug, pluginName, unsub) {
|
|
880
|
+
const key = this.getScopedHookKey(appSlug, pluginName);
|
|
881
|
+
if (!this.scopedHookUnsubscribers.has(key)) {
|
|
882
|
+
this.scopedHookUnsubscribers.set(key, []);
|
|
883
|
+
}
|
|
884
|
+
this.scopedHookUnsubscribers.get(key).push(unsub);
|
|
885
|
+
}
|
|
886
|
+
removeScopedHooks(appSlug, pluginName) {
|
|
887
|
+
const key = this.getScopedHookKey(appSlug, pluginName);
|
|
888
|
+
const unsubs = this.scopedHookUnsubscribers.get(key);
|
|
889
|
+
if (unsubs) {
|
|
890
|
+
for (const unsub of unsubs) {
|
|
891
|
+
try {
|
|
892
|
+
unsub();
|
|
893
|
+
}
|
|
894
|
+
catch { }
|
|
895
|
+
}
|
|
896
|
+
this.scopedHookUnsubscribers.delete(key);
|
|
897
|
+
}
|
|
898
|
+
const scopedEntry = this.scopedPlugins.get(key);
|
|
899
|
+
if (scopedEntry) {
|
|
900
|
+
if (typeof scopedEntry.plugin.onDestroy === 'function') {
|
|
901
|
+
try {
|
|
902
|
+
scopedEntry.plugin.onDestroy(scopedEntry.context);
|
|
903
|
+
}
|
|
904
|
+
catch { }
|
|
905
|
+
}
|
|
906
|
+
this.scopedPlugins.delete(key);
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
disposeScope(appSlug) {
|
|
910
|
+
for (const [key, entry] of this.scopedPlugins.entries()) {
|
|
911
|
+
if (key.startsWith(`${appSlug}:`)) {
|
|
912
|
+
if (typeof entry.plugin.onDestroy === 'function') {
|
|
913
|
+
try {
|
|
914
|
+
entry.plugin.onDestroy(entry.context);
|
|
915
|
+
}
|
|
916
|
+
catch { }
|
|
917
|
+
}
|
|
918
|
+
this.scopedPlugins.delete(key);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
for (const [key, unsubs] of this.scopedHookUnsubscribers.entries()) {
|
|
922
|
+
if (key.startsWith(`${appSlug}:`)) {
|
|
923
|
+
for (const unsub of unsubs) {
|
|
924
|
+
try {
|
|
925
|
+
unsub();
|
|
926
|
+
}
|
|
927
|
+
catch { }
|
|
928
|
+
}
|
|
929
|
+
this.scopedHookUnsubscribers.delete(key);
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
for (const prov of Array.from(this.provisionedScopes)) {
|
|
933
|
+
if (prov.startsWith(`${appSlug}:`)) {
|
|
934
|
+
this.provisionedScopes.delete(prov);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
wireScopedPluginLifecycle(plugin, scope) {
|
|
939
|
+
if (typeof plugin.register !== 'function')
|
|
940
|
+
return;
|
|
941
|
+
try {
|
|
942
|
+
const def = exports.OFFICIAL_PLUGINS.find((p) => p.name === plugin.name || p.id === plugin.name);
|
|
943
|
+
const scopedPlugin = def ? def.factory() : plugin;
|
|
944
|
+
const scopedApp = new Proxy(this.app, {
|
|
945
|
+
get(target, prop, receiver) {
|
|
946
|
+
if (prop === 'db')
|
|
947
|
+
return scope.db;
|
|
948
|
+
if (prop === 'schema')
|
|
949
|
+
return scope.schema;
|
|
950
|
+
if (prop === 'records')
|
|
951
|
+
return scope.records;
|
|
952
|
+
if (prop === 'eventBus')
|
|
953
|
+
return scope.eventBus;
|
|
954
|
+
if (prop === 'files')
|
|
955
|
+
return scope.files;
|
|
956
|
+
if (prop === 'fts')
|
|
957
|
+
return scope.fts;
|
|
958
|
+
if (prop === 'analytics')
|
|
959
|
+
return scope.analytics;
|
|
960
|
+
if (prop === 'auditLogs')
|
|
961
|
+
return scope.auditLogs;
|
|
962
|
+
if (prop === 'webhooks')
|
|
963
|
+
return scope.webhooks;
|
|
964
|
+
return Reflect.get(target, prop, receiver);
|
|
965
|
+
},
|
|
966
|
+
});
|
|
967
|
+
const scopedContext = {
|
|
968
|
+
app: scopedApp,
|
|
969
|
+
container: this.container,
|
|
970
|
+
tokens: Tokens_1.TOKENS,
|
|
971
|
+
config: scope.config,
|
|
972
|
+
db: scope.db,
|
|
973
|
+
schema: scope.schema,
|
|
974
|
+
eventBus: scope.eventBus,
|
|
975
|
+
adminUi: this.app.adminUi,
|
|
976
|
+
auth: {
|
|
977
|
+
requireAdmin: () => this.app.authMiddleware.requireAdmin(),
|
|
978
|
+
requireAdminOrInitial: () => this.app.authMiddleware.requireAdminOrInitialSetup(),
|
|
979
|
+
requireAuth: () => this.app.authMiddleware.requireAuth(),
|
|
980
|
+
},
|
|
981
|
+
router: {
|
|
982
|
+
get: () => { },
|
|
983
|
+
post: () => { },
|
|
984
|
+
patch: () => { },
|
|
985
|
+
delete: () => { },
|
|
986
|
+
put: () => { },
|
|
987
|
+
raw: this.app.server?.app,
|
|
988
|
+
},
|
|
989
|
+
registerRoute: () => { },
|
|
990
|
+
registerAdminNav: () => { },
|
|
991
|
+
registerSystemCollection: (dto) => scope.schema.registerSystemCollection(dto),
|
|
992
|
+
registerHook: (event, handler, collection) => {
|
|
993
|
+
const guardedHandler = async (...args) => {
|
|
994
|
+
if (!this.isPluginEnabledInDb(scopedPlugin.name, scope.db)) {
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
return handler(...args);
|
|
998
|
+
};
|
|
999
|
+
let unsubscribe;
|
|
1000
|
+
switch (event) {
|
|
1001
|
+
case 'beforeCreate':
|
|
1002
|
+
unsubscribe = scope.eventBus.onRecordBeforeCreate(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
1003
|
+
break;
|
|
1004
|
+
case 'afterCreate':
|
|
1005
|
+
unsubscribe = scope.eventBus.onRecordAfterCreate(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
1006
|
+
break;
|
|
1007
|
+
case 'beforeUpdate':
|
|
1008
|
+
unsubscribe = scope.eventBus.onRecordBeforeUpdate(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
1009
|
+
break;
|
|
1010
|
+
case 'afterUpdate':
|
|
1011
|
+
unsubscribe = scope.eventBus.onRecordAfterUpdate(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
1012
|
+
break;
|
|
1013
|
+
case 'beforeDelete':
|
|
1014
|
+
unsubscribe = scope.eventBus.onRecordBeforeDelete(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
1015
|
+
break;
|
|
1016
|
+
case 'afterDelete':
|
|
1017
|
+
unsubscribe = scope.eventBus.onRecordAfterDelete(collection ? collection : guardedHandler, collection ? guardedHandler : undefined);
|
|
1018
|
+
break;
|
|
1019
|
+
case 'beforeServe':
|
|
1020
|
+
unsubscribe = scope.eventBus.onBeforeServe(guardedHandler);
|
|
1021
|
+
break;
|
|
1022
|
+
case 'afterServe':
|
|
1023
|
+
unsubscribe = scope.eventBus.onAfterServe(guardedHandler);
|
|
1024
|
+
break;
|
|
1025
|
+
default:
|
|
1026
|
+
unsubscribe = scope.eventBus.on(event, guardedHandler);
|
|
1027
|
+
break;
|
|
1028
|
+
}
|
|
1029
|
+
this.addScopedHookUnsubscriber(scope.app.slug, scopedPlugin.name, unsubscribe);
|
|
1030
|
+
},
|
|
1031
|
+
getService: (token) => this.container.get(token),
|
|
1032
|
+
bindService: () => { },
|
|
1033
|
+
};
|
|
1034
|
+
const key = this.getScopedHookKey(scope.app.slug, scopedPlugin.name);
|
|
1035
|
+
this.scopedPlugins.set(key, { plugin: scopedPlugin, context: scopedContext });
|
|
1036
|
+
if (typeof scopedPlugin.register === 'function') {
|
|
1037
|
+
const regRes = scopedPlugin.register(scopedContext);
|
|
1038
|
+
if (regRes instanceof Promise) {
|
|
1039
|
+
this.pendingInits.push(regRes.catch((err) => {
|
|
1040
|
+
console.error(`[PluginManager] Scoped register error for "${scopedPlugin.name}" in app "${scope.app.slug}":`, err);
|
|
1041
|
+
}));
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
if (typeof scopedPlugin.init === 'function') {
|
|
1045
|
+
const initRes = scopedPlugin.init(scopedContext);
|
|
1046
|
+
if (initRes instanceof Promise) {
|
|
1047
|
+
this.pendingInits.push(initRes.catch((err) => {
|
|
1048
|
+
console.error(`[PluginManager] Scoped init error for "${scopedPlugin.name}" in app "${scope.app.slug}":`, err);
|
|
1049
|
+
}));
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
if (scopedPlugin.configSchema?.fields && typeof scopedPlugin.onConfigUpdate === 'function') {
|
|
1053
|
+
try {
|
|
1054
|
+
const effective = this.getEffectiveConfig(scopedPlugin.name, scope.db);
|
|
1055
|
+
const initialSync = scopedPlugin.onConfigUpdate(effective);
|
|
1056
|
+
if (initialSync instanceof Promise) {
|
|
1057
|
+
this.pendingInits.push(initialSync.catch(() => { }));
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
catch { }
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
catch (err) {
|
|
1064
|
+
console.error(`[PluginManager] Error wiring scoped lifecycle for "${plugin.name}" in app "${scope.app.slug}":`, err);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
provisionPluginForScope(plugin, scope) {
|
|
1068
|
+
if (!plugin || !scope)
|
|
1069
|
+
return;
|
|
1070
|
+
const key = `${scope.app.slug}:${plugin.name}`;
|
|
1071
|
+
if (this.provisionedScopes.has(key)) {
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
1074
|
+
this.provisionedScopes.add(key);
|
|
1075
|
+
// 1. Provision declarative collections on scope schema
|
|
1076
|
+
if (plugin.collections && Array.isArray(plugin.collections)) {
|
|
1077
|
+
for (const colDto of plugin.collections) {
|
|
1078
|
+
scope.schema.registerSystemCollection(colDto);
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
// 2. For non-default scopes, wire up scoped context, lifecycle, and eventBus hooks
|
|
1082
|
+
const isDefaultScope = scope === this.app.defaultApp || scope.app.slug === 'default' || scope.db === this.app.db;
|
|
1083
|
+
if (!isDefaultScope) {
|
|
1084
|
+
this.wireScopedPluginLifecycle(plugin, scope);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
provisionScope(scope) {
|
|
1088
|
+
if (!scope || !scope.db)
|
|
1089
|
+
return;
|
|
1090
|
+
this.initSettingsTable(scope.db);
|
|
1091
|
+
// 1. If it's the default app, ensure all plugins registered via app.use() have collections provisioned
|
|
1092
|
+
const isDefaultScope = scope === this.app.defaultApp || scope.app.slug === 'default' || scope.db === this.app.db;
|
|
1093
|
+
if (isDefaultScope) {
|
|
1094
|
+
for (const record of this.plugins.values()) {
|
|
1095
|
+
this.provisionPluginForScope(record.plugin, scope);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
// 2. Read _plugin_settings from scope.db
|
|
1099
|
+
try {
|
|
1100
|
+
if (typeof scope.db.all === 'function') {
|
|
1101
|
+
const rows = scope.db.all('SELECT pluginName, settings FROM _plugin_settings');
|
|
1102
|
+
for (const row of rows) {
|
|
1103
|
+
try {
|
|
1104
|
+
const parsed = JSON.parse(row.settings);
|
|
1105
|
+
if (parsed && parsed._enabled === true) {
|
|
1106
|
+
let plugin = this.plugins.get(row.pluginName)?.plugin;
|
|
1107
|
+
if (!plugin) {
|
|
1108
|
+
const def = exports.OFFICIAL_PLUGINS.find((p) => p.name === row.pluginName || p.id === row.pluginName);
|
|
1109
|
+
if (def) {
|
|
1110
|
+
this.runtimeLoadedOfficialPlugins.add(def.name);
|
|
1111
|
+
plugin = def.factory();
|
|
1112
|
+
this.use(plugin, scope);
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
else {
|
|
1116
|
+
this.provisionPluginForScope(plugin, scope);
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
catch { }
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
catch {
|
|
1125
|
+
// Ignore during uninitialized state
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
/**
|
|
1129
|
+
* Auto-load any official plugins previously enabled in _plugin_settings on startup
|
|
1130
|
+
*/
|
|
1131
|
+
loadAutoEnabledPlugins() {
|
|
1132
|
+
if (this.app.defaultApp) {
|
|
1133
|
+
this.provisionScope(this.app.defaultApp);
|
|
1134
|
+
}
|
|
1135
|
+
else {
|
|
1136
|
+
this.initSettingsTable(this.app.db);
|
|
1137
|
+
}
|
|
1138
|
+
if (this.app.apps) {
|
|
1139
|
+
try {
|
|
1140
|
+
const apps = this.app.apps.registry.getAllApps();
|
|
1141
|
+
for (const app of apps) {
|
|
1142
|
+
if (app.slug !== 'default') {
|
|
1143
|
+
const scope = this.app.apps.get(app.slug);
|
|
1144
|
+
this.provisionScope(scope);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
catch { }
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Initialize SQLite settings table for plugins if not already present
|
|
1153
|
+
*/
|
|
1154
|
+
initSettingsTable(db) {
|
|
1155
|
+
const targetDb = db || this.app.db;
|
|
1156
|
+
try {
|
|
1157
|
+
if (targetDb && typeof targetDb.run === 'function') {
|
|
1158
|
+
targetDb.run(`
|
|
1159
|
+
CREATE TABLE IF NOT EXISTS _plugin_settings (
|
|
1160
|
+
pluginName TEXT PRIMARY KEY,
|
|
1161
|
+
settings TEXT NOT NULL DEFAULT '{}',
|
|
1162
|
+
updatedAt TEXT NOT NULL
|
|
1163
|
+
)
|
|
1164
|
+
`);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
catch {
|
|
1168
|
+
// Ignore during mock or container tests
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* Register Fastify routes for retrieving and updating plugin configuration
|
|
1173
|
+
*/
|
|
1174
|
+
registerConfigRoutes() {
|
|
1175
|
+
const fastify = this.app.server?.app;
|
|
1176
|
+
if (!fastify)
|
|
1177
|
+
return;
|
|
1178
|
+
const setupRoutes = (prefix = '/api') => {
|
|
1179
|
+
fastify.get(`${prefix}/plugins/available`, { preHandler: this.app.authMiddleware.requireAdmin() }, async (req, reply) => {
|
|
1180
|
+
const targetDb = req.appScope?.db || this.app.db;
|
|
1181
|
+
return reply.send({
|
|
1182
|
+
plugins: this.getOfficialCatalog(targetDb),
|
|
1183
|
+
});
|
|
1184
|
+
});
|
|
1185
|
+
fastify.post(`${prefix}/plugins/:name/enable`, { preHandler: this.app.authMiddleware.requireAdmin() }, async (req, reply) => {
|
|
1186
|
+
const { name } = req.params;
|
|
1187
|
+
const targetScope = req.appScope || this.app.defaultApp;
|
|
1188
|
+
try {
|
|
1189
|
+
const config = await this.enableOfficialPlugin(name, targetScope);
|
|
1190
|
+
return reply.send({
|
|
1191
|
+
success: true,
|
|
1192
|
+
message: `Plugin "${name}" enabled successfully`,
|
|
1193
|
+
config,
|
|
1194
|
+
});
|
|
1195
|
+
}
|
|
1196
|
+
catch (err) {
|
|
1197
|
+
const statusCode = err.statusCode || 400;
|
|
1198
|
+
return reply.status(statusCode).send({
|
|
1199
|
+
statusCode,
|
|
1200
|
+
message: err.message || `Failed to enable plugin "${name}"`,
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
1203
|
+
});
|
|
1204
|
+
fastify.post(`${prefix}/plugins/:name/disable`, { preHandler: this.app.authMiddleware.requireAdmin() }, async (req, reply) => {
|
|
1205
|
+
const { name } = req.params;
|
|
1206
|
+
const targetScope = req.appScope || this.app.defaultApp;
|
|
1207
|
+
try {
|
|
1208
|
+
await this.disableOfficialPlugin(name, targetScope);
|
|
1209
|
+
return reply.send({
|
|
1210
|
+
success: true,
|
|
1211
|
+
message: `Plugin "${name}" disabled successfully`,
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1214
|
+
catch (err) {
|
|
1215
|
+
const statusCode = err.statusCode || 400;
|
|
1216
|
+
return reply.status(statusCode).send({
|
|
1217
|
+
statusCode,
|
|
1218
|
+
message: err.message || `Failed to disable plugin "${name}"`,
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
});
|
|
1222
|
+
fastify.get(`${prefix}/plugins/:name/config`, { preHandler: this.app.authMiddleware.requireAdmin() }, async (req, reply) => {
|
|
1223
|
+
const { name } = req.params;
|
|
1224
|
+
const targetDb = req.appScope?.db || this.app.db;
|
|
1225
|
+
try {
|
|
1226
|
+
const config = this.getPluginConfig(name, targetDb);
|
|
1227
|
+
return reply.send(config);
|
|
1228
|
+
}
|
|
1229
|
+
catch (err) {
|
|
1230
|
+
const statusCode = err.statusCode || 404;
|
|
1231
|
+
return reply.status(statusCode).send({
|
|
1232
|
+
statusCode,
|
|
1233
|
+
message: err.message || `Plugin "${name}" not found`,
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
});
|
|
1237
|
+
fastify.put(`${prefix}/plugins/:name/config`, { preHandler: this.app.authMiddleware.requireAdmin() }, async (req, reply) => {
|
|
1238
|
+
const { name } = req.params;
|
|
1239
|
+
const body = req.body || {};
|
|
1240
|
+
const targetDb = req.appScope?.db || this.app.db;
|
|
1241
|
+
try {
|
|
1242
|
+
const updated = await this.updatePluginConfig(name, body, targetDb);
|
|
1243
|
+
return reply.send(updated);
|
|
1244
|
+
}
|
|
1245
|
+
catch (err) {
|
|
1246
|
+
const statusCode = err.statusCode || 400;
|
|
1247
|
+
return reply.status(statusCode).send({
|
|
1248
|
+
statusCode,
|
|
1249
|
+
message: err.message,
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
});
|
|
1253
|
+
};
|
|
1254
|
+
setupRoutes('/api');
|
|
1255
|
+
setupRoutes('/api/apps/:appId');
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Resolve raw effective configuration dictionary for internal plugin execution.
|
|
1259
|
+
* Resolves values from environment variables, database (_plugin_settings), code options, and defaults.
|
|
1260
|
+
* Unlike getPluginConfig, this preserves raw secrets required by plugins at runtime.
|
|
1261
|
+
*/
|
|
1262
|
+
getEffectiveConfig(name, db) {
|
|
1263
|
+
const targetDb = db || this.app.db;
|
|
1264
|
+
let record = this.plugins.get(name);
|
|
1265
|
+
if (!record) {
|
|
1266
|
+
for (const rec of this.plugins.values()) {
|
|
1267
|
+
if (rec.plugin.adminNavItems?.some((i) => i.id === name)) {
|
|
1268
|
+
record = rec;
|
|
1269
|
+
name = rec.name;
|
|
1270
|
+
break;
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
if (!record) {
|
|
1275
|
+
throw new AppError_1.NotFoundError(`Plugin "${name}" is not registered`);
|
|
1276
|
+
}
|
|
1277
|
+
const plugin = record.plugin;
|
|
1278
|
+
if (!plugin.configSchema?.fields || plugin.configSchema.fields.length === 0) {
|
|
1279
|
+
return {};
|
|
1280
|
+
}
|
|
1281
|
+
this.initSettingsTable(targetDb);
|
|
1282
|
+
let dbSettings = {};
|
|
1283
|
+
try {
|
|
1284
|
+
const row = targetDb.get('SELECT settings FROM _plugin_settings WHERE pluginName = ?', [name]);
|
|
1285
|
+
if (row?.settings) {
|
|
1286
|
+
dbSettings = JSON.parse(row.settings);
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
catch { }
|
|
1290
|
+
const effective = {};
|
|
1291
|
+
for (const field of plugin.configSchema.fields) {
|
|
1292
|
+
let val = undefined;
|
|
1293
|
+
// 1. Environment Variable
|
|
1294
|
+
if (field.envKey && process.env[field.envKey] !== undefined && process.env[field.envKey] !== '') {
|
|
1295
|
+
val = process.env[field.envKey];
|
|
1296
|
+
}
|
|
1297
|
+
// 2. Database Settings
|
|
1298
|
+
else if (dbSettings[field.name] !== undefined) {
|
|
1299
|
+
val = dbSettings[field.name];
|
|
1300
|
+
}
|
|
1301
|
+
// 3. Code Options
|
|
1302
|
+
else if (plugin.codeOptions &&
|
|
1303
|
+
plugin.codeOptions[field.name] !== undefined &&
|
|
1304
|
+
plugin.codeOptions[field.name] !== '') {
|
|
1305
|
+
val = plugin.codeOptions[field.name];
|
|
1306
|
+
}
|
|
1307
|
+
// 4. Default Fallback
|
|
1308
|
+
else {
|
|
1309
|
+
val =
|
|
1310
|
+
field.defaultValue !== undefined
|
|
1311
|
+
? field.defaultValue
|
|
1312
|
+
: (field.type === 'boolean'
|
|
1313
|
+
? false
|
|
1314
|
+
: (field.type === 'select' && field.required && field.options && field.options.length > 0
|
|
1315
|
+
? (typeof field.options[0] === 'object' && field.options[0] !== null && 'value' in field.options[0]
|
|
1316
|
+
? field.options[0].value
|
|
1317
|
+
: field.options[0])
|
|
1318
|
+
: undefined));
|
|
1319
|
+
}
|
|
1320
|
+
if (val !== undefined && val !== '') {
|
|
1321
|
+
effective[field.name] = val;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
return effective;
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* Option B: Resolve plugin configuration with strict environment & code precedence.
|
|
1328
|
+
* If a setting is defined via process.env, it is locked.
|
|
1329
|
+
* If not defined in env, it is editable via SQLite database (_plugin_settings).
|
|
1330
|
+
*
|
|
1331
|
+
* SECURITY: For fields of type 'password', raw secret values are NEVER returned in responses.
|
|
1332
|
+
* value is omitted (undefined), and hasValue indicates whether a secret is configured.
|
|
1333
|
+
*/
|
|
1334
|
+
getPluginConfig(name, db) {
|
|
1335
|
+
const targetDb = db || this.app.db;
|
|
1336
|
+
let record = this.plugins.get(name);
|
|
1337
|
+
if (!record) {
|
|
1338
|
+
for (const rec of this.plugins.values()) {
|
|
1339
|
+
if (rec.plugin.adminNavItems?.some((i) => i.id === name)) {
|
|
1340
|
+
record = rec;
|
|
1341
|
+
name = rec.name;
|
|
1342
|
+
break;
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
if (!record) {
|
|
1347
|
+
throw new AppError_1.NotFoundError(`Plugin "${name}" is not registered`);
|
|
1348
|
+
}
|
|
1349
|
+
const plugin = record.plugin;
|
|
1350
|
+
if (!plugin.configSchema || !plugin.configSchema.fields || plugin.configSchema.fields.length === 0) {
|
|
1351
|
+
return {
|
|
1352
|
+
plugin: name,
|
|
1353
|
+
hasConfig: false,
|
|
1354
|
+
fields: [],
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
this.initSettingsTable(targetDb);
|
|
1358
|
+
let dbSettings = {};
|
|
1359
|
+
try {
|
|
1360
|
+
const row = targetDb.get('SELECT settings FROM _plugin_settings WHERE pluginName = ?', [name]);
|
|
1361
|
+
if (row?.settings) {
|
|
1362
|
+
dbSettings = JSON.parse(row.settings);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
catch { }
|
|
1366
|
+
const fields = plugin.configSchema.fields.map((field) => {
|
|
1367
|
+
let rawValue = undefined;
|
|
1368
|
+
let isLocked = false;
|
|
1369
|
+
let source = 'default';
|
|
1370
|
+
let lockReason = undefined;
|
|
1371
|
+
// 1. Strict Option B: Check Environment Variable (The ONLY source that locks)
|
|
1372
|
+
if (field.envKey && process.env[field.envKey] !== undefined && process.env[field.envKey] !== '') {
|
|
1373
|
+
rawValue = process.env[field.envKey];
|
|
1374
|
+
isLocked = true;
|
|
1375
|
+
source = 'env';
|
|
1376
|
+
lockReason = `Managed by environment variable (${field.envKey})`;
|
|
1377
|
+
}
|
|
1378
|
+
// 2. Check Database Settings (Editable via Admin UI, overrides code fallbacks)
|
|
1379
|
+
else if (dbSettings[field.name] !== undefined) {
|
|
1380
|
+
rawValue = dbSettings[field.name];
|
|
1381
|
+
isLocked = false;
|
|
1382
|
+
source = 'db';
|
|
1383
|
+
}
|
|
1384
|
+
// 3. Programmatic Code Options / Fallback (Editable in UI)
|
|
1385
|
+
else if (plugin.codeOptions &&
|
|
1386
|
+
plugin.codeOptions[field.name] !== undefined &&
|
|
1387
|
+
plugin.codeOptions[field.name] !== '') {
|
|
1388
|
+
rawValue = plugin.codeOptions[field.name];
|
|
1389
|
+
isLocked = false;
|
|
1390
|
+
source = 'code';
|
|
1391
|
+
}
|
|
1392
|
+
// 4. Default Fallback
|
|
1393
|
+
else {
|
|
1394
|
+
rawValue =
|
|
1395
|
+
field.defaultValue !== undefined
|
|
1396
|
+
? field.defaultValue
|
|
1397
|
+
: (field.type === 'boolean'
|
|
1398
|
+
? false
|
|
1399
|
+
: (field.type === 'select' && field.required && field.options && field.options.length > 0
|
|
1400
|
+
? (typeof field.options[0] === 'object' && field.options[0] !== null && 'value' in field.options[0]
|
|
1401
|
+
? field.options[0].value
|
|
1402
|
+
: field.options[0])
|
|
1403
|
+
: undefined));
|
|
1404
|
+
isLocked = false;
|
|
1405
|
+
source = 'default';
|
|
1406
|
+
}
|
|
1407
|
+
// Security: Omit raw password values from responses and provide write-only hint
|
|
1408
|
+
if (field.type === 'password') {
|
|
1409
|
+
const hasValue = rawValue !== undefined && rawValue !== '' && rawValue !== null;
|
|
1410
|
+
return {
|
|
1411
|
+
...field,
|
|
1412
|
+
value: undefined, // Omit raw secret from API and UI response!
|
|
1413
|
+
hasValue,
|
|
1414
|
+
maskedValue: hasValue ? '••••••••' : undefined,
|
|
1415
|
+
isLocked,
|
|
1416
|
+
source,
|
|
1417
|
+
lockReason,
|
|
1418
|
+
};
|
|
1419
|
+
}
|
|
1420
|
+
return {
|
|
1421
|
+
...field,
|
|
1422
|
+
value: rawValue,
|
|
1423
|
+
isLocked,
|
|
1424
|
+
source,
|
|
1425
|
+
lockReason,
|
|
1426
|
+
};
|
|
1427
|
+
});
|
|
1428
|
+
return {
|
|
1429
|
+
plugin: name,
|
|
1430
|
+
hasConfig: true,
|
|
1431
|
+
fields,
|
|
1432
|
+
};
|
|
1433
|
+
}
|
|
1434
|
+
/**
|
|
1435
|
+
* Option B: Update plugin configuration from Admin UI.
|
|
1436
|
+
* Throws 400 Bad Request if trying to update any locked field.
|
|
1437
|
+
* Implements a write-only / unchanged-secret update path:
|
|
1438
|
+
* - Password fields left empty or set to '••••••••' preserve existing secrets unchanged.
|
|
1439
|
+
* - A non-empty string updates the secret in _plugin_settings.
|
|
1440
|
+
* Saves updates to _plugin_settings and fires onConfigUpdate on the plugin with effective settings.
|
|
1441
|
+
*/
|
|
1442
|
+
async updatePluginConfig(name, updates, db) {
|
|
1443
|
+
const targetDb = db || this.app.db;
|
|
1444
|
+
let record = this.plugins.get(name);
|
|
1445
|
+
if (!record) {
|
|
1446
|
+
for (const rec of this.plugins.values()) {
|
|
1447
|
+
if (rec.plugin.adminNavItems?.some((i) => i.id === name)) {
|
|
1448
|
+
record = rec;
|
|
1449
|
+
name = rec.name;
|
|
1450
|
+
break;
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
if (!record) {
|
|
1455
|
+
throw new AppError_1.NotFoundError(`Plugin "${name}" is not registered`);
|
|
1456
|
+
}
|
|
1457
|
+
const currentConfig = this.getPluginConfig(name, targetDb);
|
|
1458
|
+
if (!currentConfig.hasConfig) {
|
|
1459
|
+
throw new AppError_1.AppError(`Plugin "${name}" does not define a configuration schema`, 400);
|
|
1460
|
+
}
|
|
1461
|
+
this.initSettingsTable(targetDb);
|
|
1462
|
+
let dbSettings = {};
|
|
1463
|
+
try {
|
|
1464
|
+
const row = targetDb.get('SELECT settings FROM _plugin_settings WHERE pluginName = ?', [name]);
|
|
1465
|
+
if (row?.settings) {
|
|
1466
|
+
dbSettings = JSON.parse(row.settings);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
catch { }
|
|
1470
|
+
// Validate that no locked fields are being modified
|
|
1471
|
+
for (const [key, val] of Object.entries(updates)) {
|
|
1472
|
+
const field = currentConfig.fields.find((f) => f.name === key);
|
|
1473
|
+
if (!field)
|
|
1474
|
+
continue;
|
|
1475
|
+
if (field.isLocked) {
|
|
1476
|
+
// If unchanged placeholder or blank is passed for a locked field, ignore without error
|
|
1477
|
+
if (val === undefined || val === '' || val === null || val === '••••••••') {
|
|
1478
|
+
continue;
|
|
1479
|
+
}
|
|
1480
|
+
throw new AppError_1.AppError(`Field "${key}" is locked by ${field.lockReason || 'production environment'} and cannot be modified via UI.`, 400);
|
|
1481
|
+
}
|
|
1482
|
+
// Write-only / unchanged-secret update path:
|
|
1483
|
+
if (field.type === 'password') {
|
|
1484
|
+
if (val === undefined || val === '' || val === null || val === '••••••••') {
|
|
1485
|
+
// Unchanged: preserve existing stored secret
|
|
1486
|
+
continue;
|
|
1487
|
+
}
|
|
1488
|
+
// Operator provided a new secret
|
|
1489
|
+
dbSettings[key] = String(val).trim();
|
|
1490
|
+
continue;
|
|
1491
|
+
}
|
|
1492
|
+
// Format/sanitize values for other field types
|
|
1493
|
+
let cleanedVal = val;
|
|
1494
|
+
if (field.type === 'number') {
|
|
1495
|
+
cleanedVal = val === '' ? undefined : Number(val);
|
|
1496
|
+
}
|
|
1497
|
+
else if (field.type === 'boolean') {
|
|
1498
|
+
cleanedVal = Boolean(val);
|
|
1499
|
+
}
|
|
1500
|
+
else if (field.type === 'select') {
|
|
1501
|
+
if (field.options && field.options.length > 0) {
|
|
1502
|
+
const matchedOpt = field.options.find((opt) => {
|
|
1503
|
+
const optVal = typeof opt === 'object' && opt !== null && 'value' in opt ? opt.value : opt;
|
|
1504
|
+
return String(optVal) === String(val);
|
|
1505
|
+
});
|
|
1506
|
+
if (matchedOpt) {
|
|
1507
|
+
const rawOptVal = typeof matchedOpt === 'object' && matchedOpt !== null && 'value' in matchedOpt
|
|
1508
|
+
? matchedOpt.value
|
|
1509
|
+
: matchedOpt;
|
|
1510
|
+
cleanedVal = rawOptVal;
|
|
1511
|
+
}
|
|
1512
|
+
else if (val === '' || val === undefined || val === null) {
|
|
1513
|
+
if (field.required) {
|
|
1514
|
+
throw new AppError_1.AppError(`Field "${key}" is required.`, 400);
|
|
1515
|
+
}
|
|
1516
|
+
cleanedVal = undefined;
|
|
1517
|
+
}
|
|
1518
|
+
else {
|
|
1519
|
+
const allowedLabels = field.options.map((opt) => {
|
|
1520
|
+
const optVal = typeof opt === 'object' && opt !== null && 'value' in opt ? opt.value : opt;
|
|
1521
|
+
return JSON.stringify(optVal);
|
|
1522
|
+
});
|
|
1523
|
+
throw new AppError_1.AppError(`Invalid value "${val}" for select field "${key}". Allowed choices: ${allowedLabels.join(', ')}`, 400);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
if (cleanedVal === undefined) {
|
|
1528
|
+
delete dbSettings[key];
|
|
1529
|
+
}
|
|
1530
|
+
else {
|
|
1531
|
+
dbSettings[key] = cleanedVal;
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
const now = new Date().toISOString();
|
|
1535
|
+
targetDb.prepare(`
|
|
1536
|
+
INSERT INTO _plugin_settings (pluginName, settings, updatedAt)
|
|
1537
|
+
VALUES (?, ?, ?)
|
|
1538
|
+
ON CONFLICT(pluginName) DO UPDATE SET settings=excluded.settings, updatedAt=excluded.updatedAt
|
|
1539
|
+
`).run(name, JSON.stringify(dbSettings), now);
|
|
1540
|
+
// Compute effective full configuration with raw secrets for runtime update
|
|
1541
|
+
const targetScope = this.findScopeForDb(targetDb);
|
|
1542
|
+
const isDefaultDb = !db || targetDb === this.app.db || targetScope?.app.slug === 'default' || (targetScope && targetScope === this.app.defaultApp);
|
|
1543
|
+
if (isDefaultDb) {
|
|
1544
|
+
if (typeof record.plugin.onConfigUpdate === 'function') {
|
|
1545
|
+
const effectiveConfig = this.getEffectiveConfig(name, targetDb);
|
|
1546
|
+
await record.plugin.onConfigUpdate(effectiveConfig);
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
else if (targetScope) {
|
|
1550
|
+
const key = this.getScopedHookKey(targetScope.app.slug, name);
|
|
1551
|
+
let scopedEntry = this.scopedPlugins.get(key);
|
|
1552
|
+
if (!scopedEntry && this.isPluginEnabledInDb(name, targetDb)) {
|
|
1553
|
+
this.provisionPluginForScope(record.plugin, targetScope);
|
|
1554
|
+
scopedEntry = this.scopedPlugins.get(key);
|
|
1555
|
+
}
|
|
1556
|
+
if (scopedEntry && typeof scopedEntry.plugin.onConfigUpdate === 'function') {
|
|
1557
|
+
const effectiveConfig = this.getEffectiveConfig(name, targetDb);
|
|
1558
|
+
await scopedEntry.plugin.onConfigUpdate(effectiveConfig);
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
return this.getPluginConfig(name, targetDb);
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* Clean up and destroy all plugins
|
|
1565
|
+
*/
|
|
1566
|
+
async dispose() {
|
|
1567
|
+
for (const scopedEntry of this.scopedPlugins.values()) {
|
|
1568
|
+
if (typeof scopedEntry.plugin.onDestroy === 'function') {
|
|
1569
|
+
try {
|
|
1570
|
+
await scopedEntry.plugin.onDestroy(scopedEntry.context);
|
|
1571
|
+
}
|
|
1572
|
+
catch { }
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
this.scopedPlugins.clear();
|
|
1576
|
+
for (const record of this.plugins.values()) {
|
|
1577
|
+
if (typeof record.plugin.onDestroy === 'function') {
|
|
1578
|
+
try {
|
|
1579
|
+
await record.plugin.onDestroy(record.context);
|
|
1580
|
+
}
|
|
1581
|
+
catch (e) {
|
|
1582
|
+
console.error(`[PluginManager] Error disposing plugin "${record.name}":`, e);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
this.plugins.clear();
|
|
1587
|
+
this.pendingInits = [];
|
|
1588
|
+
this.registeredFunctions.clear();
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
exports.PluginManager = PluginManager;
|
|
1592
|
+
//# sourceMappingURL=PluginManager.js.map
|