@objectstack/core 1.0.2 → 1.0.5

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 (125) hide show
  1. package/.turbo/turbo-build.log +58 -0
  2. package/CHANGELOG.md +25 -0
  3. package/dist/index.cjs +4294 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +1777 -0
  6. package/dist/index.d.ts +1776 -21
  7. package/dist/index.js +4246 -23
  8. package/dist/index.js.map +1 -0
  9. package/package.json +4 -4
  10. package/tsconfig.json +1 -3
  11. package/dist/api-registry-plugin.d.ts +0 -54
  12. package/dist/api-registry-plugin.d.ts.map +0 -1
  13. package/dist/api-registry-plugin.js +0 -53
  14. package/dist/api-registry-plugin.test.d.ts +0 -2
  15. package/dist/api-registry-plugin.test.d.ts.map +0 -1
  16. package/dist/api-registry-plugin.test.js +0 -334
  17. package/dist/api-registry.d.ts +0 -259
  18. package/dist/api-registry.d.ts.map +0 -1
  19. package/dist/api-registry.js +0 -600
  20. package/dist/api-registry.test.d.ts +0 -2
  21. package/dist/api-registry.test.d.ts.map +0 -1
  22. package/dist/api-registry.test.js +0 -957
  23. package/dist/contracts/data-engine.d.ts +0 -62
  24. package/dist/contracts/data-engine.d.ts.map +0 -1
  25. package/dist/contracts/data-engine.js +0 -1
  26. package/dist/contracts/http-server.d.ts +0 -119
  27. package/dist/contracts/http-server.d.ts.map +0 -1
  28. package/dist/contracts/http-server.js +0 -11
  29. package/dist/contracts/logger.d.ts +0 -63
  30. package/dist/contracts/logger.d.ts.map +0 -1
  31. package/dist/contracts/logger.js +0 -1
  32. package/dist/dependency-resolver.d.ts +0 -62
  33. package/dist/dependency-resolver.d.ts.map +0 -1
  34. package/dist/dependency-resolver.js +0 -317
  35. package/dist/dependency-resolver.test.d.ts +0 -2
  36. package/dist/dependency-resolver.test.d.ts.map +0 -1
  37. package/dist/dependency-resolver.test.js +0 -241
  38. package/dist/health-monitor.d.ts +0 -65
  39. package/dist/health-monitor.d.ts.map +0 -1
  40. package/dist/health-monitor.js +0 -269
  41. package/dist/health-monitor.test.d.ts +0 -2
  42. package/dist/health-monitor.test.d.ts.map +0 -1
  43. package/dist/health-monitor.test.js +0 -68
  44. package/dist/hot-reload.d.ts +0 -79
  45. package/dist/hot-reload.d.ts.map +0 -1
  46. package/dist/hot-reload.js +0 -313
  47. package/dist/index.d.ts.map +0 -1
  48. package/dist/kernel-base.d.ts +0 -84
  49. package/dist/kernel-base.d.ts.map +0 -1
  50. package/dist/kernel-base.js +0 -219
  51. package/dist/kernel.d.ts +0 -113
  52. package/dist/kernel.d.ts.map +0 -1
  53. package/dist/kernel.js +0 -472
  54. package/dist/kernel.test.d.ts +0 -2
  55. package/dist/kernel.test.d.ts.map +0 -1
  56. package/dist/kernel.test.js +0 -414
  57. package/dist/lite-kernel.d.ts +0 -55
  58. package/dist/lite-kernel.d.ts.map +0 -1
  59. package/dist/lite-kernel.js +0 -112
  60. package/dist/lite-kernel.test.d.ts +0 -2
  61. package/dist/lite-kernel.test.d.ts.map +0 -1
  62. package/dist/lite-kernel.test.js +0 -161
  63. package/dist/logger.d.ts +0 -71
  64. package/dist/logger.d.ts.map +0 -1
  65. package/dist/logger.js +0 -312
  66. package/dist/logger.test.d.ts +0 -2
  67. package/dist/logger.test.d.ts.map +0 -1
  68. package/dist/logger.test.js +0 -92
  69. package/dist/plugin-loader.d.ts +0 -164
  70. package/dist/plugin-loader.d.ts.map +0 -1
  71. package/dist/plugin-loader.js +0 -319
  72. package/dist/plugin-loader.test.d.ts +0 -2
  73. package/dist/plugin-loader.test.d.ts.map +0 -1
  74. package/dist/plugin-loader.test.js +0 -348
  75. package/dist/qa/adapter.d.ts +0 -14
  76. package/dist/qa/adapter.d.ts.map +0 -1
  77. package/dist/qa/adapter.js +0 -1
  78. package/dist/qa/http-adapter.d.ts +0 -16
  79. package/dist/qa/http-adapter.d.ts.map +0 -1
  80. package/dist/qa/http-adapter.js +0 -107
  81. package/dist/qa/index.d.ts +0 -4
  82. package/dist/qa/index.d.ts.map +0 -1
  83. package/dist/qa/index.js +0 -3
  84. package/dist/qa/runner.d.ts +0 -27
  85. package/dist/qa/runner.d.ts.map +0 -1
  86. package/dist/qa/runner.js +0 -157
  87. package/dist/security/index.d.ts +0 -17
  88. package/dist/security/index.d.ts.map +0 -1
  89. package/dist/security/index.js +0 -17
  90. package/dist/security/permission-manager.d.ts +0 -96
  91. package/dist/security/permission-manager.d.ts.map +0 -1
  92. package/dist/security/permission-manager.js +0 -235
  93. package/dist/security/permission-manager.test.d.ts +0 -2
  94. package/dist/security/permission-manager.test.d.ts.map +0 -1
  95. package/dist/security/permission-manager.test.js +0 -220
  96. package/dist/security/plugin-config-validator.d.ts +0 -79
  97. package/dist/security/plugin-config-validator.d.ts.map +0 -1
  98. package/dist/security/plugin-config-validator.js +0 -166
  99. package/dist/security/plugin-config-validator.test.d.ts +0 -2
  100. package/dist/security/plugin-config-validator.test.d.ts.map +0 -1
  101. package/dist/security/plugin-config-validator.test.js +0 -223
  102. package/dist/security/plugin-permission-enforcer.d.ts +0 -154
  103. package/dist/security/plugin-permission-enforcer.d.ts.map +0 -1
  104. package/dist/security/plugin-permission-enforcer.js +0 -323
  105. package/dist/security/plugin-permission-enforcer.test.d.ts +0 -2
  106. package/dist/security/plugin-permission-enforcer.test.d.ts.map +0 -1
  107. package/dist/security/plugin-permission-enforcer.test.js +0 -205
  108. package/dist/security/plugin-signature-verifier.d.ts +0 -96
  109. package/dist/security/plugin-signature-verifier.d.ts.map +0 -1
  110. package/dist/security/plugin-signature-verifier.js +0 -250
  111. package/dist/security/sandbox-runtime.d.ts +0 -115
  112. package/dist/security/sandbox-runtime.d.ts.map +0 -1
  113. package/dist/security/sandbox-runtime.js +0 -311
  114. package/dist/security/security-scanner.d.ts +0 -92
  115. package/dist/security/security-scanner.d.ts.map +0 -1
  116. package/dist/security/security-scanner.js +0 -273
  117. package/dist/types.d.ts +0 -89
  118. package/dist/types.d.ts.map +0 -1
  119. package/dist/types.js +0 -1
  120. package/dist/utils/env.d.ts +0 -20
  121. package/dist/utils/env.d.ts.map +0 -1
  122. package/dist/utils/env.js +0 -46
  123. package/dist/utils/env.test.d.ts +0 -2
  124. package/dist/utils/env.test.d.ts.map +0 -1
  125. package/dist/utils/env.test.js +0 -52
@@ -0,0 +1,1777 @@
1
+ import { LoggerConfig } from '@objectstack/spec/system';
2
+ import { Logger, IServiceRegistry } from '@objectstack/spec/contracts';
3
+ export { DriverInterface, IDataEngine, IHttpRequest, IHttpResponse, IHttpServer, Logger, Middleware, RouteHandler } from '@objectstack/spec/contracts';
4
+ import { z } from 'zod';
5
+ import { ConflictResolutionStrategy, ApiRegistryEntryInput, ApiRegistryEntry, ApiDiscoveryQuery, ApiDiscoveryResponse, ApiEndpointRegistration, ApiRegistry as ApiRegistry$1 } from '@objectstack/spec/api';
6
+ import { QA } from '@objectstack/spec';
7
+ import { PluginCapability, PermissionSet, ResourceType, PermissionAction, Permission, SandboxConfig, SecurityScanResult, SecurityVulnerability, PluginHealthCheck, PluginHealthStatus as PluginHealthStatus$1, PluginHealthReport, HotReloadConfig, SemanticVersion, VersionConstraint, CompatibilityLevel, DependencyConflict } from '@objectstack/spec/kernel';
8
+
9
+ /**
10
+ * Service Lifecycle Types
11
+ * Defines how services are instantiated and managed
12
+ */
13
+ declare enum ServiceLifecycle {
14
+ /** Single instance shared across all requests */
15
+ SINGLETON = "singleton",
16
+ /** New instance created for each request */
17
+ TRANSIENT = "transient",
18
+ /** New instance per scope (e.g., per HTTP request) */
19
+ SCOPED = "scoped"
20
+ }
21
+ /**
22
+ * Service Factory
23
+ * Function that creates a service instance
24
+ */
25
+ type ServiceFactory<T = any> = (ctx: PluginContext) => T | Promise<T>;
26
+ /**
27
+ * Service Registration Options
28
+ */
29
+ interface ServiceRegistration {
30
+ name: string;
31
+ factory: ServiceFactory;
32
+ lifecycle: ServiceLifecycle;
33
+ dependencies?: string[];
34
+ }
35
+ /**
36
+ * Plugin Configuration Validator Interface
37
+ * Uses Zod for runtime validation of plugin configurations
38
+ * @deprecated Use the PluginConfigValidator class from security module instead
39
+ */
40
+ interface IPluginConfigValidator {
41
+ schema: z.ZodSchema;
42
+ validate(config: any): any;
43
+ }
44
+ /**
45
+ * Plugin Metadata with Enhanced Features
46
+ */
47
+ interface PluginMetadata extends Plugin {
48
+ /** Semantic version (e.g., "1.0.0") */
49
+ version: string;
50
+ /** Configuration schema for validation */
51
+ configSchema?: z.ZodSchema;
52
+ /** Plugin signature for security verification */
53
+ signature?: string;
54
+ /** Plugin health check function */
55
+ healthCheck?(): Promise<PluginHealthStatus>;
56
+ /** Startup timeout in milliseconds (default: 30000) */
57
+ startupTimeout?: number;
58
+ /** Whether plugin supports hot reload */
59
+ hotReloadable?: boolean;
60
+ }
61
+ /**
62
+ * Plugin Health Status
63
+ */
64
+ interface PluginHealthStatus {
65
+ healthy: boolean;
66
+ message?: string;
67
+ details?: Record<string, any>;
68
+ lastCheck?: Date;
69
+ }
70
+ /**
71
+ * Plugin Load Result
72
+ */
73
+ interface PluginLoadResult {
74
+ success: boolean;
75
+ plugin?: PluginMetadata;
76
+ error?: Error;
77
+ loadTime?: number;
78
+ }
79
+ /**
80
+ * Plugin Startup Result
81
+ */
82
+ interface PluginStartupResult {
83
+ success: boolean;
84
+ pluginName: string;
85
+ startTime?: number;
86
+ error?: Error;
87
+ timedOut?: boolean;
88
+ }
89
+ /**
90
+ * Version Compatibility Result
91
+ */
92
+ interface VersionCompatibility {
93
+ compatible: boolean;
94
+ pluginVersion: string;
95
+ requiredVersion?: string;
96
+ message?: string;
97
+ }
98
+ /**
99
+ * Enhanced Plugin Loader
100
+ * Provides advanced plugin loading capabilities with validation, security, and lifecycle management
101
+ */
102
+ declare class PluginLoader {
103
+ private logger;
104
+ private context?;
105
+ private configValidator;
106
+ private loadedPlugins;
107
+ private serviceFactories;
108
+ private serviceInstances;
109
+ private scopedServices;
110
+ private creating;
111
+ constructor(logger: Logger);
112
+ /**
113
+ * Set the plugin context for service factories
114
+ */
115
+ setContext(context: PluginContext): void;
116
+ /**
117
+ * Get a synchronous service instance if it exists (Sync Helper)
118
+ */
119
+ getServiceInstance<T>(name: string): T | undefined;
120
+ /**
121
+ * Load a plugin asynchronously with validation
122
+ */
123
+ loadPlugin(plugin: Plugin): Promise<PluginLoadResult>;
124
+ /**
125
+ * Register a service with factory function
126
+ */
127
+ registerServiceFactory(registration: ServiceRegistration): void;
128
+ /**
129
+ * Get or create a service instance based on lifecycle type
130
+ */
131
+ getService<T>(name: string, scopeId?: string): Promise<T>;
132
+ /**
133
+ * Register a static service instance (legacy support)
134
+ */
135
+ registerService(name: string, service: any): void;
136
+ /**
137
+ * Check if a service is registered (either as instance or factory)
138
+ */
139
+ hasService(name: string): boolean;
140
+ /**
141
+ * Detect circular dependencies in service factories
142
+ * Note: This only detects cycles in service dependencies, not plugin dependencies.
143
+ * Plugin dependency cycles are detected in the kernel's resolveDependencies method.
144
+ */
145
+ detectCircularDependencies(): string[];
146
+ /**
147
+ * Check plugin health
148
+ */
149
+ checkPluginHealth(pluginName: string): Promise<PluginHealthStatus>;
150
+ /**
151
+ * Clear scoped services for a scope
152
+ */
153
+ clearScope(scopeId: string): void;
154
+ /**
155
+ * Get all loaded plugins
156
+ */
157
+ getLoadedPlugins(): Map<string, PluginMetadata>;
158
+ private toPluginMetadata;
159
+ private validatePluginStructure;
160
+ private checkVersionCompatibility;
161
+ private isValidSemanticVersion;
162
+ private validatePluginConfig;
163
+ private verifyPluginSignature;
164
+ private getSingletonService;
165
+ private createTransientService;
166
+ private getScopedService;
167
+ private createServiceInstance;
168
+ }
169
+
170
+ /**
171
+ * Enhanced Kernel Configuration
172
+ */
173
+ interface ObjectKernelConfig {
174
+ logger?: Partial<LoggerConfig>;
175
+ /** Default plugin startup timeout in milliseconds */
176
+ defaultStartupTimeout?: number;
177
+ /** Whether to enable graceful shutdown */
178
+ gracefulShutdown?: boolean;
179
+ /** Graceful shutdown timeout in milliseconds */
180
+ shutdownTimeout?: number;
181
+ /** Whether to rollback on startup failure */
182
+ rollbackOnFailure?: boolean;
183
+ /** Whether to skip strict system requirement validation (Critical for testing) */
184
+ skipSystemValidation?: boolean;
185
+ }
186
+ /**
187
+ * Enhanced ObjectKernel with Advanced Plugin Management
188
+ *
189
+ * Extends the basic ObjectKernel with:
190
+ * - Async plugin loading with validation
191
+ * - Version compatibility checking
192
+ * - Plugin signature verification
193
+ * - Configuration validation (Zod)
194
+ * - Factory-based dependency injection
195
+ * - Service lifecycle management (singleton/transient/scoped)
196
+ * - Circular dependency detection
197
+ * - Lazy loading services
198
+ * - Graceful shutdown
199
+ * - Plugin startup timeout control
200
+ * - Startup failure rollback
201
+ * - Plugin health checks
202
+ */
203
+ declare class ObjectKernel {
204
+ private plugins;
205
+ private services;
206
+ private hooks;
207
+ private state;
208
+ private logger;
209
+ private context;
210
+ private pluginLoader;
211
+ private config;
212
+ private startedPlugins;
213
+ private pluginStartTimes;
214
+ private shutdownHandlers;
215
+ constructor(config?: ObjectKernelConfig);
216
+ /**
217
+ * Register a plugin with enhanced validation
218
+ */
219
+ use(plugin: Plugin): Promise<this>;
220
+ /**
221
+ * Register a service instance directly
222
+ */
223
+ registerService<T>(name: string, service: T): this;
224
+ /**
225
+ * Register a service factory with lifecycle management
226
+ */
227
+ registerServiceFactory<T>(name: string, factory: ServiceFactory<T>, lifecycle?: ServiceLifecycle, dependencies?: string[]): this;
228
+ /**
229
+ * Validate Critical System Requirements
230
+ */
231
+ private validateSystemRequirements;
232
+ /**
233
+ * Bootstrap the kernel with enhanced features
234
+ */
235
+ bootstrap(): Promise<void>;
236
+ /**
237
+ * Graceful shutdown with timeout
238
+ */
239
+ shutdown(): Promise<void>;
240
+ /**
241
+ * Check health of a specific plugin
242
+ */
243
+ checkPluginHealth(pluginName: string): Promise<any>;
244
+ /**
245
+ * Check health of all plugins
246
+ */
247
+ checkAllPluginsHealth(): Promise<Map<string, any>>;
248
+ /**
249
+ * Get plugin startup metrics
250
+ */
251
+ getPluginMetrics(): Map<string, number>;
252
+ /**
253
+ * Get a service (sync helper)
254
+ */
255
+ getService<T>(name: string): T;
256
+ /**
257
+ * Get a service asynchronously (supports factories)
258
+ */
259
+ getServiceAsync<T>(name: string, scopeId?: string): Promise<T>;
260
+ /**
261
+ * Check if kernel is running
262
+ */
263
+ isRunning(): boolean;
264
+ /**
265
+ * Get kernel state
266
+ */
267
+ getState(): string;
268
+ private initPluginWithTimeout;
269
+ private startPluginWithTimeout;
270
+ private rollbackStartedPlugins;
271
+ private performShutdown;
272
+ private resolveDependencies;
273
+ private registerShutdownSignals;
274
+ /**
275
+ * Register a custom shutdown handler
276
+ */
277
+ onShutdown(handler: () => Promise<void>): void;
278
+ }
279
+
280
+ /**
281
+ * PluginContext - Runtime context available to plugins
282
+ *
283
+ * Provides access to:
284
+ * - Service registry (registerService/getService)
285
+ * - Event/Hook system (hook/trigger)
286
+ * - Logger
287
+ * - Kernel instance (for advanced use cases)
288
+ */
289
+ interface PluginContext {
290
+ /**
291
+ * Register a service that can be consumed by other plugins
292
+ * @param name - Service name (e.g., 'db', 'http-server', 'objectql')
293
+ * @param service - Service instance
294
+ */
295
+ registerService(name: string, service: any): void;
296
+ /**
297
+ * Get a service registered by another plugin
298
+ * @param name - Service name
299
+ * @returns Service instance
300
+ * @throws Error if service not found
301
+ */
302
+ getService<T>(name: string): T;
303
+ /**
304
+ * Get all registered services
305
+ */
306
+ getServices(): Map<string, any>;
307
+ /**
308
+ * Register a hook handler
309
+ * @param name - Hook name (e.g., 'kernel:ready', 'data:beforeInsert')
310
+ * @param handler - Hook handler function
311
+ */
312
+ hook(name: string, handler: (...args: any[]) => void | Promise<void>): void;
313
+ /**
314
+ * Trigger a hook
315
+ * @param name - Hook name
316
+ * @param args - Arguments to pass to hook handlers
317
+ */
318
+ trigger(name: string, ...args: any[]): Promise<void>;
319
+ /**
320
+ * Logger instance
321
+ */
322
+ logger: Logger;
323
+ /**
324
+ * Get the kernel instance (for advanced use cases)
325
+ * @returns Kernel instance
326
+ */
327
+ getKernel(): ObjectKernel;
328
+ }
329
+ /**
330
+ * Plugin Interface
331
+ *
332
+ * All ObjectStack plugins must implement this interface.
333
+ */
334
+ interface Plugin {
335
+ /**
336
+ * Unique plugin name (e.g., 'com.objectstack.engine.objectql')
337
+ */
338
+ name: string;
339
+ /**
340
+ * Plugin version
341
+ */
342
+ version?: string;
343
+ /**
344
+ * List of other plugin names that this plugin depends on.
345
+ * The kernel ensures these plugins are initialized before this one.
346
+ */
347
+ dependencies?: string[];
348
+ /**
349
+ * Init Phase: Register services
350
+ * Called when kernel is initializing.
351
+ * Use this to register services that other plugins might need.
352
+ */
353
+ init(ctx: PluginContext): Promise<void> | void;
354
+ /**
355
+ * Start Phase: Execute business logic
356
+ * Called after all plugins have been initialized.
357
+ * Use this to start servers, connect to DBs, or execute main logic.
358
+ */
359
+ start?(ctx: PluginContext): Promise<void> | void;
360
+ /**
361
+ * Destroy Phase: Cleanup
362
+ * Called when kernel is shutting down.
363
+ */
364
+ destroy?(): Promise<void> | void;
365
+ }
366
+
367
+ /**
368
+ * Kernel state machine
369
+ */
370
+ type KernelState = 'idle' | 'initializing' | 'running' | 'stopping' | 'stopped';
371
+ /**
372
+ * ObjectKernelBase - Abstract Base Class for Microkernel
373
+ *
374
+ * Provides common functionality for ObjectKernel and LiteKernel:
375
+ * - Plugin management (Map storage)
376
+ * - Dependency resolution (topological sort)
377
+ * - Hook/Event system
378
+ * - Context creation
379
+ * - State validation
380
+ *
381
+ * This eliminates code duplication between the implementations.
382
+ */
383
+ declare abstract class ObjectKernelBase {
384
+ protected plugins: Map<string, Plugin>;
385
+ protected services: IServiceRegistry | Map<string, any>;
386
+ protected hooks: Map<string, Array<(...args: any[]) => void | Promise<void>>>;
387
+ protected state: KernelState;
388
+ protected logger: Logger;
389
+ protected context: PluginContext;
390
+ constructor(logger: Logger);
391
+ /**
392
+ * Validate kernel state
393
+ * @param requiredState - Required state for the operation
394
+ * @throws Error if current state doesn't match
395
+ */
396
+ protected validateState(requiredState: KernelState): void;
397
+ /**
398
+ * Validate kernel is in idle state (for plugin registration)
399
+ */
400
+ protected validateIdle(): void;
401
+ /**
402
+ * Create the plugin context
403
+ * Subclasses can override to customize context creation
404
+ */
405
+ protected createContext(): PluginContext;
406
+ /**
407
+ * Resolve plugin dependencies using topological sort
408
+ * @returns Ordered list of plugins (dependencies first)
409
+ */
410
+ protected resolveDependencies(): Plugin[];
411
+ /**
412
+ * Run plugin init phase
413
+ * @param plugin - Plugin to initialize
414
+ */
415
+ protected runPluginInit(plugin: Plugin): Promise<void>;
416
+ /**
417
+ * Run plugin start phase
418
+ * @param plugin - Plugin to start
419
+ */
420
+ protected runPluginStart(plugin: Plugin): Promise<void>;
421
+ /**
422
+ * Run plugin destroy phase
423
+ * @param plugin - Plugin to destroy
424
+ */
425
+ protected runPluginDestroy(plugin: Plugin): Promise<void>;
426
+ /**
427
+ * Trigger a hook with all registered handlers
428
+ * @param name - Hook name
429
+ * @param args - Arguments to pass to handlers
430
+ */
431
+ protected triggerHook(name: string, ...args: any[]): Promise<void>;
432
+ /**
433
+ * Get current kernel state
434
+ */
435
+ getState(): KernelState;
436
+ /**
437
+ * Get all registered plugins
438
+ */
439
+ getPlugins(): Map<string, Plugin>;
440
+ /**
441
+ * Abstract methods to be implemented by subclasses
442
+ */
443
+ abstract use(plugin: Plugin): this | Promise<this>;
444
+ abstract bootstrap(): Promise<void>;
445
+ abstract destroy(): Promise<void>;
446
+ }
447
+
448
+ /**
449
+ * ObjectKernel - MiniKernel Architecture
450
+ *
451
+ * A highly modular, plugin-based microkernel that:
452
+ * - Manages plugin lifecycle (init, start, destroy)
453
+ * - Provides dependency injection via service registry
454
+ * - Implements event/hook system for inter-plugin communication
455
+ * - Handles dependency resolution (topological sort)
456
+ * - Provides configurable logging for server and browser
457
+ *
458
+ * Core philosophy:
459
+ * - Business logic is completely separated into plugins
460
+ * - Kernel only manages lifecycle, DI, and hooks
461
+ * - Plugins are loaded as equal building blocks
462
+ */
463
+ declare class LiteKernel extends ObjectKernelBase {
464
+ constructor(config?: {
465
+ logger?: Partial<LoggerConfig>;
466
+ });
467
+ /**
468
+ * Register a plugin
469
+ * @param plugin - Plugin instance
470
+ */
471
+ use(plugin: Plugin): this;
472
+ /**
473
+ * Bootstrap the kernel
474
+ * 1. Resolve dependencies (topological sort)
475
+ * 2. Init phase - plugins register services
476
+ * 3. Start phase - plugins execute business logic
477
+ * 4. Trigger 'kernel:ready' hook
478
+ */
479
+ bootstrap(): Promise<void>;
480
+ /**
481
+ * Shutdown the kernel
482
+ * Calls destroy on all plugins in reverse order
483
+ */
484
+ shutdown(): Promise<void>;
485
+ /**
486
+ * Graceful shutdown - destroy all plugins in reverse order
487
+ */
488
+ destroy(): Promise<void>;
489
+ /**
490
+ * Get a service from the registry
491
+ * Convenience method for external access
492
+ */
493
+ getService<T>(name: string): T;
494
+ /**
495
+ * Check if kernel is running
496
+ */
497
+ isRunning(): boolean;
498
+ }
499
+
500
+ /**
501
+ * Universal Logger Implementation
502
+ *
503
+ * A configurable logger that works in both browser and Node.js environments.
504
+ * - Node.js: Uses Pino for high-performance structured logging
505
+ * - Browser: Simple console-based implementation
506
+ *
507
+ * Features:
508
+ * - Structured logging with multiple formats (json, text, pretty)
509
+ * - Log level filtering
510
+ * - Sensitive data redaction
511
+ * - File logging with rotation (Node.js only via Pino)
512
+ * - Browser console integration
513
+ * - Distributed tracing support (traceId, spanId)
514
+ */
515
+ declare class ObjectLogger implements Logger {
516
+ private config;
517
+ private isNode;
518
+ private pinoLogger?;
519
+ private pinoInstance?;
520
+ private require?;
521
+ constructor(config?: Partial<LoggerConfig>);
522
+ /**
523
+ * Initialize Pino logger for Node.js
524
+ */
525
+ private initPinoLogger;
526
+ /**
527
+ * Redact sensitive keys from context object (for browser)
528
+ */
529
+ private redactSensitive;
530
+ /**
531
+ * Format log entry for browser
532
+ */
533
+ private formatBrowserLog;
534
+ /**
535
+ * Log using browser console
536
+ */
537
+ private logBrowser;
538
+ /**
539
+ * Public logging methods
540
+ */
541
+ debug(message: string, meta?: Record<string, any>): void;
542
+ info(message: string, meta?: Record<string, any>): void;
543
+ warn(message: string, meta?: Record<string, any>): void;
544
+ error(message: string, errorOrMeta?: Error | Record<string, any>, meta?: Record<string, any>): void;
545
+ fatal(message: string, errorOrMeta?: Error | Record<string, any>, meta?: Record<string, any>): void;
546
+ /**
547
+ * Create a child logger with additional context
548
+ * Note: Child loggers share the parent's Pino instance
549
+ */
550
+ child(context: Record<string, any>): ObjectLogger;
551
+ /**
552
+ * Set trace context for distributed tracing
553
+ */
554
+ withTrace(traceId: string, spanId?: string): ObjectLogger;
555
+ /**
556
+ * Cleanup resources
557
+ */
558
+ destroy(): Promise<void>;
559
+ /**
560
+ * Compatibility method for console.log usage
561
+ */
562
+ log(message: string, ...args: any[]): void;
563
+ }
564
+ /**
565
+ * Create a logger instance
566
+ */
567
+ declare function createLogger(config?: Partial<LoggerConfig>): ObjectLogger;
568
+
569
+ /**
570
+ * API Registry Service
571
+ *
572
+ * Central registry for managing API endpoints across different protocols.
573
+ * Provides endpoint registration, discovery, and conflict resolution.
574
+ *
575
+ * **Features:**
576
+ * - Multi-protocol support (REST, GraphQL, OData, WebSocket, etc.)
577
+ * - Route conflict detection with configurable resolution strategies
578
+ * - RBAC permission integration
579
+ * - Dynamic schema linking with ObjectQL references
580
+ * - Plugin API registration
581
+ *
582
+ * **Architecture Alignment:**
583
+ * - Kubernetes: Service Discovery & API Server
584
+ * - AWS API Gateway: Unified API Management
585
+ * - Kong Gateway: Plugin-based API Management
586
+ *
587
+ * @example
588
+ * ```typescript
589
+ * const registry = new ApiRegistry(logger, 'priority');
590
+ *
591
+ * // Register an API
592
+ * registry.registerApi({
593
+ * id: 'customer_api',
594
+ * name: 'Customer API',
595
+ * type: 'rest',
596
+ * version: 'v1',
597
+ * basePath: '/api/v1/customers',
598
+ * endpoints: [...]
599
+ * });
600
+ *
601
+ * // Discover APIs
602
+ * const apis = registry.findApis({ type: 'rest', status: 'active' });
603
+ *
604
+ * // Get registry snapshot
605
+ * const snapshot = registry.getRegistry();
606
+ * ```
607
+ */
608
+ declare class ApiRegistry {
609
+ private apis;
610
+ private endpoints;
611
+ private routes;
612
+ private apisByType;
613
+ private apisByTag;
614
+ private apisByStatus;
615
+ private conflictResolution;
616
+ private logger;
617
+ private version;
618
+ private updatedAt;
619
+ constructor(logger: Logger, conflictResolution?: ConflictResolutionStrategy, version?: string);
620
+ /**
621
+ * Register an API with its endpoints
622
+ *
623
+ * @param api - API registry entry
624
+ * @throws Error if API already registered or route conflicts detected
625
+ */
626
+ registerApi(api: ApiRegistryEntryInput): void;
627
+ /**
628
+ * Unregister an API and all its endpoints
629
+ *
630
+ * @param apiId - API identifier
631
+ */
632
+ unregisterApi(apiId: string): void;
633
+ /**
634
+ * Register a single endpoint
635
+ *
636
+ * @param apiId - API identifier
637
+ * @param endpoint - Endpoint registration
638
+ * @throws Error if route conflict detected
639
+ */
640
+ private registerEndpoint;
641
+ /**
642
+ * Unregister a single endpoint
643
+ *
644
+ * @param apiId - API identifier
645
+ * @param endpointId - Endpoint identifier
646
+ */
647
+ private unregisterEndpoint;
648
+ /**
649
+ * Register a route with conflict detection
650
+ *
651
+ * @param apiId - API identifier
652
+ * @param endpoint - Endpoint registration
653
+ * @throws Error if route conflict detected (based on strategy)
654
+ */
655
+ private registerRoute;
656
+ /**
657
+ * Handle route conflict based on resolution strategy
658
+ *
659
+ * @param routeKey - Route key
660
+ * @param apiId - New API identifier
661
+ * @param endpoint - New endpoint
662
+ * @param existingRoute - Existing route registration
663
+ * @param newPriority - New endpoint priority
664
+ * @throws Error if strategy is 'error'
665
+ */
666
+ private handleRouteConflict;
667
+ /**
668
+ * Generate a unique route key for conflict detection
669
+ *
670
+ * NOTE: This implementation uses exact string matching for route conflict detection.
671
+ * It works well for static paths but has limitations with parameterized routes.
672
+ * For example, `/api/users/:id` and `/api/users/:userId` will NOT be detected as conflicts
673
+ * even though they are semantically identical parameterized patterns. Similarly,
674
+ * `/api/:resource/list` and `/api/:entity/list` would also not be detected as conflicting.
675
+ *
676
+ * For more advanced conflict detection (e.g., path-to-regexp pattern matching),
677
+ * consider integrating with your routing library's conflict detection mechanism.
678
+ *
679
+ * @param endpoint - Endpoint registration
680
+ * @returns Route key (e.g., "GET:/api/v1/customers/:id")
681
+ */
682
+ private getRouteKey;
683
+ /**
684
+ * Validate endpoint registration
685
+ *
686
+ * @param endpoint - Endpoint to validate
687
+ * @param apiId - API identifier (for error messages)
688
+ * @throws Error if endpoint is invalid
689
+ */
690
+ private validateEndpoint;
691
+ /**
692
+ * Get an API by ID
693
+ *
694
+ * @param apiId - API identifier
695
+ * @returns API registry entry or undefined
696
+ */
697
+ getApi(apiId: string): ApiRegistryEntry | undefined;
698
+ /**
699
+ * Get all registered APIs
700
+ *
701
+ * @returns Array of all APIs
702
+ */
703
+ getAllApis(): ApiRegistryEntry[];
704
+ /**
705
+ * Find APIs matching query criteria
706
+ *
707
+ * Performance optimized with auxiliary indices for O(1) lookups on type, tags, and status.
708
+ *
709
+ * @param query - Discovery query parameters
710
+ * @returns Matching APIs
711
+ */
712
+ findApis(query: ApiDiscoveryQuery): ApiDiscoveryResponse;
713
+ /**
714
+ * Get endpoint by API ID and endpoint ID
715
+ *
716
+ * @param apiId - API identifier
717
+ * @param endpointId - Endpoint identifier
718
+ * @returns Endpoint registration or undefined
719
+ */
720
+ getEndpoint(apiId: string, endpointId: string): ApiEndpointRegistration | undefined;
721
+ /**
722
+ * Find endpoint by route (method + path)
723
+ *
724
+ * @param method - HTTP method
725
+ * @param path - URL path
726
+ * @returns Endpoint registration or undefined
727
+ */
728
+ findEndpointByRoute(method: string, path: string): {
729
+ api: ApiRegistryEntry;
730
+ endpoint: ApiEndpointRegistration;
731
+ } | undefined;
732
+ /**
733
+ * Get complete registry snapshot
734
+ *
735
+ * @returns Current registry state
736
+ */
737
+ getRegistry(): ApiRegistry$1;
738
+ /**
739
+ * Clear all registered APIs
740
+ *
741
+ * **⚠️ SAFETY WARNING:**
742
+ * This method clears all registered APIs and should be used with caution.
743
+ *
744
+ * **Usage Restrictions:**
745
+ * - In production environments (NODE_ENV=production), a `force: true` parameter is required
746
+ * - Primarily intended for testing and development hot-reload scenarios
747
+ *
748
+ * @param options - Clear options
749
+ * @param options.force - Force clear in production environment (default: false)
750
+ * @throws Error if called in production without force flag
751
+ *
752
+ * @example Safe usage in tests
753
+ * ```typescript
754
+ * beforeEach(() => {
755
+ * registry.clear(); // OK in test environment
756
+ * });
757
+ * ```
758
+ *
759
+ * @example Usage in production (requires explicit force)
760
+ * ```typescript
761
+ * // In production, explicit force is required
762
+ * registry.clear({ force: true });
763
+ * ```
764
+ */
765
+ clear(options?: {
766
+ force?: boolean;
767
+ }): void;
768
+ /**
769
+ * Get registry statistics
770
+ *
771
+ * @returns Registry statistics
772
+ */
773
+ getStats(): {
774
+ totalApis: number;
775
+ totalEndpoints: number;
776
+ totalRoutes: number;
777
+ apisByType: Record<string, number>;
778
+ endpointsByApi: Record<string, number>;
779
+ };
780
+ /**
781
+ * Update auxiliary indices when an API is registered
782
+ *
783
+ * @param api - API entry to index
784
+ * @private
785
+ * @internal
786
+ */
787
+ private updateIndices;
788
+ /**
789
+ * Remove API from auxiliary indices when unregistered
790
+ *
791
+ * @param api - API entry to remove from indices
792
+ * @private
793
+ * @internal
794
+ */
795
+ private removeFromIndices;
796
+ /**
797
+ * Helper to ensure an index set exists and return it
798
+ *
799
+ * @param map - Index map
800
+ * @param key - Index key
801
+ * @returns The Set for this key (created if needed)
802
+ * @private
803
+ * @internal
804
+ */
805
+ private ensureIndexSet;
806
+ /**
807
+ * Helper to remove an ID from an index set and clean up empty sets
808
+ *
809
+ * @param map - Index map
810
+ * @param key - Index key
811
+ * @param id - API ID to remove
812
+ * @private
813
+ * @internal
814
+ */
815
+ private removeFromIndexSet;
816
+ /**
817
+ * Check if running in production environment
818
+ *
819
+ * @returns true if NODE_ENV is 'production'
820
+ * @private
821
+ * @internal
822
+ */
823
+ private isProductionEnvironment;
824
+ }
825
+
826
+ /**
827
+ * API Registry Plugin Configuration
828
+ */
829
+ interface ApiRegistryPluginConfig {
830
+ /**
831
+ * Conflict resolution strategy for route conflicts
832
+ * @default 'error'
833
+ */
834
+ conflictResolution?: ConflictResolutionStrategy;
835
+ /**
836
+ * Registry version
837
+ * @default '1.0.0'
838
+ */
839
+ version?: string;
840
+ }
841
+ /**
842
+ * API Registry Plugin
843
+ *
844
+ * Registers the API Registry service in the kernel, making it available
845
+ * to all plugins for endpoint registration and discovery.
846
+ *
847
+ * **Usage:**
848
+ * ```typescript
849
+ * const kernel = new ObjectKernel();
850
+ *
851
+ * // Register API Registry Plugin
852
+ * kernel.use(createApiRegistryPlugin({ conflictResolution: 'priority' }));
853
+ *
854
+ * // In other plugins, access the API Registry
855
+ * const plugin: Plugin = {
856
+ * name: 'my-plugin',
857
+ * init: async (ctx) => {
858
+ * const registry = ctx.getService<ApiRegistry>('api-registry');
859
+ *
860
+ * // Register plugin APIs
861
+ * registry.registerApi({
862
+ * id: 'my_plugin_api',
863
+ * name: 'My Plugin API',
864
+ * type: 'rest',
865
+ * version: 'v1',
866
+ * basePath: '/api/v1/my-plugin',
867
+ * endpoints: [...]
868
+ * });
869
+ * }
870
+ * };
871
+ * ```
872
+ *
873
+ * @param config - Plugin configuration
874
+ * @returns Plugin instance
875
+ */
876
+ declare function createApiRegistryPlugin(config?: ApiRegistryPluginConfig): Plugin;
877
+
878
+ /**
879
+ * Interface for executing test actions against a target system.
880
+ * The target could be a local Kernel instance or a remote API.
881
+ */
882
+ interface TestExecutionAdapter {
883
+ /**
884
+ * Execute a single test action.
885
+ * @param action The action to perform (create_record, api_call, etc.)
886
+ * @returns The result of the action (e.g. created record, API response)
887
+ */
888
+ execute(action: QA.TestAction, context: Record<string, unknown>): Promise<unknown>;
889
+ }
890
+
891
+ interface TestResult {
892
+ scenarioId: string;
893
+ passed: boolean;
894
+ steps: StepResult[];
895
+ error?: unknown;
896
+ duration: number;
897
+ }
898
+ interface StepResult {
899
+ stepName: string;
900
+ passed: boolean;
901
+ error?: unknown;
902
+ output?: unknown;
903
+ duration: number;
904
+ }
905
+ declare class TestRunner {
906
+ private adapter;
907
+ constructor(adapter: TestExecutionAdapter);
908
+ runSuite(suite: QA.TestSuite): Promise<TestResult[]>;
909
+ runScenario(scenario: QA.TestScenario): Promise<TestResult>;
910
+ private runStep;
911
+ private resolveVariables;
912
+ private getValueByPath;
913
+ private assert;
914
+ }
915
+
916
+ declare class HttpTestAdapter implements TestExecutionAdapter {
917
+ private baseUrl;
918
+ private authToken?;
919
+ constructor(baseUrl: string, authToken?: string | undefined);
920
+ execute(action: QA.TestAction, _context: Record<string, unknown>): Promise<unknown>;
921
+ private createRecord;
922
+ private updateRecord;
923
+ private deleteRecord;
924
+ private readRecord;
925
+ private queryRecords;
926
+ private rawApiCall;
927
+ private handleResponse;
928
+ }
929
+
930
+ type index_HttpTestAdapter = HttpTestAdapter;
931
+ declare const index_HttpTestAdapter: typeof HttpTestAdapter;
932
+ type index_StepResult = StepResult;
933
+ type index_TestExecutionAdapter = TestExecutionAdapter;
934
+ type index_TestResult = TestResult;
935
+ type index_TestRunner = TestRunner;
936
+ declare const index_TestRunner: typeof TestRunner;
937
+ declare namespace index {
938
+ export { index_HttpTestAdapter as HttpTestAdapter, type index_StepResult as StepResult, type index_TestExecutionAdapter as TestExecutionAdapter, type index_TestResult as TestResult, index_TestRunner as TestRunner };
939
+ }
940
+
941
+ /**
942
+ * Plugin Signature Configuration
943
+ * Controls how plugin signatures are verified
944
+ */
945
+ interface PluginSignatureConfig {
946
+ /**
947
+ * Map of publisher IDs to their trusted public keys
948
+ * Format: { 'com.objectstack': '-----BEGIN PUBLIC KEY-----...' }
949
+ */
950
+ trustedPublicKeys: Map<string, string>;
951
+ /**
952
+ * Signature algorithm to use
953
+ * - RS256: RSA with SHA-256
954
+ * - ES256: ECDSA with SHA-256
955
+ */
956
+ algorithm: 'RS256' | 'ES256';
957
+ /**
958
+ * Strict mode: reject plugins without signatures
959
+ * - true: All plugins must be signed
960
+ * - false: Unsigned plugins are allowed with warning
961
+ */
962
+ strictMode: boolean;
963
+ /**
964
+ * Allow self-signed plugins in development
965
+ */
966
+ allowSelfSigned?: boolean;
967
+ }
968
+ /**
969
+ * Plugin Signature Verification Result
970
+ */
971
+ interface SignatureVerificationResult {
972
+ verified: boolean;
973
+ error?: string;
974
+ publisherId?: string;
975
+ algorithm?: string;
976
+ signedAt?: Date;
977
+ }
978
+ /**
979
+ * Plugin Signature Verifier
980
+ *
981
+ * Implements cryptographic verification of plugin signatures to ensure:
982
+ * 1. Plugin integrity - code hasn't been tampered with
983
+ * 2. Publisher authenticity - plugin comes from trusted source
984
+ * 3. Non-repudiation - publisher cannot deny signing
985
+ *
986
+ * Architecture:
987
+ * - Uses Node.js crypto module for signature verification
988
+ * - Supports RSA (RS256) and ECDSA (ES256) algorithms
989
+ * - Verifies against trusted public key registry
990
+ * - Computes hash of plugin code for integrity check
991
+ *
992
+ * Security Model:
993
+ * - Public keys are pre-registered and trusted
994
+ * - Plugin signature is verified before loading
995
+ * - Strict mode rejects unsigned plugins
996
+ * - Development mode allows self-signed plugins
997
+ */
998
+ declare class PluginSignatureVerifier {
999
+ private config;
1000
+ private logger;
1001
+ constructor(config: PluginSignatureConfig, logger: Logger);
1002
+ /**
1003
+ * Verify plugin signature
1004
+ *
1005
+ * @param plugin - Plugin metadata with signature
1006
+ * @returns Verification result
1007
+ * @throws Error if verification fails in strict mode
1008
+ */
1009
+ verifyPluginSignature(plugin: PluginMetadata): Promise<SignatureVerificationResult>;
1010
+ /**
1011
+ * Register a trusted public key for a publisher
1012
+ */
1013
+ registerPublicKey(publisherId: string, publicKey: string): void;
1014
+ /**
1015
+ * Remove a trusted public key
1016
+ */
1017
+ revokePublicKey(publisherId: string): void;
1018
+ /**
1019
+ * Get list of trusted publishers
1020
+ */
1021
+ getTrustedPublishers(): string[];
1022
+ private handleUnsignedPlugin;
1023
+ private extractPublisherId;
1024
+ private computePluginHash;
1025
+ private computePluginHashNode;
1026
+ private computePluginHashBrowser;
1027
+ private computePluginHashFallback;
1028
+ private serializePluginCode;
1029
+ private verifyCryptoSignature;
1030
+ private verifyCryptoSignatureNode;
1031
+ private verifyCryptoSignatureBrowser;
1032
+ private validateConfig;
1033
+ }
1034
+
1035
+ /**
1036
+ * Plugin Configuration Validator
1037
+ *
1038
+ * Validates plugin configurations against Zod schemas to ensure:
1039
+ * 1. Type safety - all config values have correct types
1040
+ * 2. Business rules - values meet constraints (min/max, regex, etc.)
1041
+ * 3. Required fields - all mandatory configuration is provided
1042
+ * 4. Default values - missing optional fields get defaults
1043
+ *
1044
+ * Architecture:
1045
+ * - Uses Zod for runtime validation
1046
+ * - Provides detailed error messages with field paths
1047
+ * - Supports nested configuration objects
1048
+ * - Allows partial validation for incremental updates
1049
+ *
1050
+ * Usage:
1051
+ * ```typescript
1052
+ * const validator = new PluginConfigValidator(logger);
1053
+ * const validConfig = validator.validatePluginConfig(plugin, userConfig);
1054
+ * ```
1055
+ */
1056
+ declare class PluginConfigValidator {
1057
+ private logger;
1058
+ constructor(logger: Logger);
1059
+ /**
1060
+ * Validate plugin configuration against its Zod schema
1061
+ *
1062
+ * @param plugin - Plugin metadata with configSchema
1063
+ * @param config - User-provided configuration
1064
+ * @returns Validated and typed configuration
1065
+ * @throws Error with detailed validation errors
1066
+ */
1067
+ validatePluginConfig<T = any>(plugin: PluginMetadata, config: any): T;
1068
+ /**
1069
+ * Validate partial configuration (for incremental updates)
1070
+ *
1071
+ * @param plugin - Plugin metadata
1072
+ * @param partialConfig - Partial configuration to validate
1073
+ * @returns Validated partial configuration
1074
+ */
1075
+ validatePartialConfig<T = any>(plugin: PluginMetadata, partialConfig: any): Partial<T>;
1076
+ /**
1077
+ * Get default configuration from schema
1078
+ *
1079
+ * @param plugin - Plugin metadata
1080
+ * @returns Default configuration object
1081
+ */
1082
+ getDefaultConfig<T = any>(plugin: PluginMetadata): T | undefined;
1083
+ /**
1084
+ * Check if configuration is valid without throwing
1085
+ *
1086
+ * @param plugin - Plugin metadata
1087
+ * @param config - Configuration to check
1088
+ * @returns True if valid, false otherwise
1089
+ */
1090
+ isConfigValid(plugin: PluginMetadata, config: any): boolean;
1091
+ /**
1092
+ * Get configuration errors without throwing
1093
+ *
1094
+ * @param plugin - Plugin metadata
1095
+ * @param config - Configuration to check
1096
+ * @returns Array of validation errors, or empty array if valid
1097
+ */
1098
+ getConfigErrors(plugin: PluginMetadata, config: any): Array<{
1099
+ path: string;
1100
+ message: string;
1101
+ }>;
1102
+ private formatZodErrors;
1103
+ }
1104
+ /**
1105
+ * Create a plugin config validator
1106
+ *
1107
+ * @param logger - Logger instance
1108
+ * @returns Plugin config validator
1109
+ */
1110
+ declare function createPluginConfigValidator(logger: Logger): PluginConfigValidator;
1111
+
1112
+ /**
1113
+ * Plugin Permissions
1114
+ * Defines what actions a plugin is allowed to perform
1115
+ */
1116
+ interface PluginPermissions {
1117
+ canAccessService(serviceName: string): boolean;
1118
+ canTriggerHook(hookName: string): boolean;
1119
+ canReadFile(path: string): boolean;
1120
+ canWriteFile(path: string): boolean;
1121
+ canNetworkRequest(url: string): boolean;
1122
+ }
1123
+ /**
1124
+ * Permission Check Result
1125
+ */
1126
+ interface PermissionCheckResult$1 {
1127
+ allowed: boolean;
1128
+ reason?: string;
1129
+ capability?: string;
1130
+ }
1131
+ /**
1132
+ * Plugin Permission Enforcer
1133
+ *
1134
+ * Implements capability-based security model to enforce:
1135
+ * 1. Service access control - which services a plugin can use
1136
+ * 2. Hook restrictions - which hooks a plugin can trigger
1137
+ * 3. File system permissions - what files a plugin can read/write
1138
+ * 4. Network permissions - what URLs a plugin can access
1139
+ *
1140
+ * Architecture:
1141
+ * - Uses capability declarations from plugin manifest
1142
+ * - Checks permissions before allowing operations
1143
+ * - Logs all permission denials for security audit
1144
+ * - Supports allowlist and denylist patterns
1145
+ *
1146
+ * Security Model:
1147
+ * - Principle of least privilege - plugins get minimal permissions
1148
+ * - Explicit declaration - all capabilities must be declared
1149
+ * - Runtime enforcement - checks happen at operation time
1150
+ * - Audit trail - all denials are logged
1151
+ *
1152
+ * Usage:
1153
+ * ```typescript
1154
+ * const enforcer = new PluginPermissionEnforcer(logger);
1155
+ * enforcer.registerPluginPermissions(pluginName, capabilities);
1156
+ * enforcer.enforceServiceAccess(pluginName, 'database');
1157
+ * ```
1158
+ */
1159
+ declare class PluginPermissionEnforcer {
1160
+ private logger;
1161
+ private permissionRegistry;
1162
+ private capabilityRegistry;
1163
+ constructor(logger: Logger);
1164
+ /**
1165
+ * Register plugin capabilities and build permission set
1166
+ *
1167
+ * @param pluginName - Plugin identifier
1168
+ * @param capabilities - Array of capability declarations
1169
+ */
1170
+ registerPluginPermissions(pluginName: string, capabilities: PluginCapability[]): void;
1171
+ /**
1172
+ * Enforce service access permission
1173
+ *
1174
+ * @param pluginName - Plugin requesting access
1175
+ * @param serviceName - Service to access
1176
+ * @throws Error if permission denied
1177
+ */
1178
+ enforceServiceAccess(pluginName: string, serviceName: string): void;
1179
+ /**
1180
+ * Enforce hook trigger permission
1181
+ *
1182
+ * @param pluginName - Plugin requesting access
1183
+ * @param hookName - Hook to trigger
1184
+ * @throws Error if permission denied
1185
+ */
1186
+ enforceHookTrigger(pluginName: string, hookName: string): void;
1187
+ /**
1188
+ * Enforce file read permission
1189
+ *
1190
+ * @param pluginName - Plugin requesting access
1191
+ * @param path - File path to read
1192
+ * @throws Error if permission denied
1193
+ */
1194
+ enforceFileRead(pluginName: string, path: string): void;
1195
+ /**
1196
+ * Enforce file write permission
1197
+ *
1198
+ * @param pluginName - Plugin requesting access
1199
+ * @param path - File path to write
1200
+ * @throws Error if permission denied
1201
+ */
1202
+ enforceFileWrite(pluginName: string, path: string): void;
1203
+ /**
1204
+ * Enforce network request permission
1205
+ *
1206
+ * @param pluginName - Plugin requesting access
1207
+ * @param url - URL to access
1208
+ * @throws Error if permission denied
1209
+ */
1210
+ enforceNetworkRequest(pluginName: string, url: string): void;
1211
+ /**
1212
+ * Get plugin capabilities
1213
+ *
1214
+ * @param pluginName - Plugin identifier
1215
+ * @returns Array of capabilities or undefined
1216
+ */
1217
+ getPluginCapabilities(pluginName: string): PluginCapability[] | undefined;
1218
+ /**
1219
+ * Get plugin permissions
1220
+ *
1221
+ * @param pluginName - Plugin identifier
1222
+ * @returns Permissions object or undefined
1223
+ */
1224
+ getPluginPermissions(pluginName: string): PluginPermissions | undefined;
1225
+ /**
1226
+ * Revoke all permissions for a plugin
1227
+ *
1228
+ * @param pluginName - Plugin identifier
1229
+ */
1230
+ revokePermissions(pluginName: string): void;
1231
+ private checkPermission;
1232
+ private checkServiceAccess;
1233
+ private checkHookAccess;
1234
+ private checkFileRead;
1235
+ private checkFileWrite;
1236
+ private checkNetworkAccess;
1237
+ }
1238
+ /**
1239
+ * Secure Plugin Context
1240
+ * Wraps PluginContext with permission checks
1241
+ */
1242
+ declare class SecurePluginContext implements PluginContext {
1243
+ private pluginName;
1244
+ private permissionEnforcer;
1245
+ private baseContext;
1246
+ constructor(pluginName: string, permissionEnforcer: PluginPermissionEnforcer, baseContext: PluginContext);
1247
+ registerService(name: string, service: any): void;
1248
+ getService<T>(name: string): T;
1249
+ getServices(): Map<string, any>;
1250
+ hook(name: string, handler: (...args: any[]) => void | Promise<void>): void;
1251
+ trigger(name: string, ...args: any[]): Promise<void>;
1252
+ get logger(): Logger;
1253
+ getKernel(): ObjectKernel;
1254
+ }
1255
+ /**
1256
+ * Create a plugin permission enforcer
1257
+ *
1258
+ * @param logger - Logger instance
1259
+ * @returns Plugin permission enforcer
1260
+ */
1261
+ declare function createPluginPermissionEnforcer(logger: Logger): PluginPermissionEnforcer;
1262
+
1263
+ /**
1264
+ * Permission Grant
1265
+ * Represents a granted permission at runtime
1266
+ */
1267
+ interface PermissionGrant {
1268
+ permissionId: string;
1269
+ pluginId: string;
1270
+ grantedAt: Date;
1271
+ grantedBy?: string;
1272
+ expiresAt?: Date;
1273
+ conditions?: Record<string, any>;
1274
+ }
1275
+ /**
1276
+ * Permission Check Result
1277
+ */
1278
+ interface PermissionCheckResult {
1279
+ allowed: boolean;
1280
+ reason?: string;
1281
+ requiredPermission?: string;
1282
+ grantedPermissions?: string[];
1283
+ }
1284
+ /**
1285
+ * Plugin Permission Manager
1286
+ *
1287
+ * Manages fine-grained permissions for plugin security and access control
1288
+ */
1289
+ declare class PluginPermissionManager {
1290
+ private logger;
1291
+ private permissionSets;
1292
+ private grants;
1293
+ private grantDetails;
1294
+ constructor(logger: ObjectLogger);
1295
+ /**
1296
+ * Register permission requirements for a plugin
1297
+ */
1298
+ registerPermissions(pluginId: string, permissionSet: PermissionSet): void;
1299
+ /**
1300
+ * Grant a permission to a plugin
1301
+ */
1302
+ grantPermission(pluginId: string, permissionId: string, grantedBy?: string, expiresAt?: Date): void;
1303
+ /**
1304
+ * Revoke a permission from a plugin
1305
+ */
1306
+ revokePermission(pluginId: string, permissionId: string): void;
1307
+ /**
1308
+ * Grant all permissions for a plugin
1309
+ */
1310
+ grantAllPermissions(pluginId: string, grantedBy?: string): void;
1311
+ /**
1312
+ * Check if a plugin has a specific permission
1313
+ */
1314
+ hasPermission(pluginId: string, permissionId: string): boolean;
1315
+ /**
1316
+ * Check if plugin can perform an action on a resource
1317
+ */
1318
+ checkAccess(pluginId: string, resource: ResourceType, action: PermissionAction, resourceId?: string): PermissionCheckResult;
1319
+ /**
1320
+ * Get all permissions for a plugin
1321
+ */
1322
+ getPluginPermissions(pluginId: string): Permission[];
1323
+ /**
1324
+ * Get granted permissions for a plugin
1325
+ */
1326
+ getGrantedPermissions(pluginId: string): string[];
1327
+ /**
1328
+ * Get required but not granted permissions
1329
+ */
1330
+ getMissingPermissions(pluginId: string): Permission[];
1331
+ /**
1332
+ * Check if all required permissions are granted
1333
+ */
1334
+ hasAllRequiredPermissions(pluginId: string): boolean;
1335
+ /**
1336
+ * Get permission grant details
1337
+ */
1338
+ getGrantDetails(pluginId: string, permissionId: string): PermissionGrant | undefined;
1339
+ /**
1340
+ * Validate permission against scope constraints
1341
+ */
1342
+ validatePermissionScope(permission: Permission, context: {
1343
+ tenantId?: string;
1344
+ userId?: string;
1345
+ resourceId?: string;
1346
+ }): boolean;
1347
+ /**
1348
+ * Clear all permissions for a plugin
1349
+ */
1350
+ clearPluginPermissions(pluginId: string): void;
1351
+ /**
1352
+ * Shutdown permission manager
1353
+ */
1354
+ shutdown(): void;
1355
+ }
1356
+
1357
+ /**
1358
+ * Resource Usage Statistics
1359
+ */
1360
+ interface ResourceUsage {
1361
+ memory: {
1362
+ current: number;
1363
+ peak: number;
1364
+ limit?: number;
1365
+ };
1366
+ cpu: {
1367
+ current: number;
1368
+ average: number;
1369
+ limit?: number;
1370
+ };
1371
+ connections: {
1372
+ current: number;
1373
+ limit?: number;
1374
+ };
1375
+ }
1376
+ /**
1377
+ * Sandbox Execution Context
1378
+ * Represents an isolated execution environment for a plugin
1379
+ */
1380
+ interface SandboxContext {
1381
+ pluginId: string;
1382
+ config: SandboxConfig;
1383
+ startTime: Date;
1384
+ resourceUsage: ResourceUsage;
1385
+ }
1386
+ /**
1387
+ * Plugin Sandbox Runtime
1388
+ *
1389
+ * Provides isolated execution environments for plugins with resource limits
1390
+ * and access controls
1391
+ */
1392
+ declare class PluginSandboxRuntime {
1393
+ private logger;
1394
+ private sandboxes;
1395
+ private monitoringIntervals;
1396
+ constructor(logger: ObjectLogger);
1397
+ /**
1398
+ * Create a sandbox for a plugin
1399
+ */
1400
+ createSandbox(pluginId: string, config: SandboxConfig): SandboxContext;
1401
+ /**
1402
+ * Destroy a sandbox
1403
+ */
1404
+ destroySandbox(pluginId: string): void;
1405
+ /**
1406
+ * Check if resource access is allowed
1407
+ */
1408
+ checkResourceAccess(pluginId: string, resourceType: 'file' | 'network' | 'process' | 'env', resourcePath?: string): {
1409
+ allowed: boolean;
1410
+ reason?: string;
1411
+ };
1412
+ /**
1413
+ * Check file system access
1414
+ * WARNING: Uses simple prefix matching. For production, use proper path
1415
+ * resolution with path.resolve() and path.normalize() to prevent traversal.
1416
+ */
1417
+ private checkFileAccess;
1418
+ /**
1419
+ * Check network access
1420
+ * WARNING: Uses simple string matching. For production, use proper URL
1421
+ * parsing with new URL() and check hostname property.
1422
+ */
1423
+ private checkNetworkAccess;
1424
+ /**
1425
+ * Check process spawning access
1426
+ */
1427
+ private checkProcessAccess;
1428
+ /**
1429
+ * Check environment variable access
1430
+ */
1431
+ private checkEnvAccess;
1432
+ /**
1433
+ * Check resource limits
1434
+ */
1435
+ checkResourceLimits(pluginId: string): {
1436
+ withinLimits: boolean;
1437
+ violations: string[];
1438
+ };
1439
+ /**
1440
+ * Get resource usage for a plugin
1441
+ */
1442
+ getResourceUsage(pluginId: string): ResourceUsage | undefined;
1443
+ /**
1444
+ * Start monitoring resource usage
1445
+ */
1446
+ private startResourceMonitoring;
1447
+ /**
1448
+ * Stop monitoring resource usage
1449
+ */
1450
+ private stopResourceMonitoring;
1451
+ /**
1452
+ * Update resource usage statistics
1453
+ *
1454
+ * NOTE: Currently uses global process.memoryUsage() which tracks the entire
1455
+ * Node.js process, not individual plugins. For production, implement proper
1456
+ * per-plugin tracking using V8 heap snapshots or allocation tracking at
1457
+ * plugin boundaries.
1458
+ */
1459
+ private updateResourceUsage;
1460
+ /**
1461
+ * Get all active sandboxes
1462
+ */
1463
+ getAllSandboxes(): Map<string, SandboxContext>;
1464
+ /**
1465
+ * Shutdown sandbox runtime
1466
+ */
1467
+ shutdown(): void;
1468
+ }
1469
+
1470
+ /**
1471
+ * Scan Target
1472
+ */
1473
+ interface ScanTarget {
1474
+ pluginId: string;
1475
+ version: string;
1476
+ files?: string[];
1477
+ dependencies?: Record<string, string>;
1478
+ }
1479
+ /**
1480
+ * Security Issue
1481
+ */
1482
+ interface SecurityIssue {
1483
+ id: string;
1484
+ severity: 'critical' | 'high' | 'medium' | 'low' | 'info';
1485
+ category: 'vulnerability' | 'malware' | 'license' | 'code-quality' | 'configuration';
1486
+ title: string;
1487
+ description: string;
1488
+ location?: {
1489
+ file?: string;
1490
+ line?: number;
1491
+ column?: number;
1492
+ };
1493
+ remediation?: string;
1494
+ cve?: string;
1495
+ cvss?: number;
1496
+ }
1497
+ /**
1498
+ * Plugin Security Scanner
1499
+ *
1500
+ * Scans plugins for security vulnerabilities, malware, and license issues
1501
+ */
1502
+ declare class PluginSecurityScanner {
1503
+ private logger;
1504
+ private vulnerabilityDb;
1505
+ private scanResults;
1506
+ private passThreshold;
1507
+ constructor(logger: ObjectLogger, config?: {
1508
+ passThreshold?: number;
1509
+ });
1510
+ /**
1511
+ * Perform a comprehensive security scan on a plugin
1512
+ */
1513
+ scan(target: ScanTarget): Promise<SecurityScanResult>;
1514
+ /**
1515
+ * Scan code for vulnerabilities
1516
+ */
1517
+ private scanCode;
1518
+ /**
1519
+ * Scan dependencies for known vulnerabilities
1520
+ */
1521
+ private scanDependencies;
1522
+ /**
1523
+ * Scan for malware patterns
1524
+ */
1525
+ private scanMalware;
1526
+ /**
1527
+ * Check license compliance
1528
+ */
1529
+ private scanLicenses;
1530
+ /**
1531
+ * Check configuration security
1532
+ */
1533
+ private scanConfiguration;
1534
+ /**
1535
+ * Calculate security score based on issues
1536
+ */
1537
+ private calculateSecurityScore;
1538
+ /**
1539
+ * Add a vulnerability to the database
1540
+ */
1541
+ addVulnerability(packageName: string, version: string, vulnerability: SecurityVulnerability): void;
1542
+ /**
1543
+ * Get scan result from cache
1544
+ */
1545
+ getScanResult(pluginId: string, version: string): SecurityScanResult | undefined;
1546
+ /**
1547
+ * Clear scan results cache
1548
+ */
1549
+ clearCache(): void;
1550
+ /**
1551
+ * Update vulnerability database from external source
1552
+ */
1553
+ updateVulnerabilityDatabase(): Promise<void>;
1554
+ /**
1555
+ * Shutdown security scanner
1556
+ */
1557
+ shutdown(): void;
1558
+ }
1559
+
1560
+ /**
1561
+ * Environment utilities for universal (Node/Browser) compatibility.
1562
+ */
1563
+ declare const isNode: boolean;
1564
+ /**
1565
+ * Safely access environment variables
1566
+ */
1567
+ declare function getEnv(key: string, defaultValue?: string): string | undefined;
1568
+ /**
1569
+ * Safely exit the process if in Node.js
1570
+ */
1571
+ declare function safeExit(code?: number): void;
1572
+ /**
1573
+ * Safely get memory usage
1574
+ */
1575
+ declare function getMemoryUsage(): {
1576
+ heapUsed: number;
1577
+ heapTotal: number;
1578
+ };
1579
+
1580
+ /**
1581
+ * Plugin Health Monitor
1582
+ *
1583
+ * Monitors plugin health status and performs automatic recovery actions.
1584
+ * Implements the advanced lifecycle health monitoring protocol.
1585
+ */
1586
+ declare class PluginHealthMonitor {
1587
+ private logger;
1588
+ private healthChecks;
1589
+ private healthStatus;
1590
+ private healthReports;
1591
+ private checkIntervals;
1592
+ private failureCounters;
1593
+ private successCounters;
1594
+ private restartAttempts;
1595
+ constructor(logger: ObjectLogger);
1596
+ /**
1597
+ * Register a plugin for health monitoring
1598
+ */
1599
+ registerPlugin(pluginName: string, config: PluginHealthCheck): void;
1600
+ /**
1601
+ * Start monitoring a plugin
1602
+ */
1603
+ startMonitoring(pluginName: string, plugin: Plugin): void;
1604
+ /**
1605
+ * Stop monitoring a plugin
1606
+ */
1607
+ stopMonitoring(pluginName: string): void;
1608
+ /**
1609
+ * Perform a health check on a plugin
1610
+ */
1611
+ private performHealthCheck;
1612
+ /**
1613
+ * Attempt to restart a plugin
1614
+ */
1615
+ private attemptRestart;
1616
+ /**
1617
+ * Calculate backoff delay for restarts
1618
+ */
1619
+ private calculateBackoff;
1620
+ /**
1621
+ * Get current health status of a plugin
1622
+ */
1623
+ getHealthStatus(pluginName: string): PluginHealthStatus$1 | undefined;
1624
+ /**
1625
+ * Get latest health report for a plugin
1626
+ */
1627
+ getHealthReport(pluginName: string): PluginHealthReport | undefined;
1628
+ /**
1629
+ * Get all health statuses
1630
+ */
1631
+ getAllHealthStatuses(): Map<string, PluginHealthStatus$1>;
1632
+ /**
1633
+ * Shutdown health monitor
1634
+ */
1635
+ shutdown(): void;
1636
+ /**
1637
+ * Timeout helper
1638
+ */
1639
+ private timeout;
1640
+ }
1641
+
1642
+ /**
1643
+ * Plugin State Manager
1644
+ *
1645
+ * Handles state persistence and restoration during hot reloads
1646
+ */
1647
+ declare class PluginStateManager {
1648
+ private logger;
1649
+ private stateSnapshots;
1650
+ private memoryStore;
1651
+ constructor(logger: ObjectLogger);
1652
+ /**
1653
+ * Save plugin state before reload
1654
+ */
1655
+ saveState(pluginId: string, version: string, state: Record<string, any>, config: HotReloadConfig): Promise<string>;
1656
+ /**
1657
+ * Restore plugin state after reload
1658
+ */
1659
+ restoreState(pluginId: string, snapshotId?: string): Promise<Record<string, any> | undefined>;
1660
+ /**
1661
+ * Clear state for a plugin
1662
+ */
1663
+ clearState(pluginId: string): void;
1664
+ /**
1665
+ * Calculate simple checksum for state verification
1666
+ * WARNING: This is a simple hash for demo purposes.
1667
+ * In production, use a cryptographic hash like SHA-256.
1668
+ */
1669
+ private calculateChecksum;
1670
+ /**
1671
+ * Shutdown state manager
1672
+ */
1673
+ shutdown(): void;
1674
+ }
1675
+ /**
1676
+ * Hot Reload Manager
1677
+ *
1678
+ * Manages hot reloading of plugins with state preservation
1679
+ */
1680
+ declare class HotReloadManager {
1681
+ private logger;
1682
+ private stateManager;
1683
+ private reloadConfigs;
1684
+ private watchHandles;
1685
+ private reloadTimers;
1686
+ constructor(logger: ObjectLogger);
1687
+ /**
1688
+ * Register a plugin for hot reload
1689
+ */
1690
+ registerPlugin(pluginName: string, config: HotReloadConfig): void;
1691
+ /**
1692
+ * Start watching for changes (requires file system integration)
1693
+ */
1694
+ startWatching(pluginName: string): void;
1695
+ /**
1696
+ * Stop watching for changes
1697
+ */
1698
+ stopWatching(pluginName: string): void;
1699
+ /**
1700
+ * Trigger hot reload for a plugin
1701
+ */
1702
+ reloadPlugin(pluginName: string, plugin: Plugin, version: string, getPluginState: () => Record<string, any>, restorePluginState: (state: Record<string, any>) => void): Promise<boolean>;
1703
+ /**
1704
+ * Schedule a reload with debouncing
1705
+ */
1706
+ scheduleReload(pluginName: string, reloadFn: () => Promise<void>): void;
1707
+ /**
1708
+ * Get state manager for direct access
1709
+ */
1710
+ getStateManager(): PluginStateManager;
1711
+ /**
1712
+ * Shutdown hot reload manager
1713
+ */
1714
+ shutdown(): void;
1715
+ }
1716
+
1717
+ /**
1718
+ * Semantic Version Parser and Comparator
1719
+ *
1720
+ * Implements semantic versioning comparison and constraint matching
1721
+ */
1722
+ declare class SemanticVersionManager {
1723
+ /**
1724
+ * Parse a version string into semantic version components
1725
+ */
1726
+ static parse(versionStr: string): SemanticVersion;
1727
+ /**
1728
+ * Convert semantic version back to string
1729
+ */
1730
+ static toString(version: SemanticVersion): string;
1731
+ /**
1732
+ * Compare two semantic versions
1733
+ * Returns: -1 if a < b, 0 if a === b, 1 if a > b
1734
+ */
1735
+ static compare(a: SemanticVersion, b: SemanticVersion): number;
1736
+ /**
1737
+ * Check if version satisfies constraint
1738
+ */
1739
+ static satisfies(version: SemanticVersion, constraint: VersionConstraint): boolean;
1740
+ /**
1741
+ * Determine compatibility level between two versions
1742
+ */
1743
+ static getCompatibilityLevel(from: SemanticVersion, to: SemanticVersion): CompatibilityLevel;
1744
+ }
1745
+ /**
1746
+ * Plugin Dependency Resolver
1747
+ *
1748
+ * Resolves plugin dependencies using topological sorting and conflict detection
1749
+ */
1750
+ declare class DependencyResolver {
1751
+ private logger;
1752
+ constructor(logger: ObjectLogger);
1753
+ /**
1754
+ * Resolve dependencies using topological sort
1755
+ */
1756
+ resolve(plugins: Map<string, {
1757
+ version?: string;
1758
+ dependencies?: string[];
1759
+ }>): string[];
1760
+ /**
1761
+ * Detect dependency conflicts
1762
+ */
1763
+ detectConflicts(plugins: Map<string, {
1764
+ version: string;
1765
+ dependencies?: Record<string, VersionConstraint>;
1766
+ }>): DependencyConflict[];
1767
+ /**
1768
+ * Find best version that satisfies all constraints
1769
+ */
1770
+ findBestVersion(availableVersions: string[], constraints: VersionConstraint[]): string | undefined;
1771
+ /**
1772
+ * Check if dependencies form a valid DAG (no cycles)
1773
+ */
1774
+ isAcyclic(dependencies: Map<string, string[]>): boolean;
1775
+ }
1776
+
1777
+ export { ApiRegistry, type ApiRegistryPluginConfig, DependencyResolver, HotReloadManager, type IPluginConfigValidator, type KernelState, LiteKernel, ObjectKernel, ObjectKernelBase, type ObjectKernelConfig, ObjectLogger, type PermissionCheckResult$1 as PermissionCheckResult, type PermissionGrant, type Plugin, PluginConfigValidator, type PluginContext, PluginHealthMonitor, type PluginHealthStatus, type PluginLoadResult, PluginLoader, type PluginMetadata, type PermissionCheckResult as PluginPermissionCheckResult, PluginPermissionEnforcer, PluginPermissionManager, type PluginPermissions, PluginSandboxRuntime, PluginSecurityScanner, type PluginSignatureConfig, PluginSignatureVerifier, type PluginStartupResult, index as QA, type ResourceUsage, type SandboxContext, type ScanTarget, SecurePluginContext, type SecurityIssue, SemanticVersionManager, type ServiceFactory, ServiceLifecycle, type ServiceRegistration, type SignatureVerificationResult, type VersionCompatibility, createApiRegistryPlugin, createLogger, createPluginConfigValidator, createPluginPermissionEnforcer, getEnv, getMemoryUsage, isNode, safeExit };