mailery 0.15.0 → 0.16.1

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.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as RunnerContext, N as NormalizedEvent, C as ContactAdapter, a as Contact, A as AdapterFilter, M as MailProvider, S as SendArgs, b as SendResult, c as MailTesterFeedback, d as Mailer, T as TemplateDoc, e as SuppressionScope, D as DeliveryWindow, F as FlowStep, f as SegmentFilter, P as Predicate } from './null-CnhsvKvy.cjs';
2
- export { g as AuditLogDoc, B as BotFilterConfig, h as BroadcastDoc, i as BroadcastStatus, j as CircuitBreakerThresholds, k as Collections, l as ContactTagDoc, E as EventDoc, m as FlowDoc, n as FlowGoal, o as FlowRunDoc, p as FlowRunStatus, q as FlowVersionDoc, H as HealthDoc, r as HealthStatus, L as LeadDoc, s as MailerConfig, t as NullProvider, O as OutboxDoc, u as RESERVED_VAR_KEYS, v as RedisOptions, w as SegmentDefinition, x as SendDoc, y as SendStatus, z as SenderDomainConfig, G as SenderDomainRegistry, I as SenderDomainValidation, J as SubscriptionDoc, K as SubscriptionStatus, Q as SuppressionDoc, U as SuppressionReason, V as TemplateKind, W as TemplateVersionDoc, X as VarsAdapter, Y as VarsResolveInfo, Z as WebhookEventDoc, _ as defineVars, $ as ensureIndexes, a0 as getCollections, a1 as validateSenderDomain, a2 as varsJsonSchema } from './null-CnhsvKvy.cjs';
1
+ import { R as RunnerContext, N as NormalizedEvent, C as ContactAdapter, a as Contact, A as AdapterFilter, M as MailProvider, S as SendArgs, b as SendResult, c as MailTesterFeedback, d as Mailer, T as TemplateDoc, F as FlowStep, e as Collections, f as FlowDoc, g as SuppressionScope, D as DeliveryWindow, h as SegmentFilter, P as Predicate } from './null-CDlseQxO.cjs';
2
+ export { i as AuditLogDoc, B as BotFilterConfig, j as BroadcastDoc, k as BroadcastStatus, l as CircuitBreakerThresholds, m as ContactTagDoc, E as EventDoc, n as FlowGoal, o as FlowRunDoc, p as FlowRunStatus, q as FlowVersionDoc, H as HealthDoc, r as HealthStatus, L as LeadDoc, s as MailerConfig, t as NullProvider, O as OutboxDoc, u as RESERVED_VAR_KEYS, v as RedisOptions, w as SegmentDefinition, x as SendDoc, y as SendStatus, z as SenderDomainConfig, G as SenderDomainRegistry, I as SenderDomainValidation, J as SubscriptionDoc, K as SubscriptionStatus, Q as SuppressionDoc, U as SuppressionReason, V as TemplateKind, W as TemplateVersionDoc, X as VarsAdapter, Y as VarsResolveInfo, Z as WebhookEventDoc, _ as defineVars, $ as ensureIndexes, a0 as getCollections, a1 as validateSenderDomain, a2 as varsJsonSchema } from './null-CDlseQxO.cjs';
3
3
  import { ObjectId, Db, Filter } from 'mongodb';
4
4
  import { Request, Router } from 'express';
5
5
  import Handlebars from 'handlebars';
@@ -190,7 +190,15 @@ type WebhookToleranceOption = number | false;
190
190
 
191
191
  interface SendGridProviderOptions {
192
192
  apiKey: string;
193
- /** ECDSA public key (PEM) from SendGrid → Settings → Mail Settings → Signed Event Webhook. */
193
+ /**
194
+ * ECDSA public key from SendGrid → Settings → Mail Settings → Signed Event
195
+ * Webhook. Either form SendGrid hands out is accepted: the single-line
196
+ * base64 string its dashboard shows and its API returns as `public_key`
197
+ * (what `mailery setup-sendgrid` prints), or the same key as a PEM block.
198
+ * A PEM whose newlines were escaped to `\n` for an .env line is unescaped.
199
+ * Anything that does not parse as a public key throws at construction —
200
+ * a key that silently verifies nothing is the failure this replaces.
201
+ */
194
202
  webhookVerificationKey?: string;
195
203
  /**
196
204
  * Replay window for the signed webhook timestamp, in seconds.
@@ -213,6 +221,8 @@ declare class SendGridProvider implements MailProvider {
213
221
  readonly sendRatePerSecond: number;
214
222
  /** Resolved replay window in seconds; `0` means the check is disabled. */
215
223
  readonly webhookToleranceSeconds: number;
224
+ /** The verification key as PEM, whatever shape it was configured in. */
225
+ private readonly verificationKeyPem;
216
226
  constructor(opts: SendGridProviderOptions);
217
227
  send(args: SendArgs): Promise<SendResult>;
218
228
  verifyWebhook(rawBody: Buffer, headers: Record<string, string>): Promise<boolean>;
@@ -271,6 +281,14 @@ interface AdminRouterOptions {
271
281
  mailTesterClient?: MailTesterClient;
272
282
  }
273
283
  declare function createAdminRouter(mailer: Mailer, opts?: AdminRouterOptions): Router;
284
+ /**
285
+ * The JSON API alone, without the SPA shell or the static assets. Exported
286
+ * so `createAgentRouter` can offer the same endpoints under bearer-token
287
+ * auth; hosts mounting the SPA should keep using `createAdminRouter`.
288
+ *
289
+ * Expects `(req as any).actor` to be set by whatever sits in front of it.
290
+ */
291
+ declare function createAdminApiRouter(mailer: Mailer, opts?: AdminRouterOptions): Router;
274
292
 
275
293
  /**
276
294
  * Async handler wrapper for the *public* router.
@@ -318,6 +336,412 @@ interface RouteLogger {
318
336
  info?: (fields: Record<string, unknown>, msg?: string) => void;
319
337
  }
320
338
 
339
+ /**
340
+ * Template render pipeline.
341
+ *
342
+ * authorMjml + handlebarsContext
343
+ * ↓ Handlebars render → MJML with substituted vars
344
+ * ↓ mjml-core compile → HTML
345
+ * ↓ html-to-text derive → plain text alternative
346
+ * ↓ applyTracking(sendId) → tracked HTML with rewritten links + open pixel
347
+ *
348
+ * Subject and preheader run through Handlebars too. Plain text is auto-derived
349
+ * unless the template explicitly overrides it.
350
+ */
351
+
352
+ interface CompileResult {
353
+ html: string;
354
+ plainText: string;
355
+ errors: Array<{
356
+ line?: number;
357
+ message: string;
358
+ tagName?: string;
359
+ formattedMessage?: string;
360
+ }>;
361
+ }
362
+ /** Compile MJML → HTML, then derive plain text. Called at template publish time. */
363
+ declare function compileTemplate(mjml: string): Promise<CompileResult>;
364
+ /**
365
+ * Compile Maily editor JSON (Tiptap-shape) → HTML via `@maily-to/render`, then
366
+ * derive plain text. Called at template publish time when the template was
367
+ * authored via the WYSIWYG editor.
368
+ */
369
+ declare function compileMailyTemplate(content: unknown): Promise<CompileResult>;
370
+ /** Auto-derive plain text from compiled HTML. */
371
+ declare function derivePlaintext(html: string): string;
372
+ interface RenderContext {
373
+ /**
374
+ * Host-resolved variables (varsAdapter) live at the context root, so a
375
+ * schema key `user` renders as `{{user.name}}`. Reserved keys below always
376
+ * win over resolved keys.
377
+ */
378
+ [resolvedVar: string]: unknown;
379
+ contact: Contact;
380
+ vars: Record<string, unknown>;
381
+ /** Properties of the event that triggered the flow run ({{event.*}}). Empty outside flow sends. */
382
+ event?: Record<string, unknown>;
383
+ /** URL the recipient hits to one-click unsubscribe. */
384
+ unsubscribeUrl: string;
385
+ /** URL to view this email in a browser (when implemented). */
386
+ viewInBrowserUrl?: string;
387
+ /** URL for the preference center (when implemented). */
388
+ preferenceCenterUrl?: string;
389
+ /** Configured sender postal address (CAN-SPAM). */
390
+ senderAddress?: string;
391
+ }
392
+ interface RenderedTemplate {
393
+ subject: string;
394
+ preheader: string;
395
+ html: string;
396
+ plainText: string;
397
+ fromName: string;
398
+ fromEmail: string;
399
+ replyTo: string | null;
400
+ }
401
+ interface RenderOptions {
402
+ /** Extra Handlebars helpers contributed by the host. */
403
+ helpers?: Record<string, Handlebars.HelperDelegate>;
404
+ }
405
+ /**
406
+ * Render a published template against a contact + vars context. Returns the
407
+ * substituted subject/preheader/html/plainText. Tracking is NOT applied here —
408
+ * that step needs the send id and runs separately via `applyTracking`.
409
+ */
410
+ declare function renderTemplate(template: TemplateDoc, ctx: RenderContext, opts?: RenderOptions): Promise<RenderedTemplate>;
411
+ interface TrackingOptions {
412
+ sendId: string;
413
+ publicUrl: string;
414
+ trackOpens: boolean;
415
+ trackClicks: boolean;
416
+ /** URL that must NOT be rewritten (e.g. the resolved unsubscribe URL). */
417
+ preserveUrls?: string[];
418
+ /**
419
+ * HMAC key for tracking-URL signatures — pass `config.unsubscribeSecret`.
420
+ *
421
+ * When set, every generated `/m/open` and `/m/click` URL carries a truncated
422
+ * HMAC so it cannot be forged or enumerated from a neighbouring ObjectId.
423
+ * When omitted the legacy unsigned shape is emitted; that path exists for
424
+ * preview/test renders that never reach the tracking endpoints, not as a
425
+ * supported production mode.
426
+ */
427
+ signingSecret?: string;
428
+ }
429
+ interface TrackingResult {
430
+ html: string;
431
+ /** linkId → original URL map; persist on `mailer_sends.links` for click resolution. */
432
+ links: Array<{
433
+ linkId: string;
434
+ url: string;
435
+ }>;
436
+ }
437
+ /**
438
+ * Rewrite `<a href>` in `html` to /m/click/<sendId>/<linkId>/<sig> and append
439
+ * an open pixel at /m/open/<sendId>.<sig>.png. Returns the modified HTML plus
440
+ * the link map to persist on the send document.
441
+ *
442
+ * The `<sig>` components are 12-character truncated HMACs (see
443
+ * `signTrackingToken`) and are present whenever `opts.signingSecret` is set.
444
+ * Without them a Mongo ObjectId is the only thing standing between an attacker
445
+ * and a forged open — and ObjectIds are a timestamp plus a per-process counter,
446
+ * so one received email hands out its neighbours.
447
+ */
448
+ declare function applyTracking(html: string, opts: TrackingOptions): TrackingResult;
449
+
450
+ /**
451
+ * Agent router — the mailery surface for automation.
452
+ *
453
+ * Everything an operator does by hand in the admin SPA to take an email
454
+ * program from "deployed" to "safely on" — render a template as a real
455
+ * contact and check it, send it through the real pipeline and watch delivery,
456
+ * ask what a flow would do to a contact, walk a canary run step by step,
457
+ * gate and arm a flow — is reachable here as JSON, behind a bearer token,
458
+ * with no browser session. It is built for an AI agent or a CI job to drive,
459
+ * which shapes three things:
460
+ *
461
+ * - Every answer is structured. A verification is a list of named checks
462
+ * with pass/warn/fail, not a rendered page to squint at.
463
+ * - Every operation that could touch a real person is guarded by the
464
+ * `testContacts` pattern: test sends, event firing, run stepping and
465
+ * resets only apply to contacts whose email matches it. A router with no
466
+ * pattern configured refuses those routes outright rather than assuming.
467
+ * - Nothing here can enable a flow without stamping its trigger watermark
468
+ * (see runner/arm.ts), so an agent cannot replay a month of signups.
469
+ *
470
+ * Mount it beside the admin router, on a path the host's session middleware
471
+ * does not cover, and give it the same JSON body the SPA would:
472
+ *
473
+ * app.use('/admin/mailer/agent', createAgentRouter(mailer, {
474
+ * tokens: [{ token: process.env.MAILERY_AGENT_TOKEN!, actor: 'agent:claude' }],
475
+ * testContacts: /^qa\+.*@example\.com$/i,
476
+ * }))
477
+ *
478
+ * `GET /` describes every route so a client can discover the surface. The
479
+ * full admin JSON API (docs/reference/admin-api.md) is mounted under `/api`
480
+ * with the token's actor, so reads and existing operations need no second
481
+ * auth path.
482
+ */
483
+
484
+ interface AgentToken {
485
+ /** The bearer token. At least 24 characters; generate it, never type it. */
486
+ token: string;
487
+ /** Audit actor recorded for everything done with this token, e.g. `agent:claude`. */
488
+ actor: string;
489
+ }
490
+ interface AgentRouterOptions {
491
+ /** Required. The router refuses to construct without at least one token. */
492
+ tokens: AgentToken[];
493
+ /**
494
+ * Which contacts may be test-sent to, stepped through flows, fired events
495
+ * for, or reset. A regular expression over the email address, or a
496
+ * predicate. Routes that need it answer 403 when it is not configured —
497
+ * the safe default for a surface an automated caller drives.
498
+ */
499
+ testContacts?: RegExp | ((email: string) => boolean);
500
+ /** Structured logger for failures. Defaults to console. */
501
+ logger?: RouteLogger;
502
+ /** Passed through to the admin JSON API (tests inject a stub). */
503
+ mailTesterClient?: AdminRouterOptions['mailTesterClient'];
504
+ }
505
+ declare const MIN_AGENT_TOKEN_LENGTH = 24;
506
+ type Check = {
507
+ id: string;
508
+ status: 'pass' | 'warn' | 'fail';
509
+ detail?: unknown;
510
+ };
511
+ declare function createAgentRouter(mailer: Mailer, opts: AgentRouterOptions): Router;
512
+ interface VerifyOptions {
513
+ eventProperties?: Record<string, unknown>;
514
+ vars?: Record<string, unknown>;
515
+ includeRendered?: boolean;
516
+ varsSchema?: Record<string, unknown> | null;
517
+ }
518
+ interface VerifyReport {
519
+ ok: boolean;
520
+ template: {
521
+ slug: string;
522
+ kind: TemplateDoc['kind'];
523
+ name: string;
524
+ };
525
+ contact: {
526
+ externalId: string;
527
+ email: string;
528
+ };
529
+ checks: Check[];
530
+ links: {
531
+ total: number;
532
+ sample: string[];
533
+ };
534
+ rendered: {
535
+ subject: string;
536
+ preheader: string;
537
+ htmlBytes: number;
538
+ textLength: number;
539
+ fromEmail: string;
540
+ } | {
541
+ subject: string;
542
+ preheader: string;
543
+ html: string;
544
+ plainText: string;
545
+ fromEmail: string;
546
+ fromName: string;
547
+ replyTo: string | null;
548
+ } | null;
549
+ }
550
+ declare function verifyTemplate(mailer: Mailer, tpl: TemplateDoc, contact: Contact, opts?: VerifyOptions): Promise<VerifyReport>;
551
+ interface RenderForContactOptions {
552
+ reason: 'preview' | 'test';
553
+ eventProperties?: Record<string, unknown>;
554
+ vars?: Record<string, unknown>;
555
+ }
556
+ /**
557
+ * Render a published template for one real contact the way a send would:
558
+ * host vars resolved through the varsAdapter, the contact at the root, a
559
+ * genuinely signed unsubscribe URL. The one difference from a send is that
560
+ * no tracking is applied — nothing here is queued.
561
+ */
562
+ declare function renderForContact(mailer: Mailer, tpl: TemplateDoc, contact: Contact, opts: RenderForContactOptions): Promise<{
563
+ rendered: RenderedTemplate;
564
+ resolved: Record<string, unknown>;
565
+ unsubscribeUrl: string;
566
+ /** The exact object the template was rendered against. */
567
+ context: Record<string, unknown>;
568
+ }>;
569
+ /**
570
+ * Every dotted path a Handlebars source references outside `#each`/`#with`
571
+ * blocks (whose paths are relative to the iterated item and cannot be
572
+ * resolved against the root context) and outside HTML comments. Helper
573
+ * names, literals, hash keys, `@data` variables and Handlebars comments are
574
+ * skipped.
575
+ */
576
+ declare function referencedPaths(source: string, helperNames?: Iterable<string>): string[];
577
+
578
+ /**
579
+ * Enabling a flow, done safely — and running it against test contacts only.
580
+ *
581
+ * The trigger scan starts from `flow.lastTriggerScanAt ?? flow.createdAt`
582
+ * (triggers.ts). A flow that has never been enabled has a null watermark, so a
583
+ * bare `enabled: true` replays every matching event since the flow document
584
+ * was created: every signup of the past month gets the welcome email in one
585
+ * tick, a week or more late. That is the single most dangerous write in the
586
+ * admin surface, and until 0.16 it was one click (publish, or resume).
587
+ *
588
+ * `armFlow` is the path that flips `enabled` on. It stamps the watermark
589
+ * (default: now) in the SAME update, reports how many events it is choosing
590
+ * to skip, and writes an audit row. `publish` and `resume` in the admin API
591
+ * go through `stampWatermarkIfNull` for the same guarantee.
592
+ *
593
+ * `gateFlow` publishes a canary version whose first step exits anyone
594
+ * without a tag, so the real runner can exercise the real steps in
595
+ * production against test contacts while every real contact enters and
596
+ * exits at step 0 with no send. `ungateFlow` restores the newest ungated
597
+ * version. Runs pin their version, so a contact mid-canary finishes on it.
598
+ */
599
+
600
+ /** A typed failure the HTTP layer can map to a status code without guessing. */
601
+ declare class FlowOperationError extends Error {
602
+ readonly code: string;
603
+ readonly status: number;
604
+ constructor(code: string, message: string, status?: number);
605
+ }
606
+ interface ArmFlowOptions {
607
+ /** Audit actor, e.g. `agent:claude` or `human:jeff@example.com`. */
608
+ actor: string;
609
+ /**
610
+ * Watermark to stamp. Defaults to now, which means only events fired AFTER
611
+ * this call enter the flow. Pass an earlier instant only when you mean for
612
+ * the events after it to enter — the result says how many that is.
613
+ */
614
+ since?: Date;
615
+ }
616
+ interface ArmFlowResult {
617
+ slug: string;
618
+ version: number;
619
+ /** True when this call flipped `enabled` on. */
620
+ armed: boolean;
621
+ /** True when the flow was already enabled; nothing was written. */
622
+ alreadyEnabled: boolean;
623
+ /** The watermark now on the flow. */
624
+ watermark: Date | null;
625
+ eventName: string | null;
626
+ /** Events for the trigger name that fired before the watermark and will never enter. */
627
+ skippedEvents: number;
628
+ /**
629
+ * Events that WILL enter on the next tick: everything after the watermark,
630
+ * plus anything created inside the scanner's 30-second overlap window just
631
+ * before it.
632
+ */
633
+ pendingEvents: number;
634
+ }
635
+ /**
636
+ * Stamp `lastTriggerScanAt` when it is null. Used by every code path that
637
+ * turns `enabled` on so a first enable never replays history. A flow that
638
+ * has scanned before keeps its watermark: pausing and resuming deliberately
639
+ * lets the events fired during the pause enter.
640
+ */
641
+ declare function stampWatermarkIfNull(collections: Collections, flow: FlowDoc, now?: Date): Promise<Date | null>;
642
+ declare function armFlow(mailer: Mailer, slug: string, opts: ArmFlowOptions): Promise<ArmFlowResult>;
643
+ /** The inverse: `enabled: false`. In-flight runs continue (that is what pause means). */
644
+ declare function disarmFlow(mailer: Mailer, slug: string, actor: string): Promise<{
645
+ slug: string;
646
+ disarmed: boolean;
647
+ }>;
648
+ /**
649
+ * The gate step. `canaryGate` is a marker the runner ignores (it evaluates
650
+ * the condition like any other) and this module uses to recognise its own
651
+ * work when removing it.
652
+ */
653
+ type CanaryGateStep = Extract<FlowStep, {
654
+ type: 'condition';
655
+ }> & {
656
+ canaryGate: true;
657
+ };
658
+ declare function isCanaryGate(step: unknown): step is CanaryGateStep;
659
+ interface GateFlowResult {
660
+ slug: string;
661
+ version: number;
662
+ tag: string;
663
+ enabled: boolean;
664
+ }
665
+ declare function gateFlow(mailer: Mailer, slug: string, opts: {
666
+ tag: string;
667
+ actor: string;
668
+ }): Promise<GateFlowResult>;
669
+ interface UngateFlowResult {
670
+ slug: string;
671
+ version: number;
672
+ /** The version whose steps were restored. */
673
+ restoredFrom: number;
674
+ enabled: boolean;
675
+ }
676
+ declare function ungateFlow(mailer: Mailer, slug: string, opts: {
677
+ actor: string;
678
+ }): Promise<UngateFlowResult>;
679
+
680
+ /**
681
+ * Flow simulation: "what would happen to this contact if the trigger fired
682
+ * now?" — answered by walking the published steps against the contact's real
683
+ * state (tags, fields, events, sends, subscription) with a virtual clock and
684
+ * WITHOUT writing anything.
685
+ *
686
+ * This is the dry run an operator wants before arming a flow: it shows the
687
+ * branch a contact takes, every gate's verdict, the sends and the wall-clock
688
+ * moment each would go out (waits and delivery windows applied), and where
689
+ * the run ends. It reads the same predicate evaluator the runner uses, so a
690
+ * gate that passes here passes in production — for the state as it is at the
691
+ * moment of the call. Events that would arrive during the run are of course
692
+ * not known, which is why `path[].at` is labelled a projection.
693
+ */
694
+
695
+ interface SimulateOptions {
696
+ /** Virtual "now" the simulated run enters at. Defaults to the real now. */
697
+ at?: Date;
698
+ /** Properties of the simulated trigger event ({{event.*}}, triggerProperty* predicates). */
699
+ eventProperties?: Record<string, unknown>;
700
+ /** Steps to walk. Defaults to the flow's live steps. */
701
+ steps?: FlowStep[];
702
+ }
703
+ interface SimulatedStep {
704
+ /** Projected wall-clock moment the step is reached. */
705
+ at: Date;
706
+ stepIndex: number;
707
+ branchPath: Array<number | 'true' | 'false'>;
708
+ type: FlowStep['type'];
709
+ outcome: 'waited' | 'passed' | 'skipped_next' | 'exited' | 'branch_true' | 'branch_false' | 'send' | 'send_deferred' | 'tagged' | 'event_fired' | 'webhook' | 'completed';
710
+ detail?: Record<string, unknown>;
711
+ }
712
+ interface SimulationResult {
713
+ flow: {
714
+ slug: string;
715
+ version: number;
716
+ enabled: boolean;
717
+ };
718
+ contact: {
719
+ externalId: string;
720
+ email: string;
721
+ };
722
+ enteredAt: Date;
723
+ /** Whether the trigger scan would create a run at all, and why not. */
724
+ wouldEnter: {
725
+ ok: boolean;
726
+ reasons: string[];
727
+ };
728
+ path: SimulatedStep[];
729
+ sends: Array<{
730
+ templateSlug: string;
731
+ at: Date;
732
+ stepIndex: number;
733
+ branchPath: Array<number | 'true' | 'false'>;
734
+ }>;
735
+ terminal: {
736
+ kind: 'completed' | 'exited' | 'truncated';
737
+ reason: string;
738
+ at: Date;
739
+ };
740
+ /** Projected time from entry to the terminal step. */
741
+ durationMs: number;
742
+ }
743
+ declare function simulateFlow(flow: FlowDoc, contact: Contact, ctx: RunnerContext, opts?: SimulateOptions): Promise<SimulationResult>;
744
+
321
745
  /**
322
746
  * Inbound DMARC aggregate-report webhook.
323
747
  *
@@ -486,117 +910,6 @@ interface PublicRouterOptions {
486
910
  }
487
911
  declare function createPublicRouter(mailer: Mailer, opts?: PublicRouterOptions): Router;
488
912
 
489
- /**
490
- * Template render pipeline.
491
- *
492
- * authorMjml + handlebarsContext
493
- * ↓ Handlebars render → MJML with substituted vars
494
- * ↓ mjml-core compile → HTML
495
- * ↓ html-to-text derive → plain text alternative
496
- * ↓ applyTracking(sendId) → tracked HTML with rewritten links + open pixel
497
- *
498
- * Subject and preheader run through Handlebars too. Plain text is auto-derived
499
- * unless the template explicitly overrides it.
500
- */
501
-
502
- interface CompileResult {
503
- html: string;
504
- plainText: string;
505
- errors: Array<{
506
- line?: number;
507
- message: string;
508
- tagName?: string;
509
- formattedMessage?: string;
510
- }>;
511
- }
512
- /** Compile MJML → HTML, then derive plain text. Called at template publish time. */
513
- declare function compileTemplate(mjml: string): Promise<CompileResult>;
514
- /**
515
- * Compile Maily editor JSON (Tiptap-shape) → HTML via `@maily-to/render`, then
516
- * derive plain text. Called at template publish time when the template was
517
- * authored via the WYSIWYG editor.
518
- */
519
- declare function compileMailyTemplate(content: unknown): Promise<CompileResult>;
520
- /** Auto-derive plain text from compiled HTML. */
521
- declare function derivePlaintext(html: string): string;
522
- interface RenderContext {
523
- /**
524
- * Host-resolved variables (varsAdapter) live at the context root, so a
525
- * schema key `user` renders as `{{user.name}}`. Reserved keys below always
526
- * win over resolved keys.
527
- */
528
- [resolvedVar: string]: unknown;
529
- contact: Contact;
530
- vars: Record<string, unknown>;
531
- /** Properties of the event that triggered the flow run ({{event.*}}). Empty outside flow sends. */
532
- event?: Record<string, unknown>;
533
- /** URL the recipient hits to one-click unsubscribe. */
534
- unsubscribeUrl: string;
535
- /** URL to view this email in a browser (when implemented). */
536
- viewInBrowserUrl?: string;
537
- /** URL for the preference center (when implemented). */
538
- preferenceCenterUrl?: string;
539
- /** Configured sender postal address (CAN-SPAM). */
540
- senderAddress?: string;
541
- }
542
- interface RenderedTemplate {
543
- subject: string;
544
- preheader: string;
545
- html: string;
546
- plainText: string;
547
- fromName: string;
548
- fromEmail: string;
549
- replyTo: string | null;
550
- }
551
- interface RenderOptions {
552
- /** Extra Handlebars helpers contributed by the host. */
553
- helpers?: Record<string, Handlebars.HelperDelegate>;
554
- }
555
- /**
556
- * Render a published template against a contact + vars context. Returns the
557
- * substituted subject/preheader/html/plainText. Tracking is NOT applied here —
558
- * that step needs the send id and runs separately via `applyTracking`.
559
- */
560
- declare function renderTemplate(template: TemplateDoc, ctx: RenderContext, opts?: RenderOptions): Promise<RenderedTemplate>;
561
- interface TrackingOptions {
562
- sendId: string;
563
- publicUrl: string;
564
- trackOpens: boolean;
565
- trackClicks: boolean;
566
- /** URL that must NOT be rewritten (e.g. the resolved unsubscribe URL). */
567
- preserveUrls?: string[];
568
- /**
569
- * HMAC key for tracking-URL signatures — pass `config.unsubscribeSecret`.
570
- *
571
- * When set, every generated `/m/open` and `/m/click` URL carries a truncated
572
- * HMAC so it cannot be forged or enumerated from a neighbouring ObjectId.
573
- * When omitted the legacy unsigned shape is emitted; that path exists for
574
- * preview/test renders that never reach the tracking endpoints, not as a
575
- * supported production mode.
576
- */
577
- signingSecret?: string;
578
- }
579
- interface TrackingResult {
580
- html: string;
581
- /** linkId → original URL map; persist on `mailer_sends.links` for click resolution. */
582
- links: Array<{
583
- linkId: string;
584
- url: string;
585
- }>;
586
- }
587
- /**
588
- * Rewrite `<a href>` in `html` to /m/click/<sendId>/<linkId>/<sig> and append
589
- * an open pixel at /m/open/<sendId>.<sig>.png. Returns the modified HTML plus
590
- * the link map to persist on the send document.
591
- *
592
- * The `<sig>` components are 12-character truncated HMACs (see
593
- * `signTrackingToken`) and are present whenever `opts.signingSecret` is set.
594
- * Without them a Mongo ObjectId is the only thing standing between an attacker
595
- * and a forged open — and ObjectIds are a timestamp plus a per-process counter,
596
- * so one received email hands out its neighbours.
597
- */
598
- declare function applyTracking(html: string, opts: TrackingOptions): TrackingResult;
599
-
600
913
  /**
601
914
  * HMAC-signed tokens for unsubscribe + preference-center URLs.
602
915
  *
@@ -750,4 +1063,4 @@ declare const DEDUPE_POLICIES: readonly DedupePolicyOption[];
750
1063
  */
751
1064
  declare const VERSION: string;
752
1065
 
753
- export { AdapterFilter, type AdminRouterOptions, Contact, ContactAdapter, DEDUPE_POLICIES, DEFAULT_BOT_UA_RE, type DedupePolicyOption, DeliveryWindow, type DmarcInboundOptions, type DrainPendingUnsubsOptions, type DrainPendingUnsubsResult, FLOW_STEP_KINDS, FlowStep, type FlowStepKindOption, type InboundAttachment, type InboundParser, MailProvider, Mailer, MongoContactAdapter, type MongoContactAdapterOptions, NormalizedEvent, PREDICATE_KINDS, Predicate, type PredicateKind, type PredicateKindOption, type PublicRouterOptions, type RouteLogger, SEGMENT_FILTER_KINDS, SegmentFilter, type SegmentFilterKind, type SegmentFilterKindOption, SendArgs, SendGridProvider, type SendGridProviderOptions, SendResult, SuppressionScope, TRACKING_SIG_LENGTH, TemplateDoc, type TrackingScope, type TrackingTokenParams, VERSION, applyTracking, applyWebhookEvent, compileMailyTemplate, compileTemplate, computeDeliveryTime, createAdminRouter, createPublicRouter, defaultFlowStep, defaultPredicate, defaultSegmentFilter, derivePlaintext, dispatchSend, drainPendingUnsubscribes, predicateKind, processNewlyFiredEventTriggers, processOneRunStep, renderTemplate, runTick, sendgridInboundParser, sha256Hex, signTrackingToken, signUnsubscribeToken, sweepStrandedFlowRuns, verifyTrackingToken, verifyUnsubscribeToken };
1066
+ export { AdapterFilter, type AdminRouterOptions, type AgentRouterOptions, type AgentToken, type ArmFlowOptions, type ArmFlowResult, Collections, Contact, ContactAdapter, DEDUPE_POLICIES, DEFAULT_BOT_UA_RE, type DedupePolicyOption, DeliveryWindow, type DmarcInboundOptions, type DrainPendingUnsubsOptions, type DrainPendingUnsubsResult, FLOW_STEP_KINDS, FlowDoc, FlowOperationError, FlowStep, type FlowStepKindOption, type GateFlowResult, type InboundAttachment, type InboundParser, MIN_AGENT_TOKEN_LENGTH, MailProvider, Mailer, MongoContactAdapter, type MongoContactAdapterOptions, NormalizedEvent, PREDICATE_KINDS, Predicate, type PredicateKind, type PredicateKindOption, type PublicRouterOptions, type RouteLogger, SEGMENT_FILTER_KINDS, SegmentFilter, type SegmentFilterKind, type SegmentFilterKindOption, SendArgs, SendGridProvider, type SendGridProviderOptions, SendResult, type SimulateOptions, type SimulatedStep, type SimulationResult, SuppressionScope, TRACKING_SIG_LENGTH, TemplateDoc, type TrackingScope, type TrackingTokenParams, type UngateFlowResult, VERSION, type VerifyOptions, type VerifyReport, applyTracking, applyWebhookEvent, armFlow, compileMailyTemplate, compileTemplate, computeDeliveryTime, createAdminApiRouter, createAdminRouter, createAgentRouter, createPublicRouter, defaultFlowStep, defaultPredicate, defaultSegmentFilter, derivePlaintext, disarmFlow, dispatchSend, drainPendingUnsubscribes, gateFlow, isCanaryGate, predicateKind, processNewlyFiredEventTriggers, processOneRunStep, referencedPaths, renderForContact, renderTemplate, runTick, sendgridInboundParser, sha256Hex, signTrackingToken, signUnsubscribeToken, simulateFlow, stampWatermarkIfNull, sweepStrandedFlowRuns, ungateFlow, verifyTemplate, verifyTrackingToken, verifyUnsubscribeToken };