@digilogiclabs/platform-core 1.0.0 → 1.1.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/dist/{ConsoleEmail-XeUBAnwc.d.mts → ConsoleEmail-Drr30nct.d.mts} +291 -128
- package/dist/{ConsoleEmail-XeUBAnwc.d.ts → ConsoleEmail-Drr30nct.d.ts} +291 -128
- package/dist/index.d.mts +2434 -5
- package/dist/index.d.ts +2434 -5
- package/dist/index.js +4779 -165
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4730 -165
- package/dist/index.mjs.map +1 -1
- package/dist/migrate.js +0 -0
- package/dist/testing.d.mts +2 -2
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +583 -17
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +583 -17
- package/dist/testing.mjs.map +1 -1
- package/package.json +9 -9
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { p as ILogger, q as IMetrics, I as IPlatform, P as PlatformHealthStatus, u as MetricsSummary, e as IDatabase, k as IQueryBuilder, Q as QueryResult, l as ICache, m as IStorage, U as UploadOptions, S as StorageFile, n as IEmail, t as EmailMessage, v as EmailResult, o as IQueue, s as JobOptions, J as Job } from './ConsoleEmail-
|
|
2
|
-
export {
|
|
1
|
+
import { p as ILogger, q as IMetrics, I as IPlatform, P as PlatformHealthStatus, u as MetricsSummary, e as IDatabase, k as IQueryBuilder, Q as QueryResult, l as ICache, m as IStorage, U as UploadOptions, S as StorageFile, n as IEmail, t as EmailMessage, v as EmailResult, o as IQueue, s as JobOptions, J as Job, R as RepeatOptions, w as JobState, x as JobEventType, y as JobEventHandler } from './ConsoleEmail-Drr30nct.js';
|
|
2
|
+
export { G as BackoffOptions, ax as BulkheadConfigSchema, aH as CacheConfig, aq as CacheConfigSchema, aj as CacheProviderSchema, av as CircuitBreakerConfigSchema, C as ConsoleEmail, h as ConsoleLogger, aG as DatabaseConfig, ap as DatabaseConfigSchema, ai as DatabaseProviderSchema, ac as EmailAddress, ad as EmailAttachment, aJ as EmailConfig, as as EmailConfigSchema, al as EmailProviderSchema, E as EnvSecrets, Z as GetSecretOptions, V as HistogramStats, z as ICacheOptions, r as ISecrets, a6 as ISpan, a5 as ITracing, B as JobContext, D as JobEvent, A as JobResult, K as LogEntry, L as LogLevel, ao as LogLevelSchema, H as LogMeta, O as LoggerConfig, az as LoggingConfigSchema, a as MemoryCache, M as MemoryDatabase, c as MemoryEmail, i as MemoryMetrics, d as MemoryQueue, f as MemorySecrets, b as MemoryStorage, a3 as MemoryTracing, T as MetricTags, aA as MetricsConfigSchema, aN as MiddlewareConfig, aD as MiddlewareConfigSchema, N as NoopLogger, j as NoopMetrics, a4 as NoopTracing, aM as ObservabilityConfig, aC as ObservabilityConfigSchema, aF as PlatformConfig, aE as PlatformConfigSchema, aK as QueueConfig, at as QueueConfigSchema, am as QueueProviderSchema, F as QueueStats, aL as ResilienceConfig, ay as ResilienceConfigSchema, au as RetryConfigSchema, $ as RotateSecretOptions, a0 as RotationResult, X as Secret, Y as SecretMetadata, _ as SetSecretOptions, a7 as SpanContext, ah as SpanEvent, aa as SpanKind, a8 as SpanOptions, a9 as SpanStatus, ag as SpanStatusCode, aI as StorageConfig, ar as StorageConfigSchema, ak as StorageProviderSchema, aw as TimeoutConfigSchema, W as TimingStats, ab as TracingConfig, aB as TracingConfigSchema, an as TracingProviderSchema, ae as calculateBackoff, g as createPlatform, a1 as createPlatformAsync, a2 as createScopedMetrics, af as generateJobId, aR as getDefaultConfig, aO as loadConfig, aQ as safeValidateConfig, aP as validateConfig } from './ConsoleEmail-Drr30nct.js';
|
|
3
3
|
export { i as IMigrationDatabase, I as IMigrator, a as Migration, b as MigrationRecord, e as MigrationResult, f as MigrationStatus, M as Migrator, h as MigratorConfig, S as SQL, c as createMigration, d as defineMigration, g as generateVersion, s as sqlMigration } from './index-C_2W7Byw.js';
|
|
4
4
|
import { SupabaseClient } from '@supabase/supabase-js';
|
|
5
5
|
import { Pool } from 'pg';
|
|
@@ -83,6 +83,1687 @@ declare function toHealthCheckResult(healthy: boolean, latencyMs: number, messag
|
|
|
83
83
|
*/
|
|
84
84
|
declare function timedHealthCheck<T>(fn: () => Promise<T>, successCheck?: (result: T) => boolean): Promise<HealthCheckResult>;
|
|
85
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Error Reporter Interface
|
|
88
|
+
*
|
|
89
|
+
* Provides a vendor-agnostic way to report and track errors.
|
|
90
|
+
* Self-hosted by default with optional external integrations.
|
|
91
|
+
*
|
|
92
|
+
* Design Principles:
|
|
93
|
+
* - Self-hostable: Console, File, Memory adapters included
|
|
94
|
+
* - No cloud lock-in: External services (Sentry, GlitchTip) are optional
|
|
95
|
+
* - Correlation-aware: Integrates with CorrelationContext
|
|
96
|
+
* - Zero external costs: Works without any external service
|
|
97
|
+
*/
|
|
98
|
+
interface ErrorContext {
|
|
99
|
+
/** Unique error ID */
|
|
100
|
+
errorId?: string;
|
|
101
|
+
/** Trace ID for distributed tracing */
|
|
102
|
+
traceId?: string;
|
|
103
|
+
/** Correlation ID for request/job tracking */
|
|
104
|
+
correlationId?: string;
|
|
105
|
+
/** Request ID */
|
|
106
|
+
requestId?: string;
|
|
107
|
+
/** User ID if authenticated */
|
|
108
|
+
userId?: string;
|
|
109
|
+
/** Tenant ID for multi-tenant apps */
|
|
110
|
+
tenantId?: string;
|
|
111
|
+
/** Operation/endpoint that failed */
|
|
112
|
+
operation?: string;
|
|
113
|
+
/** Environment (dev, staging, production) */
|
|
114
|
+
environment?: string;
|
|
115
|
+
/** Service/component name */
|
|
116
|
+
service?: string;
|
|
117
|
+
/** Release/version */
|
|
118
|
+
release?: string;
|
|
119
|
+
/** Additional tags for filtering */
|
|
120
|
+
tags?: Record<string, string>;
|
|
121
|
+
/** Extra contextual data */
|
|
122
|
+
extra?: Record<string, unknown>;
|
|
123
|
+
}
|
|
124
|
+
interface ErrorReport {
|
|
125
|
+
/** Unique report ID */
|
|
126
|
+
id: string;
|
|
127
|
+
/** Error message */
|
|
128
|
+
message: string;
|
|
129
|
+
/** Error name/type */
|
|
130
|
+
name: string;
|
|
131
|
+
/** Stack trace */
|
|
132
|
+
stack?: string;
|
|
133
|
+
/** Context at time of error */
|
|
134
|
+
context: ErrorContext;
|
|
135
|
+
/** Severity level */
|
|
136
|
+
level: ErrorLevel;
|
|
137
|
+
/** Timestamp */
|
|
138
|
+
timestamp: number;
|
|
139
|
+
/** Whether error was handled */
|
|
140
|
+
handled: boolean;
|
|
141
|
+
/** Fingerprint for grouping similar errors */
|
|
142
|
+
fingerprint?: string[];
|
|
143
|
+
/** Breadcrumbs/trail leading to error */
|
|
144
|
+
breadcrumbs?: Breadcrumb[];
|
|
145
|
+
}
|
|
146
|
+
type ErrorLevel = 'fatal' | 'error' | 'warning' | 'info' | 'debug';
|
|
147
|
+
interface Breadcrumb {
|
|
148
|
+
/** Category (http, navigation, user, etc.) */
|
|
149
|
+
category: string;
|
|
150
|
+
/** Breadcrumb message */
|
|
151
|
+
message: string;
|
|
152
|
+
/** Severity level */
|
|
153
|
+
level?: ErrorLevel;
|
|
154
|
+
/** Timestamp */
|
|
155
|
+
timestamp: number;
|
|
156
|
+
/** Additional data */
|
|
157
|
+
data?: Record<string, unknown>;
|
|
158
|
+
}
|
|
159
|
+
interface CaptureOptions {
|
|
160
|
+
/** Override error level */
|
|
161
|
+
level?: ErrorLevel;
|
|
162
|
+
/** Additional context */
|
|
163
|
+
context?: Partial<ErrorContext>;
|
|
164
|
+
/** Custom fingerprint for grouping */
|
|
165
|
+
fingerprint?: string[];
|
|
166
|
+
/** Mark as handled/unhandled */
|
|
167
|
+
handled?: boolean;
|
|
168
|
+
/** Additional tags */
|
|
169
|
+
tags?: Record<string, string>;
|
|
170
|
+
/** Extra data */
|
|
171
|
+
extra?: Record<string, unknown>;
|
|
172
|
+
}
|
|
173
|
+
interface ErrorReporterConfig {
|
|
174
|
+
/** Service/application name */
|
|
175
|
+
serviceName: string;
|
|
176
|
+
/** Environment */
|
|
177
|
+
environment?: string;
|
|
178
|
+
/** Release version */
|
|
179
|
+
release?: string;
|
|
180
|
+
/** Default tags */
|
|
181
|
+
defaultTags?: Record<string, string>;
|
|
182
|
+
/** Maximum breadcrumbs to keep */
|
|
183
|
+
maxBreadcrumbs?: number;
|
|
184
|
+
/** Whether to capture unhandled errors */
|
|
185
|
+
captureUnhandled?: boolean;
|
|
186
|
+
/** Sample rate (0.0 to 1.0) */
|
|
187
|
+
sampleRate?: number;
|
|
188
|
+
/** Filter errors before reporting */
|
|
189
|
+
beforeSend?: (report: ErrorReport) => ErrorReport | null;
|
|
190
|
+
}
|
|
191
|
+
interface IErrorReporter {
|
|
192
|
+
/**
|
|
193
|
+
* Capture and report an error
|
|
194
|
+
*/
|
|
195
|
+
captureError(error: Error, options?: CaptureOptions): string;
|
|
196
|
+
/**
|
|
197
|
+
* Capture a message (non-error event)
|
|
198
|
+
*/
|
|
199
|
+
captureMessage(message: string, options?: CaptureOptions): string;
|
|
200
|
+
/**
|
|
201
|
+
* Add a breadcrumb to the trail
|
|
202
|
+
*/
|
|
203
|
+
addBreadcrumb(breadcrumb: Omit<Breadcrumb, 'timestamp'>): void;
|
|
204
|
+
/**
|
|
205
|
+
* Set user context for future errors
|
|
206
|
+
*/
|
|
207
|
+
setUser(user: {
|
|
208
|
+
id?: string;
|
|
209
|
+
email?: string;
|
|
210
|
+
username?: string;
|
|
211
|
+
} | null): void;
|
|
212
|
+
/**
|
|
213
|
+
* Set extra context for future errors
|
|
214
|
+
*/
|
|
215
|
+
setContext(name: string, context: Record<string, unknown> | null): void;
|
|
216
|
+
/**
|
|
217
|
+
* Set a tag for future errors
|
|
218
|
+
*/
|
|
219
|
+
setTag(key: string, value: string): void;
|
|
220
|
+
/**
|
|
221
|
+
* Get recent error reports (for self-hosted review)
|
|
222
|
+
*/
|
|
223
|
+
getReports(options?: {
|
|
224
|
+
limit?: number;
|
|
225
|
+
level?: ErrorLevel;
|
|
226
|
+
}): ErrorReport[];
|
|
227
|
+
/**
|
|
228
|
+
* Clear stored reports
|
|
229
|
+
*/
|
|
230
|
+
clearReports(): void;
|
|
231
|
+
/**
|
|
232
|
+
* Flush pending reports (for async reporters)
|
|
233
|
+
*/
|
|
234
|
+
flush(timeout?: number): Promise<boolean>;
|
|
235
|
+
/**
|
|
236
|
+
* Close the reporter
|
|
237
|
+
*/
|
|
238
|
+
close(): Promise<void>;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Generate unique error ID
|
|
242
|
+
*/
|
|
243
|
+
declare function generateErrorId(): string;
|
|
244
|
+
/**
|
|
245
|
+
* Generate fingerprint from error
|
|
246
|
+
*/
|
|
247
|
+
declare function generateFingerprint(error: Error): string[];
|
|
248
|
+
/**
|
|
249
|
+
* Create error report from Error object
|
|
250
|
+
*/
|
|
251
|
+
declare function createErrorReport(error: Error, context: ErrorContext, options?: CaptureOptions): ErrorReport;
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Audit Log Interface
|
|
255
|
+
*
|
|
256
|
+
* Provides immutable, compliance-ready audit trail logging.
|
|
257
|
+
* Self-hosted, no external dependencies.
|
|
258
|
+
*
|
|
259
|
+
* Features:
|
|
260
|
+
* - Immutable event logging (append-only)
|
|
261
|
+
* - Correlation with trace/request context
|
|
262
|
+
* - Query and filtering capabilities
|
|
263
|
+
* - Retention policy support
|
|
264
|
+
* - Tamper detection via checksums
|
|
265
|
+
*/
|
|
266
|
+
/**
|
|
267
|
+
* Categories of audit events
|
|
268
|
+
*/
|
|
269
|
+
type AuditCategory = 'authentication' | 'authorization' | 'data_access' | 'data_mutation' | 'admin_action' | 'security' | 'system' | 'billing' | 'integration' | 'custom';
|
|
270
|
+
/**
|
|
271
|
+
* Outcome of the audited action
|
|
272
|
+
*/
|
|
273
|
+
type AuditOutcome = 'success' | 'failure' | 'denied' | 'error';
|
|
274
|
+
/**
|
|
275
|
+
* Actor who performed the action
|
|
276
|
+
*/
|
|
277
|
+
interface AuditActor {
|
|
278
|
+
/** Actor type */
|
|
279
|
+
type: 'user' | 'service' | 'system' | 'anonymous';
|
|
280
|
+
/** Actor ID (user ID, service name, etc.) */
|
|
281
|
+
id?: string;
|
|
282
|
+
/** Display name */
|
|
283
|
+
name?: string;
|
|
284
|
+
/** Email if applicable */
|
|
285
|
+
email?: string;
|
|
286
|
+
/** IP address */
|
|
287
|
+
ip?: string;
|
|
288
|
+
/** User agent */
|
|
289
|
+
userAgent?: string;
|
|
290
|
+
/** Session ID */
|
|
291
|
+
sessionId?: string;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Target of the audited action
|
|
295
|
+
*/
|
|
296
|
+
interface AuditTarget {
|
|
297
|
+
/** Target type (e.g., 'user', 'document', 'setting') */
|
|
298
|
+
type: string;
|
|
299
|
+
/** Target ID */
|
|
300
|
+
id?: string;
|
|
301
|
+
/** Human-readable name */
|
|
302
|
+
name?: string;
|
|
303
|
+
/** Additional target attributes */
|
|
304
|
+
attributes?: Record<string, unknown>;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Audit event structure
|
|
308
|
+
*/
|
|
309
|
+
interface AuditEvent {
|
|
310
|
+
/** Unique event ID (generated if not provided) */
|
|
311
|
+
id?: string;
|
|
312
|
+
/** Event timestamp (ISO 8601) */
|
|
313
|
+
timestamp?: string;
|
|
314
|
+
/** Event category */
|
|
315
|
+
category: AuditCategory;
|
|
316
|
+
/** Action performed (e.g., 'user.login', 'document.delete') */
|
|
317
|
+
action: string;
|
|
318
|
+
/** Action outcome */
|
|
319
|
+
outcome: AuditOutcome;
|
|
320
|
+
/** Actor who performed the action */
|
|
321
|
+
actor: AuditActor;
|
|
322
|
+
/** Target of the action */
|
|
323
|
+
target?: AuditTarget;
|
|
324
|
+
/** Additional event data */
|
|
325
|
+
data?: Record<string, unknown>;
|
|
326
|
+
/** Changes made (for mutations) */
|
|
327
|
+
changes?: {
|
|
328
|
+
before?: Record<string, unknown>;
|
|
329
|
+
after?: Record<string, unknown>;
|
|
330
|
+
};
|
|
331
|
+
/** Error details if outcome is 'error' or 'failure' */
|
|
332
|
+
error?: {
|
|
333
|
+
code?: string;
|
|
334
|
+
message?: string;
|
|
335
|
+
stack?: string;
|
|
336
|
+
};
|
|
337
|
+
/** Correlation context */
|
|
338
|
+
context?: {
|
|
339
|
+
traceId?: string;
|
|
340
|
+
correlationId?: string;
|
|
341
|
+
requestId?: string;
|
|
342
|
+
tenantId?: string;
|
|
343
|
+
environment?: string;
|
|
344
|
+
service?: string;
|
|
345
|
+
};
|
|
346
|
+
/** Event checksum for tamper detection */
|
|
347
|
+
checksum?: string;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Stored audit event (includes all generated fields)
|
|
351
|
+
*/
|
|
352
|
+
interface StoredAuditEvent extends Required<Pick<AuditEvent, 'id' | 'timestamp'>> {
|
|
353
|
+
id: string;
|
|
354
|
+
timestamp: string;
|
|
355
|
+
category: AuditCategory;
|
|
356
|
+
action: string;
|
|
357
|
+
outcome: AuditOutcome;
|
|
358
|
+
actor: AuditActor;
|
|
359
|
+
target?: AuditTarget;
|
|
360
|
+
data?: Record<string, unknown>;
|
|
361
|
+
changes?: {
|
|
362
|
+
before?: Record<string, unknown>;
|
|
363
|
+
after?: Record<string, unknown>;
|
|
364
|
+
};
|
|
365
|
+
error?: {
|
|
366
|
+
code?: string;
|
|
367
|
+
message?: string;
|
|
368
|
+
stack?: string;
|
|
369
|
+
};
|
|
370
|
+
context?: {
|
|
371
|
+
traceId?: string;
|
|
372
|
+
correlationId?: string;
|
|
373
|
+
requestId?: string;
|
|
374
|
+
tenantId?: string;
|
|
375
|
+
environment?: string;
|
|
376
|
+
service?: string;
|
|
377
|
+
};
|
|
378
|
+
checksum: string;
|
|
379
|
+
/** Sequence number for ordering */
|
|
380
|
+
sequence: number;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Query filter for audit events
|
|
384
|
+
*/
|
|
385
|
+
interface AuditQuery {
|
|
386
|
+
/** Filter by category */
|
|
387
|
+
category?: AuditCategory | AuditCategory[];
|
|
388
|
+
/** Filter by action (supports wildcards: 'user.*') */
|
|
389
|
+
action?: string | string[];
|
|
390
|
+
/** Filter by outcome */
|
|
391
|
+
outcome?: AuditOutcome | AuditOutcome[];
|
|
392
|
+
/** Filter by actor ID */
|
|
393
|
+
actorId?: string;
|
|
394
|
+
/** Filter by actor type */
|
|
395
|
+
actorType?: AuditActor['type'];
|
|
396
|
+
/** Filter by target type */
|
|
397
|
+
targetType?: string;
|
|
398
|
+
/** Filter by target ID */
|
|
399
|
+
targetId?: string;
|
|
400
|
+
/** Filter by tenant ID */
|
|
401
|
+
tenantId?: string;
|
|
402
|
+
/** Filter by trace ID */
|
|
403
|
+
traceId?: string;
|
|
404
|
+
/** Filter by correlation ID */
|
|
405
|
+
correlationId?: string;
|
|
406
|
+
/** Start time (inclusive) */
|
|
407
|
+
from?: Date | string;
|
|
408
|
+
/** End time (inclusive) */
|
|
409
|
+
to?: Date | string;
|
|
410
|
+
/** Search in data fields (JSON path queries) */
|
|
411
|
+
dataQuery?: Record<string, unknown>;
|
|
412
|
+
/** Pagination: offset */
|
|
413
|
+
offset?: number;
|
|
414
|
+
/** Pagination: limit (default 100, max 1000) */
|
|
415
|
+
limit?: number;
|
|
416
|
+
/** Sort order */
|
|
417
|
+
orderBy?: 'timestamp' | 'sequence';
|
|
418
|
+
/** Sort direction */
|
|
419
|
+
order?: 'asc' | 'desc';
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Query result with pagination info
|
|
423
|
+
*/
|
|
424
|
+
interface AuditQueryResult {
|
|
425
|
+
/** Matching events */
|
|
426
|
+
events: StoredAuditEvent[];
|
|
427
|
+
/** Total count (for pagination) */
|
|
428
|
+
total: number;
|
|
429
|
+
/** Has more results */
|
|
430
|
+
hasMore: boolean;
|
|
431
|
+
/** Query execution time (ms) */
|
|
432
|
+
executionTime: number;
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Retention policy configuration
|
|
436
|
+
*/
|
|
437
|
+
interface AuditRetentionPolicy {
|
|
438
|
+
/** Days to retain events (0 = forever) */
|
|
439
|
+
retentionDays: number;
|
|
440
|
+
/** Categories exempt from retention policy */
|
|
441
|
+
exemptCategories?: AuditCategory[];
|
|
442
|
+
/** Archive before deletion */
|
|
443
|
+
archiveBeforeDelete?: boolean;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Audit log statistics
|
|
447
|
+
*/
|
|
448
|
+
interface AuditStats {
|
|
449
|
+
/** Total events */
|
|
450
|
+
total: number;
|
|
451
|
+
/** Events by category */
|
|
452
|
+
byCategory: Record<AuditCategory, number>;
|
|
453
|
+
/** Events by outcome */
|
|
454
|
+
byOutcome: Record<AuditOutcome, number>;
|
|
455
|
+
/** Oldest event timestamp */
|
|
456
|
+
oldestEvent?: string;
|
|
457
|
+
/** Newest event timestamp */
|
|
458
|
+
newestEvent?: string;
|
|
459
|
+
/** Storage size in bytes (if available) */
|
|
460
|
+
storageBytes?: number;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Configuration for audit log
|
|
464
|
+
*/
|
|
465
|
+
interface AuditLogConfig {
|
|
466
|
+
/** Service name for context */
|
|
467
|
+
serviceName: string;
|
|
468
|
+
/** Environment (development, staging, production) */
|
|
469
|
+
environment?: string;
|
|
470
|
+
/** Retention policy */
|
|
471
|
+
retention?: AuditRetentionPolicy;
|
|
472
|
+
/** Enable checksum verification */
|
|
473
|
+
enableChecksums?: boolean;
|
|
474
|
+
/** Custom ID generator */
|
|
475
|
+
idGenerator?: () => string;
|
|
476
|
+
/** Automatically include correlation context */
|
|
477
|
+
autoCorrelation?: boolean;
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Audit Log Interface
|
|
481
|
+
*
|
|
482
|
+
* Provides immutable, queryable audit trail for compliance and security.
|
|
483
|
+
*/
|
|
484
|
+
interface IAuditLog {
|
|
485
|
+
/**
|
|
486
|
+
* Log an audit event
|
|
487
|
+
* @param event - The audit event to log
|
|
488
|
+
* @returns The stored event with generated fields
|
|
489
|
+
*/
|
|
490
|
+
log(event: AuditEvent): Promise<StoredAuditEvent>;
|
|
491
|
+
/**
|
|
492
|
+
* Log multiple events atomically
|
|
493
|
+
* @param events - Events to log
|
|
494
|
+
* @returns Stored events
|
|
495
|
+
*/
|
|
496
|
+
logBatch(events: AuditEvent[]): Promise<StoredAuditEvent[]>;
|
|
497
|
+
/**
|
|
498
|
+
* Query audit events
|
|
499
|
+
* @param query - Query filters
|
|
500
|
+
* @returns Query result with events and pagination info
|
|
501
|
+
*/
|
|
502
|
+
query(query: AuditQuery): Promise<AuditQueryResult>;
|
|
503
|
+
/**
|
|
504
|
+
* Get a single event by ID
|
|
505
|
+
* @param id - Event ID
|
|
506
|
+
* @returns The event or null if not found
|
|
507
|
+
*/
|
|
508
|
+
getEvent(id: string): Promise<StoredAuditEvent | null>;
|
|
509
|
+
/**
|
|
510
|
+
* Verify event integrity (checksum validation)
|
|
511
|
+
* @param id - Event ID
|
|
512
|
+
* @returns True if event is valid, false if tampered
|
|
513
|
+
*/
|
|
514
|
+
verifyIntegrity(id: string): Promise<boolean>;
|
|
515
|
+
/**
|
|
516
|
+
* Get audit statistics
|
|
517
|
+
* @returns Statistics about the audit log
|
|
518
|
+
*/
|
|
519
|
+
getStats(): Promise<AuditStats>;
|
|
520
|
+
/**
|
|
521
|
+
* Apply retention policy (delete old events)
|
|
522
|
+
* @param policy - Retention policy to apply (uses config if not provided)
|
|
523
|
+
* @returns Number of events deleted
|
|
524
|
+
*/
|
|
525
|
+
applyRetention(policy?: AuditRetentionPolicy): Promise<number>;
|
|
526
|
+
/**
|
|
527
|
+
* Export events for archival
|
|
528
|
+
* @param query - Filter events to export
|
|
529
|
+
* @returns Events in exportable format
|
|
530
|
+
*/
|
|
531
|
+
export(query: AuditQuery): Promise<StoredAuditEvent[]>;
|
|
532
|
+
/**
|
|
533
|
+
* Health check
|
|
534
|
+
* @returns True if audit log is operational
|
|
535
|
+
*/
|
|
536
|
+
healthCheck(): Promise<boolean>;
|
|
537
|
+
/**
|
|
538
|
+
* Close connections and cleanup
|
|
539
|
+
*/
|
|
540
|
+
close(): Promise<void>;
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Generate a unique audit event ID
|
|
544
|
+
*/
|
|
545
|
+
declare function generateAuditId(): string;
|
|
546
|
+
/**
|
|
547
|
+
* Generate checksum for audit event (SHA-256 hash of canonical JSON)
|
|
548
|
+
*/
|
|
549
|
+
declare function generateChecksum(event: Omit<AuditEvent, 'checksum'>): string;
|
|
550
|
+
/**
|
|
551
|
+
* Verify if an action matches a pattern (supports wildcards)
|
|
552
|
+
* @example matchAction('user.login', 'user.*') // true
|
|
553
|
+
* @example matchAction('user.login', 'user.login') // true
|
|
554
|
+
* @example matchAction('user.login', 'admin.*') // false
|
|
555
|
+
*/
|
|
556
|
+
declare function matchAction(action: string, pattern: string): boolean;
|
|
557
|
+
/**
|
|
558
|
+
* Create a standardized audit event for common actions
|
|
559
|
+
*/
|
|
560
|
+
declare const AuditEvents: {
|
|
561
|
+
/** User authentication events */
|
|
562
|
+
auth: {
|
|
563
|
+
login: (actor: AuditActor, outcome: AuditOutcome, data?: Record<string, unknown>) => AuditEvent;
|
|
564
|
+
logout: (actor: AuditActor) => AuditEvent;
|
|
565
|
+
tokenRefresh: (actor: AuditActor, outcome: AuditOutcome) => AuditEvent;
|
|
566
|
+
passwordChange: (actor: AuditActor, outcome: AuditOutcome) => AuditEvent;
|
|
567
|
+
mfaEnabled: (actor: AuditActor) => AuditEvent;
|
|
568
|
+
};
|
|
569
|
+
/** Data access events */
|
|
570
|
+
data: {
|
|
571
|
+
read: (actor: AuditActor, target: AuditTarget, outcome?: AuditOutcome) => AuditEvent;
|
|
572
|
+
create: (actor: AuditActor, target: AuditTarget, data?: Record<string, unknown>) => AuditEvent;
|
|
573
|
+
update: (actor: AuditActor, target: AuditTarget, before?: Record<string, unknown>, after?: Record<string, unknown>) => AuditEvent;
|
|
574
|
+
delete: (actor: AuditActor, target: AuditTarget, data?: Record<string, unknown>) => AuditEvent;
|
|
575
|
+
};
|
|
576
|
+
/** Admin actions */
|
|
577
|
+
admin: {
|
|
578
|
+
settingChange: (actor: AuditActor, setting: string, before: unknown, after: unknown) => AuditEvent;
|
|
579
|
+
userSuspend: (actor: AuditActor, targetUserId: string, reason?: string) => AuditEvent;
|
|
580
|
+
};
|
|
581
|
+
/** Security events */
|
|
582
|
+
security: {
|
|
583
|
+
accessDenied: (actor: AuditActor, resource: string, reason?: string) => AuditEvent;
|
|
584
|
+
rateLimited: (actor: AuditActor, endpoint: string) => AuditEvent;
|
|
585
|
+
suspiciousActivity: (actor: AuditActor, description: string, data?: Record<string, unknown>) => AuditEvent;
|
|
586
|
+
};
|
|
587
|
+
/** Billing events */
|
|
588
|
+
billing: {
|
|
589
|
+
subscriptionCreated: (actor: AuditActor, subscriptionId: string, plan: string) => AuditEvent;
|
|
590
|
+
paymentProcessed: (actor: AuditActor, paymentId: string, amount: number, currency: string) => AuditEvent;
|
|
591
|
+
paymentFailed: (actor: AuditActor, paymentId: string, reason: string) => AuditEvent;
|
|
592
|
+
};
|
|
593
|
+
};
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Scheduler Interface
|
|
597
|
+
*
|
|
598
|
+
* Job scheduling abstraction for cron-based and one-time scheduled tasks.
|
|
599
|
+
* Built on top of IQueue for execution, providing:
|
|
600
|
+
* - Cron-based recurring jobs
|
|
601
|
+
* - One-time scheduled jobs
|
|
602
|
+
* - Job management (pause, resume, cancel)
|
|
603
|
+
* - Schedule status and history
|
|
604
|
+
*
|
|
605
|
+
* Self-hosted, no external dependencies beyond IQueue.
|
|
606
|
+
*/
|
|
607
|
+
/**
|
|
608
|
+
* Cron expression type (standard 5-field or 6-field with seconds)
|
|
609
|
+
* @example '0 * * * *' - Every hour
|
|
610
|
+
* @example '0 9 * * 1-5' - 9 AM on weekdays
|
|
611
|
+
* @example '0 0 1 * *' - First day of every month
|
|
612
|
+
*/
|
|
613
|
+
type CronExpression = string;
|
|
614
|
+
/**
|
|
615
|
+
* Schedule state
|
|
616
|
+
*/
|
|
617
|
+
type ScheduleState = 'active' | 'paused' | 'completed' | 'cancelled';
|
|
618
|
+
/**
|
|
619
|
+
* Scheduled job definition
|
|
620
|
+
*/
|
|
621
|
+
interface ScheduledJob<T = unknown> {
|
|
622
|
+
/** Unique schedule ID */
|
|
623
|
+
id: string;
|
|
624
|
+
/** Schedule name (for display/identification) */
|
|
625
|
+
name: string;
|
|
626
|
+
/** Job description */
|
|
627
|
+
description?: string;
|
|
628
|
+
/** Cron expression for recurring jobs */
|
|
629
|
+
cron?: CronExpression;
|
|
630
|
+
/** Specific run time for one-time jobs (ISO 8601) */
|
|
631
|
+
runAt?: string;
|
|
632
|
+
/** Timezone for cron interpretation (default: UTC) */
|
|
633
|
+
timezone?: string;
|
|
634
|
+
/** Job data to pass to handler */
|
|
635
|
+
data: T;
|
|
636
|
+
/** Schedule state */
|
|
637
|
+
state: ScheduleState;
|
|
638
|
+
/** Creation timestamp */
|
|
639
|
+
createdAt: string;
|
|
640
|
+
/** Last modification timestamp */
|
|
641
|
+
updatedAt: string;
|
|
642
|
+
/** Next scheduled run time (ISO 8601) */
|
|
643
|
+
nextRun?: string;
|
|
644
|
+
/** Last run time (ISO 8601) */
|
|
645
|
+
lastRun?: string;
|
|
646
|
+
/** Last run result */
|
|
647
|
+
lastResult?: 'success' | 'failure';
|
|
648
|
+
/** Last run error message */
|
|
649
|
+
lastError?: string;
|
|
650
|
+
/** Total run count */
|
|
651
|
+
runCount: number;
|
|
652
|
+
/** Total failure count */
|
|
653
|
+
failureCount: number;
|
|
654
|
+
/** Maximum run count (0 = unlimited) */
|
|
655
|
+
maxRuns?: number;
|
|
656
|
+
/** Tags for organization */
|
|
657
|
+
tags?: string[];
|
|
658
|
+
/** Metadata */
|
|
659
|
+
metadata?: Record<string, unknown>;
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Schedule creation options
|
|
663
|
+
*/
|
|
664
|
+
interface CreateScheduleOptions<T = unknown> {
|
|
665
|
+
/** Unique ID (generated if not provided) */
|
|
666
|
+
id?: string;
|
|
667
|
+
/** Schedule name */
|
|
668
|
+
name: string;
|
|
669
|
+
/** Description */
|
|
670
|
+
description?: string;
|
|
671
|
+
/** Cron expression (for recurring) */
|
|
672
|
+
cron?: CronExpression;
|
|
673
|
+
/** Run at specific time (for one-time) */
|
|
674
|
+
runAt?: Date | string;
|
|
675
|
+
/** Timezone (default: UTC) */
|
|
676
|
+
timezone?: string;
|
|
677
|
+
/** Job data */
|
|
678
|
+
data: T;
|
|
679
|
+
/** Maximum runs (0 = unlimited, default for recurring) */
|
|
680
|
+
maxRuns?: number;
|
|
681
|
+
/** Tags */
|
|
682
|
+
tags?: string[];
|
|
683
|
+
/** Metadata */
|
|
684
|
+
metadata?: Record<string, unknown>;
|
|
685
|
+
/** Start in paused state */
|
|
686
|
+
paused?: boolean;
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Schedule update options
|
|
690
|
+
*/
|
|
691
|
+
interface UpdateScheduleOptions<T = unknown> {
|
|
692
|
+
/** Update cron expression */
|
|
693
|
+
cron?: CronExpression;
|
|
694
|
+
/** Update run at time */
|
|
695
|
+
runAt?: Date | string;
|
|
696
|
+
/** Update timezone */
|
|
697
|
+
timezone?: string;
|
|
698
|
+
/** Update job data */
|
|
699
|
+
data?: T;
|
|
700
|
+
/** Update max runs */
|
|
701
|
+
maxRuns?: number;
|
|
702
|
+
/** Update tags */
|
|
703
|
+
tags?: string[];
|
|
704
|
+
/** Update metadata */
|
|
705
|
+
metadata?: Record<string, unknown>;
|
|
706
|
+
/** Update description */
|
|
707
|
+
description?: string;
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* Schedule query options
|
|
711
|
+
*/
|
|
712
|
+
interface ScheduleQuery {
|
|
713
|
+
/** Filter by state */
|
|
714
|
+
state?: ScheduleState | ScheduleState[];
|
|
715
|
+
/** Filter by tags (any match) */
|
|
716
|
+
tags?: string[];
|
|
717
|
+
/** Filter by name pattern (supports wildcards) */
|
|
718
|
+
name?: string;
|
|
719
|
+
/** Include schedules with next run before this time */
|
|
720
|
+
nextRunBefore?: Date | string;
|
|
721
|
+
/** Include schedules with next run after this time */
|
|
722
|
+
nextRunAfter?: Date | string;
|
|
723
|
+
/** Pagination: offset */
|
|
724
|
+
offset?: number;
|
|
725
|
+
/** Pagination: limit */
|
|
726
|
+
limit?: number;
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Schedule execution history entry
|
|
730
|
+
*/
|
|
731
|
+
interface ScheduleExecution {
|
|
732
|
+
/** Execution ID */
|
|
733
|
+
id: string;
|
|
734
|
+
/** Schedule ID */
|
|
735
|
+
scheduleId: string;
|
|
736
|
+
/** Start time */
|
|
737
|
+
startedAt: string;
|
|
738
|
+
/** End time */
|
|
739
|
+
completedAt?: string;
|
|
740
|
+
/** Duration in ms */
|
|
741
|
+
duration?: number;
|
|
742
|
+
/** Result */
|
|
743
|
+
result: 'success' | 'failure' | 'running';
|
|
744
|
+
/** Error message */
|
|
745
|
+
error?: string;
|
|
746
|
+
/** Job ID (from queue) */
|
|
747
|
+
jobId?: string;
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Scheduler statistics
|
|
751
|
+
*/
|
|
752
|
+
interface SchedulerStats {
|
|
753
|
+
/** Total schedules */
|
|
754
|
+
total: number;
|
|
755
|
+
/** Active schedules */
|
|
756
|
+
active: number;
|
|
757
|
+
/** Paused schedules */
|
|
758
|
+
paused: number;
|
|
759
|
+
/** Completed schedules */
|
|
760
|
+
completed: number;
|
|
761
|
+
/** Cancelled schedules */
|
|
762
|
+
cancelled: number;
|
|
763
|
+
/** Executions in last 24 hours */
|
|
764
|
+
executionsLast24h: number;
|
|
765
|
+
/** Failures in last 24 hours */
|
|
766
|
+
failuresLast24h: number;
|
|
767
|
+
/** Next scheduled execution */
|
|
768
|
+
nextExecution?: string;
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Job handler function
|
|
772
|
+
*/
|
|
773
|
+
type ScheduleHandler<T = unknown> = (job: ScheduledJob<T>, context: ScheduleContext) => Promise<void>;
|
|
774
|
+
/**
|
|
775
|
+
* Context passed to schedule handler
|
|
776
|
+
*/
|
|
777
|
+
interface ScheduleContext {
|
|
778
|
+
/** Execution ID */
|
|
779
|
+
executionId: string;
|
|
780
|
+
/** Schedule ID */
|
|
781
|
+
scheduleId: string;
|
|
782
|
+
/** Scheduled run time */
|
|
783
|
+
scheduledAt: string;
|
|
784
|
+
/** Actual run time */
|
|
785
|
+
startedAt: string;
|
|
786
|
+
/** Report progress */
|
|
787
|
+
progress: (percent: number) => void;
|
|
788
|
+
/** Log message */
|
|
789
|
+
log: (message: string, level?: 'info' | 'warn' | 'error') => void;
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Scheduler configuration
|
|
793
|
+
*/
|
|
794
|
+
interface SchedulerConfig {
|
|
795
|
+
/** Default timezone for schedules */
|
|
796
|
+
defaultTimezone?: string;
|
|
797
|
+
/** Default max retries for failed jobs */
|
|
798
|
+
defaultRetries?: number;
|
|
799
|
+
/** Check interval for upcoming jobs (ms, default 60000) */
|
|
800
|
+
checkInterval?: number;
|
|
801
|
+
/** How far ahead to look for jobs (ms, default 300000) */
|
|
802
|
+
lookAheadWindow?: number;
|
|
803
|
+
/** Execution history retention (days, default 30) */
|
|
804
|
+
historyRetentionDays?: number;
|
|
805
|
+
/** Maximum concurrent executions */
|
|
806
|
+
maxConcurrency?: number;
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Scheduler Interface
|
|
810
|
+
*
|
|
811
|
+
* Provides job scheduling on top of queue infrastructure.
|
|
812
|
+
*/
|
|
813
|
+
interface IScheduler {
|
|
814
|
+
/**
|
|
815
|
+
* Create a new schedule
|
|
816
|
+
*/
|
|
817
|
+
create<T>(options: CreateScheduleOptions<T>): Promise<ScheduledJob<T>>;
|
|
818
|
+
/**
|
|
819
|
+
* Get a schedule by ID
|
|
820
|
+
*/
|
|
821
|
+
get<T>(id: string): Promise<ScheduledJob<T> | null>;
|
|
822
|
+
/**
|
|
823
|
+
* Update an existing schedule
|
|
824
|
+
*/
|
|
825
|
+
update<T>(id: string, options: UpdateScheduleOptions<T>): Promise<ScheduledJob<T>>;
|
|
826
|
+
/**
|
|
827
|
+
* Delete a schedule
|
|
828
|
+
*/
|
|
829
|
+
delete(id: string): Promise<void>;
|
|
830
|
+
/**
|
|
831
|
+
* Pause a schedule (stop future executions)
|
|
832
|
+
*/
|
|
833
|
+
pause(id: string): Promise<void>;
|
|
834
|
+
/**
|
|
835
|
+
* Resume a paused schedule
|
|
836
|
+
*/
|
|
837
|
+
resume(id: string): Promise<void>;
|
|
838
|
+
/**
|
|
839
|
+
* Trigger immediate execution of a schedule
|
|
840
|
+
*/
|
|
841
|
+
trigger(id: string): Promise<string>;
|
|
842
|
+
/**
|
|
843
|
+
* List schedules with optional filters
|
|
844
|
+
*/
|
|
845
|
+
list<T>(query?: ScheduleQuery): Promise<ScheduledJob<T>[]>;
|
|
846
|
+
/**
|
|
847
|
+
* Get execution history for a schedule
|
|
848
|
+
*/
|
|
849
|
+
getHistory(scheduleId: string, limit?: number): Promise<ScheduleExecution[]>;
|
|
850
|
+
/**
|
|
851
|
+
* Register a handler for schedules
|
|
852
|
+
*/
|
|
853
|
+
handle<T>(name: string, handler: ScheduleHandler<T>): void;
|
|
854
|
+
/**
|
|
855
|
+
* Start the scheduler (begin processing)
|
|
856
|
+
*/
|
|
857
|
+
start(): Promise<void>;
|
|
858
|
+
/**
|
|
859
|
+
* Stop the scheduler (stop processing)
|
|
860
|
+
*/
|
|
861
|
+
stop(): Promise<void>;
|
|
862
|
+
/**
|
|
863
|
+
* Get scheduler statistics
|
|
864
|
+
*/
|
|
865
|
+
getStats(): Promise<SchedulerStats>;
|
|
866
|
+
/**
|
|
867
|
+
* Health check
|
|
868
|
+
*/
|
|
869
|
+
healthCheck(): Promise<boolean>;
|
|
870
|
+
/**
|
|
871
|
+
* Close and cleanup
|
|
872
|
+
*/
|
|
873
|
+
close(): Promise<void>;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Generate schedule ID
|
|
877
|
+
*/
|
|
878
|
+
declare function generateScheduleId(): string;
|
|
879
|
+
/**
|
|
880
|
+
* Parse cron expression and get next run time
|
|
881
|
+
* Simple implementation for common patterns
|
|
882
|
+
*/
|
|
883
|
+
declare function getNextCronRun(cron: CronExpression, after?: Date, timezone?: string): Date | null;
|
|
884
|
+
/**
|
|
885
|
+
* Check if a cron expression is valid
|
|
886
|
+
*/
|
|
887
|
+
declare function isValidCron(cron: CronExpression): boolean;
|
|
888
|
+
/**
|
|
889
|
+
* Common cron expressions
|
|
890
|
+
*/
|
|
891
|
+
declare const CronPresets: {
|
|
892
|
+
/** Every minute */
|
|
893
|
+
readonly everyMinute: "* * * * *";
|
|
894
|
+
/** Every 5 minutes */
|
|
895
|
+
readonly every5Minutes: "*/5 * * * *";
|
|
896
|
+
/** Every 15 minutes */
|
|
897
|
+
readonly every15Minutes: "*/15 * * * *";
|
|
898
|
+
/** Every 30 minutes */
|
|
899
|
+
readonly every30Minutes: "*/30 * * * *";
|
|
900
|
+
/** Every hour */
|
|
901
|
+
readonly hourly: "0 * * * *";
|
|
902
|
+
/** Every day at midnight */
|
|
903
|
+
readonly daily: "0 0 * * *";
|
|
904
|
+
/** Every day at 9 AM */
|
|
905
|
+
readonly dailyAt9AM: "0 9 * * *";
|
|
906
|
+
/** Every Monday at 9 AM */
|
|
907
|
+
readonly weeklyMonday: "0 9 * * 1";
|
|
908
|
+
/** First day of month at midnight */
|
|
909
|
+
readonly monthly: "0 0 1 * *";
|
|
910
|
+
/** Every weekday at 9 AM */
|
|
911
|
+
readonly weekdays: "0 9 * * 1-5";
|
|
912
|
+
/** Every weekend at 10 AM */
|
|
913
|
+
readonly weekends: "0 10 * * 0,6";
|
|
914
|
+
};
|
|
915
|
+
/**
|
|
916
|
+
* Describe a cron expression in human-readable format
|
|
917
|
+
*/
|
|
918
|
+
declare function describeCron(cron: CronExpression): string;
|
|
919
|
+
|
|
920
|
+
/**
|
|
921
|
+
* Webhook Interface
|
|
922
|
+
*
|
|
923
|
+
* Platform abstraction for webhook management.
|
|
924
|
+
* Self-hosted, no vendor lock-in.
|
|
925
|
+
*
|
|
926
|
+
* Supports both:
|
|
927
|
+
* - Outbound webhooks (sending events to external systems)
|
|
928
|
+
* - Inbound webhooks (receiving events from external systems)
|
|
929
|
+
*
|
|
930
|
+
* Features:
|
|
931
|
+
* - Signature verification (HMAC-SHA256, etc.)
|
|
932
|
+
* - Automatic retries with exponential backoff
|
|
933
|
+
* - Event filtering
|
|
934
|
+
* - Delivery tracking and history
|
|
935
|
+
*/
|
|
936
|
+
/**
|
|
937
|
+
* Webhook state
|
|
938
|
+
*/
|
|
939
|
+
type WebhookState = 'active' | 'paused' | 'disabled' | 'failed';
|
|
940
|
+
/**
|
|
941
|
+
* Delivery status
|
|
942
|
+
*/
|
|
943
|
+
type DeliveryStatus = 'pending' | 'success' | 'failed' | 'skipped';
|
|
944
|
+
/**
|
|
945
|
+
* Signature algorithm
|
|
946
|
+
*/
|
|
947
|
+
type SignatureAlgorithm = 'sha256' | 'sha512' | 'sha1';
|
|
948
|
+
/**
|
|
949
|
+
* Registered webhook endpoint
|
|
950
|
+
*/
|
|
951
|
+
interface WebhookEndpoint {
|
|
952
|
+
/** Unique identifier */
|
|
953
|
+
id: string;
|
|
954
|
+
/** Human-readable name */
|
|
955
|
+
name: string;
|
|
956
|
+
/** Description */
|
|
957
|
+
description?: string;
|
|
958
|
+
/** Target URL for delivery */
|
|
959
|
+
url: string;
|
|
960
|
+
/** Secret for signature verification */
|
|
961
|
+
secret: string;
|
|
962
|
+
/** Signature algorithm */
|
|
963
|
+
signatureAlgorithm: SignatureAlgorithm;
|
|
964
|
+
/** Header name for signature */
|
|
965
|
+
signatureHeader: string;
|
|
966
|
+
/** Events this webhook subscribes to (glob patterns supported) */
|
|
967
|
+
events: string[];
|
|
968
|
+
/** Current state */
|
|
969
|
+
state: WebhookState;
|
|
970
|
+
/** Custom headers to include */
|
|
971
|
+
headers?: Record<string, string>;
|
|
972
|
+
/** Metadata */
|
|
973
|
+
metadata?: Record<string, unknown>;
|
|
974
|
+
/** Tags for organization */
|
|
975
|
+
tags?: string[];
|
|
976
|
+
/** Created timestamp */
|
|
977
|
+
createdAt: string;
|
|
978
|
+
/** Last updated timestamp */
|
|
979
|
+
updatedAt: string;
|
|
980
|
+
/** Last delivery attempt */
|
|
981
|
+
lastDeliveryAt?: string;
|
|
982
|
+
/** Last successful delivery */
|
|
983
|
+
lastSuccessAt?: string;
|
|
984
|
+
/** Consecutive failures */
|
|
985
|
+
failureCount: number;
|
|
986
|
+
/** Total deliveries */
|
|
987
|
+
totalDeliveries: number;
|
|
988
|
+
/** Successful deliveries */
|
|
989
|
+
successfulDeliveries: number;
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Webhook event to send
|
|
993
|
+
*/
|
|
994
|
+
interface WebhookEvent<T = unknown> {
|
|
995
|
+
/** Event type (e.g., 'user.created', 'order.completed') */
|
|
996
|
+
type: string;
|
|
997
|
+
/** Event payload */
|
|
998
|
+
payload: T;
|
|
999
|
+
/** Optional event ID (auto-generated if not provided) */
|
|
1000
|
+
id?: string;
|
|
1001
|
+
/** Timestamp (ISO 8601, auto-generated if not provided) */
|
|
1002
|
+
timestamp?: string;
|
|
1003
|
+
/** Correlation ID for tracing */
|
|
1004
|
+
correlationId?: string;
|
|
1005
|
+
/** Source of the event */
|
|
1006
|
+
source?: string;
|
|
1007
|
+
/** Metadata */
|
|
1008
|
+
metadata?: Record<string, unknown>;
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Delivery attempt record
|
|
1012
|
+
*/
|
|
1013
|
+
interface DeliveryAttempt {
|
|
1014
|
+
/** Attempt ID */
|
|
1015
|
+
id: string;
|
|
1016
|
+
/** Webhook endpoint ID */
|
|
1017
|
+
endpointId: string;
|
|
1018
|
+
/** Event ID */
|
|
1019
|
+
eventId: string;
|
|
1020
|
+
/** Event type */
|
|
1021
|
+
eventType: string;
|
|
1022
|
+
/** Attempt number (1-based) */
|
|
1023
|
+
attemptNumber: number;
|
|
1024
|
+
/** Status */
|
|
1025
|
+
status: DeliveryStatus;
|
|
1026
|
+
/** HTTP status code */
|
|
1027
|
+
statusCode?: number;
|
|
1028
|
+
/** Response body (truncated) */
|
|
1029
|
+
responseBody?: string;
|
|
1030
|
+
/** Response headers */
|
|
1031
|
+
responseHeaders?: Record<string, string>;
|
|
1032
|
+
/** Request duration in ms */
|
|
1033
|
+
duration?: number;
|
|
1034
|
+
/** Error message if failed */
|
|
1035
|
+
error?: string;
|
|
1036
|
+
/** Timestamp */
|
|
1037
|
+
timestamp: string;
|
|
1038
|
+
/** Next retry timestamp (if scheduled) */
|
|
1039
|
+
nextRetryAt?: string;
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* Delivery record
|
|
1043
|
+
*/
|
|
1044
|
+
interface WebhookDelivery {
|
|
1045
|
+
/** Unique delivery ID */
|
|
1046
|
+
id: string;
|
|
1047
|
+
/** Webhook endpoint ID */
|
|
1048
|
+
endpointId: string;
|
|
1049
|
+
/** Event ID */
|
|
1050
|
+
eventId: string;
|
|
1051
|
+
/** Event type */
|
|
1052
|
+
eventType: string;
|
|
1053
|
+
/** Event payload (JSON string) */
|
|
1054
|
+
payload: string;
|
|
1055
|
+
/** Final status */
|
|
1056
|
+
status: DeliveryStatus;
|
|
1057
|
+
/** Total attempts */
|
|
1058
|
+
attempts: number;
|
|
1059
|
+
/** All attempt records */
|
|
1060
|
+
attemptHistory: DeliveryAttempt[];
|
|
1061
|
+
/** Created timestamp */
|
|
1062
|
+
createdAt: string;
|
|
1063
|
+
/** Completed timestamp */
|
|
1064
|
+
completedAt?: string;
|
|
1065
|
+
}
|
|
1066
|
+
/**
|
|
1067
|
+
* Options for creating a webhook endpoint
|
|
1068
|
+
*/
|
|
1069
|
+
interface CreateWebhookOptions {
|
|
1070
|
+
/** Optional custom ID */
|
|
1071
|
+
id?: string;
|
|
1072
|
+
/** Human-readable name */
|
|
1073
|
+
name: string;
|
|
1074
|
+
/** Description */
|
|
1075
|
+
description?: string;
|
|
1076
|
+
/** Target URL */
|
|
1077
|
+
url: string;
|
|
1078
|
+
/** Secret for signatures (auto-generated if not provided) */
|
|
1079
|
+
secret?: string;
|
|
1080
|
+
/** Signature algorithm (default: sha256) */
|
|
1081
|
+
signatureAlgorithm?: SignatureAlgorithm;
|
|
1082
|
+
/** Signature header name (default: X-Webhook-Signature) */
|
|
1083
|
+
signatureHeader?: string;
|
|
1084
|
+
/** Events to subscribe to */
|
|
1085
|
+
events: string[];
|
|
1086
|
+
/** Custom headers */
|
|
1087
|
+
headers?: Record<string, string>;
|
|
1088
|
+
/** Metadata */
|
|
1089
|
+
metadata?: Record<string, unknown>;
|
|
1090
|
+
/** Tags */
|
|
1091
|
+
tags?: string[];
|
|
1092
|
+
/** Start as paused */
|
|
1093
|
+
paused?: boolean;
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Options for updating a webhook endpoint
|
|
1097
|
+
*/
|
|
1098
|
+
interface UpdateWebhookOptions {
|
|
1099
|
+
/** Name */
|
|
1100
|
+
name?: string;
|
|
1101
|
+
/** Description */
|
|
1102
|
+
description?: string;
|
|
1103
|
+
/** URL */
|
|
1104
|
+
url?: string;
|
|
1105
|
+
/** Rotate secret */
|
|
1106
|
+
rotateSecret?: boolean;
|
|
1107
|
+
/** Events */
|
|
1108
|
+
events?: string[];
|
|
1109
|
+
/** Headers */
|
|
1110
|
+
headers?: Record<string, string>;
|
|
1111
|
+
/** Metadata */
|
|
1112
|
+
metadata?: Record<string, unknown>;
|
|
1113
|
+
/** Tags */
|
|
1114
|
+
tags?: string[];
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* Query options for webhooks
|
|
1118
|
+
*/
|
|
1119
|
+
interface WebhookQuery {
|
|
1120
|
+
/** Filter by state */
|
|
1121
|
+
state?: WebhookState | WebhookState[];
|
|
1122
|
+
/** Filter by events (match any) */
|
|
1123
|
+
events?: string[];
|
|
1124
|
+
/** Filter by tags (match any) */
|
|
1125
|
+
tags?: string[];
|
|
1126
|
+
/** Filter by name pattern */
|
|
1127
|
+
name?: string;
|
|
1128
|
+
/** Pagination offset */
|
|
1129
|
+
offset?: number;
|
|
1130
|
+
/** Pagination limit */
|
|
1131
|
+
limit?: number;
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* Query options for deliveries
|
|
1135
|
+
*/
|
|
1136
|
+
interface DeliveryQuery {
|
|
1137
|
+
/** Filter by endpoint ID */
|
|
1138
|
+
endpointId?: string;
|
|
1139
|
+
/** Filter by event type */
|
|
1140
|
+
eventType?: string;
|
|
1141
|
+
/** Filter by status */
|
|
1142
|
+
status?: DeliveryStatus | DeliveryStatus[];
|
|
1143
|
+
/** Filter by date range - from */
|
|
1144
|
+
from?: Date | string;
|
|
1145
|
+
/** Filter by date range - to */
|
|
1146
|
+
to?: Date | string;
|
|
1147
|
+
/** Pagination offset */
|
|
1148
|
+
offset?: number;
|
|
1149
|
+
/** Pagination limit */
|
|
1150
|
+
limit?: number;
|
|
1151
|
+
}
|
|
1152
|
+
/**
|
|
1153
|
+
* Webhook statistics
|
|
1154
|
+
*/
|
|
1155
|
+
interface WebhookStats {
|
|
1156
|
+
/** Total endpoints */
|
|
1157
|
+
totalEndpoints: number;
|
|
1158
|
+
/** Active endpoints */
|
|
1159
|
+
activeEndpoints: number;
|
|
1160
|
+
/** Paused endpoints */
|
|
1161
|
+
pausedEndpoints: number;
|
|
1162
|
+
/** Failed endpoints (in failure state) */
|
|
1163
|
+
failedEndpoints: number;
|
|
1164
|
+
/** Deliveries in last 24h */
|
|
1165
|
+
deliveriesLast24h: number;
|
|
1166
|
+
/** Successful deliveries in last 24h */
|
|
1167
|
+
successLast24h: number;
|
|
1168
|
+
/** Failed deliveries in last 24h */
|
|
1169
|
+
failuresLast24h: number;
|
|
1170
|
+
/** Average delivery time in ms */
|
|
1171
|
+
avgDeliveryTime: number;
|
|
1172
|
+
}
|
|
1173
|
+
/**
|
|
1174
|
+
* Inbound webhook verification result
|
|
1175
|
+
*/
|
|
1176
|
+
interface VerificationResult {
|
|
1177
|
+
/** Whether signature is valid */
|
|
1178
|
+
valid: boolean;
|
|
1179
|
+
/** Parsed payload if valid */
|
|
1180
|
+
payload?: unknown;
|
|
1181
|
+
/** Error message if invalid */
|
|
1182
|
+
error?: string;
|
|
1183
|
+
}
|
|
1184
|
+
/**
|
|
1185
|
+
* Inbound webhook handler context
|
|
1186
|
+
*/
|
|
1187
|
+
interface InboundWebhookContext {
|
|
1188
|
+
/** Raw body */
|
|
1189
|
+
rawBody: string | Buffer;
|
|
1190
|
+
/** Signature header value */
|
|
1191
|
+
signature: string;
|
|
1192
|
+
/** Request headers */
|
|
1193
|
+
headers: Record<string, string>;
|
|
1194
|
+
/** Request method */
|
|
1195
|
+
method: string;
|
|
1196
|
+
/** Request path */
|
|
1197
|
+
path: string;
|
|
1198
|
+
/** Query params */
|
|
1199
|
+
query?: Record<string, string>;
|
|
1200
|
+
/** Timestamp header if present */
|
|
1201
|
+
timestamp?: string;
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Inbound webhook configuration
|
|
1205
|
+
*/
|
|
1206
|
+
interface InboundWebhookConfig {
|
|
1207
|
+
/** Webhook name/identifier */
|
|
1208
|
+
name: string;
|
|
1209
|
+
/** Secret for verification */
|
|
1210
|
+
secret: string;
|
|
1211
|
+
/** Signature algorithm */
|
|
1212
|
+
signatureAlgorithm?: SignatureAlgorithm;
|
|
1213
|
+
/** Signature header name */
|
|
1214
|
+
signatureHeader?: string;
|
|
1215
|
+
/** Timestamp header name (for replay prevention) */
|
|
1216
|
+
timestampHeader?: string;
|
|
1217
|
+
/** Max age for timestamp validation (seconds) */
|
|
1218
|
+
timestampTolerance?: number;
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Webhook configuration
|
|
1222
|
+
*/
|
|
1223
|
+
interface WebhookConfig {
|
|
1224
|
+
/** Max retry attempts */
|
|
1225
|
+
maxRetries?: number;
|
|
1226
|
+
/** Initial retry delay in ms */
|
|
1227
|
+
retryDelayMs?: number;
|
|
1228
|
+
/** Max retry delay in ms */
|
|
1229
|
+
maxRetryDelayMs?: number;
|
|
1230
|
+
/** Backoff multiplier */
|
|
1231
|
+
backoffMultiplier?: number;
|
|
1232
|
+
/** Request timeout in ms */
|
|
1233
|
+
timeoutMs?: number;
|
|
1234
|
+
/** Max concurrent deliveries */
|
|
1235
|
+
maxConcurrent?: number;
|
|
1236
|
+
/** Failure threshold before disabling webhook */
|
|
1237
|
+
failureThreshold?: number;
|
|
1238
|
+
/** Delivery history retention in days */
|
|
1239
|
+
historyRetentionDays?: number;
|
|
1240
|
+
/** User agent header */
|
|
1241
|
+
userAgent?: string;
|
|
1242
|
+
}
|
|
1243
|
+
/**
|
|
1244
|
+
* Webhook manager interface
|
|
1245
|
+
*/
|
|
1246
|
+
interface IWebhook {
|
|
1247
|
+
/**
|
|
1248
|
+
* Create a new webhook endpoint
|
|
1249
|
+
*/
|
|
1250
|
+
create(options: CreateWebhookOptions): Promise<WebhookEndpoint>;
|
|
1251
|
+
/**
|
|
1252
|
+
* Get a webhook endpoint by ID
|
|
1253
|
+
*/
|
|
1254
|
+
get(id: string): Promise<WebhookEndpoint | null>;
|
|
1255
|
+
/**
|
|
1256
|
+
* Update a webhook endpoint
|
|
1257
|
+
*/
|
|
1258
|
+
update(id: string, options: UpdateWebhookOptions): Promise<WebhookEndpoint>;
|
|
1259
|
+
/**
|
|
1260
|
+
* Delete a webhook endpoint
|
|
1261
|
+
*/
|
|
1262
|
+
delete(id: string): Promise<void>;
|
|
1263
|
+
/**
|
|
1264
|
+
* List webhook endpoints
|
|
1265
|
+
*/
|
|
1266
|
+
list(query?: WebhookQuery): Promise<WebhookEndpoint[]>;
|
|
1267
|
+
/**
|
|
1268
|
+
* Pause a webhook endpoint
|
|
1269
|
+
*/
|
|
1270
|
+
pause(id: string): Promise<void>;
|
|
1271
|
+
/**
|
|
1272
|
+
* Resume a paused webhook endpoint
|
|
1273
|
+
*/
|
|
1274
|
+
resume(id: string): Promise<void>;
|
|
1275
|
+
/**
|
|
1276
|
+
* Test a webhook endpoint with a test payload
|
|
1277
|
+
*/
|
|
1278
|
+
test(id: string): Promise<DeliveryAttempt>;
|
|
1279
|
+
/**
|
|
1280
|
+
* Dispatch an event to all matching webhooks
|
|
1281
|
+
* Returns number of deliveries queued
|
|
1282
|
+
*/
|
|
1283
|
+
dispatch<T>(event: WebhookEvent<T>): Promise<string[]>;
|
|
1284
|
+
/**
|
|
1285
|
+
* Dispatch to a specific endpoint
|
|
1286
|
+
*/
|
|
1287
|
+
dispatchTo<T>(endpointId: string, event: WebhookEvent<T>): Promise<string>;
|
|
1288
|
+
/**
|
|
1289
|
+
* Retry a failed delivery
|
|
1290
|
+
*/
|
|
1291
|
+
retry(deliveryId: string): Promise<DeliveryAttempt>;
|
|
1292
|
+
/**
|
|
1293
|
+
* Get a delivery by ID
|
|
1294
|
+
*/
|
|
1295
|
+
getDelivery(id: string): Promise<WebhookDelivery | null>;
|
|
1296
|
+
/**
|
|
1297
|
+
* List deliveries
|
|
1298
|
+
*/
|
|
1299
|
+
listDeliveries(query?: DeliveryQuery): Promise<WebhookDelivery[]>;
|
|
1300
|
+
/**
|
|
1301
|
+
* Get delivery attempts for a delivery
|
|
1302
|
+
*/
|
|
1303
|
+
getAttempts(deliveryId: string): Promise<DeliveryAttempt[]>;
|
|
1304
|
+
/**
|
|
1305
|
+
* Register an inbound webhook configuration
|
|
1306
|
+
*/
|
|
1307
|
+
registerInbound(config: InboundWebhookConfig): void;
|
|
1308
|
+
/**
|
|
1309
|
+
* Verify an incoming webhook request
|
|
1310
|
+
*/
|
|
1311
|
+
verify(name: string, context: InboundWebhookContext): VerificationResult;
|
|
1312
|
+
/**
|
|
1313
|
+
* Get webhook statistics
|
|
1314
|
+
*/
|
|
1315
|
+
getStats(): Promise<WebhookStats>;
|
|
1316
|
+
/**
|
|
1317
|
+
* Health check
|
|
1318
|
+
*/
|
|
1319
|
+
healthCheck(): Promise<boolean>;
|
|
1320
|
+
/**
|
|
1321
|
+
* Close and cleanup resources
|
|
1322
|
+
*/
|
|
1323
|
+
close(): Promise<void>;
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* Generate a webhook ID
|
|
1327
|
+
*/
|
|
1328
|
+
declare function generateWebhookId(): string;
|
|
1329
|
+
/**
|
|
1330
|
+
* Generate a delivery ID
|
|
1331
|
+
*/
|
|
1332
|
+
declare function generateDeliveryId(): string;
|
|
1333
|
+
/**
|
|
1334
|
+
* Generate an event ID
|
|
1335
|
+
*/
|
|
1336
|
+
declare function generateEventId(): string;
|
|
1337
|
+
/**
|
|
1338
|
+
* Generate a webhook secret
|
|
1339
|
+
*/
|
|
1340
|
+
declare function generateWebhookSecret(length?: number): string;
|
|
1341
|
+
/**
|
|
1342
|
+
* Check if event type matches a pattern
|
|
1343
|
+
* Supports wildcards: *, **
|
|
1344
|
+
* - * matches single segment: 'user.*' matches 'user.created' but not 'user.profile.updated'
|
|
1345
|
+
* - ** matches all segments: 'user.**' matches 'user.created' and 'user.profile.updated'
|
|
1346
|
+
*/
|
|
1347
|
+
declare function matchEventType(eventType: string, pattern: string): boolean;
|
|
1348
|
+
/**
|
|
1349
|
+
* Calculate next retry delay with exponential backoff
|
|
1350
|
+
*/
|
|
1351
|
+
declare function calculateRetryDelay(attempt: number, initialDelay?: number, maxDelay?: number, // 1 hour
|
|
1352
|
+
multiplier?: number): number;
|
|
1353
|
+
/**
|
|
1354
|
+
* Common event type patterns
|
|
1355
|
+
*/
|
|
1356
|
+
declare const WebhookEventTypes: {
|
|
1357
|
+
readonly USER_CREATED: "user.created";
|
|
1358
|
+
readonly USER_UPDATED: "user.updated";
|
|
1359
|
+
readonly USER_DELETED: "user.deleted";
|
|
1360
|
+
readonly USER_LOGIN: "user.login";
|
|
1361
|
+
readonly USER_LOGOUT: "user.logout";
|
|
1362
|
+
readonly SUBSCRIPTION_CREATED: "subscription.created";
|
|
1363
|
+
readonly SUBSCRIPTION_UPDATED: "subscription.updated";
|
|
1364
|
+
readonly SUBSCRIPTION_CANCELLED: "subscription.cancelled";
|
|
1365
|
+
readonly SUBSCRIPTION_RENEWED: "subscription.renewed";
|
|
1366
|
+
readonly PAYMENT_SUCCEEDED: "payment.succeeded";
|
|
1367
|
+
readonly PAYMENT_FAILED: "payment.failed";
|
|
1368
|
+
readonly PAYMENT_REFUNDED: "payment.refunded";
|
|
1369
|
+
readonly INVOICE_CREATED: "invoice.created";
|
|
1370
|
+
readonly INVOICE_PAID: "invoice.paid";
|
|
1371
|
+
readonly INVOICE_FAILED: "invoice.failed";
|
|
1372
|
+
readonly ORDER_CREATED: "order.created";
|
|
1373
|
+
readonly ORDER_UPDATED: "order.updated";
|
|
1374
|
+
readonly ORDER_COMPLETED: "order.completed";
|
|
1375
|
+
readonly ORDER_CANCELLED: "order.cancelled";
|
|
1376
|
+
readonly ALL: "**";
|
|
1377
|
+
readonly ALL_USER: "user.**";
|
|
1378
|
+
readonly ALL_PAYMENT: "payment.**";
|
|
1379
|
+
readonly ALL_SUBSCRIPTION: "subscription.**";
|
|
1380
|
+
readonly ALL_ORDER: "order.**";
|
|
1381
|
+
};
|
|
1382
|
+
|
|
1383
|
+
/**
|
|
1384
|
+
* Notification Interface
|
|
1385
|
+
*
|
|
1386
|
+
* Multi-channel notification system with self-hosted options.
|
|
1387
|
+
* Supports in-app, email, push, and SMS notifications.
|
|
1388
|
+
*
|
|
1389
|
+
* Channels:
|
|
1390
|
+
* - in_app: Stored in database, fetched by clients
|
|
1391
|
+
* - email: Uses IEmail adapter
|
|
1392
|
+
* - push: Web Push Protocol (no external service)
|
|
1393
|
+
* - sms: Via SMTP gateway or direct carrier API
|
|
1394
|
+
*
|
|
1395
|
+
* Design Principles:
|
|
1396
|
+
* - Self-hosted by default
|
|
1397
|
+
* - No vendor lock-in
|
|
1398
|
+
* - Multi-channel delivery
|
|
1399
|
+
* - User preferences respected
|
|
1400
|
+
*/
|
|
1401
|
+
/**
|
|
1402
|
+
* Notification channels
|
|
1403
|
+
*/
|
|
1404
|
+
type NotificationChannel = 'in_app' | 'email' | 'push' | 'sms';
|
|
1405
|
+
/**
|
|
1406
|
+
* Notification priority
|
|
1407
|
+
*/
|
|
1408
|
+
type NotificationPriority = 'low' | 'normal' | 'high' | 'urgent';
|
|
1409
|
+
/**
|
|
1410
|
+
* Notification status
|
|
1411
|
+
*/
|
|
1412
|
+
type NotificationStatus = 'pending' | 'sent' | 'delivered' | 'read' | 'failed';
|
|
1413
|
+
/**
|
|
1414
|
+
* Notification category for filtering and preferences
|
|
1415
|
+
*/
|
|
1416
|
+
type NotificationCategory = 'system' | 'security' | 'account' | 'billing' | 'marketing' | 'social' | 'updates' | 'alerts' | string;
|
|
1417
|
+
/**
|
|
1418
|
+
* Notification template data
|
|
1419
|
+
*/
|
|
1420
|
+
interface NotificationData {
|
|
1421
|
+
/** Notification title */
|
|
1422
|
+
title: string;
|
|
1423
|
+
/** Notification body/message */
|
|
1424
|
+
body: string;
|
|
1425
|
+
/** Category for filtering */
|
|
1426
|
+
category?: NotificationCategory;
|
|
1427
|
+
/** Priority level */
|
|
1428
|
+
priority?: NotificationPriority;
|
|
1429
|
+
/** URL to link to */
|
|
1430
|
+
url?: string;
|
|
1431
|
+
/** Icon URL */
|
|
1432
|
+
icon?: string;
|
|
1433
|
+
/** Image URL for rich notifications */
|
|
1434
|
+
image?: string;
|
|
1435
|
+
/** Action buttons */
|
|
1436
|
+
actions?: NotificationAction[];
|
|
1437
|
+
/** Custom data payload */
|
|
1438
|
+
data?: Record<string, unknown>;
|
|
1439
|
+
/** Time to live in seconds (default: 86400 = 24 hours) */
|
|
1440
|
+
ttl?: number;
|
|
1441
|
+
/** Collapse key for grouping */
|
|
1442
|
+
collapseKey?: string;
|
|
1443
|
+
/** Sound to play */
|
|
1444
|
+
sound?: string;
|
|
1445
|
+
/** Badge count */
|
|
1446
|
+
badge?: number;
|
|
1447
|
+
/** Tags for filtering */
|
|
1448
|
+
tags?: string[];
|
|
1449
|
+
}
|
|
1450
|
+
/**
|
|
1451
|
+
* Action button for notifications
|
|
1452
|
+
*/
|
|
1453
|
+
interface NotificationAction {
|
|
1454
|
+
/** Action identifier */
|
|
1455
|
+
action: string;
|
|
1456
|
+
/** Display title */
|
|
1457
|
+
title: string;
|
|
1458
|
+
/** Icon URL */
|
|
1459
|
+
icon?: string;
|
|
1460
|
+
/** URL to open */
|
|
1461
|
+
url?: string;
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* Target for notification delivery
|
|
1465
|
+
*/
|
|
1466
|
+
interface NotificationTarget {
|
|
1467
|
+
/** User ID */
|
|
1468
|
+
userId?: string;
|
|
1469
|
+
/** User email */
|
|
1470
|
+
email?: string;
|
|
1471
|
+
/** Phone number for SMS */
|
|
1472
|
+
phone?: string;
|
|
1473
|
+
/** Push subscription for web push */
|
|
1474
|
+
pushSubscription?: PushSubscription;
|
|
1475
|
+
/** Device token for mobile push */
|
|
1476
|
+
deviceToken?: string;
|
|
1477
|
+
/** Custom data */
|
|
1478
|
+
data?: Record<string, unknown>;
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* Web Push subscription (standard format)
|
|
1482
|
+
*/
|
|
1483
|
+
interface PushSubscription {
|
|
1484
|
+
/** Push endpoint URL */
|
|
1485
|
+
endpoint: string;
|
|
1486
|
+
/** Expiration time */
|
|
1487
|
+
expirationTime?: number | null;
|
|
1488
|
+
/** Keys for encryption */
|
|
1489
|
+
keys: {
|
|
1490
|
+
/** P-256 key */
|
|
1491
|
+
p256dh: string;
|
|
1492
|
+
/** Auth secret */
|
|
1493
|
+
auth: string;
|
|
1494
|
+
};
|
|
1495
|
+
}
|
|
1496
|
+
/**
|
|
1497
|
+
* Stored notification record
|
|
1498
|
+
*/
|
|
1499
|
+
interface StoredNotification {
|
|
1500
|
+
/** Unique notification ID */
|
|
1501
|
+
id: string;
|
|
1502
|
+
/** User ID */
|
|
1503
|
+
userId: string;
|
|
1504
|
+
/** Notification data */
|
|
1505
|
+
data: NotificationData;
|
|
1506
|
+
/** Channels sent to */
|
|
1507
|
+
channels: NotificationChannel[];
|
|
1508
|
+
/** Status per channel */
|
|
1509
|
+
status: Partial<Record<NotificationChannel, NotificationStatus>>;
|
|
1510
|
+
/** Created timestamp */
|
|
1511
|
+
createdAt: string;
|
|
1512
|
+
/** Read timestamp */
|
|
1513
|
+
readAt?: string;
|
|
1514
|
+
/** Metadata */
|
|
1515
|
+
metadata?: Record<string, unknown>;
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Options for sending notifications
|
|
1519
|
+
*/
|
|
1520
|
+
interface SendNotificationOptions {
|
|
1521
|
+
/** Target user/device */
|
|
1522
|
+
target: NotificationTarget;
|
|
1523
|
+
/** Notification data */
|
|
1524
|
+
notification: NotificationData;
|
|
1525
|
+
/** Channels to send to (default: based on user preferences) */
|
|
1526
|
+
channels?: NotificationChannel[];
|
|
1527
|
+
/** Override user preferences */
|
|
1528
|
+
force?: boolean;
|
|
1529
|
+
/** Schedule for later delivery */
|
|
1530
|
+
scheduledFor?: Date | string;
|
|
1531
|
+
/** Idempotency key */
|
|
1532
|
+
idempotencyKey?: string;
|
|
1533
|
+
}
|
|
1534
|
+
/**
|
|
1535
|
+
* Options for batch notifications
|
|
1536
|
+
*/
|
|
1537
|
+
interface BatchNotificationOptions {
|
|
1538
|
+
/** Target users */
|
|
1539
|
+
targets: NotificationTarget[];
|
|
1540
|
+
/** Notification data */
|
|
1541
|
+
notification: NotificationData;
|
|
1542
|
+
/** Channels to send to */
|
|
1543
|
+
channels?: NotificationChannel[];
|
|
1544
|
+
/** Max concurrent sends */
|
|
1545
|
+
concurrency?: number;
|
|
1546
|
+
}
|
|
1547
|
+
/**
|
|
1548
|
+
* User notification preferences
|
|
1549
|
+
*/
|
|
1550
|
+
interface NotificationPreferences {
|
|
1551
|
+
/** User ID */
|
|
1552
|
+
userId: string;
|
|
1553
|
+
/** Enabled channels */
|
|
1554
|
+
enabledChannels: NotificationChannel[];
|
|
1555
|
+
/** Per-category preferences */
|
|
1556
|
+
categories: Partial<Record<NotificationCategory, {
|
|
1557
|
+
enabled: boolean;
|
|
1558
|
+
channels: NotificationChannel[];
|
|
1559
|
+
}>>;
|
|
1560
|
+
/** Quiet hours (no notifications) */
|
|
1561
|
+
quietHours?: {
|
|
1562
|
+
enabled: boolean;
|
|
1563
|
+
start: string;
|
|
1564
|
+
end: string;
|
|
1565
|
+
timezone: string;
|
|
1566
|
+
};
|
|
1567
|
+
/** Email preferences */
|
|
1568
|
+
email?: {
|
|
1569
|
+
digest: boolean;
|
|
1570
|
+
digestFrequency: 'daily' | 'weekly' | 'never';
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
/**
|
|
1574
|
+
* Query options for notifications
|
|
1575
|
+
*/
|
|
1576
|
+
interface NotificationQuery {
|
|
1577
|
+
/** Filter by user ID */
|
|
1578
|
+
userId?: string;
|
|
1579
|
+
/** Filter by category */
|
|
1580
|
+
category?: NotificationCategory | NotificationCategory[];
|
|
1581
|
+
/** Filter by status */
|
|
1582
|
+
status?: NotificationStatus | NotificationStatus[];
|
|
1583
|
+
/** Filter by read status */
|
|
1584
|
+
unreadOnly?: boolean;
|
|
1585
|
+
/** Filter by date range */
|
|
1586
|
+
from?: Date | string;
|
|
1587
|
+
to?: Date | string;
|
|
1588
|
+
/** Pagination */
|
|
1589
|
+
offset?: number;
|
|
1590
|
+
limit?: number;
|
|
1591
|
+
}
|
|
1592
|
+
/**
|
|
1593
|
+
* Notification result
|
|
1594
|
+
*/
|
|
1595
|
+
interface NotificationResult {
|
|
1596
|
+
/** Notification ID */
|
|
1597
|
+
id: string;
|
|
1598
|
+
/** Success per channel */
|
|
1599
|
+
results: Partial<Record<NotificationChannel, {
|
|
1600
|
+
success: boolean;
|
|
1601
|
+
messageId?: string;
|
|
1602
|
+
error?: string;
|
|
1603
|
+
}>>;
|
|
1604
|
+
}
|
|
1605
|
+
/**
|
|
1606
|
+
* Notification statistics
|
|
1607
|
+
*/
|
|
1608
|
+
interface NotificationStats {
|
|
1609
|
+
/** Total notifications sent */
|
|
1610
|
+
totalSent: number;
|
|
1611
|
+
/** Per channel stats */
|
|
1612
|
+
byChannel: Partial<Record<NotificationChannel, {
|
|
1613
|
+
sent: number;
|
|
1614
|
+
delivered: number;
|
|
1615
|
+
read: number;
|
|
1616
|
+
failed: number;
|
|
1617
|
+
}>>;
|
|
1618
|
+
/** Per category stats */
|
|
1619
|
+
byCategory: Partial<Record<NotificationCategory, number>>;
|
|
1620
|
+
/** Unread count */
|
|
1621
|
+
unreadCount: number;
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* Notification configuration
|
|
1625
|
+
*/
|
|
1626
|
+
interface NotificationConfig {
|
|
1627
|
+
/** Default channels */
|
|
1628
|
+
defaultChannels?: NotificationChannel[];
|
|
1629
|
+
/** Default TTL in seconds */
|
|
1630
|
+
defaultTtl?: number;
|
|
1631
|
+
/** Web Push VAPID keys */
|
|
1632
|
+
vapidKeys?: {
|
|
1633
|
+
publicKey: string;
|
|
1634
|
+
privateKey: string;
|
|
1635
|
+
subject: string;
|
|
1636
|
+
};
|
|
1637
|
+
/** SMS gateway configuration */
|
|
1638
|
+
smsGateway?: {
|
|
1639
|
+
type: 'smtp' | 'twilio' | 'custom';
|
|
1640
|
+
config: Record<string, unknown>;
|
|
1641
|
+
};
|
|
1642
|
+
/** Batch size for bulk sends */
|
|
1643
|
+
batchSize?: number;
|
|
1644
|
+
/** Rate limits per channel */
|
|
1645
|
+
rateLimits?: Partial<Record<NotificationChannel, {
|
|
1646
|
+
perSecond?: number;
|
|
1647
|
+
perMinute?: number;
|
|
1648
|
+
perHour?: number;
|
|
1649
|
+
}>>;
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* Notification service interface
|
|
1653
|
+
*/
|
|
1654
|
+
interface INotification {
|
|
1655
|
+
/**
|
|
1656
|
+
* Send a notification to a user
|
|
1657
|
+
*/
|
|
1658
|
+
send(options: SendNotificationOptions): Promise<NotificationResult>;
|
|
1659
|
+
/**
|
|
1660
|
+
* Send notifications to multiple users
|
|
1661
|
+
*/
|
|
1662
|
+
sendBatch(options: BatchNotificationOptions): Promise<NotificationResult[]>;
|
|
1663
|
+
/**
|
|
1664
|
+
* Send to a topic/segment (all subscribed users)
|
|
1665
|
+
*/
|
|
1666
|
+
sendToTopic(topic: string, notification: NotificationData): Promise<number>;
|
|
1667
|
+
/**
|
|
1668
|
+
* Get notifications for a user
|
|
1669
|
+
*/
|
|
1670
|
+
getForUser(userId: string, query?: NotificationQuery): Promise<StoredNotification[]>;
|
|
1671
|
+
/**
|
|
1672
|
+
* Get unread count for a user
|
|
1673
|
+
*/
|
|
1674
|
+
getUnreadCount(userId: string, category?: NotificationCategory): Promise<number>;
|
|
1675
|
+
/**
|
|
1676
|
+
* Mark notification as read
|
|
1677
|
+
*/
|
|
1678
|
+
markAsRead(notificationId: string): Promise<void>;
|
|
1679
|
+
/**
|
|
1680
|
+
* Mark all notifications as read for a user
|
|
1681
|
+
*/
|
|
1682
|
+
markAllAsRead(userId: string, category?: NotificationCategory): Promise<number>;
|
|
1683
|
+
/**
|
|
1684
|
+
* Delete a notification
|
|
1685
|
+
*/
|
|
1686
|
+
delete(notificationId: string): Promise<void>;
|
|
1687
|
+
/**
|
|
1688
|
+
* Delete all notifications for a user
|
|
1689
|
+
*/
|
|
1690
|
+
deleteAllForUser(userId: string): Promise<number>;
|
|
1691
|
+
/**
|
|
1692
|
+
* Register a push subscription
|
|
1693
|
+
*/
|
|
1694
|
+
registerPushSubscription(userId: string, subscription: PushSubscription): Promise<void>;
|
|
1695
|
+
/**
|
|
1696
|
+
* Remove a push subscription
|
|
1697
|
+
*/
|
|
1698
|
+
removePushSubscription(userId: string, endpoint: string): Promise<void>;
|
|
1699
|
+
/**
|
|
1700
|
+
* Get push subscriptions for a user
|
|
1701
|
+
*/
|
|
1702
|
+
getPushSubscriptions(userId: string): Promise<PushSubscription[]>;
|
|
1703
|
+
/**
|
|
1704
|
+
* Get user notification preferences
|
|
1705
|
+
*/
|
|
1706
|
+
getPreferences(userId: string): Promise<NotificationPreferences>;
|
|
1707
|
+
/**
|
|
1708
|
+
* Update user notification preferences
|
|
1709
|
+
*/
|
|
1710
|
+
updatePreferences(userId: string, preferences: Partial<NotificationPreferences>): Promise<void>;
|
|
1711
|
+
/**
|
|
1712
|
+
* Subscribe user to a topic
|
|
1713
|
+
*/
|
|
1714
|
+
subscribeToTopic(userId: string, topic: string): Promise<void>;
|
|
1715
|
+
/**
|
|
1716
|
+
* Unsubscribe user from a topic
|
|
1717
|
+
*/
|
|
1718
|
+
unsubscribeFromTopic(userId: string, topic: string): Promise<void>;
|
|
1719
|
+
/**
|
|
1720
|
+
* Get user's subscribed topics
|
|
1721
|
+
*/
|
|
1722
|
+
getUserTopics(userId: string): Promise<string[]>;
|
|
1723
|
+
/**
|
|
1724
|
+
* Get notification statistics
|
|
1725
|
+
*/
|
|
1726
|
+
getStats(options?: {
|
|
1727
|
+
userId?: string;
|
|
1728
|
+
period?: 'day' | 'week' | 'month';
|
|
1729
|
+
}): Promise<NotificationStats>;
|
|
1730
|
+
/**
|
|
1731
|
+
* Health check
|
|
1732
|
+
*/
|
|
1733
|
+
healthCheck(): Promise<boolean>;
|
|
1734
|
+
/**
|
|
1735
|
+
* Close and cleanup
|
|
1736
|
+
*/
|
|
1737
|
+
close(): Promise<void>;
|
|
1738
|
+
}
|
|
1739
|
+
/**
|
|
1740
|
+
* Generate notification ID
|
|
1741
|
+
*/
|
|
1742
|
+
declare function generateNotificationId(): string;
|
|
1743
|
+
/**
|
|
1744
|
+
* Check if notification is within quiet hours
|
|
1745
|
+
*/
|
|
1746
|
+
declare function isInQuietHours(preferences: NotificationPreferences): boolean;
|
|
1747
|
+
/**
|
|
1748
|
+
* Default preferences factory
|
|
1749
|
+
*/
|
|
1750
|
+
declare function createDefaultPreferences(userId: string): NotificationPreferences;
|
|
1751
|
+
/**
|
|
1752
|
+
* Filter channels based on user preferences
|
|
1753
|
+
*/
|
|
1754
|
+
declare function filterChannelsByPreferences(requestedChannels: NotificationChannel[], preferences: NotificationPreferences, category?: NotificationCategory, force?: boolean): NotificationChannel[];
|
|
1755
|
+
/**
|
|
1756
|
+
* Common notification templates
|
|
1757
|
+
*/
|
|
1758
|
+
declare const NotificationTemplates: {
|
|
1759
|
+
readonly welcome: (name: string) => NotificationData;
|
|
1760
|
+
readonly passwordChanged: () => NotificationData;
|
|
1761
|
+
readonly newLogin: (location?: string) => NotificationData;
|
|
1762
|
+
readonly paymentSucceeded: (amount: string) => NotificationData;
|
|
1763
|
+
readonly paymentFailed: (reason?: string) => NotificationData;
|
|
1764
|
+
readonly subscriptionExpiring: (daysLeft: number) => NotificationData;
|
|
1765
|
+
};
|
|
1766
|
+
|
|
86
1767
|
/**
|
|
87
1768
|
* Middleware System for Platform Core
|
|
88
1769
|
*
|
|
@@ -392,6 +2073,171 @@ declare const RateLimitPresets: {
|
|
|
392
2073
|
};
|
|
393
2074
|
};
|
|
394
2075
|
|
|
2076
|
+
/**
|
|
2077
|
+
* Correlation Context using AsyncLocalStorage
|
|
2078
|
+
*
|
|
2079
|
+
* Provides automatic propagation of trace/correlation IDs and request context
|
|
2080
|
+
* across async operations without explicit passing.
|
|
2081
|
+
*
|
|
2082
|
+
* Design Principles:
|
|
2083
|
+
* - Zero external dependencies (uses Node.js built-in AsyncLocalStorage)
|
|
2084
|
+
* - Self-hosted compatible
|
|
2085
|
+
* - Integrates with logging, metrics, and tracing
|
|
2086
|
+
*/
|
|
2087
|
+
interface CorrelationData {
|
|
2088
|
+
/** Unique trace ID for distributed tracing */
|
|
2089
|
+
traceId?: string;
|
|
2090
|
+
/** Span ID for current operation */
|
|
2091
|
+
spanId?: string;
|
|
2092
|
+
/** Request ID for HTTP requests */
|
|
2093
|
+
requestId?: string;
|
|
2094
|
+
/** Correlation ID for job/event processing */
|
|
2095
|
+
correlationId?: string;
|
|
2096
|
+
/** User ID if authenticated */
|
|
2097
|
+
userId?: string;
|
|
2098
|
+
/** Tenant ID for multi-tenant applications */
|
|
2099
|
+
tenantId?: string;
|
|
2100
|
+
/** Session ID */
|
|
2101
|
+
sessionId?: string;
|
|
2102
|
+
/** Custom metadata */
|
|
2103
|
+
metadata?: Record<string, unknown>;
|
|
2104
|
+
/** Operation name (for logging) */
|
|
2105
|
+
operation?: string;
|
|
2106
|
+
/** Start time of the context */
|
|
2107
|
+
startTime?: number;
|
|
2108
|
+
}
|
|
2109
|
+
/**
|
|
2110
|
+
* Singleton correlation context using AsyncLocalStorage
|
|
2111
|
+
*/
|
|
2112
|
+
declare class CorrelationContextManager {
|
|
2113
|
+
private storage;
|
|
2114
|
+
private idGenerator;
|
|
2115
|
+
constructor();
|
|
2116
|
+
/**
|
|
2117
|
+
* Set custom ID generator
|
|
2118
|
+
*/
|
|
2119
|
+
setIdGenerator(generator: () => string): void;
|
|
2120
|
+
/**
|
|
2121
|
+
* Generate a new ID
|
|
2122
|
+
*/
|
|
2123
|
+
generateId(): string;
|
|
2124
|
+
/**
|
|
2125
|
+
* Run a function with correlation context
|
|
2126
|
+
*/
|
|
2127
|
+
run<T>(data: CorrelationData, fn: () => T): T;
|
|
2128
|
+
/**
|
|
2129
|
+
* Run an async function with correlation context
|
|
2130
|
+
*/
|
|
2131
|
+
runAsync<T>(data: CorrelationData, fn: () => Promise<T>): Promise<T>;
|
|
2132
|
+
/**
|
|
2133
|
+
* Get current correlation data
|
|
2134
|
+
*/
|
|
2135
|
+
get(): CorrelationData | undefined;
|
|
2136
|
+
/**
|
|
2137
|
+
* Get current correlation data or empty object
|
|
2138
|
+
*/
|
|
2139
|
+
getOrEmpty(): CorrelationData;
|
|
2140
|
+
/**
|
|
2141
|
+
* Get trace ID from current context
|
|
2142
|
+
*/
|
|
2143
|
+
getTraceId(): string | undefined;
|
|
2144
|
+
/**
|
|
2145
|
+
* Get correlation ID from current context
|
|
2146
|
+
*/
|
|
2147
|
+
getCorrelationId(): string | undefined;
|
|
2148
|
+
/**
|
|
2149
|
+
* Get request ID from current context
|
|
2150
|
+
*/
|
|
2151
|
+
getRequestId(): string | undefined;
|
|
2152
|
+
/**
|
|
2153
|
+
* Get user ID from current context
|
|
2154
|
+
*/
|
|
2155
|
+
getUserId(): string | undefined;
|
|
2156
|
+
/**
|
|
2157
|
+
* Get tenant ID from current context
|
|
2158
|
+
*/
|
|
2159
|
+
getTenantId(): string | undefined;
|
|
2160
|
+
/**
|
|
2161
|
+
* Check if we're in a correlation context
|
|
2162
|
+
*/
|
|
2163
|
+
isInContext(): boolean;
|
|
2164
|
+
/**
|
|
2165
|
+
* Update current context (merge data)
|
|
2166
|
+
* Note: This doesn't actually update the store, but returns merged data
|
|
2167
|
+
* for use in nested contexts
|
|
2168
|
+
*/
|
|
2169
|
+
extend(data: Partial<CorrelationData>): CorrelationData;
|
|
2170
|
+
/**
|
|
2171
|
+
* Run a nested context with extended data
|
|
2172
|
+
*/
|
|
2173
|
+
runNested<T>(data: Partial<CorrelationData>, fn: () => T): T;
|
|
2174
|
+
/**
|
|
2175
|
+
* Run a nested async context with extended data
|
|
2176
|
+
*/
|
|
2177
|
+
runNestedAsync<T>(data: Partial<CorrelationData>, fn: () => Promise<T>): Promise<T>;
|
|
2178
|
+
/**
|
|
2179
|
+
* Get context as log metadata (for structured logging)
|
|
2180
|
+
*/
|
|
2181
|
+
getLogMeta(): Record<string, unknown>;
|
|
2182
|
+
/**
|
|
2183
|
+
* Get context as HTTP headers (for propagation)
|
|
2184
|
+
*/
|
|
2185
|
+
getHeaders(): Record<string, string>;
|
|
2186
|
+
/**
|
|
2187
|
+
* Parse context from HTTP headers
|
|
2188
|
+
*/
|
|
2189
|
+
parseHeaders(headers: Record<string, string | string[] | undefined>): CorrelationData;
|
|
2190
|
+
/**
|
|
2191
|
+
* Get elapsed time since context start (ms)
|
|
2192
|
+
*/
|
|
2193
|
+
getElapsed(): number;
|
|
2194
|
+
/**
|
|
2195
|
+
* Create a child span context
|
|
2196
|
+
*/
|
|
2197
|
+
createChildSpan(operation: string): CorrelationData;
|
|
2198
|
+
}
|
|
2199
|
+
/**
|
|
2200
|
+
* Global correlation context instance
|
|
2201
|
+
*/
|
|
2202
|
+
declare const correlationContext: CorrelationContextManager;
|
|
2203
|
+
declare const runWithContext: <T>(data: CorrelationData, fn: () => T) => T;
|
|
2204
|
+
declare const runWithContextAsync: <T>(data: CorrelationData, fn: () => Promise<T>) => Promise<T>;
|
|
2205
|
+
declare const getContext: () => CorrelationData | undefined;
|
|
2206
|
+
declare const getTraceId: () => string | undefined;
|
|
2207
|
+
declare const getCorrelationId: () => string | undefined;
|
|
2208
|
+
declare const getRequestId: () => string | undefined;
|
|
2209
|
+
declare const getUserId: () => string | undefined;
|
|
2210
|
+
declare const getTenantId: () => string | undefined;
|
|
2211
|
+
declare const getLogMeta: () => Record<string, unknown>;
|
|
2212
|
+
declare const isInContext: () => boolean;
|
|
2213
|
+
/**
|
|
2214
|
+
* Create correlation context from incoming HTTP request
|
|
2215
|
+
*/
|
|
2216
|
+
declare function createRequestContext(headers: Record<string, string | string[] | undefined>, options?: {
|
|
2217
|
+
generateTraceId?: boolean;
|
|
2218
|
+
generateRequestId?: boolean;
|
|
2219
|
+
operation?: string;
|
|
2220
|
+
userId?: string;
|
|
2221
|
+
tenantId?: string;
|
|
2222
|
+
}): CorrelationData;
|
|
2223
|
+
/**
|
|
2224
|
+
* Create correlation context for queue job processing
|
|
2225
|
+
*/
|
|
2226
|
+
declare function createJobContext(job: {
|
|
2227
|
+
id: string;
|
|
2228
|
+
name: string;
|
|
2229
|
+
correlationId?: string;
|
|
2230
|
+
metadata?: Record<string, unknown>;
|
|
2231
|
+
}): CorrelationData;
|
|
2232
|
+
/**
|
|
2233
|
+
* Decorator to wrap a function with correlation context
|
|
2234
|
+
*/
|
|
2235
|
+
declare function withCorrelation<TArgs extends unknown[], TReturn>(fn: (...args: TArgs) => TReturn, getContext: (...args: TArgs) => CorrelationData): (...args: TArgs) => TReturn;
|
|
2236
|
+
/**
|
|
2237
|
+
* Decorator to wrap an async function with correlation context
|
|
2238
|
+
*/
|
|
2239
|
+
declare function withCorrelationAsync<TArgs extends unknown[], TReturn>(fn: (...args: TArgs) => Promise<TReturn>, getContext: (...args: TArgs) => CorrelationData): (...args: TArgs) => Promise<TReturn>;
|
|
2240
|
+
|
|
395
2241
|
/**
|
|
396
2242
|
* Hooks System for Platform Core
|
|
397
2243
|
*
|
|
@@ -1532,6 +3378,252 @@ declare function createObservabilityServer(healthEndpoints: HealthEndpoints, met
|
|
|
1532
3378
|
port: number;
|
|
1533
3379
|
}>;
|
|
1534
3380
|
|
|
3381
|
+
/**
|
|
3382
|
+
* Memory Error Reporter
|
|
3383
|
+
*
|
|
3384
|
+
* Self-hosted error reporting with in-memory storage.
|
|
3385
|
+
* Perfect for development, testing, and self-hosted production.
|
|
3386
|
+
*
|
|
3387
|
+
* Features:
|
|
3388
|
+
* - No external dependencies
|
|
3389
|
+
* - Automatic correlation context integration
|
|
3390
|
+
* - Configurable retention and sampling
|
|
3391
|
+
* - Query/filter error reports
|
|
3392
|
+
*/
|
|
3393
|
+
|
|
3394
|
+
interface MemoryErrorReporterConfig extends ErrorReporterConfig {
|
|
3395
|
+
/** Maximum reports to keep in memory */
|
|
3396
|
+
maxReports?: number;
|
|
3397
|
+
/** Log errors to console */
|
|
3398
|
+
logToConsole?: boolean;
|
|
3399
|
+
/** Console log level threshold */
|
|
3400
|
+
consoleLogLevel?: ErrorLevel;
|
|
3401
|
+
}
|
|
3402
|
+
declare class MemoryErrorReporter implements IErrorReporter {
|
|
3403
|
+
private reports;
|
|
3404
|
+
private breadcrumbs;
|
|
3405
|
+
private userContext;
|
|
3406
|
+
private contexts;
|
|
3407
|
+
private tags;
|
|
3408
|
+
private config;
|
|
3409
|
+
constructor(config: MemoryErrorReporterConfig);
|
|
3410
|
+
captureError(error: Error, options?: CaptureOptions): string;
|
|
3411
|
+
captureMessage(message: string, options?: CaptureOptions): string;
|
|
3412
|
+
addBreadcrumb(breadcrumb: Omit<Breadcrumb, 'timestamp'>): void;
|
|
3413
|
+
setUser(user: {
|
|
3414
|
+
id?: string;
|
|
3415
|
+
email?: string;
|
|
3416
|
+
username?: string;
|
|
3417
|
+
} | null): void;
|
|
3418
|
+
setContext(name: string, context: Record<string, unknown> | null): void;
|
|
3419
|
+
setTag(key: string, value: string): void;
|
|
3420
|
+
getReports(options?: {
|
|
3421
|
+
limit?: number;
|
|
3422
|
+
level?: ErrorLevel;
|
|
3423
|
+
}): ErrorReport[];
|
|
3424
|
+
clearReports(): void;
|
|
3425
|
+
flush(_timeout?: number): Promise<boolean>;
|
|
3426
|
+
close(): Promise<void>;
|
|
3427
|
+
/**
|
|
3428
|
+
* Get reports by fingerprint (for grouping analysis)
|
|
3429
|
+
*/
|
|
3430
|
+
getReportsByFingerprint(): Map<string, ErrorReport[]>;
|
|
3431
|
+
/**
|
|
3432
|
+
* Get error statistics
|
|
3433
|
+
*/
|
|
3434
|
+
getStats(): {
|
|
3435
|
+
total: number;
|
|
3436
|
+
byLevel: Record<ErrorLevel, number>;
|
|
3437
|
+
uniqueErrors: number;
|
|
3438
|
+
};
|
|
3439
|
+
/**
|
|
3440
|
+
* Find reports matching criteria
|
|
3441
|
+
*/
|
|
3442
|
+
findReports(predicate: (report: ErrorReport) => boolean): ErrorReport[];
|
|
3443
|
+
/**
|
|
3444
|
+
* Get the most recent report
|
|
3445
|
+
*/
|
|
3446
|
+
getLastReport(): ErrorReport | undefined;
|
|
3447
|
+
private buildContext;
|
|
3448
|
+
private createReport;
|
|
3449
|
+
private storeReport;
|
|
3450
|
+
private logToConsole;
|
|
3451
|
+
}
|
|
3452
|
+
|
|
3453
|
+
/**
|
|
3454
|
+
* Memory Audit Log Implementation
|
|
3455
|
+
*
|
|
3456
|
+
* In-memory audit log for testing and development.
|
|
3457
|
+
* Full IAuditLog compliance with query support.
|
|
3458
|
+
*/
|
|
3459
|
+
|
|
3460
|
+
interface MemoryAuditLogConfig extends AuditLogConfig {
|
|
3461
|
+
/** Maximum events to store (default 10000) */
|
|
3462
|
+
maxEvents?: number;
|
|
3463
|
+
}
|
|
3464
|
+
declare class MemoryAuditLog implements IAuditLog {
|
|
3465
|
+
private events;
|
|
3466
|
+
private sequence;
|
|
3467
|
+
private config;
|
|
3468
|
+
constructor(config: MemoryAuditLogConfig);
|
|
3469
|
+
log(event: AuditEvent): Promise<StoredAuditEvent>;
|
|
3470
|
+
logBatch(events: AuditEvent[]): Promise<StoredAuditEvent[]>;
|
|
3471
|
+
query(query: AuditQuery): Promise<AuditQueryResult>;
|
|
3472
|
+
getEvent(id: string): Promise<StoredAuditEvent | null>;
|
|
3473
|
+
verifyIntegrity(id: string): Promise<boolean>;
|
|
3474
|
+
getStats(): Promise<AuditStats>;
|
|
3475
|
+
applyRetention(policy?: AuditRetentionPolicy): Promise<number>;
|
|
3476
|
+
export(query: AuditQuery): Promise<StoredAuditEvent[]>;
|
|
3477
|
+
healthCheck(): Promise<boolean>;
|
|
3478
|
+
close(): Promise<void>;
|
|
3479
|
+
/**
|
|
3480
|
+
* Get all events (for testing)
|
|
3481
|
+
*/
|
|
3482
|
+
getAll(): StoredAuditEvent[];
|
|
3483
|
+
/**
|
|
3484
|
+
* Clear all events (for testing)
|
|
3485
|
+
*/
|
|
3486
|
+
clear(): void;
|
|
3487
|
+
/**
|
|
3488
|
+
* Get event count (for testing)
|
|
3489
|
+
*/
|
|
3490
|
+
get count(): number;
|
|
3491
|
+
/**
|
|
3492
|
+
* Find events by action (for testing)
|
|
3493
|
+
*/
|
|
3494
|
+
findByAction(action: string): StoredAuditEvent[];
|
|
3495
|
+
/**
|
|
3496
|
+
* Find events by actor ID (for testing)
|
|
3497
|
+
*/
|
|
3498
|
+
findByActor(actorId: string): StoredAuditEvent[];
|
|
3499
|
+
private createStoredEvent;
|
|
3500
|
+
private applyFilters;
|
|
3501
|
+
private enforceMaxEvents;
|
|
3502
|
+
}
|
|
3503
|
+
|
|
3504
|
+
/**
|
|
3505
|
+
* Memory Webhook Implementation
|
|
3506
|
+
*
|
|
3507
|
+
* In-memory webhook manager for testing.
|
|
3508
|
+
* Simulates HTTP delivery without actual network calls.
|
|
3509
|
+
*/
|
|
3510
|
+
|
|
3511
|
+
interface MemoryWebhookConfig extends WebhookConfig {
|
|
3512
|
+
/** Simulate failures for testing */
|
|
3513
|
+
failureRate?: number;
|
|
3514
|
+
/** Simulated response delay in ms */
|
|
3515
|
+
simulatedDelay?: number;
|
|
3516
|
+
}
|
|
3517
|
+
declare class MemoryWebhook implements IWebhook {
|
|
3518
|
+
private endpoints;
|
|
3519
|
+
private deliveries;
|
|
3520
|
+
private inboundConfigs;
|
|
3521
|
+
private config;
|
|
3522
|
+
private dispatchedEvents;
|
|
3523
|
+
constructor(config?: MemoryWebhookConfig);
|
|
3524
|
+
create(options: CreateWebhookOptions): Promise<WebhookEndpoint>;
|
|
3525
|
+
get(id: string): Promise<WebhookEndpoint | null>;
|
|
3526
|
+
update(id: string, options: UpdateWebhookOptions): Promise<WebhookEndpoint>;
|
|
3527
|
+
delete(id: string): Promise<void>;
|
|
3528
|
+
list(query?: WebhookQuery): Promise<WebhookEndpoint[]>;
|
|
3529
|
+
pause(id: string): Promise<void>;
|
|
3530
|
+
resume(id: string): Promise<void>;
|
|
3531
|
+
test(id: string): Promise<DeliveryAttempt>;
|
|
3532
|
+
dispatch<T>(event: WebhookEvent<T>): Promise<string[]>;
|
|
3533
|
+
dispatchTo<T>(endpointId: string, event: WebhookEvent<T>): Promise<string>;
|
|
3534
|
+
retry(deliveryId: string): Promise<DeliveryAttempt>;
|
|
3535
|
+
getDelivery(id: string): Promise<WebhookDelivery | null>;
|
|
3536
|
+
listDeliveries(query?: DeliveryQuery): Promise<WebhookDelivery[]>;
|
|
3537
|
+
getAttempts(deliveryId: string): Promise<DeliveryAttempt[]>;
|
|
3538
|
+
registerInbound(config: InboundWebhookConfig): void;
|
|
3539
|
+
verify(name: string, context: InboundWebhookContext): VerificationResult;
|
|
3540
|
+
getStats(): Promise<WebhookStats>;
|
|
3541
|
+
healthCheck(): Promise<boolean>;
|
|
3542
|
+
close(): Promise<void>;
|
|
3543
|
+
/**
|
|
3544
|
+
* Get all dispatched events (for testing)
|
|
3545
|
+
*/
|
|
3546
|
+
getDispatchedEvents(): Array<{
|
|
3547
|
+
endpoint: WebhookEndpoint;
|
|
3548
|
+
event: WebhookEvent;
|
|
3549
|
+
}>;
|
|
3550
|
+
/**
|
|
3551
|
+
* Clear dispatched events (for testing)
|
|
3552
|
+
*/
|
|
3553
|
+
clearDispatchedEvents(): void;
|
|
3554
|
+
/**
|
|
3555
|
+
* Get all deliveries (for testing)
|
|
3556
|
+
*/
|
|
3557
|
+
getAllDeliveries(): WebhookDelivery[];
|
|
3558
|
+
private executeWithRetries;
|
|
3559
|
+
private executeDelivery;
|
|
3560
|
+
private updateEndpointStats;
|
|
3561
|
+
private computeSignature;
|
|
3562
|
+
}
|
|
3563
|
+
|
|
3564
|
+
/**
|
|
3565
|
+
* Memory Notification Implementation
|
|
3566
|
+
*
|
|
3567
|
+
* In-memory notification service for testing.
|
|
3568
|
+
* Stores notifications, subscriptions, and preferences in memory.
|
|
3569
|
+
*/
|
|
3570
|
+
|
|
3571
|
+
interface MemoryNotificationConfig extends NotificationConfig {
|
|
3572
|
+
/** Service name */
|
|
3573
|
+
serviceName?: string;
|
|
3574
|
+
}
|
|
3575
|
+
declare class MemoryNotification implements INotification {
|
|
3576
|
+
private notifications;
|
|
3577
|
+
private pushSubscriptions;
|
|
3578
|
+
private preferences;
|
|
3579
|
+
private topics;
|
|
3580
|
+
private userTopics;
|
|
3581
|
+
private config;
|
|
3582
|
+
private sentNotifications;
|
|
3583
|
+
constructor(config?: MemoryNotificationConfig);
|
|
3584
|
+
send(options: SendNotificationOptions): Promise<NotificationResult>;
|
|
3585
|
+
sendBatch(options: BatchNotificationOptions): Promise<NotificationResult[]>;
|
|
3586
|
+
sendToTopic(topic: string, notification: NotificationData): Promise<number>;
|
|
3587
|
+
private storeInAppNotification;
|
|
3588
|
+
getForUser(userId: string, query?: NotificationQuery): Promise<StoredNotification[]>;
|
|
3589
|
+
getUnreadCount(userId: string, category?: NotificationCategory): Promise<number>;
|
|
3590
|
+
markAsRead(notificationId: string): Promise<void>;
|
|
3591
|
+
markAllAsRead(userId: string, category?: NotificationCategory): Promise<number>;
|
|
3592
|
+
delete(notificationId: string): Promise<void>;
|
|
3593
|
+
deleteAllForUser(userId: string): Promise<number>;
|
|
3594
|
+
registerPushSubscription(userId: string, subscription: PushSubscription): Promise<void>;
|
|
3595
|
+
removePushSubscription(userId: string, endpoint: string): Promise<void>;
|
|
3596
|
+
getPushSubscriptions(userId: string): Promise<PushSubscription[]>;
|
|
3597
|
+
getPreferences(userId: string): Promise<NotificationPreferences>;
|
|
3598
|
+
updatePreferences(userId: string, preferences: Partial<NotificationPreferences>): Promise<void>;
|
|
3599
|
+
subscribeToTopic(userId: string, topic: string): Promise<void>;
|
|
3600
|
+
unsubscribeFromTopic(userId: string, topic: string): Promise<void>;
|
|
3601
|
+
getUserTopics(userId: string): Promise<string[]>;
|
|
3602
|
+
getStats(options?: {
|
|
3603
|
+
userId?: string;
|
|
3604
|
+
period?: 'day' | 'week' | 'month';
|
|
3605
|
+
}): Promise<NotificationStats>;
|
|
3606
|
+
healthCheck(): Promise<boolean>;
|
|
3607
|
+
close(): Promise<void>;
|
|
3608
|
+
/**
|
|
3609
|
+
* Get all sent notifications (for testing)
|
|
3610
|
+
*/
|
|
3611
|
+
getSentNotifications(): Array<{
|
|
3612
|
+
target: NotificationTarget;
|
|
3613
|
+
notification: NotificationData;
|
|
3614
|
+
channels: NotificationChannel[];
|
|
3615
|
+
result: NotificationResult;
|
|
3616
|
+
}>;
|
|
3617
|
+
/**
|
|
3618
|
+
* Clear sent notifications (for testing)
|
|
3619
|
+
*/
|
|
3620
|
+
clearSentNotifications(): void;
|
|
3621
|
+
/**
|
|
3622
|
+
* Get all stored notifications (for testing)
|
|
3623
|
+
*/
|
|
3624
|
+
getAllNotifications(): StoredNotification[];
|
|
3625
|
+
}
|
|
3626
|
+
|
|
1535
3627
|
/**
|
|
1536
3628
|
* Supabase Database Adapter
|
|
1537
3629
|
* Production implementation using Supabase as the database provider
|
|
@@ -1984,7 +4076,17 @@ declare class SmtpEmail implements IEmail {
|
|
|
1984
4076
|
|
|
1985
4077
|
/**
|
|
1986
4078
|
* BullMQ Queue Adapter
|
|
1987
|
-
*
|
|
4079
|
+
*
|
|
4080
|
+
* Production queue implementation using BullMQ (Redis-backed).
|
|
4081
|
+
* Self-hosted, no cloud lock-in - only requires Redis.
|
|
4082
|
+
*
|
|
4083
|
+
* Features:
|
|
4084
|
+
* - Retry with exponential backoff
|
|
4085
|
+
* - Cron/recurring jobs
|
|
4086
|
+
* - Job events
|
|
4087
|
+
* - Dead letter queue (failed jobs)
|
|
4088
|
+
* - Concurrency control
|
|
4089
|
+
* - Progress tracking
|
|
1988
4090
|
*/
|
|
1989
4091
|
|
|
1990
4092
|
interface BullMQConfig {
|
|
@@ -2002,6 +4104,8 @@ interface BullMQConfig {
|
|
|
2002
4104
|
queueName: string;
|
|
2003
4105
|
/** Default job options */
|
|
2004
4106
|
defaultJobOptions?: JobOptions;
|
|
4107
|
+
/** Default worker concurrency */
|
|
4108
|
+
concurrency?: number;
|
|
2005
4109
|
}
|
|
2006
4110
|
/**
|
|
2007
4111
|
* BullMQ Queue Adapter
|
|
@@ -2012,6 +4116,7 @@ declare class BullMQQueue<T = unknown> implements IQueue<T> {
|
|
|
2012
4116
|
private worker;
|
|
2013
4117
|
private config;
|
|
2014
4118
|
private initialized;
|
|
4119
|
+
private eventHandlers;
|
|
2015
4120
|
constructor(config: BullMQConfig);
|
|
2016
4121
|
/**
|
|
2017
4122
|
* Initialize the queue (called lazily on first use)
|
|
@@ -2024,8 +4129,12 @@ declare class BullMQQueue<T = unknown> implements IQueue<T> {
|
|
|
2024
4129
|
data: T;
|
|
2025
4130
|
options?: JobOptions;
|
|
2026
4131
|
}>): Promise<Job<T>[]>;
|
|
2027
|
-
process(handler: (job: Job<T>) => Promise<unknown
|
|
4132
|
+
process(handler: (job: Job<T>) => Promise<unknown>, options?: {
|
|
4133
|
+
concurrency?: number;
|
|
4134
|
+
}): void;
|
|
2028
4135
|
private startWorker;
|
|
4136
|
+
private emitEvent;
|
|
4137
|
+
private emitEventById;
|
|
2029
4138
|
getJob(id: string): Promise<Job<T> | null>;
|
|
2030
4139
|
removeJob(id: string): Promise<void>;
|
|
2031
4140
|
pause(): Promise<void>;
|
|
@@ -2039,7 +4148,327 @@ declare class BullMQQueue<T = unknown> implements IQueue<T> {
|
|
|
2039
4148
|
}>;
|
|
2040
4149
|
healthCheck(): Promise<boolean>;
|
|
2041
4150
|
close(): Promise<void>;
|
|
4151
|
+
addRecurring(name: string, data: T, repeat: RepeatOptions, options?: Omit<JobOptions, 'repeat'>): Promise<Job<T>>;
|
|
4152
|
+
getJobs(state: JobState | JobState[], start?: number, end?: number): Promise<Job<T>[]>;
|
|
4153
|
+
getFailedJobs(start?: number, end?: number): Promise<Job<T>[]>;
|
|
4154
|
+
retryJob(id: string): Promise<void>;
|
|
4155
|
+
replayAllFailed(): Promise<number>;
|
|
4156
|
+
updateProgress(id: string, progress: number): Promise<void>;
|
|
4157
|
+
clean(grace: number, limit: number, state: JobState): Promise<string[]>;
|
|
4158
|
+
obliterate(options?: {
|
|
4159
|
+
force?: boolean;
|
|
4160
|
+
}): Promise<void>;
|
|
4161
|
+
on(event: JobEventType, handler: JobEventHandler<T>): void;
|
|
4162
|
+
off(event: JobEventType, handler: JobEventHandler<T>): void;
|
|
4163
|
+
getName(): string;
|
|
2042
4164
|
private mapJob;
|
|
4165
|
+
private getJobState;
|
|
4166
|
+
}
|
|
4167
|
+
|
|
4168
|
+
/**
|
|
4169
|
+
* Database Audit Log Implementation
|
|
4170
|
+
*
|
|
4171
|
+
* Production-ready audit log using IDatabase abstraction.
|
|
4172
|
+
* Self-hosted, no vendor lock-in.
|
|
4173
|
+
*
|
|
4174
|
+
* Requires a table with this schema:
|
|
4175
|
+
*
|
|
4176
|
+
* CREATE TABLE audit_logs (
|
|
4177
|
+
* id VARCHAR(255) PRIMARY KEY,
|
|
4178
|
+
* sequence BIGSERIAL,
|
|
4179
|
+
* timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
4180
|
+
* category VARCHAR(50) NOT NULL,
|
|
4181
|
+
* action VARCHAR(255) NOT NULL,
|
|
4182
|
+
* outcome VARCHAR(20) NOT NULL,
|
|
4183
|
+
* actor JSONB NOT NULL,
|
|
4184
|
+
* target JSONB,
|
|
4185
|
+
* data JSONB,
|
|
4186
|
+
* changes JSONB,
|
|
4187
|
+
* error JSONB,
|
|
4188
|
+
* context JSONB,
|
|
4189
|
+
* checksum VARCHAR(255),
|
|
4190
|
+
* created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
4191
|
+
* );
|
|
4192
|
+
*
|
|
4193
|
+
* CREATE INDEX idx_audit_logs_timestamp ON audit_logs(timestamp DESC);
|
|
4194
|
+
* CREATE INDEX idx_audit_logs_category ON audit_logs(category);
|
|
4195
|
+
* CREATE INDEX idx_audit_logs_action ON audit_logs(action);
|
|
4196
|
+
* CREATE INDEX idx_audit_logs_actor_id ON audit_logs((actor->>'id'));
|
|
4197
|
+
* CREATE INDEX idx_audit_logs_tenant_id ON audit_logs((context->>'tenantId'));
|
|
4198
|
+
*/
|
|
4199
|
+
|
|
4200
|
+
interface DatabaseAuditLogConfig extends AuditLogConfig {
|
|
4201
|
+
/** Database instance */
|
|
4202
|
+
database: IDatabase;
|
|
4203
|
+
/** Table name (default: 'audit_logs') */
|
|
4204
|
+
tableName?: string;
|
|
4205
|
+
/** Batch size for bulk operations */
|
|
4206
|
+
batchSize?: number;
|
|
4207
|
+
}
|
|
4208
|
+
declare class DatabaseAuditLog implements IAuditLog {
|
|
4209
|
+
private db;
|
|
4210
|
+
private tableName;
|
|
4211
|
+
private config;
|
|
4212
|
+
private sequence;
|
|
4213
|
+
constructor(config: DatabaseAuditLogConfig);
|
|
4214
|
+
log(event: AuditEvent): Promise<StoredAuditEvent>;
|
|
4215
|
+
logBatch(events: AuditEvent[]): Promise<StoredAuditEvent[]>;
|
|
4216
|
+
query(query: AuditQuery): Promise<AuditQueryResult>;
|
|
4217
|
+
getEvent(id: string): Promise<StoredAuditEvent | null>;
|
|
4218
|
+
verifyIntegrity(id: string): Promise<boolean>;
|
|
4219
|
+
getStats(): Promise<AuditStats>;
|
|
4220
|
+
applyRetention(policy?: AuditRetentionPolicy): Promise<number>;
|
|
4221
|
+
export(query: AuditQuery): Promise<StoredAuditEvent[]>;
|
|
4222
|
+
healthCheck(): Promise<boolean>;
|
|
4223
|
+
close(): Promise<void>;
|
|
4224
|
+
/**
|
|
4225
|
+
* SQL to create the audit_logs table (PostgreSQL)
|
|
4226
|
+
*/
|
|
4227
|
+
static getCreateTableSQL(tableName?: string): string;
|
|
4228
|
+
private prepareEvent;
|
|
4229
|
+
private rowToEvent;
|
|
4230
|
+
}
|
|
4231
|
+
|
|
4232
|
+
/**
|
|
4233
|
+
* Database Error Reporter Implementation
|
|
4234
|
+
*
|
|
4235
|
+
* Self-hosted error reporting using database storage.
|
|
4236
|
+
* No external service dependencies, full data ownership.
|
|
4237
|
+
*
|
|
4238
|
+
* Features:
|
|
4239
|
+
* - Error capture and storage
|
|
4240
|
+
* - Stack trace parsing
|
|
4241
|
+
* - Breadcrumb trail
|
|
4242
|
+
* - User context
|
|
4243
|
+
* - Error grouping by fingerprint
|
|
4244
|
+
* - Retention policy
|
|
4245
|
+
*/
|
|
4246
|
+
|
|
4247
|
+
interface DatabaseErrorReporterConfig extends ErrorReporterConfig {
|
|
4248
|
+
/** Database instance */
|
|
4249
|
+
database: IDatabase;
|
|
4250
|
+
/** Table name for errors (default: 'error_reports') */
|
|
4251
|
+
errorsTable?: string;
|
|
4252
|
+
/** Table name for breadcrumbs (default: 'error_breadcrumbs') */
|
|
4253
|
+
breadcrumbsTable?: string;
|
|
4254
|
+
/** Max stack trace length to store */
|
|
4255
|
+
maxStackTraceLength?: number;
|
|
4256
|
+
/** Retention period in days */
|
|
4257
|
+
retentionDays?: number;
|
|
4258
|
+
}
|
|
4259
|
+
declare class DatabaseErrorReporter implements IErrorReporter {
|
|
4260
|
+
private db;
|
|
4261
|
+
private errorsTable;
|
|
4262
|
+
private breadcrumbsTable;
|
|
4263
|
+
private maxStackTraceLength;
|
|
4264
|
+
private retentionDays;
|
|
4265
|
+
private breadcrumbs;
|
|
4266
|
+
private reports;
|
|
4267
|
+
private context;
|
|
4268
|
+
private tags;
|
|
4269
|
+
private userContext;
|
|
4270
|
+
private maxBreadcrumbs;
|
|
4271
|
+
private sampleRate;
|
|
4272
|
+
private beforeSend?;
|
|
4273
|
+
private writeQueue;
|
|
4274
|
+
constructor(config: DatabaseErrorReporterConfig);
|
|
4275
|
+
captureError(error: Error, options?: CaptureOptions): string;
|
|
4276
|
+
captureMessage(message: string, options?: CaptureOptions): string;
|
|
4277
|
+
addBreadcrumb(breadcrumb: Omit<Breadcrumb, 'timestamp'>): void;
|
|
4278
|
+
setUser(user: {
|
|
4279
|
+
id?: string;
|
|
4280
|
+
email?: string;
|
|
4281
|
+
username?: string;
|
|
4282
|
+
} | null): void;
|
|
4283
|
+
setContext(name: string, context: Record<string, unknown> | null): void;
|
|
4284
|
+
setTag(key: string, value: string): void;
|
|
4285
|
+
getReports(options?: {
|
|
4286
|
+
limit?: number;
|
|
4287
|
+
level?: ErrorLevel;
|
|
4288
|
+
}): ErrorReport[];
|
|
4289
|
+
clearReports(): void;
|
|
4290
|
+
flush(timeout?: number): Promise<boolean>;
|
|
4291
|
+
close(): Promise<void>;
|
|
4292
|
+
/**
|
|
4293
|
+
* Load reports from database
|
|
4294
|
+
*/
|
|
4295
|
+
loadReports(options?: {
|
|
4296
|
+
level?: ErrorLevel;
|
|
4297
|
+
from?: Date | number;
|
|
4298
|
+
to?: Date | number;
|
|
4299
|
+
limit?: number;
|
|
4300
|
+
offset?: number;
|
|
4301
|
+
}): Promise<ErrorReport[]>;
|
|
4302
|
+
/**
|
|
4303
|
+
* Clean up old errors based on retention policy
|
|
4304
|
+
*/
|
|
4305
|
+
cleanup(): Promise<number>;
|
|
4306
|
+
/**
|
|
4307
|
+
* Get error statistics
|
|
4308
|
+
*/
|
|
4309
|
+
getStats(periodMs?: number): Promise<{
|
|
4310
|
+
total: number;
|
|
4311
|
+
byLevel: Record<ErrorLevel, number>;
|
|
4312
|
+
recentErrors: number;
|
|
4313
|
+
}>;
|
|
4314
|
+
/**
|
|
4315
|
+
* SQL to create error reporter tables (PostgreSQL)
|
|
4316
|
+
*/
|
|
4317
|
+
static getCreateTableSQL(errorsTable?: string, breadcrumbsTable?: string): string;
|
|
4318
|
+
private queueWrite;
|
|
4319
|
+
private writeReportToDb;
|
|
4320
|
+
private loadBreadcrumbs;
|
|
4321
|
+
private rowToReport;
|
|
4322
|
+
}
|
|
4323
|
+
|
|
4324
|
+
/**
|
|
4325
|
+
* Queue-based Scheduler Implementation
|
|
4326
|
+
*
|
|
4327
|
+
* Scheduler built on top of IQueue for job execution.
|
|
4328
|
+
* Self-hosted, uses database for persistence.
|
|
4329
|
+
*
|
|
4330
|
+
* Features:
|
|
4331
|
+
* - Cron-based recurring jobs
|
|
4332
|
+
* - One-time scheduled jobs
|
|
4333
|
+
* - Automatic next-run calculation
|
|
4334
|
+
* - Execution history tracking
|
|
4335
|
+
* - Correlation context integration
|
|
4336
|
+
*/
|
|
4337
|
+
|
|
4338
|
+
interface QueueSchedulerConfig extends SchedulerConfig {
|
|
4339
|
+
/** Queue instance for job execution */
|
|
4340
|
+
queue: IQueue;
|
|
4341
|
+
/** Database for persistence (optional, uses memory if not provided) */
|
|
4342
|
+
database?: IDatabase;
|
|
4343
|
+
/** Table name for schedules (default: 'scheduled_jobs') */
|
|
4344
|
+
schedulesTable?: string;
|
|
4345
|
+
/** Table name for execution history (default: 'schedule_executions') */
|
|
4346
|
+
executionsTable?: string;
|
|
4347
|
+
/** Service name for correlation */
|
|
4348
|
+
serviceName?: string;
|
|
4349
|
+
}
|
|
4350
|
+
declare class QueueScheduler implements IScheduler {
|
|
4351
|
+
private queue;
|
|
4352
|
+
private db?;
|
|
4353
|
+
private schedulesTable;
|
|
4354
|
+
private executionsTable;
|
|
4355
|
+
private config;
|
|
4356
|
+
private handlers;
|
|
4357
|
+
private checkTimer?;
|
|
4358
|
+
private running;
|
|
4359
|
+
private memorySchedules;
|
|
4360
|
+
private memoryExecutions;
|
|
4361
|
+
constructor(config: QueueSchedulerConfig);
|
|
4362
|
+
create<T>(options: CreateScheduleOptions<T>): Promise<ScheduledJob<T>>;
|
|
4363
|
+
get<T>(id: string): Promise<ScheduledJob<T> | null>;
|
|
4364
|
+
update<T>(id: string, options: UpdateScheduleOptions<T>): Promise<ScheduledJob<T>>;
|
|
4365
|
+
delete(id: string): Promise<void>;
|
|
4366
|
+
pause(id: string): Promise<void>;
|
|
4367
|
+
resume(id: string): Promise<void>;
|
|
4368
|
+
trigger(id: string): Promise<string>;
|
|
4369
|
+
list<T>(query?: ScheduleQuery): Promise<ScheduledJob<T>[]>;
|
|
4370
|
+
getHistory(scheduleId: string, limit?: number): Promise<ScheduleExecution[]>;
|
|
4371
|
+
handle<T>(name: string, handler: ScheduleHandler<T>): void;
|
|
4372
|
+
start(): Promise<void>;
|
|
4373
|
+
stop(): Promise<void>;
|
|
4374
|
+
getStats(): Promise<SchedulerStats>;
|
|
4375
|
+
healthCheck(): Promise<boolean>;
|
|
4376
|
+
close(): Promise<void>;
|
|
4377
|
+
/**
|
|
4378
|
+
* SQL to create scheduler tables (PostgreSQL)
|
|
4379
|
+
*/
|
|
4380
|
+
static getCreateTableSQL(schedulesTable?: string, executionsTable?: string): string;
|
|
4381
|
+
private saveSchedule;
|
|
4382
|
+
private loadSchedule;
|
|
4383
|
+
private loadAllSchedules;
|
|
4384
|
+
private scheduleToRow;
|
|
4385
|
+
private rowToSchedule;
|
|
4386
|
+
private rowToExecution;
|
|
4387
|
+
private checkUpcomingJobs;
|
|
4388
|
+
private executeSchedule;
|
|
4389
|
+
private processScheduledJob;
|
|
4390
|
+
private updateScheduleAfterTrigger;
|
|
4391
|
+
private updateScheduleResult;
|
|
4392
|
+
private saveExecution;
|
|
4393
|
+
private completeExecution;
|
|
4394
|
+
}
|
|
4395
|
+
|
|
4396
|
+
/**
|
|
4397
|
+
* HTTP Webhook Implementation
|
|
4398
|
+
*
|
|
4399
|
+
* Production webhook manager using native fetch.
|
|
4400
|
+
* Self-hosted, uses database for persistence.
|
|
4401
|
+
*
|
|
4402
|
+
* Features:
|
|
4403
|
+
* - HMAC signature verification
|
|
4404
|
+
* - Automatic retries with exponential backoff
|
|
4405
|
+
* - Event filtering with glob patterns
|
|
4406
|
+
* - Delivery tracking and history
|
|
4407
|
+
* - Queue-based async delivery (optional)
|
|
4408
|
+
*/
|
|
4409
|
+
|
|
4410
|
+
interface HttpWebhookConfig extends WebhookConfig {
|
|
4411
|
+
/** Database for persistence (optional, uses memory if not provided) */
|
|
4412
|
+
database?: IDatabase;
|
|
4413
|
+
/** Queue for async delivery (optional, uses sync if not provided) */
|
|
4414
|
+
queue?: IQueue;
|
|
4415
|
+
/** Table name for endpoints (default: 'webhook_endpoints') */
|
|
4416
|
+
endpointsTable?: string;
|
|
4417
|
+
/** Table name for deliveries (default: 'webhook_deliveries') */
|
|
4418
|
+
deliveriesTable?: string;
|
|
4419
|
+
/** Table name for attempts (default: 'webhook_attempts') */
|
|
4420
|
+
attemptsTable?: string;
|
|
4421
|
+
/** Service name for correlation */
|
|
4422
|
+
serviceName?: string;
|
|
4423
|
+
}
|
|
4424
|
+
declare class HttpWebhook implements IWebhook {
|
|
4425
|
+
private db?;
|
|
4426
|
+
private queue?;
|
|
4427
|
+
private endpointsTable;
|
|
4428
|
+
private deliveriesTable;
|
|
4429
|
+
private attemptsTable;
|
|
4430
|
+
private config;
|
|
4431
|
+
private inboundConfigs;
|
|
4432
|
+
private memoryEndpoints;
|
|
4433
|
+
private memoryDeliveries;
|
|
4434
|
+
constructor(config?: HttpWebhookConfig);
|
|
4435
|
+
create(options: CreateWebhookOptions): Promise<WebhookEndpoint>;
|
|
4436
|
+
get(id: string): Promise<WebhookEndpoint | null>;
|
|
4437
|
+
update(id: string, options: UpdateWebhookOptions): Promise<WebhookEndpoint>;
|
|
4438
|
+
delete(id: string): Promise<void>;
|
|
4439
|
+
list(query?: WebhookQuery): Promise<WebhookEndpoint[]>;
|
|
4440
|
+
pause(id: string): Promise<void>;
|
|
4441
|
+
resume(id: string): Promise<void>;
|
|
4442
|
+
test(id: string): Promise<DeliveryAttempt>;
|
|
4443
|
+
dispatch<T>(event: WebhookEvent<T>): Promise<string[]>;
|
|
4444
|
+
dispatchTo<T>(endpointId: string, event: WebhookEvent<T>): Promise<string>;
|
|
4445
|
+
retry(deliveryId: string): Promise<DeliveryAttempt>;
|
|
4446
|
+
getDelivery(id: string): Promise<WebhookDelivery | null>;
|
|
4447
|
+
listDeliveries(query?: DeliveryQuery): Promise<WebhookDelivery[]>;
|
|
4448
|
+
getAttempts(deliveryId: string): Promise<DeliveryAttempt[]>;
|
|
4449
|
+
registerInbound(config: InboundWebhookConfig): void;
|
|
4450
|
+
verify(name: string, context: InboundWebhookContext): VerificationResult;
|
|
4451
|
+
getStats(): Promise<WebhookStats>;
|
|
4452
|
+
healthCheck(): Promise<boolean>;
|
|
4453
|
+
close(): Promise<void>;
|
|
4454
|
+
/**
|
|
4455
|
+
* SQL to create webhook tables (PostgreSQL)
|
|
4456
|
+
*/
|
|
4457
|
+
static getCreateTableSQL(endpointsTable?: string, deliveriesTable?: string, attemptsTable?: string): string;
|
|
4458
|
+
private saveEndpoint;
|
|
4459
|
+
private loadEndpoint;
|
|
4460
|
+
private loadAllEndpoints;
|
|
4461
|
+
private saveDelivery;
|
|
4462
|
+
private saveAttempt;
|
|
4463
|
+
private executeWithRetries;
|
|
4464
|
+
private executeDelivery;
|
|
4465
|
+
private updateEndpointStats;
|
|
4466
|
+
private computeSignature;
|
|
4467
|
+
private endpointToRow;
|
|
4468
|
+
private rowToEndpoint;
|
|
4469
|
+
private deliveryToRow;
|
|
4470
|
+
private rowToDelivery;
|
|
4471
|
+
private rowToAttempt;
|
|
2043
4472
|
}
|
|
2044
4473
|
|
|
2045
|
-
export { Bulkhead, type BulkheadOptions, BulkheadRegistry, BulkheadRejectedError, type BulkheadStats, type BullMQConfig, BullMQQueue, CircuitBreaker, type CircuitBreakerOptions, CircuitBreakerRegistry, type CircuitBreakerStats, CircuitOpenError, type CircuitState, DEFAULT_BULKHEAD_OPTIONS, DEFAULT_CIRCUIT_BREAKER_OPTIONS, DEFAULT_RETRY_OPTIONS, DefaultTimeouts, type DeleteHookContext, type DetailedHealthResponse, type EmailHookContext, EmailMessage, EmailResult, type ErrorHookContext, type FallbackOptions, type FallbackResult, FallbackStrategies, type HealthCheckResult, type HealthEndpoints, type HealthEndpointsOptions, type HealthStatus, type HookRegistry, ICache, IDatabase, IEmail, type IHealth, type IHealthCheckable, ILogger, IMetrics, IPlatform, IQueryBuilder, IQueue, IStorage, type InsertHookContext, Job, type JobHookContext, JobOptions, type LivenessResponse, MemoryRateLimiterStorage, type MetricsEndpoint, type MetricsEndpointOptions, MetricsSummary, type Middleware, type MiddlewareChain, type MiddlewareChainOptions, type MiddlewareContext, type PlatformHealthResult, PlatformHealthStatus, type PlatformHooks, type PostgresConfig, PostgresDatabase, type QueryHookContext, QueryResult, type RateLimitAlgorithm, RateLimitError, type RateLimitInfo, type RateLimitOptions, RateLimitPresets, type RateLimiterStorage, type ReadinessResponse, RedisCache, type RedisConfig, ResendEmail, RetryConfigs, type RetryOptions, RetryPredicates, type RetryResult, S3Storage, type ServiceHealth, type SlidingWindowRateLimitOptions, type SmtpConfig, SmtpEmail, type StartupResponse, StorageFile, SupabaseDatabase, SupabaseStorage, type SupabaseStorageConfig, TimeoutError, type TimeoutOptions, type TokenBucketOptions, type UpdateHookContext, type UploadHookContext, UploadOptions, UpstashCache, composeHookRegistries, createBulkhead, createCacheMiddleware, createCachedFallback, createCircuitBreaker, createExpressHealthHandlers, createExpressMetricsHandler, createHealthEndpoints, createHealthServer, createHookRegistry, createIpKeyGenerator, createLoggingMiddleware, createMetricsEndpoint, createMetricsMiddleware, createMetricsServer, createMiddlewareChain, createMiddlewareContext, createObservabilityServer, createRateLimitMiddleware, createRequestIdMiddleware, createSlowQueryMiddleware, createTenantMiddleware, createTimeoutMiddleware, createUserKeyGenerator, raceTimeout, retryable, timedHealthCheck, toHealthCheckResult, withFallback, withFallbackChain, withFallbackResult, withRetry, withRetryResult, withTimeout, withTimeoutWrapper };
|
|
4474
|
+
export { type AuditActor, type AuditCategory, type AuditEvent, AuditEvents, type AuditLogConfig, type AuditOutcome, type AuditQuery, type AuditQueryResult, type AuditRetentionPolicy, type AuditStats, type AuditTarget, type BatchNotificationOptions, type Breadcrumb, Bulkhead, type BulkheadOptions, BulkheadRegistry, BulkheadRejectedError, type BulkheadStats, type BullMQConfig, BullMQQueue, type CaptureOptions, CircuitBreaker, type CircuitBreakerOptions, CircuitBreakerRegistry, type CircuitBreakerStats, CircuitOpenError, type CircuitState, type CorrelationData, type CreateScheduleOptions, type CreateWebhookOptions, type CronExpression, CronPresets, DEFAULT_BULKHEAD_OPTIONS, DEFAULT_CIRCUIT_BREAKER_OPTIONS, DEFAULT_RETRY_OPTIONS, DatabaseAuditLog, type DatabaseAuditLogConfig, DatabaseErrorReporter, type DatabaseErrorReporterConfig, DefaultTimeouts, type DeleteHookContext, type DeliveryAttempt, type DeliveryQuery, type DeliveryStatus, type DetailedHealthResponse, type EmailHookContext, EmailMessage, EmailResult, type ErrorContext, type ErrorHookContext, type ErrorLevel, type ErrorReport, type ErrorReporterConfig, type FallbackOptions, type FallbackResult, FallbackStrategies, type HealthCheckResult, type HealthEndpoints, type HealthEndpointsOptions, type HealthStatus, type HookRegistry, HttpWebhook, type HttpWebhookConfig, type IAuditLog, ICache, IDatabase, IEmail, type IErrorReporter, type IHealth, type IHealthCheckable, ILogger, IMetrics, type INotification, IPlatform, IQueryBuilder, IQueue, type IScheduler, IStorage, type IWebhook, type InboundWebhookConfig, type InboundWebhookContext, type InsertHookContext, Job, JobEventHandler, JobEventType, type JobHookContext, JobOptions, JobState, type LivenessResponse, MemoryAuditLog, type MemoryAuditLogConfig, MemoryErrorReporter, type MemoryErrorReporterConfig, MemoryNotification, type MemoryNotificationConfig, MemoryRateLimiterStorage, MemoryWebhook, type MemoryWebhookConfig, type MetricsEndpoint, type MetricsEndpointOptions, MetricsSummary, type Middleware, type MiddlewareChain, type MiddlewareChainOptions, type MiddlewareContext, type NotificationAction, type NotificationCategory, type NotificationChannel, type NotificationConfig, type NotificationData, type NotificationPreferences, type NotificationPriority, type NotificationQuery, type NotificationResult, type NotificationStats, type NotificationStatus, type NotificationTarget, NotificationTemplates, type PlatformHealthResult, PlatformHealthStatus, type PlatformHooks, type PostgresConfig, PostgresDatabase, type PushSubscription, type QueryHookContext, QueryResult, QueueScheduler, type QueueSchedulerConfig, type RateLimitAlgorithm, RateLimitError, type RateLimitInfo, type RateLimitOptions, RateLimitPresets, type RateLimiterStorage, type ReadinessResponse, RedisCache, type RedisConfig, RepeatOptions, ResendEmail, RetryConfigs, type RetryOptions, RetryPredicates, type RetryResult, S3Storage, type ScheduleContext, type ScheduleExecution, type ScheduleHandler, type ScheduleQuery, type ScheduleState, type ScheduledJob, type SchedulerConfig, type SchedulerStats, type SendNotificationOptions, type ServiceHealth, type SignatureAlgorithm, type SlidingWindowRateLimitOptions, type SmtpConfig, SmtpEmail, type StartupResponse, StorageFile, type StoredAuditEvent, type StoredNotification, SupabaseDatabase, SupabaseStorage, type SupabaseStorageConfig, TimeoutError, type TimeoutOptions, type TokenBucketOptions, type UpdateHookContext, type UpdateScheduleOptions, type UpdateWebhookOptions, type UploadHookContext, UploadOptions, UpstashCache, type VerificationResult, type WebhookConfig, type WebhookDelivery, type WebhookEndpoint, type WebhookEvent, WebhookEventTypes, type WebhookQuery, type WebhookState, type WebhookStats, calculateRetryDelay, composeHookRegistries, correlationContext, createBulkhead, createCacheMiddleware, createCachedFallback, createCircuitBreaker, createDefaultPreferences, createErrorReport, createExpressHealthHandlers, createExpressMetricsHandler, createHealthEndpoints, createHealthServer, createHookRegistry, createIpKeyGenerator, createJobContext, createLoggingMiddleware, createMetricsEndpoint, createMetricsMiddleware, createMetricsServer, createMiddlewareChain, createMiddlewareContext, createObservabilityServer, createRateLimitMiddleware, createRequestContext, createRequestIdMiddleware, createSlowQueryMiddleware, createTenantMiddleware, createTimeoutMiddleware, createUserKeyGenerator, describeCron, filterChannelsByPreferences, generateAuditId, generateChecksum, generateDeliveryId, generateErrorId, generateEventId, generateFingerprint, generateNotificationId, generateScheduleId, generateWebhookId, generateWebhookSecret, getContext, getCorrelationId, getLogMeta, getNextCronRun, getRequestId, getTenantId, getTraceId, getUserId, isInContext, isInQuietHours, isValidCron, matchAction, matchEventType, raceTimeout, retryable, runWithContext, runWithContextAsync, timedHealthCheck, toHealthCheckResult, withCorrelation, withCorrelationAsync, withFallback, withFallbackChain, withFallbackResult, withRetry, withRetryResult, withTimeout, withTimeoutWrapper };
|