@astralibx/email-rule-engine 12.10.1 → 14.0.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/index.d.mts CHANGED
@@ -1,255 +1,12 @@
1
- import * as mongoose from 'mongoose';
2
- import { Connection, Model, HydratedDocument, Schema, Types } from 'mongoose';
3
- import { Redis } from 'ioredis';
4
- import { LogAdapter, AlxError } from '@astralibx/core';
5
- export { LogAdapter, RedisLock } from '@astralibx/core';
6
- import { Router } from 'express';
1
+ import { RuleEngineConfig, RuleEngine } from '@astralibx/rule-engine';
2
+ export * from '@astralibx/rule-engine';
7
3
 
8
- type FieldType = 'string' | 'number' | 'boolean' | 'date' | 'objectId' | 'array' | 'object';
9
- interface FieldDefinition {
10
- name: string;
11
- type: FieldType;
12
- label?: string;
13
- description?: string;
14
- enumValues?: string[];
15
- fields?: FieldDefinition[];
16
- }
17
- interface JoinDefinition {
18
- from: string;
19
- localField: string;
20
- foreignField: string;
21
- as: string;
22
- }
23
- interface CollectionSchema {
24
- name: string;
25
- label?: string;
26
- description?: string;
27
- identifierField?: string;
28
- fields: FieldDefinition[];
29
- joins?: JoinDefinition[];
30
- }
31
- interface FlattenedField {
32
- path: string;
33
- type: FieldType;
34
- label?: string;
35
- description?: string;
36
- enumValues?: string[];
37
- isArray?: boolean;
38
- }
4
+ declare function renderMjml(body: string): string;
5
+ declare function htmlToPlainText(html: string): string;
39
6
 
40
- declare const FIELD_TYPE: {
41
- readonly String: "string";
42
- readonly Number: "number";
43
- readonly Boolean: "boolean";
44
- readonly Date: "date";
45
- readonly ObjectId: "objectId";
46
- readonly Array: "array";
47
- readonly Object: "object";
48
- };
7
+ declare function registerEmailHelpers(): void;
49
8
 
50
- declare const TYPE_OPERATORS: Record<FieldType, string[]>;
51
-
52
- declare const TEMPLATE_CATEGORY: {
53
- readonly Onboarding: "onboarding";
54
- readonly Engagement: "engagement";
55
- readonly Transactional: "transactional";
56
- readonly ReEngagement: "re-engagement";
57
- readonly Announcement: "announcement";
58
- };
59
- type TemplateCategory = (typeof TEMPLATE_CATEGORY)[keyof typeof TEMPLATE_CATEGORY];
60
- declare const TEMPLATE_AUDIENCE: {
61
- readonly Customer: "customer";
62
- readonly Provider: "provider";
63
- readonly All: "all";
64
- };
65
- type TemplateAudience = (typeof TEMPLATE_AUDIENCE)[keyof typeof TEMPLATE_AUDIENCE];
66
- declare const RULE_OPERATOR: {
67
- readonly Eq: "eq";
68
- readonly Neq: "neq";
69
- readonly Gt: "gt";
70
- readonly Gte: "gte";
71
- readonly Lt: "lt";
72
- readonly Lte: "lte";
73
- readonly Exists: "exists";
74
- readonly NotExists: "not_exists";
75
- readonly In: "in";
76
- readonly NotIn: "not_in";
77
- readonly Contains: "contains";
78
- };
79
- type RuleOperator = (typeof RULE_OPERATOR)[keyof typeof RULE_OPERATOR];
80
- declare const EMAIL_TYPE: {
81
- readonly Automated: "automated";
82
- readonly Transactional: "transactional";
83
- };
84
- type EmailType = (typeof EMAIL_TYPE)[keyof typeof EMAIL_TYPE];
85
- declare const RUN_TRIGGER: {
86
- readonly Cron: "cron";
87
- readonly Manual: "manual";
88
- };
89
- type RunTrigger = (typeof RUN_TRIGGER)[keyof typeof RUN_TRIGGER];
90
- declare const THROTTLE_WINDOW: {
91
- readonly Rolling: "rolling";
92
- };
93
- type ThrottleWindow = (typeof THROTTLE_WINDOW)[keyof typeof THROTTLE_WINDOW];
94
- declare const EMAIL_SEND_STATUS: {
95
- readonly Sent: "sent";
96
- readonly Error: "error";
97
- readonly Skipped: "skipped";
98
- readonly Invalid: "invalid";
99
- readonly Throttled: "throttled";
100
- };
101
- type EmailSendStatus = (typeof EMAIL_SEND_STATUS)[keyof typeof EMAIL_SEND_STATUS];
102
- declare const TARGET_MODE: {
103
- readonly Query: "query";
104
- readonly List: "list";
105
- };
106
- type TargetMode = (typeof TARGET_MODE)[keyof typeof TARGET_MODE];
107
- declare const RUN_LOG_STATUS: {
108
- readonly Completed: "completed";
109
- readonly Cancelled: "cancelled";
110
- readonly Failed: "failed";
111
- };
112
- type RunLogStatus = (typeof RUN_LOG_STATUS)[keyof typeof RUN_LOG_STATUS];
113
-
114
- interface RuleCondition {
115
- field: string;
116
- operator: RuleOperator;
117
- value: unknown;
118
- }
119
- interface RuleRunStats {
120
- matched: number;
121
- sent: number;
122
- skipped: number;
123
- skippedByThrottle: number;
124
- errorCount: number;
125
- }
126
- interface QueryTarget {
127
- mode: 'query';
128
- role: string;
129
- platform: string;
130
- conditions: RuleCondition[];
131
- collectionName?: string;
132
- }
133
- interface ListTarget {
134
- mode: 'list';
135
- identifiers: string[];
136
- }
137
- type RuleTarget = QueryTarget | ListTarget;
138
- interface EmailRule {
139
- _id: string;
140
- name: string;
141
- description?: string;
142
- isActive: boolean;
143
- sortOrder: number;
144
- target: RuleTarget;
145
- templateId: string;
146
- sendOnce: boolean;
147
- resendAfterDays?: number;
148
- cooldownDays?: number;
149
- autoApprove: boolean;
150
- maxPerRun?: number;
151
- validFrom?: Date;
152
- validTill?: Date;
153
- bypassThrottle: boolean;
154
- throttleOverride?: {
155
- maxPerUserPerDay?: number;
156
- maxPerUserPerWeek?: number;
157
- minGapDays?: number;
158
- };
159
- emailType: EmailType;
160
- schedule?: {
161
- enabled: boolean;
162
- cron: string;
163
- timezone?: string;
164
- };
165
- totalSent: number;
166
- totalSkipped: number;
167
- lastRunAt?: Date;
168
- lastRunStats?: RuleRunStats;
169
- createdAt: Date;
170
- updatedAt: Date;
171
- }
172
- interface CreateEmailRuleInput {
173
- name: string;
174
- description?: string;
175
- target: RuleTarget;
176
- templateId: string;
177
- sortOrder?: number;
178
- sendOnce?: boolean;
179
- resendAfterDays?: number;
180
- cooldownDays?: number;
181
- autoApprove?: boolean;
182
- maxPerRun?: number;
183
- validFrom?: Date;
184
- validTill?: Date;
185
- bypassThrottle?: boolean;
186
- throttleOverride?: {
187
- maxPerUserPerDay?: number;
188
- maxPerUserPerWeek?: number;
189
- minGapDays?: number;
190
- };
191
- emailType?: EmailType;
192
- schedule?: {
193
- enabled: boolean;
194
- cron: string;
195
- timezone?: string;
196
- };
197
- }
198
- interface UpdateEmailRuleInput {
199
- name?: string;
200
- description?: string;
201
- isActive?: boolean;
202
- sortOrder?: number;
203
- target?: RuleTarget;
204
- templateId?: string;
205
- sendOnce?: boolean;
206
- resendAfterDays?: number;
207
- cooldownDays?: number;
208
- autoApprove?: boolean;
209
- maxPerRun?: number;
210
- validFrom?: Date;
211
- validTill?: Date;
212
- bypassThrottle?: boolean;
213
- throttleOverride?: {
214
- maxPerUserPerDay?: number;
215
- maxPerUserPerWeek?: number;
216
- minGapDays?: number;
217
- };
218
- emailType?: EmailType;
219
- schedule?: {
220
- enabled: boolean;
221
- cron: string;
222
- timezone?: string;
223
- };
224
- }
225
- interface EmailRuleSend {
226
- _id: string;
227
- ruleId: string;
228
- userId: string;
229
- emailIdentifierId?: string;
230
- messageId?: string;
231
- sentAt: Date;
232
- status?: string;
233
- accountId?: string;
234
- senderName?: string;
235
- subject?: string;
236
- failureReason?: string;
237
- }
238
- interface PerRuleStats extends RuleRunStats {
239
- ruleId: string;
240
- ruleName: string;
241
- }
242
- interface EmailRuleRunLog {
243
- _id: string;
244
- runAt: Date;
245
- triggeredBy: RunTrigger;
246
- duration: number;
247
- rulesProcessed: number;
248
- totalStats: RuleRunStats;
249
- perRuleStats: PerRuleStats[];
250
- }
251
-
252
- interface SendEmailParams {
9
+ interface EmailSendParams {
253
10
  identifierId: string;
254
11
  contactId: string;
255
12
  accountId: string;
@@ -264,621 +21,16 @@ interface SendEmailParams {
264
21
  contentType: string;
265
22
  }>;
266
23
  }
267
- interface AgentSelection {
268
- accountId: string;
269
- email: string;
270
- metadata: Record<string, unknown>;
271
- }
272
- interface BeforeSendParams {
273
- htmlBody: string;
274
- textBody: string;
275
- subject: string;
276
- account: {
277
- id: string;
278
- email: string;
279
- metadata: Record<string, unknown>;
280
- };
281
- user: {
282
- id: string;
283
- email: string;
284
- name: string;
285
- };
286
- context: {
287
- ruleId: string;
288
- templateId: string;
289
- runId: string;
290
- };
291
- }
292
- interface BeforeSendResult {
293
- htmlBody: string;
294
- textBody: string;
295
- subject: string;
296
- }
297
- interface RecipientIdentifier {
298
- id: string;
299
- contactId: string;
300
- }
301
- interface RunProgress {
302
- rulesTotal: number;
303
- rulesCompleted: number;
304
- sent: number;
305
- failed: number;
306
- skipped: number;
307
- invalid: number;
308
- }
309
- type RunStatus = 'running' | 'completed' | 'cancelled' | 'failed';
310
- interface RunStatusResponse {
311
- runId: string;
312
- status: RunStatus;
313
- currentRule: string;
314
- progress: RunProgress;
315
- startedAt: string;
316
- elapsed: number;
317
- }
318
- interface EmailRuleEngineConfig {
319
- db: {
320
- connection: Connection;
321
- collectionPrefix?: string;
322
- };
323
- redis: {
324
- connection: Redis;
325
- keyPrefix?: string;
326
- };
327
- collections?: CollectionSchema[];
328
- adapters: {
329
- queryUsers: (target: RuleTarget, limit: number, context?: {
330
- collectionSchema?: CollectionSchema;
331
- }) => Promise<Record<string, unknown>[]>;
332
- resolveData: (user: Record<string, unknown>) => Record<string, unknown>;
333
- sendEmail: (params: SendEmailParams) => Promise<void>;
334
- selectAgent: (identifierId: string, context?: {
335
- ruleId: string;
336
- templateId: string;
337
- }) => Promise<AgentSelection | null>;
338
- findIdentifier: (email: string) => Promise<RecipientIdentifier | null>;
24
+ interface EmailRuleEngineConfig extends Omit<RuleEngineConfig, 'adapters'> {
25
+ adapters: Omit<RuleEngineConfig['adapters'], 'send' | 'sendTest'> & {
26
+ sendEmail: (params: EmailSendParams) => Promise<void>;
339
27
  sendTestEmail?: (to: string, subject: string, html: string, text: string, attachments?: Array<{
340
28
  filename: string;
341
29
  url: string;
342
30
  contentType: string;
343
31
  }>) => Promise<void>;
344
32
  };
345
- platforms?: string[];
346
- audiences?: string[];
347
- categories?: string[];
348
- logger?: LogAdapter;
349
- options?: {
350
- lockTTLMs?: number;
351
- defaultMaxPerRun?: number;
352
- sendWindow?: {
353
- startHour: number;
354
- endHour: number;
355
- timezone: string;
356
- };
357
- delayBetweenSendsMs?: number;
358
- jitterMs?: number;
359
- };
360
- hooks?: {
361
- onRunStart?: (info: {
362
- rulesCount: number;
363
- triggeredBy: string;
364
- runId: string;
365
- }) => void;
366
- onRuleStart?: (info: {
367
- ruleId: string;
368
- ruleName: string;
369
- matchedCount: number;
370
- templateId: string;
371
- runId: string;
372
- }) => void;
373
- onSend?: (info: {
374
- ruleId: string;
375
- ruleName: string;
376
- email: string;
377
- status: 'sent' | 'error' | 'skipped' | 'invalid' | 'throttled';
378
- accountId: string;
379
- templateId: string;
380
- runId: string;
381
- subjectIndex: number;
382
- bodyIndex: number;
383
- preheaderIndex?: number;
384
- failureReason?: string;
385
- }) => void;
386
- onRuleComplete?: (info: {
387
- ruleId: string;
388
- ruleName: string;
389
- stats: RuleRunStats;
390
- templateId: string;
391
- runId: string;
392
- }) => void;
393
- onRunComplete?: (info: {
394
- duration: number;
395
- totalStats: RuleRunStats;
396
- perRuleStats: PerRuleStats[];
397
- runId: string;
398
- }) => void;
399
- beforeSend?: (params: BeforeSendParams) => Promise<BeforeSendResult>;
400
- };
401
- }
402
-
403
- interface EmailAttachment {
404
- filename: string;
405
- url: string;
406
- contentType: string;
407
- }
408
- interface EmailTemplate {
409
- _id: string;
410
- name: string;
411
- slug: string;
412
- description?: string;
413
- category: string;
414
- audience: string;
415
- platform: string;
416
- textBody?: string;
417
- subjects: string[];
418
- bodies: string[];
419
- preheaders?: string[];
420
- fields?: Record<string, string>;
421
- variables: string[];
422
- version: number;
423
- isActive: boolean;
424
- attachments?: EmailAttachment[];
425
- createdAt: Date;
426
- updatedAt: Date;
427
- }
428
- interface CreateEmailTemplateInput {
429
- name: string;
430
- slug: string;
431
- description?: string;
432
- category: string;
433
- audience: string;
434
- platform: string;
435
- textBody?: string;
436
- subjects: string[];
437
- bodies: string[];
438
- preheaders?: string[];
439
- fields?: Record<string, string>;
440
- variables?: string[];
441
- attachments?: EmailAttachment[];
442
- }
443
- interface UpdateEmailTemplateInput {
444
- name?: string;
445
- description?: string;
446
- category?: string;
447
- audience?: string;
448
- platform?: string;
449
- textBody?: string;
450
- subjects?: string[];
451
- bodies?: string[];
452
- preheaders?: string[];
453
- fields?: Record<string, string>;
454
- variables?: string[];
455
- attachments?: EmailAttachment[];
456
- isActive?: boolean;
457
- }
458
-
459
- interface IEmailTemplate extends Omit<EmailTemplate, '_id'> {
460
- }
461
- type EmailTemplateDocument = HydratedDocument<IEmailTemplate>;
462
- interface EmailTemplateStatics {
463
- findBySlug(slug: string): Promise<EmailTemplateDocument | null>;
464
- findActive(): Promise<EmailTemplateDocument[]>;
465
- findByCategory(category: string): Promise<EmailTemplateDocument[]>;
466
- findByAudience(audience: string): Promise<EmailTemplateDocument[]>;
467
- createTemplate(input: CreateEmailTemplateInput): Promise<EmailTemplateDocument>;
468
- }
469
- type EmailTemplateModel = Model<IEmailTemplate> & EmailTemplateStatics;
470
- declare function createEmailTemplateSchema(platformValues?: string[], audienceValues?: string[], categoryValues?: string[], collectionPrefix?: string): Schema<IEmailTemplate, Model<IEmailTemplate, any, any, any, mongoose.Document<unknown, any, IEmailTemplate, any, {}> & IEmailTemplate & {
471
- _id: mongoose.Types.ObjectId;
472
- } & {
473
- __v: number;
474
- }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, IEmailTemplate, mongoose.Document<unknown, {}, mongoose.FlatRecord<IEmailTemplate>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<IEmailTemplate> & {
475
- _id: mongoose.Types.ObjectId;
476
- } & {
477
- __v: number;
478
- }>;
479
-
480
- interface IEmailRule extends Omit<EmailRule, '_id' | 'templateId'> {
481
- templateId: Types.ObjectId;
482
- }
483
- type EmailRuleDocument = HydratedDocument<IEmailRule>;
484
- interface EmailRuleStatics {
485
- findActive(): Promise<EmailRuleDocument[]>;
486
- findByTemplateId(templateId: string | Types.ObjectId): Promise<EmailRuleDocument[]>;
487
- createRule(input: CreateEmailRuleInput): Promise<EmailRuleDocument>;
488
- }
489
- type EmailRuleModel = Model<IEmailRule> & EmailRuleStatics;
490
- declare function createEmailRuleSchema(platformValues?: string[], audienceValues?: string[], collectionPrefix?: string): Schema<IEmailRule, Model<IEmailRule, any, any, any, mongoose.Document<unknown, any, IEmailRule, any, {}> & IEmailRule & {
491
- _id: Types.ObjectId;
492
- } & {
493
- __v: number;
494
- }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, IEmailRule, mongoose.Document<unknown, {}, mongoose.FlatRecord<IEmailRule>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<IEmailRule> & {
495
- _id: Types.ObjectId;
496
- } & {
497
- __v: number;
498
- }>;
499
-
500
- interface IEmailRuleSend {
501
- ruleId: Types.ObjectId;
502
- userId: string;
503
- emailIdentifierId?: string;
504
- messageId?: string;
505
- sentAt: Date;
506
- status?: string;
507
- accountId?: string;
508
- senderName?: string;
509
- subject?: string;
510
- subjectIndex?: number;
511
- bodyIndex?: number;
512
- preheaderIndex?: number;
513
- failureReason?: string;
514
- }
515
- type EmailRuleSendDocument = HydratedDocument<IEmailRuleSend>;
516
- interface EmailRuleSendStatics {
517
- findLatestForUser(ruleId: string | Types.ObjectId, userId: string): Promise<EmailRuleSendDocument | null>;
518
- findRecentByUserIds(userIds: string[], sinceDays: number): Promise<EmailRuleSendDocument[]>;
519
- logSend(ruleId: string | Types.ObjectId, userId: string, emailIdentifierId?: string, messageId?: string, extra?: {
520
- status?: string;
521
- accountId?: string;
522
- senderName?: string;
523
- subject?: string;
524
- subjectIndex?: number;
525
- bodyIndex?: number;
526
- preheaderIndex?: number;
527
- failureReason?: string;
528
- }): Promise<EmailRuleSendDocument>;
529
- }
530
- type EmailRuleSendModel = Model<IEmailRuleSend> & EmailRuleSendStatics;
531
- declare function createEmailRuleSendSchema(collectionPrefix?: string): Schema<IEmailRuleSend, Model<IEmailRuleSend, any, any, any, mongoose.Document<unknown, any, IEmailRuleSend, any, {}> & IEmailRuleSend & {
532
- _id: Types.ObjectId;
533
- } & {
534
- __v: number;
535
- }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, IEmailRuleSend, mongoose.Document<unknown, {}, mongoose.FlatRecord<IEmailRuleSend>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<IEmailRuleSend> & {
536
- _id: Types.ObjectId;
537
- } & {
538
- __v: number;
539
- }>;
540
-
541
- interface IEmailRuleRunLog {
542
- runId?: string;
543
- runAt: Date;
544
- triggeredBy: string;
545
- duration: number;
546
- rulesProcessed: number;
547
- status?: string;
548
- totalStats: {
549
- matched: number;
550
- sent: number;
551
- skipped: number;
552
- skippedByThrottle: number;
553
- errorCount: number;
554
- };
555
- perRuleStats: Array<{
556
- ruleId: Types.ObjectId;
557
- ruleName: string;
558
- matched: number;
559
- sent: number;
560
- skipped: number;
561
- skippedByThrottle: number;
562
- errorCount: number;
563
- }>;
564
- }
565
- type EmailRuleRunLogDocument = HydratedDocument<IEmailRuleRunLog>;
566
- interface EmailRuleRunLogStatics {
567
- getRecent(limit?: number): Promise<EmailRuleRunLogDocument[]>;
568
- getByRuleId(ruleId: string | Types.ObjectId, limit?: number): Promise<EmailRuleRunLogDocument[]>;
569
- }
570
- type EmailRuleRunLogModel = Model<IEmailRuleRunLog> & EmailRuleRunLogStatics;
571
- declare function createEmailRuleRunLogSchema(collectionPrefix?: string): Schema<IEmailRuleRunLog, Model<IEmailRuleRunLog, any, any, any, mongoose.Document<unknown, any, IEmailRuleRunLog, any, {}> & IEmailRuleRunLog & {
572
- _id: Types.ObjectId;
573
- } & {
574
- __v: number;
575
- }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, IEmailRuleRunLog, mongoose.Document<unknown, {}, mongoose.FlatRecord<IEmailRuleRunLog>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<IEmailRuleRunLog> & {
576
- _id: Types.ObjectId;
577
- } & {
578
- __v: number;
579
- }>;
580
-
581
- interface EmailThrottleConfig {
582
- _id: string;
583
- maxPerUserPerDay: number;
584
- maxPerUserPerWeek: number;
585
- minGapDays: number;
586
- throttleWindow: ThrottleWindow;
587
- updatedAt: Date;
588
- }
589
- interface UpdateEmailThrottleConfigInput {
590
- maxPerUserPerDay?: number;
591
- maxPerUserPerWeek?: number;
592
- minGapDays?: number;
593
- }
594
-
595
- interface IEmailThrottleConfig extends Omit<EmailThrottleConfig, '_id'> {
596
- }
597
- type EmailThrottleConfigDocument = HydratedDocument<IEmailThrottleConfig>;
598
- interface EmailThrottleConfigStatics {
599
- getConfig(): Promise<EmailThrottleConfigDocument>;
600
- }
601
- type EmailThrottleConfigModel = Model<IEmailThrottleConfig> & EmailThrottleConfigStatics;
602
- declare function createEmailThrottleConfigSchema(collectionPrefix?: string): Schema<IEmailThrottleConfig, Model<IEmailThrottleConfig, any, any, any, mongoose.Document<unknown, any, IEmailThrottleConfig, any, {}> & IEmailThrottleConfig & {
603
- _id: mongoose.Types.ObjectId;
604
- } & {
605
- __v: number;
606
- }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, IEmailThrottleConfig, mongoose.Document<unknown, {}, mongoose.FlatRecord<IEmailThrottleConfig>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<IEmailThrottleConfig> & {
607
- _id: mongoose.Types.ObjectId;
608
- } & {
609
- __v: number;
610
- }>;
611
-
612
- declare class TemplateService {
613
- private EmailTemplate;
614
- private config;
615
- private EmailRule?;
616
- private renderService;
617
- constructor(EmailTemplate: EmailTemplateModel, config: EmailRuleEngineConfig, EmailRule?: EmailRuleModel | undefined);
618
- list(filters?: {
619
- category?: string;
620
- audience?: string;
621
- platform?: string;
622
- isActive?: boolean;
623
- page?: number;
624
- limit?: number;
625
- }): Promise<{
626
- templates: EmailTemplateDocument[];
627
- total: number;
628
- }>;
629
- getById(id: string): Promise<EmailTemplateDocument | null>;
630
- getBySlug(slug: string): Promise<EmailTemplateDocument | null>;
631
- create(input: CreateEmailTemplateInput): Promise<EmailTemplateDocument>;
632
- update(id: string, input: UpdateEmailTemplateInput): Promise<EmailTemplateDocument | null>;
633
- delete(id: string): Promise<boolean>;
634
- toggleActive(id: string): Promise<EmailTemplateDocument | null>;
635
- private _buildSampleData;
636
- preview(id: string, sampleData: Record<string, unknown>): Promise<{
637
- html: string;
638
- text: string;
639
- subject: string;
640
- } | null>;
641
- previewRaw(subject: string, body: string, sampleData: Record<string, unknown>, variables?: string[], textBody?: string): Promise<{
642
- html: string;
643
- text: string;
644
- subject: string;
645
- }>;
646
- validate(body: string): Promise<{
647
- valid: boolean;
648
- errors: string[];
649
- variables: string[];
650
- }>;
651
- clone(sourceId: string, newName?: string): Promise<any>;
652
- sendTestEmail(id: string, testEmail: string, sampleData: Record<string, unknown>): Promise<{
653
- success: boolean;
654
- error?: string;
655
- }>;
656
- previewWithRecipient(templateId: string, recipientData: Record<string, unknown>): Promise<{
657
- html: string;
658
- text: string;
659
- subject: string;
660
- } | null>;
661
- }
662
-
663
- declare class RuleService {
664
- private EmailRule;
665
- private EmailTemplate;
666
- private EmailRuleRunLog;
667
- private config;
668
- constructor(EmailRule: EmailRuleModel, EmailTemplate: EmailTemplateModel, EmailRuleRunLog: EmailRuleRunLogModel, config: EmailRuleEngineConfig);
669
- list(opts?: {
670
- page?: number;
671
- limit?: number;
672
- }): Promise<{
673
- rules: EmailRuleDocument[];
674
- total: number;
675
- }>;
676
- getById(id: string): Promise<EmailRuleDocument | null>;
677
- create(input: CreateEmailRuleInput): Promise<EmailRuleDocument>;
678
- update(id: string, input: UpdateEmailRuleInput): Promise<EmailRuleDocument | null>;
679
- delete(id: string): Promise<{
680
- deleted: boolean;
681
- disabled?: boolean;
682
- }>;
683
- toggleActive(id: string): Promise<EmailRuleDocument | null>;
684
- dryRun(id: string): Promise<{
685
- matchedCount: number;
686
- effectiveLimit: number;
687
- willProcess: number;
688
- ruleId: string;
689
- sample: Array<{
690
- email: string;
691
- name?: string;
692
- [key: string]: unknown;
693
- }>;
694
- }>;
695
- clone(sourceId: string, newName?: string): Promise<any>;
696
- getRunHistory(limit?: number, opts?: {
697
- page?: number;
698
- from?: string;
699
- to?: string;
700
- }): Promise<unknown[]>;
701
- getRunHistoryCount(opts?: {
702
- from?: string;
703
- to?: string;
704
- }): Promise<number>;
705
- }
706
-
707
- interface UserThrottle {
708
- today: number;
709
- thisWeek: number;
710
- lastSentDate: Date | null;
711
- }
712
- declare class RuleRunnerService {
713
- private EmailRule;
714
- private EmailTemplate;
715
- private EmailRuleSend;
716
- private EmailRuleRunLog;
717
- private EmailThrottleConfig;
718
- private config;
719
- private templateRenderer;
720
- private lock;
721
- private logger;
722
- private redis;
723
- private keyPrefix;
724
- constructor(EmailRule: EmailRuleModel, EmailTemplate: EmailTemplateModel, EmailRuleSend: EmailRuleSendModel, EmailRuleRunLog: EmailRuleRunLogModel, EmailThrottleConfig: EmailThrottleConfigModel, config: EmailRuleEngineConfig);
725
- runAllRules(triggeredBy?: RunTrigger, runId?: string): Promise<{
726
- runId: string;
727
- }>;
728
- executeRule(rule: any, throttleMap: Map<string, UserThrottle>, throttleConfig: any, templateMap?: Map<string, any>, runId?: string): Promise<RuleRunStats>;
729
- private emitSendEvent;
730
- private processSingleUser;
731
- private resolveIdentifiers;
732
- private buildSendMap;
733
- private compileTemplateVariants;
734
- private checkCancelled;
735
- private applySendDelay;
736
- private finalizeRuleStats;
737
- private executeListMode;
738
- private executeQueryMode;
739
- private checkThrottle;
740
- private getTodayStart;
741
- private updateRunProgress;
742
- private updateRunSendProgress;
743
- getStatus(runId: string): Promise<RunStatusResponse | null>;
744
- cancel(runId: string): Promise<{
745
- ok: boolean;
746
- }>;
747
- trigger(triggeredBy?: RunTrigger): {
748
- runId: string;
749
- started: boolean;
750
- };
751
- buildThrottleMap(recentSends: any[]): Map<string, UserThrottle>;
752
- }
753
-
754
- declare class AlxEmailError extends AlxError {
755
- constructor(message: string, code: string);
756
- }
757
- declare class ConfigValidationError extends AlxEmailError {
758
- readonly field: string;
759
- constructor(message: string, field: string);
760
- }
761
- declare class TemplateNotFoundError extends AlxEmailError {
762
- readonly templateId: string;
763
- constructor(templateId: string);
764
- }
765
- declare class TemplateSyntaxError extends AlxEmailError {
766
- readonly errors: string[];
767
- constructor(message: string, errors: string[]);
768
- }
769
- declare class RuleNotFoundError extends AlxEmailError {
770
- readonly ruleId: string;
771
- constructor(ruleId: string);
772
- }
773
- declare class RuleTemplateIncompatibleError extends AlxEmailError {
774
- readonly reason: string;
775
- constructor(reason: string);
776
- }
777
- declare class LockAcquisitionError extends AlxEmailError {
778
- constructor();
779
- }
780
- declare class DuplicateSlugError extends AlxEmailError {
781
- readonly slug: string;
782
- constructor(slug: string);
783
- }
784
-
785
- declare function validateConfig(raw: unknown): void;
786
-
787
- interface ConditionValidationError {
788
- index: number;
789
- field: string;
790
- message: string;
791
- }
792
- declare function validateConditions(conditions: RuleCondition[], collectionName: string | undefined, collections: CollectionSchema[]): ConditionValidationError[];
793
-
794
- declare function flattenFields(fields: FieldDefinition[], prefix?: string, parentIsArray?: boolean): FlattenedField[];
795
-
796
- interface RenderResult {
797
- html: string;
798
- text: string;
799
- subject: string;
800
- }
801
- interface CompiledTemplate {
802
- subjectFn: HandlebarsTemplateDelegate;
803
- bodyFn: HandlebarsTemplateDelegate;
804
- textBodyFn?: HandlebarsTemplateDelegate;
805
- }
806
- declare class TemplateRenderService {
807
- constructor();
808
- renderSingle(subject: string, body: string, data: Record<string, unknown>, textBody?: string): RenderResult;
809
- compileBatch(subject: string, body: string, textBody?: string): CompiledTemplate;
810
- compileBatchVariants(subjects: string[], bodies: string[], textBody?: string, preheaders?: string[]): {
811
- subjectFns: HandlebarsTemplateDelegate[];
812
- bodyFns: HandlebarsTemplateDelegate[];
813
- textBodyFn?: HandlebarsTemplateDelegate;
814
- preheaderFns?: HandlebarsTemplateDelegate[];
815
- };
816
- renderFromCompiled(compiled: CompiledTemplate, data: Record<string, unknown>): RenderResult;
817
- renderPreview(subject: string, body: string, data: Record<string, unknown>, textBody?: string): RenderResult;
818
- htmlToText(html: string): string;
819
- extractVariables(template: string): string[];
820
- validateTemplate(body: string): {
821
- valid: boolean;
822
- errors: string[];
823
- };
824
- }
825
-
826
- declare class SchedulerService {
827
- private queue;
828
- private worker?;
829
- private keyPrefix;
830
- constructor(connection: Redis, keyPrefix?: string);
831
- syncRule(rule: {
832
- _id: any;
833
- schedule?: {
834
- enabled: boolean;
835
- cron: string;
836
- timezone?: string;
837
- };
838
- }): Promise<void>;
839
- removeRule(ruleId: string): Promise<void>;
840
- startWorker(runFn: (triggeredBy: string) => Promise<any>): void;
841
- stopWorker(): Promise<void>;
842
- getScheduledJobs(): Promise<Array<{
843
- ruleId: string;
844
- cron: string;
845
- next: number | null;
846
- }>>;
847
- }
848
-
849
- /**
850
- * Engine instance with Express routes and programmatic service access.
851
- */
852
- interface EmailRuleEngine {
853
- routes: Router;
854
- runner: RuleRunnerService;
855
- templateService: TemplateService;
856
- ruleService: RuleService;
857
- models: {
858
- EmailTemplate: EmailTemplateModel;
859
- EmailRule: EmailRuleModel;
860
- EmailRuleSend: EmailRuleSendModel;
861
- EmailRuleRunLog: EmailRuleRunLogModel;
862
- EmailThrottleConfig: EmailThrottleConfigModel;
863
- };
864
33
  }
865
- /**
866
- * Creates an email rule engine instance with routes, services, and models.
867
- *
868
- * @param config - Engine configuration including DB, Redis, adapters, and options.
869
- * @returns Engine instance with Express routes and programmatic service access.
870
- * @throws {ConfigValidationError} If the provided config is invalid.
871
- *
872
- * @example
873
- * ```typescript
874
- * const engine = createEmailRuleEngine({
875
- * db: { connection: mongoose.createConnection(uri) },
876
- * redis: { connection: new Redis() },
877
- * adapters: { queryUsers, resolveData, sendEmail, selectAgent, findIdentifier },
878
- * });
879
- * app.use('/api/email-rules', engine.routes);
880
- * ```
881
- */
882
- declare function createEmailRuleEngine(config: EmailRuleEngineConfig): EmailRuleEngine;
34
+ declare function createEmailRuleEngine(config: EmailRuleEngineConfig): RuleEngine;
883
35
 
884
- export { type AgentSelection, AlxEmailError, type BeforeSendParams, type BeforeSendResult, type CollectionSchema, type CompiledTemplate, type ConditionValidationError, ConfigValidationError, type CreateEmailRuleInput, type CreateEmailTemplateInput, DuplicateSlugError, EMAIL_SEND_STATUS, EMAIL_TYPE, type EmailAttachment, type EmailRule, type EmailRuleDocument, type EmailRuleEngine, type EmailRuleEngineConfig, type EmailRuleModel, type EmailRuleRunLog, type EmailRuleRunLogDocument, type EmailRuleRunLogModel, type EmailRuleRunLogStatics, type EmailRuleSend, type EmailRuleSendDocument, type EmailRuleSendModel, type EmailRuleSendStatics, type EmailRuleStatics, type EmailSendStatus, type EmailTemplate, type EmailTemplateDocument, type EmailTemplateModel, type EmailTemplateStatics, type EmailThrottleConfig, type EmailThrottleConfigDocument, type EmailThrottleConfigModel, type EmailThrottleConfigStatics, type EmailType, FIELD_TYPE, type FieldDefinition, type FieldType, type FlattenedField, type IEmailRule, type IEmailRuleRunLog, type IEmailRuleSend, type IEmailTemplate, type IEmailThrottleConfig, type JoinDefinition, type ListTarget, LockAcquisitionError, type PerRuleStats, type QueryTarget, RULE_OPERATOR, RUN_LOG_STATUS, RUN_TRIGGER, type RecipientIdentifier, type RenderResult, type RuleCondition, RuleNotFoundError, type RuleOperator, type RuleRunStats, RuleRunnerService, RuleService, type RuleTarget, RuleTemplateIncompatibleError, type RunLogStatus, type RunTrigger, SchedulerService, type SendEmailParams, TARGET_MODE, TEMPLATE_AUDIENCE, TEMPLATE_CATEGORY, THROTTLE_WINDOW, TYPE_OPERATORS, type TargetMode, type TemplateAudience, type TemplateCategory, TemplateNotFoundError, TemplateRenderService, TemplateService, TemplateSyntaxError, type ThrottleWindow, type UpdateEmailRuleInput, type UpdateEmailTemplateInput, type UpdateEmailThrottleConfigInput, createEmailRuleEngine, createEmailRuleRunLogSchema, createEmailRuleSchema, createEmailRuleSendSchema, createEmailTemplateSchema, createEmailThrottleConfigSchema, flattenFields, validateConditions, validateConfig };
36
+ export { type EmailRuleEngineConfig, type EmailSendParams, createEmailRuleEngine, htmlToPlainText, registerEmailHelpers, renderMjml };