@adatechnology/notification-contracts 0.1.0-rc.2 → 0.1.0-rc.4

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.js CHANGED
@@ -57,6 +57,18 @@ var NOTIFICATION_CATEGORY_HINT = {
57
57
  SYSTEM: "system"
58
58
  };
59
59
 
60
+ // src/emailAttachment.ts
61
+ var EMAIL_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024;
62
+ var EMAIL_ATTACHMENT_MAX_COUNT = 10;
63
+ function checkEmailAttachment(attachment) {
64
+ if (!attachment.filename.trim()) return "ATTACHMENT_FILENAME_EMPTY";
65
+ if (/[/\\]|\.\./.test(attachment.filename)) return "ATTACHMENT_FILENAME_UNSAFE";
66
+ if (!attachment.contentType.trim()) return "ATTACHMENT_CONTENT_TYPE_EMPTY";
67
+ if (!attachment.url.startsWith("https://")) return "ATTACHMENT_URL_NOT_HTTPS";
68
+ return void 0;
69
+ }
70
+ __name(checkEmailAttachment, "checkEmailAttachment");
71
+
60
72
  // src/schemas.ts
61
73
  import { z } from "zod";
62
74
  var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
@@ -93,6 +105,14 @@ var preferenceEntrySchema = z.object({
93
105
  var updatePreferencesSchema = z.object({
94
106
  preferences: z.array(preferenceEntrySchema).max(200)
95
107
  });
108
+ var categoryPolicyEntrySchema = z.object({
109
+ category: z.string().min(1).max(64),
110
+ channel: z.nativeEnum(NOTIFICATION_CHANNEL),
111
+ enabled: z.boolean()
112
+ });
113
+ var updateCategoryPoliciesSchema = z.object({
114
+ policies: z.array(categoryPolicyEntrySchema).max(500)
115
+ });
96
116
  var upsertTemplateSchema = z.object({
97
117
  key: z.string().min(1).max(128),
98
118
  channel: z.nativeEnum(NOTIFICATION_CHANNEL),
@@ -159,7 +179,38 @@ var NOTIFICATION_ERROR_CODES = {
159
179
  DUPLICATE_WEBHOOK_DELIVERY: "NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY",
160
180
  DEVICE_NOT_FOUND: "NOTIFICATION_DEVICE_NOT_FOUND",
161
181
  THROTTLED: "NOTIFICATION_THROTTLED",
162
- CONFIG_MISSING: "NOTIFICATION_CONFIG_MISSING"
182
+ CONFIG_MISSING: "NOTIFICATION_CONFIG_MISSING",
183
+ TEMPLATE_UNKNOWN_VARIABLE: "NOTIFICATION_TEMPLATE_UNKNOWN_VARIABLE"
184
+ };
185
+ var TemplateIdNotFoundError = class extends NotificationError {
186
+ static {
187
+ __name(this, "TemplateIdNotFoundError");
188
+ }
189
+ templateId;
190
+ constructor(templateId) {
191
+ super(`Template n\xE3o encontrado.`, 404, NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND, {
192
+ templateId
193
+ }), this.templateId = templateId;
194
+ }
195
+ };
196
+ var UnknownTemplateVariablesError = class extends NotificationError {
197
+ static {
198
+ __name(this, "UnknownTemplateVariablesError");
199
+ }
200
+ templateKey;
201
+ fields;
202
+ constructor(templateKey, fields) {
203
+ super(`O template usa vari\xE1veis que n\xE3o existem no cat\xE1logo desta notifica\xE7\xE3o.`, 400, NOTIFICATION_ERROR_CODES.TEMPLATE_UNKNOWN_VARIABLE, {
204
+ templateKey,
205
+ fields: [
206
+ ...fields
207
+ ],
208
+ details: fields.map((field) => ({
209
+ field,
210
+ message: "vari\xE1vel desconhecida"
211
+ }))
212
+ }), this.templateKey = templateKey, this.fields = fields;
213
+ }
163
214
  };
164
215
  var TemplateNotFoundError = class extends NotificationError {
165
216
  static {
@@ -362,6 +413,67 @@ function createWhatsAppDriverFromChannel(channel) {
362
413
  }
363
414
  __name(createWhatsAppDriverFromChannel, "createWhatsAppDriverFromChannel");
364
415
 
416
+ // src/previewViewport.ts
417
+ var PREVIEW_VIEWPORT = {
418
+ DESKTOP: "desktop",
419
+ MOBILE: "mobile"
420
+ };
421
+ var MOBILE = {
422
+ viewport: PREVIEW_VIEWPORT.MOBILE,
423
+ width: 375
424
+ };
425
+ var PREVIEW_VIEWPORT_BY_CHANNEL = {
426
+ [NOTIFICATION_CHANNEL.EMAIL]: [
427
+ {
428
+ viewport: PREVIEW_VIEWPORT.DESKTOP,
429
+ width: 600
430
+ },
431
+ MOBILE
432
+ ],
433
+ [NOTIFICATION_CHANNEL.PUSH]: [
434
+ {
435
+ viewport: PREVIEW_VIEWPORT.DESKTOP,
436
+ width: 360
437
+ },
438
+ MOBILE
439
+ ],
440
+ [NOTIFICATION_CHANNEL.WHATSAPP]: [
441
+ {
442
+ viewport: PREVIEW_VIEWPORT.DESKTOP,
443
+ width: 400
444
+ },
445
+ MOBILE
446
+ ],
447
+ [NOTIFICATION_CHANNEL.INBOX]: [
448
+ {
449
+ viewport: PREVIEW_VIEWPORT.DESKTOP,
450
+ width: 480
451
+ },
452
+ MOBILE
453
+ ],
454
+ [NOTIFICATION_CHANNEL.SMS]: [
455
+ MOBILE
456
+ ]
457
+ };
458
+ var TEMPLATE_CONSTRAINTS_BY_CHANNEL = {
459
+ [NOTIFICATION_CHANNEL.EMAIL]: {
460
+ title: 78
461
+ },
462
+ [NOTIFICATION_CHANNEL.PUSH]: {
463
+ title: 65,
464
+ body: 240
465
+ },
466
+ [NOTIFICATION_CHANNEL.WHATSAPP]: {
467
+ body: 1024
468
+ },
469
+ [NOTIFICATION_CHANNEL.INBOX]: {
470
+ title: 120
471
+ },
472
+ [NOTIFICATION_CHANNEL.SMS]: {
473
+ body: 160
474
+ }
475
+ };
476
+
365
477
  // src/templateRender.ts
366
478
  var PLACEHOLDER_PATTERN = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
367
479
  var DEFAULT_TITLE_MAX_LENGTH = 120;
@@ -398,20 +510,90 @@ function extractTemplatePlaceholders(template) {
398
510
  ];
399
511
  }
400
512
  __name(extractTemplatePlaceholders, "extractTemplatePlaceholders");
513
+ function sanitizeTitle(title) {
514
+ return title.replace(/[\r\n]+/g, " ").trim();
515
+ }
516
+ __name(sanitizeTitle, "sanitizeTitle");
517
+ function checkConstraints(params) {
518
+ const limits = TEMPLATE_CONSTRAINTS_BY_CHANNEL[params.channel];
519
+ if (!limits) return [];
520
+ const checks = [];
521
+ const values = {
522
+ title: params.title,
523
+ body: params.body
524
+ };
525
+ for (const field of [
526
+ "title",
527
+ "body"
528
+ ]) {
529
+ const limit = limits[field];
530
+ if (limit === void 0) continue;
531
+ const actual = values[field].length;
532
+ checks.push({
533
+ field,
534
+ limit,
535
+ actual,
536
+ exceeded: actual > limit
537
+ });
538
+ }
539
+ return checks;
540
+ }
541
+ __name(checkConstraints, "checkConstraints");
401
542
  function renderTemplate(params) {
402
543
  const body = interpolateTemplate(params.body, params.payload);
403
- const title = params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body);
404
- if (params.channel !== "email") return {
544
+ const title = sanitizeTitle(params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body));
545
+ const constraints = checkConstraints({
546
+ channel: params.channel,
405
547
  title,
406
548
  body
549
+ });
550
+ if (params.channel !== "email") return {
551
+ title,
552
+ body,
553
+ constraints
407
554
  };
408
555
  return {
409
556
  title,
410
557
  body,
558
+ constraints,
411
559
  html: escapeTemplateHtml(body).replace(/\n/g, "<br>")
412
560
  };
413
561
  }
414
562
  __name(renderTemplate, "renderTemplate");
563
+
564
+ // src/templateVariables.ts
565
+ var TEMPLATE_VARIABLE_KIND = {
566
+ TEXT: "text",
567
+ ATTACHMENT: "attachment"
568
+ };
569
+ function diffTemplateVariables(params) {
570
+ const used = extractTemplatePlaceholders(`${params.subject ?? ""}
571
+ ${params.body}`);
572
+ if (!params.variables) return {
573
+ used,
574
+ unknown: [],
575
+ missingRequired: [],
576
+ attachmentsInText: []
577
+ };
578
+ const declared = new Set(params.variables.map((variable) => variable.name));
579
+ const usedSet = new Set(used);
580
+ const attachments = new Set(params.variables.filter((variable) => variable.kind === TEMPLATE_VARIABLE_KIND.ATTACHMENT).map((variable) => variable.name));
581
+ return {
582
+ used,
583
+ unknown: used.filter((name) => !declared.has(name)),
584
+ missingRequired: params.variables.filter((variable) => variable.required && variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT && !usedSet.has(variable.name)).map((variable) => variable.name),
585
+ attachmentsInText: used.filter((name) => attachments.has(name))
586
+ };
587
+ }
588
+ __name(diffTemplateVariables, "diffTemplateVariables");
589
+ function buildPreviewPayload(variables) {
590
+ if (!variables) return {};
591
+ return Object.fromEntries(variables.filter((variable) => variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT).map((variable) => [
592
+ variable.name,
593
+ variable.example
594
+ ]));
595
+ }
596
+ __name(buildPreviewPayload, "buildPreviewPayload");
415
597
  export {
416
598
  ChannelNotConfiguredError,
417
599
  ConfigMissingError,
@@ -419,6 +601,8 @@ export {
419
601
  DEVICE_PLATFORM,
420
602
  DeviceNotFoundError,
421
603
  DuplicateWebhookDeliveryError,
604
+ EMAIL_ATTACHMENT_MAX_BYTES,
605
+ EMAIL_ATTACHMENT_MAX_COUNT,
422
606
  EMAIL_DRIVER,
423
607
  INTRUSIVE_CHANNELS,
424
608
  InvalidWebhookSignatureError,
@@ -429,15 +613,25 @@ export {
429
613
  NOTIFICATION_STATUS,
430
614
  NotificationError,
431
615
  NotificationNotFoundError,
616
+ PREVIEW_VIEWPORT,
617
+ PREVIEW_VIEWPORT_BY_CHANNEL,
432
618
  PUSH_DRIVER,
433
619
  RecipientUnresolvedError,
434
620
  SUPPRESSION_REASON,
435
621
  SuppressedTargetError,
622
+ TEMPLATE_CONSTRAINTS_BY_CHANNEL,
623
+ TEMPLATE_VARIABLE_KIND,
624
+ TemplateIdNotFoundError,
436
625
  TemplateNotFoundError,
437
626
  ThrottledError,
627
+ UnknownTemplateVariablesError,
628
+ buildPreviewPayload,
629
+ categoryPolicyEntrySchema,
630
+ checkEmailAttachment,
438
631
  createWhatsAppDriverFromChannel,
439
632
  deliveryWebhookSchema,
440
633
  deriveTitleFromBody,
634
+ diffTemplateVariables,
441
635
  escapeTemplateHtml,
442
636
  extractTemplatePlaceholders,
443
637
  interpolateTemplate,
@@ -446,6 +640,7 @@ export {
446
640
  registerDeviceSchema,
447
641
  renderTemplate,
448
642
  sendNotificationSchema,
643
+ updateCategoryPoliciesSchema,
449
644
  updatePreferencesSchema,
450
645
  upsertTemplateSchema
451
646
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/notification.types.ts","../src/schemas.ts","../src/events.ts","../src/errors.ts","../src/whatsappDriver.ts","../src/templateRender.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport const NOTIFICATION_CHANNEL = {\n INBOX: 'inbox',\n PUSH: 'push',\n EMAIL: 'email',\n WHATSAPP: 'whatsapp',\n SMS: 'sms',\n} as const\nexport type NotificationChannel = (typeof NOTIFICATION_CHANNEL)[keyof typeof NOTIFICATION_CHANNEL]\n\n/** Canais que interrompem o destinatário e por isso respeitam quiet hours (ver spec §10.4). */\nexport const INTRUSIVE_CHANNELS: readonly NotificationChannel[] = [\n NOTIFICATION_CHANNEL.PUSH,\n NOTIFICATION_CHANNEL.WHATSAPP,\n NOTIFICATION_CHANNEL.SMS,\n]\n\nexport const NOTIFICATION_STATUS = {\n PENDING: 'pending',\n SCHEDULED: 'scheduled',\n QUEUED: 'queued',\n DISPATCHED: 'dispatched',\n PARTIALLY_FAILED: 'partially_failed',\n FAILED: 'failed',\n} as const\nexport type NotificationStatus = (typeof NOTIFICATION_STATUS)[keyof typeof NOTIFICATION_STATUS]\n\nexport const DELIVERY_STATUS = {\n QUEUED: 'queued',\n SENT: 'sent',\n DELIVERED: 'delivered',\n FAILED: 'failed',\n BOUNCED: 'bounced',\n SKIPPED: 'skipped',\n} as const\nexport type DeliveryStatus = (typeof DELIVERY_STATUS)[keyof typeof DELIVERY_STATUS]\n\nexport const DEVICE_PLATFORM = {\n IOS: 'ios',\n ANDROID: 'android',\n WEB: 'web',\n} as const\nexport type DevicePlatform = (typeof DEVICE_PLATFORM)[keyof typeof DEVICE_PLATFORM]\n\nexport const PUSH_DRIVER = {\n EXPO: 'expo',\n FCM: 'fcm',\n} as const\nexport type PushDriver = (typeof PUSH_DRIVER)[keyof typeof PUSH_DRIVER]\n\nexport const EMAIL_DRIVER = {\n SMTP: 'smtp',\n RESEND: 'resend',\n SES: 'ses',\n} as const\nexport type EmailDriver = (typeof EMAIL_DRIVER)[keyof typeof EMAIL_DRIVER]\n\nexport const SUPPRESSION_REASON = {\n BOUNCE: 'bounce',\n COMPLAINT: 'complaint',\n OPT_OUT: 'opt_out',\n} as const\nexport type SuppressionReason = (typeof SUPPRESSION_REASON)[keyof typeof SUPPRESSION_REASON]\n\n/**\n * Sugestão de nomenclatura, sem valor normativo (decisão Q2 da spec). `category` é `varchar`\n * livre porque é vocabulário de negócio do produto — fechá-la num enum aqui obrigaria uma major\n * do pacote a cada produto novo.\n */\nexport const NOTIFICATION_CATEGORY_HINT = {\n ORDER_STATUS: 'order_status',\n PAYMENT: 'payment',\n SECURITY: 'security',\n MARKETING: 'marketing',\n SYSTEM: 'system',\n} as const\n\nexport type NotificationId = string\nexport type CompanyId = string\nexport type UserId = string\n\nexport type NotificationSummary = {\n readonly id: NotificationId\n readonly category: string\n readonly templateKey: string\n readonly title: string\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n readonly status: NotificationStatus\n readonly scheduledFor?: string\n readonly readAt?: string\n readonly createdAt: string\n}\n\nexport type DeliverySummary = {\n readonly id: string\n readonly notificationId: NotificationId\n readonly channel: NotificationChannel\n readonly driver?: string\n /** Nunca o endereço em claro: `****1234`, `a***@dominio.com` (LGPD — ver spec §5). */\n readonly targetMasked?: string\n readonly status: DeliveryStatus\n readonly attempt: number\n readonly providerMessageId?: string\n readonly errorCode?: string\n readonly sentAt?: string\n readonly deliveredAt?: string\n readonly failedAt?: string\n}\n\nexport type DeviceRegistration = {\n readonly id: string\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n readonly lastSeenAt: string\n readonly disabledAt?: string\n readonly disabledReason?: string\n}\n\nexport type NotificationPreference = {\n readonly category: string\n readonly channel: NotificationChannel\n readonly enabled: boolean\n /** `HH:mm` no timezone resolvido para o destinatário; ambos ausentes = sem janela de silêncio. */\n readonly quietHoursStart?: string\n readonly quietHoursEnd?: string\n readonly timezone?: string\n}\n\nexport type NotificationTemplate = {\n readonly id: string\n readonly key: string\n readonly channel: NotificationChannel\n readonly locale: string\n readonly version: number\n readonly subject?: string\n readonly body: string\n /**\n * Nome do template aprovado na Meta. Sem ele, o canal WhatsApp é pulado fora da janela de 24 h\n * em vez de estourar erro na cara do usuário (spec §10.7).\n */\n readonly whatsappTemplateName?: string\n readonly active: boolean\n}\n\nexport type SendNotificationParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n readonly payload?: Readonly<Record<string, unknown>>\n /** Sem canais explícitos, o fan-out resolve pelas preferências do destinatário. */\n readonly channels?: readonly NotificationChannel[]\n /** Chave de negócio da entrega. Repetição devolve a notificação existente, não uma nova. */\n readonly dedupeKey?: string\n readonly scheduledFor?: Date\n readonly locale?: string\n}\n\nexport type SendNotificationResult = {\n readonly notificationId: NotificationId\n /** `true` quando um `dedupeKey` já visto devolveu a notificação anterior — nada foi reenviado. */\n readonly deduplicated: boolean\n readonly deliveries: readonly DeliverySummary[]\n}\n\nexport type ListNotificationsParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsResult = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type DeliveryReceipt = {\n readonly providerMessageId: string\n readonly status: Extract<DeliveryStatus, 'delivered' | 'bounced' | 'failed'>\n readonly errorCode?: string\n readonly occurredAt: Date\n readonly suppressionReason?: SuppressionReason\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { z } from 'zod'\n\nimport { DEVICE_PLATFORM, NOTIFICATION_CHANNEL, PUSH_DRIVER, SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Schemas de fronteira. Regra que atravessa todos eles: **`companyId` nunca vem do corpo da\n * requisição** — é derivado do contexto autenticado (`database.md`, \"Consistência e\n * multiempresa\"). Aceitá-lo aqui seria entregar o isolamento multiempresa ao cliente.\n */\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/\nconst MAX_PER_PAGE = 100\n\nconst quietHoursShape = {\n quietHoursStart: z.string().regex(HHMM, 'Use HH:mm').optional(),\n quietHoursEnd: z.string().regex(HHMM, 'Use HH:mm').optional(),\n timezone: z.string().min(1).optional(),\n}\n\nexport const sendNotificationSchema = z.object({\n recipientUserId: z.string().uuid(),\n category: z.string().min(1).max(64),\n templateKey: z.string().min(1).max(128),\n payload: z.record(z.unknown()).optional(),\n channels: z.array(z.nativeEnum(NOTIFICATION_CHANNEL)).nonempty().optional(),\n dedupeKey: z.string().min(1).max(256).optional(),\n scheduledFor: z.coerce.date().optional(),\n locale: z.string().min(2).max(16).optional(),\n})\nexport type SendNotificationBody = z.infer<typeof sendNotificationSchema>\n\nexport const registerDeviceSchema = z.object({\n platform: z.nativeEnum(DEVICE_PLATFORM),\n driver: z.nativeEnum(PUSH_DRIVER),\n token: z.string().min(1).max(4096),\n appVersion: z.string().max(32).optional(),\n locale: z.string().min(2).max(16).optional(),\n timezone: z.string().min(1).max(64).optional(),\n})\nexport type RegisterDeviceBody = z.infer<typeof registerDeviceSchema>\n\nexport const preferenceEntrySchema = z.object({\n category: z.string().min(1).max(64),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n enabled: z.boolean(),\n ...quietHoursShape,\n})\n\nexport const updatePreferencesSchema = z.object({\n preferences: z.array(preferenceEntrySchema).max(200),\n})\nexport type UpdatePreferencesBody = z.infer<typeof updatePreferencesSchema>\n\nexport const upsertTemplateSchema = z.object({\n key: z.string().min(1).max(128),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n locale: z.string().min(2).max(16),\n subject: z.string().max(256).optional(),\n body: z.string().min(1).max(8192),\n whatsappTemplateName: z.string().max(128).optional(),\n active: z.boolean().default(true),\n})\nexport type UpsertTemplateBody = z.infer<typeof upsertTemplateSchema>\n\n/** Query string chega sempre como texto — daí o `coerce` e o booleano por literal. */\nexport const listNotificationsQuerySchema = z.object({\n category: z.string().min(1).max(64).optional(),\n read: z\n .enum(['true', 'false'])\n .transform((value) => value === 'true')\n .optional(),\n cursor: z.string().max(512).optional(),\n perPage: z.coerce.number().int().min(1).max(MAX_PER_PAGE).default(20),\n})\nexport type ListNotificationsQuery = z.infer<typeof listNotificationsQuerySchema>\n\n/**\n * Forma normalizada do recibo de entrega, depois que o parser do driver traduziu o payload do\n * provedor. A verificação de assinatura acontece antes disto, sobre o `rawBody`.\n */\nexport const deliveryWebhookSchema = z.object({\n providerMessageId: z.string().min(1),\n status: z.enum(['delivered', 'bounced', 'failed']),\n errorCode: z.string().max(64).optional(),\n occurredAt: z.coerce.date(),\n suppressionReason: z.nativeEnum(SUPPRESSION_REASON).optional(),\n})\nexport type DeliveryWebhookBody = z.infer<typeof deliveryWebhookSchema>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type {\n CompanyId,\n DevicePlatform,\n NotificationChannel,\n NotificationId,\n NotificationStatus,\n PushDriver,\n SuppressionReason,\n UserId,\n} from './notification.types'\n\n/**\n * Eventos de domínio — os pontos de extensão do produto. É aqui que entra a regra de negócio que\n * o módulo não pode ter (ex.: bounce de e-mail marca o contato como inválido no CRM), sem\n * ninguém editar código do pacote (regra de módulos plugáveis, §3).\n */\nexport const NOTIFICATION_EVENT = {\n CREATED: 'notification.created',\n DISPATCHED: 'notification.dispatched',\n READ: 'notification.read',\n DELIVERY_SENT: 'delivery.sent',\n DELIVERY_FAILED: 'delivery.failed',\n DELIVERY_BOUNCED: 'delivery.bounced',\n DEVICE_REGISTERED: 'device.registered',\n DEVICE_INVALIDATED: 'device.invalidated',\n PREFERENCES_UPDATED: 'preferences.updated',\n} as const\nexport type NotificationEvent = (typeof NOTIFICATION_EVENT)[keyof typeof NOTIFICATION_EVENT]\n\ntype BaseEvent = {\n readonly companyId: CompanyId\n readonly occurredAt: Date\n}\n\nexport type NotificationCreatedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n /** Canais que sobreviveram ao fan-out; os pulados aparecem em `skippedChannels`. */\n readonly channels: readonly NotificationChannel[]\n readonly skippedChannels: readonly { readonly channel: NotificationChannel; readonly reason: string }[]\n}\n\nexport type NotificationDispatchedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly status: NotificationStatus\n}\n\nexport type NotificationReadEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n}\n\nexport type DeliverySentEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly providerMessageId?: string\n readonly attempt: number\n}\n\nexport type DeliveryFailedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly errorCode: string\n readonly attempt: number\n /** `false` quando o retry esgotou ou o erro é permanente — é o gancho para alerta do host. */\n readonly willRetry: boolean\n}\n\nexport type DeliveryBouncedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly reason: SuppressionReason\n}\n\nexport type DeviceRegisteredEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n}\n\nexport type DeviceInvalidatedEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly driver: PushDriver\n readonly errorCode: string\n}\n\nexport type PreferencesUpdatedEvent = BaseEvent & {\n readonly userId: UserId\n readonly categories: readonly string[]\n}\n\n/**\n * Hooks são `void`-tolerantes de propósito: falha de hook do produto não pode derrubar a entrega\n * da notificação. O módulo loga e segue — quem precisa de garantia transacional usa a fila.\n */\nexport type NotificationHooks = {\n onNotificationCreated?(event: NotificationCreatedEvent): Promise<void> | void\n onNotificationDispatched?(event: NotificationDispatchedEvent): Promise<void> | void\n onNotificationRead?(event: NotificationReadEvent): Promise<void> | void\n onDeliverySent?(event: DeliverySentEvent): Promise<void> | void\n onDeliveryFailed?(event: DeliveryFailedEvent): Promise<void> | void\n onDeliveryBounced?(event: DeliveryBouncedEvent): Promise<void> | void\n onDeviceRegistered?(event: DeviceRegisteredEvent): Promise<void> | void\n onDeviceInvalidated?(event: DeviceInvalidatedEvent): Promise<void> | void\n onPreferencesUpdated?(event: PreferencesUpdatedEvent): Promise<void> | void\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { NotificationChannel } from './notification.types'\n\n/**\n * Hierarquia autocontida: um pacote publicado não importa o `DomainError` do host. O host mapeia\n * estes erros no seu exception filter — e o próprio módulo já traz um, para o consumidor das rotas\n * não precisar escrever `try/catch` por endpoint.\n */\nexport class NotificationError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message)\n this.name = 'NotificationError'\n }\n}\n\nexport const NOTIFICATION_ERROR_CODES = {\n TEMPLATE_NOT_FOUND: 'NOTIFICATION_TEMPLATE_NOT_FOUND',\n CHANNEL_NOT_CONFIGURED: 'NOTIFICATION_CHANNEL_NOT_CONFIGURED',\n RECIPIENT_UNRESOLVED: 'NOTIFICATION_RECIPIENT_UNRESOLVED',\n SUPPRESSED_TARGET: 'NOTIFICATION_SUPPRESSED_TARGET',\n NOT_FOUND: 'NOTIFICATION_NOT_FOUND',\n INVALID_WEBHOOK_SIGNATURE: 'NOTIFICATION_INVALID_WEBHOOK_SIGNATURE',\n DUPLICATE_WEBHOOK_DELIVERY: 'NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY',\n DEVICE_NOT_FOUND: 'NOTIFICATION_DEVICE_NOT_FOUND',\n THROTTLED: 'NOTIFICATION_THROTTLED',\n CONFIG_MISSING: 'NOTIFICATION_CONFIG_MISSING',\n} as const\n\nexport class TemplateNotFoundError extends NotificationError {\n constructor(\n public readonly templateKey: string,\n public readonly channel: NotificationChannel,\n public readonly locale: string,\n ) {\n super(\n `Template não encontrado para a chave informada neste canal e locale.`,\n 404,\n NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND,\n { templateKey, channel, locale },\n )\n }\n}\n\n/** Canal ligado em `features` sem driver injetado — erro de composição, detectado no boot. */\nexport class ChannelNotConfiguredError extends NotificationError {\n constructor(public readonly channel: NotificationChannel) {\n super(\n `Canal habilitado sem driver injetado — injete o driver em providers.channels ou desligue a feature.`,\n 500,\n NOTIFICATION_ERROR_CODES.CHANNEL_NOT_CONFIGURED,\n { channel },\n )\n }\n}\n\n/**\n * `RecipientResolverPort` não devolveu endereço para o canal. Mensagem sem PII de propósito: o\n * `userId` é identificador opaco, o e-mail ou telefone jamais entra no erro (`security.md` §1).\n */\nexport class RecipientUnresolvedError extends NotificationError {\n constructor(\n public readonly userId: string,\n public readonly channel: NotificationChannel,\n ) {\n super(`Destinatário sem endereço utilizável para este canal.`, 422, NOTIFICATION_ERROR_CODES.RECIPIENT_UNRESOLVED, {\n userId,\n channel,\n })\n }\n}\n\nexport class SuppressedTargetError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly reason: string,\n ) {\n super(`Endereço suprimido para este canal — envio bloqueado.`, 409, NOTIFICATION_ERROR_CODES.SUPPRESSED_TARGET, {\n channel,\n reason,\n })\n }\n}\n\n/**\n * Também é a resposta para notificação de OUTRO usuário: devolver 404 em vez de 403 não revela a\n * existência do recurso a quem não pode vê-lo (BOLA/API1).\n */\nexport class NotificationNotFoundError extends NotificationError {\n constructor(public readonly notificationId: string) {\n super(`Notificação não encontrada.`, 404, NOTIFICATION_ERROR_CODES.NOT_FOUND, { notificationId })\n }\n}\n\nexport class InvalidWebhookSignatureError extends NotificationError {\n constructor() {\n super(`Assinatura do webhook inválida.`, 401, NOTIFICATION_ERROR_CODES.INVALID_WEBHOOK_SIGNATURE)\n }\n}\n\n/** Recibo reenviado dentro da janela de replay (nonce já visto) — não é erro, é ruído esperado. */\nexport class DuplicateWebhookDeliveryError extends NotificationError {\n constructor(public readonly nonce: string) {\n super(`Entrega de webhook duplicada.`, 200, NOTIFICATION_ERROR_CODES.DUPLICATE_WEBHOOK_DELIVERY, { nonce })\n }\n}\n\nexport class DeviceNotFoundError extends NotificationError {\n constructor(public readonly deviceId: string) {\n super(`Dispositivo não encontrado.`, 404, NOTIFICATION_ERROR_CODES.DEVICE_NOT_FOUND, { deviceId })\n }\n}\n\nexport class ThrottledError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly retryAfterSeconds: number,\n ) {\n super(`Limite de envios para este destinatário atingido.`, 429, NOTIFICATION_ERROR_CODES.THROTTLED, {\n channel,\n retryAfterSeconds,\n })\n }\n}\n\n/**\n * Configuração obrigatória ausente (chave de HMAC, segredo de webhook) — falha no boot.\n *\n * Único erro do módulo cuja mensagem nomeia o campo: ele é lido por quem está subindo o serviço,\n * não devolvido a um cliente, e \"algo está faltando\" sem dizer o quê custa uma bisca no código.\n * O nome do campo é identificador de configuração, nunca valor — o segredo em si não aparece.\n */\nexport class ConfigMissingError extends NotificationError {\n constructor(public readonly field: string) {\n super(`Configuração obrigatória ausente: ${field}.`, 500, NOTIFICATION_ERROR_CODES.CONFIG_MISSING, { field })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { DeliveryAttemptResult, SendWhatsAppParams, WhatsAppDriverPort } from './channelDrivers'\nimport { SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Forma mínima que o `channel` do `meta-whatsapp-module` já satisfaz. Descrita aqui por\n * *estrutura*, e não importada do pacote de WhatsApp: é isso que mantém os dois trios\n * independentes — quem só usa inbox não carrega Meta, quem só usa WhatsApp não carrega\n * notificação, e a costura acontece no produto (regra de módulos plugáveis, §2).\n */\nexport type WhatsAppSendingChannel = {\n sendText(to: string, body: string): Promise<{ externalMessageId: string | null }>\n sendTemplate(params: {\n to: string\n templateName: string\n languageCode: string\n bodyParameters?: string[]\n }): Promise<{ externalMessageId: string | null }>\n}\n\n/**\n * Códigos da Graph API que o canal repassa. A lista é curta de propósito: cobre o que muda a\n * decisão do módulo (apagar destino × tentar de novo × desistir) e nada além disso.\n */\nconst INVALID_TARGET_CODES = new Set([131026, 131051])\nconst PERMANENT_CODES = new Set([131047, 131031, 368])\nconst RETRIABLE_CODES = new Set([613, 130429, 131056])\n\nfunction readNumericField(error: unknown, field: string): number | undefined {\n if (typeof error !== 'object' || error === null || !(field in error)) return undefined\n const value = (error as Record<string, unknown>)[field]\n return typeof value === 'number' ? value : undefined\n}\n\nfunction classifyError(error: unknown): DeliveryAttemptResult {\n const metaCode = readNumericField(error, 'code')\n if (metaCode !== undefined) {\n if (INVALID_TARGET_CODES.has(metaCode)) {\n return {\n outcome: 'invalid_target',\n errorCode: `meta_${metaCode}`,\n suppressionReason: SUPPRESSION_REASON.BOUNCE,\n }\n }\n if (PERMANENT_CODES.has(metaCode)) return { outcome: 'permanent', errorCode: `meta_${metaCode}` }\n if (RETRIABLE_CODES.has(metaCode)) return { outcome: 'retriable', errorCode: `meta_${metaCode}` }\n }\n\n const statusCode = readNumericField(error, 'statusCode') ?? readNumericField(error, 'status')\n if (statusCode === 429 || (statusCode !== undefined && statusCode >= 500)) {\n return { outcome: 'retriable', errorCode: `http_${statusCode}` }\n }\n if (statusCode !== undefined && statusCode >= 400) {\n return { outcome: 'permanent', errorCode: `http_${statusCode}` }\n }\n\n // Sem código nenhum é quase sempre falha de rede/DNS, que passa numa segunda tentativa. O risco\n // do palpite é limitado: o retry é finito (`attempts`) e termina em `failed` de qualquer forma.\n return { outcome: 'retriable', errorCode: 'unknown' }\n}\n\nexport function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel): WhatsAppDriverPort {\n return {\n async send(params: SendWhatsAppParams): Promise<DeliveryAttemptResult> {\n try {\n const result = params.template\n ? await channel.sendTemplate({\n to: params.to,\n templateName: params.template.templateName,\n languageCode: params.template.languageCode,\n bodyParameters: params.template.bodyParameters ? [...params.template.bodyParameters] : undefined,\n })\n : await channel.sendText(params.to, params.body)\n\n return { outcome: 'sent', providerMessageId: result.externalMessageId ?? undefined }\n } catch (error) {\n return classifyError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * A renderização default de template, pura e sem dependência.\n *\n * Mora no contracts, e não no módulo, por um motivo específico: a tela de configuração precisa\n * mostrar um PREVIEW do que o cliente vai receber, e o módulo carrega Drizzle — o frontend não pode\n * importá-lo. Reimplementar a interpolação no host resolveria hoje e divergiria amanhã, e **preview\n * que mente é pior que preview nenhum**: alguém salva o template confiando no que viu.\n *\n * Com a função aqui, o `notification-module` renderiza para enviar e a UI renderiza para mostrar,\n * lendo o MESMO código. Divergência deixa de ser possível em vez de ser improvável.\n */\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}/g\nconst DEFAULT_TITLE_MAX_LENGTH = 120\n\nconst HTML_ESCAPE_MAP: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n}\n\nexport function escapeTemplateHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (character) => HTML_ESCAPE_MAP[character] ?? character)\n}\n\n/** `{{campo}}` → valor do payload. Campo ausente vira string vazia, nunca o literal `{{campo}}`. */\nexport function interpolateTemplate(template: string, payload: Readonly<Record<string, unknown>>): string {\n return template.replace(PLACEHOLDER_PATTERN, (_match, key: string) => {\n const value = payload[key]\n return value === undefined || value === null ? '' : String(value)\n })\n}\n\nexport function deriveTitleFromBody(body: string): string {\n const firstLine = body.split('\\n')[0] ?? ''\n return firstLine.length > DEFAULT_TITLE_MAX_LENGTH ? `${firstLine.slice(0, DEFAULT_TITLE_MAX_LENGTH)}…` : firstLine\n}\n\n/** Os nomes de campo que um template referencia — o que a tela de configuração precisa pedir. */\nexport function extractTemplatePlaceholders(template: string): readonly string[] {\n const found = new Set<string>()\n for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {\n if (match[1]) found.add(match[1])\n }\n return [...found]\n}\n\nexport type RenderedTemplatePreview = {\n readonly title: string\n readonly body: string\n readonly html?: string\n}\n\n/**\n * Mesma saída que o envio produz. `channel` importa porque só e-mail ganha a versão HTML — mostrar\n * HTML no preview de WhatsApp faria a tela prometer formatação que o canal não tem.\n */\nexport function renderTemplate(params: {\n readonly channel: string\n readonly subject?: string | undefined\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n}): RenderedTemplatePreview {\n const body = interpolateTemplate(params.body, params.payload)\n const title = params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body)\n\n if (params.channel !== 'email') return { title, body }\n\n // Escapa o resultado já interpolado (texto do template e valores do payload juntos), depois troca\n // quebra de linha por <br> — quem quer HTML rico troca o renderer, em vez de descobrir por um bug\n // de escape.\n return { title, body, html: escapeTemplateHtml(body).replace(/\\n/g, '<br>') }\n}\n"],"mappings":";;;;AAIO,IAAMA,uBAAuB;EAClCC,OAAO;EACPC,MAAM;EACNC,OAAO;EACPC,UAAU;EACVC,KAAK;AACP;AAIO,IAAMC,qBAAqD;EAChEN,qBAAqBE;EACrBF,qBAAqBI;EACrBJ,qBAAqBK;;AAGhB,IAAME,sBAAsB;EACjCC,SAAS;EACTC,WAAW;EACXC,QAAQ;EACRC,YAAY;EACZC,kBAAkB;EAClBC,QAAQ;AACV;AAGO,IAAMC,kBAAkB;EAC7BJ,QAAQ;EACRK,MAAM;EACNC,WAAW;EACXH,QAAQ;EACRI,SAAS;EACTC,SAAS;AACX;AAGO,IAAMC,kBAAkB;EAC7BC,KAAK;EACLC,SAAS;EACTC,KAAK;AACP;AAGO,IAAMC,cAAc;EACzBC,MA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ILED","DELIVERY_STATUS","SENT","DELIVERED","BOUNCED","SKIPPED","DEVICE_PLATFORM","IOS","ANDROID","WEB","PUSH_DRIVER","EXPO","FCM","EMAIL_DRIVER","SMTP","RESEND","SES","SUPPRESSION_REASON","BOUNCE","COMPLAINT","OPT_OUT","NOTIFICATION_CATEGORY_HINT","ORDER_STATUS","PAYMENT","SECURITY","MARKETING","SYSTEM","z","HHMM","MAX_PER_PAGE","quietHoursShape","quietHoursStart","z","string","regex","optional","quietHoursEnd","timezone","min","sendNotificationSchema","object","recipientUserId","uuid","category","max","templateKey","payload","record","unknown","channels","array","nativeEnum","NOTIFICATION_CHANNEL","nonempty","dedupeKey","scheduledFor","coerce","date","locale","registerDeviceSchema","platform","DEVICE_PLATFORM","driver","PUSH_DRIVER","token","appVersion","preferenceEntrySchema","channel","enabled","boolean","updatePreferencesSchema","preferences","upsertTemplateSchema","key","subject","body","whatsappTemplateName","active","default","listNotificationsQuerySchema","read","enum","transform","value","cursor","perPage","number","int","deliveryWebhookSchema","providerMessageId","status","errorCode","occurredAt","suppressionReason","SUPPRESSION_REASON","NOTIFICATION_EVENT","CREATED","DISPATCHED","READ","DELIVERY_SENT","DELIVERY_FAILED","DELIVERY_BOUNCED","DEVICE_REGISTERED","DEVICE_INVALIDATED","PREFERENCES_UPDATED","NotificationError","Error","message","statusCode","code","details","name","NOTIFICATION_ERROR_CODES","TEMPLATE_NOT_FOUND","CHANNEL_NOT_CONFIGURED","RECIPIENT_UNRESOLVED","SUPPRESSED_TARGET","NOT_FOUND","INVALID_WEBHOOK_SIGNATURE","DUPLICATE_WEBHOOK_DELIVERY","DEVICE_NOT_FOUND","THROTTLED","CONFIG_MISSING","TemplateNotFoundError","templateKey","channel","locale","ChannelNotConfiguredError","RecipientUnresolvedError","userId","SuppressedTargetError","reason","NotificationNotFoundError","notificationId","InvalidWebhookSignatureError","DuplicateWebhookDeliveryError","nonce","DeviceNotFoundError","deviceId","ThrottledError","retryAfterSeconds","ConfigMissingError","field","INVALID_TARGET_CODES","Set","PERMANENT_CODES","RETRIABLE_CODES","readNumericField","error","field","undefined","value","classifyError","metaCode","has","outcome","errorCode","suppressionReason","SUPPRESSION_REASON","BOUNCE","statusCode","createWhatsAppDriverFromChannel","channel","send","params","result","template","sendTemplate","to","templateName","languageCode","bodyParameters","sendText","body","providerMessageId","externalMessageId","PLACEHOLDER_PATTERN","DEFAULT_TITLE_MAX_LENGTH","HTML_ESCAPE_MAP","escapeTemplateHtml","text","replace","character","interpolateTemplate","template","payload","_match","key","value","undefined","String","deriveTitleFromBody","body","firstLine","split","length","slice","extractTemplatePlaceholders","found","Set","match","matchAll","add","renderTemplate","params","title","subject","channel","html"]}
1
+ {"version":3,"sources":["../src/notification.types.ts","../src/emailAttachment.ts","../src/schemas.ts","../src/events.ts","../src/errors.ts","../src/whatsappDriver.ts","../src/previewViewport.ts","../src/templateRender.ts","../src/templateVariables.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport const NOTIFICATION_CHANNEL = {\n INBOX: 'inbox',\n PUSH: 'push',\n EMAIL: 'email',\n WHATSAPP: 'whatsapp',\n SMS: 'sms',\n} as const\nexport type NotificationChannel = (typeof NOTIFICATION_CHANNEL)[keyof typeof NOTIFICATION_CHANNEL]\n\n/** Canais que interrompem o destinatário e por isso respeitam quiet hours (ver spec §10.4). */\nexport const INTRUSIVE_CHANNELS: readonly NotificationChannel[] = [\n NOTIFICATION_CHANNEL.PUSH,\n NOTIFICATION_CHANNEL.WHATSAPP,\n NOTIFICATION_CHANNEL.SMS,\n]\n\n/**\n * O teto de canais da empresa por categoria, acima da preferência do usuário. Linha ausente\n * significa permitido — fechar por omissão calaria toda categoria existente.\n */\nexport type NotificationCategoryPolicy = {\n readonly category: string\n readonly channel: NotificationChannel\n readonly enabled: boolean\n}\n\nexport const NOTIFICATION_STATUS = {\n PENDING: 'pending',\n SCHEDULED: 'scheduled',\n QUEUED: 'queued',\n DISPATCHED: 'dispatched',\n PARTIALLY_FAILED: 'partially_failed',\n FAILED: 'failed',\n} as const\nexport type NotificationStatus = (typeof NOTIFICATION_STATUS)[keyof typeof NOTIFICATION_STATUS]\n\nexport const DELIVERY_STATUS = {\n QUEUED: 'queued',\n SENT: 'sent',\n DELIVERED: 'delivered',\n FAILED: 'failed',\n BOUNCED: 'bounced',\n SKIPPED: 'skipped',\n} as const\nexport type DeliveryStatus = (typeof DELIVERY_STATUS)[keyof typeof DELIVERY_STATUS]\n\nexport const DEVICE_PLATFORM = {\n IOS: 'ios',\n ANDROID: 'android',\n WEB: 'web',\n} as const\nexport type DevicePlatform = (typeof DEVICE_PLATFORM)[keyof typeof DEVICE_PLATFORM]\n\nexport const PUSH_DRIVER = {\n EXPO: 'expo',\n FCM: 'fcm',\n} as const\nexport type PushDriver = (typeof PUSH_DRIVER)[keyof typeof PUSH_DRIVER]\n\nexport const EMAIL_DRIVER = {\n SMTP: 'smtp',\n RESEND: 'resend',\n SES: 'ses',\n} as const\nexport type EmailDriver = (typeof EMAIL_DRIVER)[keyof typeof EMAIL_DRIVER]\n\nexport const SUPPRESSION_REASON = {\n BOUNCE: 'bounce',\n COMPLAINT: 'complaint',\n OPT_OUT: 'opt_out',\n} as const\nexport type SuppressionReason = (typeof SUPPRESSION_REASON)[keyof typeof SUPPRESSION_REASON]\n\n/**\n * Sugestão de nomenclatura, sem valor normativo (decisão Q2 da spec). `category` é `varchar`\n * livre porque é vocabulário de negócio do produto — fechá-la num enum aqui obrigaria uma major\n * do pacote a cada produto novo.\n */\nexport const NOTIFICATION_CATEGORY_HINT = {\n ORDER_STATUS: 'order_status',\n PAYMENT: 'payment',\n SECURITY: 'security',\n MARKETING: 'marketing',\n SYSTEM: 'system',\n} as const\n\nexport type NotificationId = string\nexport type CompanyId = string\nexport type UserId = string\n\nexport type NotificationSummary = {\n readonly id: NotificationId\n readonly category: string\n readonly templateKey: string\n readonly title: string\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n readonly status: NotificationStatus\n readonly scheduledFor?: string\n readonly readAt?: string\n readonly createdAt: string\n}\n\nexport type DeliverySummary = {\n readonly id: string\n readonly notificationId: NotificationId\n readonly channel: NotificationChannel\n readonly driver?: string\n /** Nunca o endereço em claro: `****1234`, `a***@dominio.com` (LGPD — ver spec §5). */\n readonly targetMasked?: string\n readonly status: DeliveryStatus\n readonly attempt: number\n readonly providerMessageId?: string\n readonly errorCode?: string\n readonly sentAt?: string\n readonly deliveredAt?: string\n readonly failedAt?: string\n}\n\nexport type DeviceRegistration = {\n readonly id: string\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n readonly lastSeenAt: string\n readonly disabledAt?: string\n readonly disabledReason?: string\n}\n\nexport type NotificationPreference = {\n readonly category: string\n readonly channel: NotificationChannel\n readonly enabled: boolean\n /** `HH:mm` no timezone resolvido para o destinatário; ambos ausentes = sem janela de silêncio. */\n readonly quietHoursStart?: string\n readonly quietHoursEnd?: string\n readonly timezone?: string\n}\n\nexport type NotificationTemplate = {\n readonly id: string\n readonly key: string\n readonly channel: NotificationChannel\n readonly locale: string\n readonly version: number\n readonly subject?: string\n readonly body: string\n /**\n * Nome do template aprovado na Meta. Sem ele, o canal WhatsApp é pulado fora da janela de 24 h\n * em vez de estourar erro na cara do usuário (spec §10.7).\n */\n readonly whatsappTemplateName?: string\n readonly active: boolean\n}\n\nexport type SendNotificationParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n readonly payload?: Readonly<Record<string, unknown>>\n /** Sem canais explícitos, o fan-out resolve pelas preferências do destinatário. */\n readonly channels?: readonly NotificationChannel[]\n /** Chave de negócio da entrega. Repetição devolve a notificação existente, não uma nova. */\n readonly dedupeKey?: string\n readonly scheduledFor?: Date\n readonly locale?: string\n}\n\nexport type SendNotificationResult = {\n readonly notificationId: NotificationId\n /** `true` quando um `dedupeKey` já visto devolveu a notificação anterior — nada foi reenviado. */\n readonly deduplicated: boolean\n readonly deliveries: readonly DeliverySummary[]\n}\n\nexport type ListNotificationsParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsResult = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type DeliveryReceipt = {\n readonly providerMessageId: string\n readonly status: Extract<DeliveryStatus, 'delivered' | 'bounced' | 'failed'>\n readonly errorCode?: string\n readonly occurredAt: Date\n readonly suppressionReason?: SuppressionReason\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Anexo de e-mail — por REFERÊNCIA, nunca por conteúdo.\n *\n * O template é linha versionada no Postgres e o job é payload no Redis. Um PDF em qualquer um dos\n * dois é blob replicado a cada versão e a cada tentativa, e uma nota fiscal é dado pessoal — o\n * `security.md` §6 já manda o payload de fila carregar referência, e o §7 manda entregar arquivo por\n * URL assinada de vida curta. Anexo segue a mesma regra: o que trafega é onde o arquivo está.\n *\n * Quem baixa é o DRIVER, no momento do envio, e é ele que aplica o teto de tamanho. Baixar antes\n * (no módulo) seria carregar bytes na memória de um processo que pode nem chegar a enviar.\n */\n\n/**\n * 25MB é o teto prático: Gmail e Outlook recusam acima disso, e o SES conta o MIME inteiro já em\n * base64 — que infla ~33%. O driver reprova ANTES de montar a mensagem, senão o erro vem do\n * provedor como uma falha genérica de envio.\n */\nexport const EMAIL_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024\n\n/** Um e-mail com trinta anexos é engano de laço, não um caso de uso. */\nexport const EMAIL_ATTACHMENT_MAX_COUNT = 10\n\nexport type EmailAttachment = {\n /** O nome que o destinatário vê. Sem caminho: `../` num nome de anexo é travessia de diretório. */\n readonly filename: string\n /**\n * URL de onde o driver baixa no momento do envio. Assinada e de vida curta quando o arquivo for\n * privado — o driver não autentica, ele só faz `GET`.\n */\n readonly url: string\n /** Declarado pelo produto, e não adivinhado da extensão: extensão mente, e cliente de e-mail confia. */\n readonly contentType: string\n}\n\n/**\n * Recusa o que não pode virar anexo antes de qualquer rede.\n *\n * Devolve o motivo em vez de lançar: o chamador é um driver, e uma tentativa de entrega registra o\n * porquê da recusa na `delivery` — `throw` viraria erro genérico e o operador ficaria sem a causa.\n */\nexport function checkEmailAttachment(attachment: EmailAttachment): string | undefined {\n if (!attachment.filename.trim()) return 'ATTACHMENT_FILENAME_EMPTY'\n\n // Travessia de diretório: o nome vai para o cabeçalho MIME e, do outro lado, para o disco de quem\n // salva. `/`, `\\` e `..` não têm por que existir num nome de arquivo anexado.\n if (/[/\\\\]|\\.\\./.test(attachment.filename)) return 'ATTACHMENT_FILENAME_UNSAFE'\n\n if (!attachment.contentType.trim()) return 'ATTACHMENT_CONTENT_TYPE_EMPTY'\n\n // Só `https`: `file:`, `data:` e `http:` puxariam do disco do servidor, inflariam a mensagem ou\n // trafegariam um documento pessoal em claro.\n if (!attachment.url.startsWith('https://')) return 'ATTACHMENT_URL_NOT_HTTPS'\n\n return undefined\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { z } from 'zod'\n\nimport { DEVICE_PLATFORM, NOTIFICATION_CHANNEL, PUSH_DRIVER, SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Schemas de fronteira. Regra que atravessa todos eles: **`companyId` nunca vem do corpo da\n * requisição** — é derivado do contexto autenticado (`database.md`, \"Consistência e\n * multiempresa\"). Aceitá-lo aqui seria entregar o isolamento multiempresa ao cliente.\n */\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/\nconst MAX_PER_PAGE = 100\n\nconst quietHoursShape = {\n quietHoursStart: z.string().regex(HHMM, 'Use HH:mm').optional(),\n quietHoursEnd: z.string().regex(HHMM, 'Use HH:mm').optional(),\n timezone: z.string().min(1).optional(),\n}\n\nexport const sendNotificationSchema = z.object({\n recipientUserId: z.string().uuid(),\n category: z.string().min(1).max(64),\n templateKey: z.string().min(1).max(128),\n payload: z.record(z.unknown()).optional(),\n channels: z.array(z.nativeEnum(NOTIFICATION_CHANNEL)).nonempty().optional(),\n dedupeKey: z.string().min(1).max(256).optional(),\n scheduledFor: z.coerce.date().optional(),\n locale: z.string().min(2).max(16).optional(),\n})\nexport type SendNotificationBody = z.infer<typeof sendNotificationSchema>\n\nexport const registerDeviceSchema = z.object({\n platform: z.nativeEnum(DEVICE_PLATFORM),\n driver: z.nativeEnum(PUSH_DRIVER),\n token: z.string().min(1).max(4096),\n appVersion: z.string().max(32).optional(),\n locale: z.string().min(2).max(16).optional(),\n timezone: z.string().min(1).max(64).optional(),\n})\nexport type RegisterDeviceBody = z.infer<typeof registerDeviceSchema>\n\nexport const preferenceEntrySchema = z.object({\n category: z.string().min(1).max(64),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n enabled: z.boolean(),\n ...quietHoursShape,\n})\n\nexport const updatePreferencesSchema = z.object({\n preferences: z.array(preferenceEntrySchema).max(200),\n})\nexport type UpdatePreferencesBody = z.infer<typeof updatePreferencesSchema>\n\nexport const categoryPolicyEntrySchema = z.object({\n category: z.string().min(1).max(64),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n enabled: z.boolean(),\n})\n\nexport const updateCategoryPoliciesSchema = z.object({\n policies: z.array(categoryPolicyEntrySchema).max(500),\n})\nexport type UpdateCategoryPoliciesBody = z.infer<typeof updateCategoryPoliciesSchema>\n\nexport const upsertTemplateSchema = z.object({\n key: z.string().min(1).max(128),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n locale: z.string().min(2).max(16),\n subject: z.string().max(256).optional(),\n body: z.string().min(1).max(8192),\n whatsappTemplateName: z.string().max(128).optional(),\n active: z.boolean().default(true),\n})\nexport type UpsertTemplateBody = z.infer<typeof upsertTemplateSchema>\n\n/** Query string chega sempre como texto — daí o `coerce` e o booleano por literal. */\nexport const listNotificationsQuerySchema = z.object({\n category: z.string().min(1).max(64).optional(),\n read: z\n .enum(['true', 'false'])\n .transform((value) => value === 'true')\n .optional(),\n cursor: z.string().max(512).optional(),\n perPage: z.coerce.number().int().min(1).max(MAX_PER_PAGE).default(20),\n})\nexport type ListNotificationsQuery = z.infer<typeof listNotificationsQuerySchema>\n\n/**\n * Forma normalizada do recibo de entrega, depois que o parser do driver traduziu o payload do\n * provedor. A verificação de assinatura acontece antes disto, sobre o `rawBody`.\n */\nexport const deliveryWebhookSchema = z.object({\n providerMessageId: z.string().min(1),\n status: z.enum(['delivered', 'bounced', 'failed']),\n errorCode: z.string().max(64).optional(),\n occurredAt: z.coerce.date(),\n suppressionReason: z.nativeEnum(SUPPRESSION_REASON).optional(),\n})\nexport type DeliveryWebhookBody = z.infer<typeof deliveryWebhookSchema>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type {\n CompanyId,\n DevicePlatform,\n NotificationChannel,\n NotificationId,\n NotificationStatus,\n PushDriver,\n SuppressionReason,\n UserId,\n} from './notification.types'\n\n/**\n * Eventos de domínio — os pontos de extensão do produto. É aqui que entra a regra de negócio que\n * o módulo não pode ter (ex.: bounce de e-mail marca o contato como inválido no CRM), sem\n * ninguém editar código do pacote (regra de módulos plugáveis, §3).\n */\nexport const NOTIFICATION_EVENT = {\n CREATED: 'notification.created',\n DISPATCHED: 'notification.dispatched',\n READ: 'notification.read',\n DELIVERY_SENT: 'delivery.sent',\n DELIVERY_FAILED: 'delivery.failed',\n DELIVERY_BOUNCED: 'delivery.bounced',\n DEVICE_REGISTERED: 'device.registered',\n DEVICE_INVALIDATED: 'device.invalidated',\n PREFERENCES_UPDATED: 'preferences.updated',\n} as const\nexport type NotificationEvent = (typeof NOTIFICATION_EVENT)[keyof typeof NOTIFICATION_EVENT]\n\ntype BaseEvent = {\n readonly companyId: CompanyId\n readonly occurredAt: Date\n}\n\nexport type NotificationCreatedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n /** Canais que sobreviveram ao fan-out; os pulados aparecem em `skippedChannels`. */\n readonly channels: readonly NotificationChannel[]\n readonly skippedChannels: readonly { readonly channel: NotificationChannel; readonly reason: string }[]\n}\n\nexport type NotificationDispatchedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly status: NotificationStatus\n}\n\nexport type NotificationReadEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n}\n\nexport type DeliverySentEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly providerMessageId?: string\n readonly attempt: number\n}\n\nexport type DeliveryFailedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly errorCode: string\n readonly attempt: number\n /** `false` quando o retry esgotou ou o erro é permanente — é o gancho para alerta do host. */\n readonly willRetry: boolean\n}\n\nexport type DeliveryBouncedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly reason: SuppressionReason\n}\n\nexport type DeviceRegisteredEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n}\n\nexport type DeviceInvalidatedEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly driver: PushDriver\n readonly errorCode: string\n}\n\nexport type PreferencesUpdatedEvent = BaseEvent & {\n readonly userId: UserId\n readonly categories: readonly string[]\n}\n\n/**\n * Hooks são `void`-tolerantes de propósito: falha de hook do produto não pode derrubar a entrega\n * da notificação. O módulo loga e segue — quem precisa de garantia transacional usa a fila.\n */\nexport type NotificationHooks = {\n onNotificationCreated?(event: NotificationCreatedEvent): Promise<void> | void\n onNotificationDispatched?(event: NotificationDispatchedEvent): Promise<void> | void\n onNotificationRead?(event: NotificationReadEvent): Promise<void> | void\n onDeliverySent?(event: DeliverySentEvent): Promise<void> | void\n onDeliveryFailed?(event: DeliveryFailedEvent): Promise<void> | void\n onDeliveryBounced?(event: DeliveryBouncedEvent): Promise<void> | void\n onDeviceRegistered?(event: DeviceRegisteredEvent): Promise<void> | void\n onDeviceInvalidated?(event: DeviceInvalidatedEvent): Promise<void> | void\n onPreferencesUpdated?(event: PreferencesUpdatedEvent): Promise<void> | void\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { NotificationChannel } from './notification.types'\n\n/**\n * Hierarquia autocontida: um pacote publicado não importa o `DomainError` do host. O host mapeia\n * estes erros no seu exception filter — e o próprio módulo já traz um, para o consumidor das rotas\n * não precisar escrever `try/catch` por endpoint.\n */\nexport class NotificationError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message)\n this.name = 'NotificationError'\n }\n}\n\nexport const NOTIFICATION_ERROR_CODES = {\n TEMPLATE_NOT_FOUND: 'NOTIFICATION_TEMPLATE_NOT_FOUND',\n CHANNEL_NOT_CONFIGURED: 'NOTIFICATION_CHANNEL_NOT_CONFIGURED',\n RECIPIENT_UNRESOLVED: 'NOTIFICATION_RECIPIENT_UNRESOLVED',\n SUPPRESSED_TARGET: 'NOTIFICATION_SUPPRESSED_TARGET',\n NOT_FOUND: 'NOTIFICATION_NOT_FOUND',\n INVALID_WEBHOOK_SIGNATURE: 'NOTIFICATION_INVALID_WEBHOOK_SIGNATURE',\n DUPLICATE_WEBHOOK_DELIVERY: 'NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY',\n DEVICE_NOT_FOUND: 'NOTIFICATION_DEVICE_NOT_FOUND',\n THROTTLED: 'NOTIFICATION_THROTTLED',\n CONFIG_MISSING: 'NOTIFICATION_CONFIG_MISSING',\n TEMPLATE_UNKNOWN_VARIABLE: 'NOTIFICATION_TEMPLATE_UNKNOWN_VARIABLE',\n} as const\n\n/** Busca por id, e não por identidade — o painel remove pela linha que listou. */\nexport class TemplateIdNotFoundError extends NotificationError {\n constructor(public readonly templateId: string) {\n super(`Template não encontrado.`, 404, NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND, { templateId })\n }\n}\n\n/**\n * O template referencia `{{campo}}` que o produto não promete enviar. Renderizaria vazio para\n * sempre, sem log e sem erro — daí ser recusa na gravação, e não aviso.\n *\n * `details.fields` traz TODAS as desconhecidas, não a primeira: corrigir uma por vez transforma o\n * salvamento em tentativa e erro (`apis.md`, Validação).\n */\nexport class UnknownTemplateVariablesError extends NotificationError {\n constructor(\n public readonly templateKey: string,\n public readonly fields: readonly string[],\n ) {\n super(\n `O template usa variáveis que não existem no catálogo desta notificação.`,\n 400,\n NOTIFICATION_ERROR_CODES.TEMPLATE_UNKNOWN_VARIABLE,\n {\n templateKey,\n fields: [...fields],\n details: fields.map((field) => ({ field, message: 'variável desconhecida' })),\n },\n )\n }\n}\n\nexport class TemplateNotFoundError extends NotificationError {\n constructor(\n public readonly templateKey: string,\n public readonly channel: NotificationChannel,\n public readonly locale: string,\n ) {\n super(\n `Template não encontrado para a chave informada neste canal e locale.`,\n 404,\n NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND,\n { templateKey, channel, locale },\n )\n }\n}\n\n/** Canal ligado em `features` sem driver injetado — erro de composição, detectado no boot. */\nexport class ChannelNotConfiguredError extends NotificationError {\n constructor(public readonly channel: NotificationChannel) {\n super(\n `Canal habilitado sem driver injetado — injete o driver em providers.channels ou desligue a feature.`,\n 500,\n NOTIFICATION_ERROR_CODES.CHANNEL_NOT_CONFIGURED,\n { channel },\n )\n }\n}\n\n/**\n * `RecipientResolverPort` não devolveu endereço para o canal. Mensagem sem PII de propósito: o\n * `userId` é identificador opaco, o e-mail ou telefone jamais entra no erro (`security.md` §1).\n */\nexport class RecipientUnresolvedError extends NotificationError {\n constructor(\n public readonly userId: string,\n public readonly channel: NotificationChannel,\n ) {\n super(`Destinatário sem endereço utilizável para este canal.`, 422, NOTIFICATION_ERROR_CODES.RECIPIENT_UNRESOLVED, {\n userId,\n channel,\n })\n }\n}\n\nexport class SuppressedTargetError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly reason: string,\n ) {\n super(`Endereço suprimido para este canal — envio bloqueado.`, 409, NOTIFICATION_ERROR_CODES.SUPPRESSED_TARGET, {\n channel,\n reason,\n })\n }\n}\n\n/**\n * Também é a resposta para notificação de OUTRO usuário: devolver 404 em vez de 403 não revela a\n * existência do recurso a quem não pode vê-lo (BOLA/API1).\n */\nexport class NotificationNotFoundError extends NotificationError {\n constructor(public readonly notificationId: string) {\n super(`Notificação não encontrada.`, 404, NOTIFICATION_ERROR_CODES.NOT_FOUND, { notificationId })\n }\n}\n\nexport class InvalidWebhookSignatureError extends NotificationError {\n constructor() {\n super(`Assinatura do webhook inválida.`, 401, NOTIFICATION_ERROR_CODES.INVALID_WEBHOOK_SIGNATURE)\n }\n}\n\n/** Recibo reenviado dentro da janela de replay (nonce já visto) — não é erro, é ruído esperado. */\nexport class DuplicateWebhookDeliveryError extends NotificationError {\n constructor(public readonly nonce: string) {\n super(`Entrega de webhook duplicada.`, 200, NOTIFICATION_ERROR_CODES.DUPLICATE_WEBHOOK_DELIVERY, { nonce })\n }\n}\n\nexport class DeviceNotFoundError extends NotificationError {\n constructor(public readonly deviceId: string) {\n super(`Dispositivo não encontrado.`, 404, NOTIFICATION_ERROR_CODES.DEVICE_NOT_FOUND, { deviceId })\n }\n}\n\nexport class ThrottledError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly retryAfterSeconds: number,\n ) {\n super(`Limite de envios para este destinatário atingido.`, 429, NOTIFICATION_ERROR_CODES.THROTTLED, {\n channel,\n retryAfterSeconds,\n })\n }\n}\n\n/**\n * Configuração obrigatória ausente (chave de HMAC, segredo de webhook) — falha no boot.\n *\n * Único erro do módulo cuja mensagem nomeia o campo: ele é lido por quem está subindo o serviço,\n * não devolvido a um cliente, e \"algo está faltando\" sem dizer o quê custa uma bisca no código.\n * O nome do campo é identificador de configuração, nunca valor — o segredo em si não aparece.\n */\nexport class ConfigMissingError extends NotificationError {\n constructor(public readonly field: string) {\n super(`Configuração obrigatória ausente: ${field}.`, 500, NOTIFICATION_ERROR_CODES.CONFIG_MISSING, { field })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { DeliveryAttemptResult, SendWhatsAppParams, WhatsAppDriverPort } from './channelDrivers'\nimport { SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Forma mínima que o `channel` do `meta-whatsapp-module` já satisfaz. Descrita aqui por\n * *estrutura*, e não importada do pacote de WhatsApp: é isso que mantém os dois trios\n * independentes — quem só usa inbox não carrega Meta, quem só usa WhatsApp não carrega\n * notificação, e a costura acontece no produto (regra de módulos plugáveis, §2).\n */\nexport type WhatsAppSendingChannel = {\n sendText(to: string, body: string): Promise<{ externalMessageId: string | null }>\n sendTemplate(params: {\n to: string\n templateName: string\n languageCode: string\n bodyParameters?: string[]\n }): Promise<{ externalMessageId: string | null }>\n}\n\n/**\n * Códigos da Graph API que o canal repassa. A lista é curta de propósito: cobre o que muda a\n * decisão do módulo (apagar destino × tentar de novo × desistir) e nada além disso.\n */\nconst INVALID_TARGET_CODES = new Set([131026, 131051])\nconst PERMANENT_CODES = new Set([131047, 131031, 368])\nconst RETRIABLE_CODES = new Set([613, 130429, 131056])\n\nfunction readNumericField(error: unknown, field: string): number | undefined {\n if (typeof error !== 'object' || error === null || !(field in error)) return undefined\n const value = (error as Record<string, unknown>)[field]\n return typeof value === 'number' ? value : undefined\n}\n\nfunction classifyError(error: unknown): DeliveryAttemptResult {\n const metaCode = readNumericField(error, 'code')\n if (metaCode !== undefined) {\n if (INVALID_TARGET_CODES.has(metaCode)) {\n return {\n outcome: 'invalid_target',\n errorCode: `meta_${metaCode}`,\n suppressionReason: SUPPRESSION_REASON.BOUNCE,\n }\n }\n if (PERMANENT_CODES.has(metaCode)) return { outcome: 'permanent', errorCode: `meta_${metaCode}` }\n if (RETRIABLE_CODES.has(metaCode)) return { outcome: 'retriable', errorCode: `meta_${metaCode}` }\n }\n\n const statusCode = readNumericField(error, 'statusCode') ?? readNumericField(error, 'status')\n if (statusCode === 429 || (statusCode !== undefined && statusCode >= 500)) {\n return { outcome: 'retriable', errorCode: `http_${statusCode}` }\n }\n if (statusCode !== undefined && statusCode >= 400) {\n return { outcome: 'permanent', errorCode: `http_${statusCode}` }\n }\n\n // Sem código nenhum é quase sempre falha de rede/DNS, que passa numa segunda tentativa. O risco\n // do palpite é limitado: o retry é finito (`attempts`) e termina em `failed` de qualquer forma.\n return { outcome: 'retriable', errorCode: 'unknown' }\n}\n\nexport function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel): WhatsAppDriverPort {\n return {\n async send(params: SendWhatsAppParams): Promise<DeliveryAttemptResult> {\n try {\n const result = params.template\n ? await channel.sendTemplate({\n to: params.to,\n templateName: params.template.templateName,\n languageCode: params.template.languageCode,\n bodyParameters: params.template.bodyParameters ? [...params.template.bodyParameters] : undefined,\n })\n : await channel.sendText(params.to, params.body)\n\n return { outcome: 'sent', providerMessageId: result.externalMessageId ?? undefined }\n } catch (error) {\n return classifyError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Larguras e limites do preview, por canal.\n *\n * Moram aqui, e não no CSS da UI, porque o host que consome a camada headless precisa deles para\n * desenhar o próprio preview — e porque o limite de caracteres não é decoração de tela: ele é a\n * regra do canal, e o editor avisa com ela antes de salvar.\n */\n\nimport { NOTIFICATION_CHANNEL } from './notification.types'\nimport type { NotificationChannel } from './notification.types'\n\nexport const PREVIEW_VIEWPORT = {\n DESKTOP: 'desktop',\n MOBILE: 'mobile',\n} as const\nexport type PreviewViewport = (typeof PREVIEW_VIEWPORT)[keyof typeof PREVIEW_VIEWPORT]\n\nexport type PreviewViewportSpec = {\n readonly viewport: PreviewViewport\n readonly width: number\n}\n\nconst MOBILE: PreviewViewportSpec = { viewport: PREVIEW_VIEWPORT.MOBILE, width: 375 }\n\n/**\n * `email` em 600px é a largura clássica de corpo de e-mail; os demais aproximam o container em que\n * a mensagem aparece no desktop. `sms` não tem desktop — a mensagem é a mesma no aparelho e ponto.\n */\nexport const PREVIEW_VIEWPORT_BY_CHANNEL: Readonly<Record<NotificationChannel, readonly PreviewViewportSpec[]>> = {\n [NOTIFICATION_CHANNEL.EMAIL]: [{ viewport: PREVIEW_VIEWPORT.DESKTOP, width: 600 }, MOBILE],\n [NOTIFICATION_CHANNEL.PUSH]: [{ viewport: PREVIEW_VIEWPORT.DESKTOP, width: 360 }, MOBILE],\n [NOTIFICATION_CHANNEL.WHATSAPP]: [{ viewport: PREVIEW_VIEWPORT.DESKTOP, width: 400 }, MOBILE],\n [NOTIFICATION_CHANNEL.INBOX]: [{ viewport: PREVIEW_VIEWPORT.DESKTOP, width: 480 }, MOBILE],\n [NOTIFICATION_CHANNEL.SMS]: [MOBILE],\n}\n\nexport type TemplateConstraintField = 'title' | 'body'\n\nexport type TemplateConstraintLimits = {\n readonly title?: number\n readonly body?: number\n}\n\n/**\n * Onde o canal corta de verdade. `email.title` são os ~78 caracteres que a lista da caixa de\n * entrada mostra no celular; `push` segue o teto prático do Android; `sms` é o segmento de 160,\n * depois do qual a operadora cobra outra mensagem; `whatsapp.body` é o teto de corpo de template\n * da Meta. `inbox` acompanha o `deriveTitleFromBody`.\n */\nexport const TEMPLATE_CONSTRAINTS_BY_CHANNEL: Readonly<Record<NotificationChannel, TemplateConstraintLimits>> = {\n [NOTIFICATION_CHANNEL.EMAIL]: { title: 78 },\n [NOTIFICATION_CHANNEL.PUSH]: { title: 65, body: 240 },\n [NOTIFICATION_CHANNEL.WHATSAPP]: { body: 1024 },\n [NOTIFICATION_CHANNEL.INBOX]: { title: 120 },\n [NOTIFICATION_CHANNEL.SMS]: { body: 160 },\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * A renderização default de template, pura e sem dependência.\n *\n * Mora no contracts, e não no módulo, por um motivo específico: a tela de configuração precisa\n * mostrar um PREVIEW do que o cliente vai receber, e o módulo carrega Drizzle — o frontend não pode\n * importá-lo. Reimplementar a interpolação no host resolveria hoje e divergiria amanhã, e **preview\n * que mente é pior que preview nenhum**: alguém salva o template confiando no que viu.\n *\n * Com a função aqui, o `notification-module` renderiza para enviar e a UI renderiza para mostrar,\n * lendo o MESMO código. Divergência deixa de ser possível em vez de ser improvável.\n */\n\nimport { TEMPLATE_CONSTRAINTS_BY_CHANNEL } from './previewViewport'\nimport type { TemplateConstraintField } from './previewViewport'\nimport type { NotificationChannel } from './notification.types'\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}/g\nconst DEFAULT_TITLE_MAX_LENGTH = 120\n\nconst HTML_ESCAPE_MAP: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n}\n\nexport function escapeTemplateHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (character) => HTML_ESCAPE_MAP[character] ?? character)\n}\n\n/** `{{campo}}` → valor do payload. Campo ausente vira string vazia, nunca o literal `{{campo}}`. */\nexport function interpolateTemplate(template: string, payload: Readonly<Record<string, unknown>>): string {\n return template.replace(PLACEHOLDER_PATTERN, (_match, key: string) => {\n const value = payload[key]\n return value === undefined || value === null ? '' : String(value)\n })\n}\n\nexport function deriveTitleFromBody(body: string): string {\n const firstLine = body.split('\\n')[0] ?? ''\n return firstLine.length > DEFAULT_TITLE_MAX_LENGTH ? `${firstLine.slice(0, DEFAULT_TITLE_MAX_LENGTH)}…` : firstLine\n}\n\n/** Os nomes de campo que um template referencia — o que a tela de configuração precisa pedir. */\nexport function extractTemplatePlaceholders(template: string): readonly string[] {\n const found = new Set<string>()\n for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {\n if (match[1]) found.add(match[1])\n }\n return [...found]\n}\n\nexport type TemplateConstraintCheck = {\n readonly field: TemplateConstraintField\n readonly limit: number\n readonly actual: number\n readonly exceeded: boolean\n}\n\nexport type RenderedTemplatePreview = {\n readonly title: string\n readonly body: string\n readonly html?: string\n /**\n * O que o canal corta. Vazio quando o canal não declara limite. O editor usa isto para avisar\n * antes de salvar, e o preview para marcar onde o texto some — sem isso, dois quadros de\n * larguras diferentes só provariam que CSS quebra linha.\n */\n readonly constraints: readonly TemplateConstraintCheck[]\n}\n\n/**\n * `\\r` e `\\n` no assunto são o vetor clássico de injeção de header em e-mail. Os providers atuais\n * (Resend e SES são API JSON, nodemailer codifica) já barram, mas o assunto vem de painel agora:\n * a defesa fica onde o texto é produzido, não na esperança de que todo provider futuro trate.\n */\nfunction sanitizeTitle(title: string): string {\n return title.replace(/[\\r\\n]+/g, ' ').trim()\n}\n\nfunction checkConstraints(params: { channel: string; title: string; body: string }): TemplateConstraintCheck[] {\n const limits = TEMPLATE_CONSTRAINTS_BY_CHANNEL[params.channel as NotificationChannel]\n if (!limits) return []\n\n const checks: TemplateConstraintCheck[] = []\n const values: Record<TemplateConstraintField, string> = { title: params.title, body: params.body }\n for (const field of ['title', 'body'] as const) {\n const limit = limits[field]\n if (limit === undefined) continue\n const actual = values[field].length\n checks.push({ field, limit, actual, exceeded: actual > limit })\n }\n return checks\n}\n\n/**\n * Mesma saída que o envio produz. `channel` importa porque só e-mail ganha a versão HTML — mostrar\n * HTML no preview de WhatsApp faria a tela prometer formatação que o canal não tem.\n */\nexport function renderTemplate(params: {\n readonly channel: string\n readonly subject?: string | undefined\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n}): RenderedTemplatePreview {\n const body = interpolateTemplate(params.body, params.payload)\n const title = sanitizeTitle(\n params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body),\n )\n const constraints = checkConstraints({ channel: params.channel, title, body })\n\n if (params.channel !== 'email') return { title, body, constraints }\n\n // Escapa o resultado já interpolado (texto do template e valores do payload juntos), depois troca\n // quebra de linha por <br> — quem quer HTML rico troca o renderer, em vez de descobrir por um bug\n // de escape.\n return { title, body, constraints, html: escapeTemplateHtml(body).replace(/\\n/g, '<br>') }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * O catálogo de variáveis de um template, e a diferença entre o que ele declara e o que o texto\n * usa.\n *\n * Existe porque `{{campo}}` desconhecido não falha: `interpolateTemplate` devolve string vazia, que\n * é o comportamento correto no envio — mensagem com buraco é melhor que mensagem com `{{campo}}`\n * cru. O preço é que um erro de digitação no painel some sem log e sem erro, e só aparece quando o\n * cliente recebe \"Olá , seu pedido\". Com um painel, isso deixa de ser raro.\n *\n * A função é pura e mora aqui, e não no módulo, pelo mesmo motivo do `renderTemplate`: a validação\n * do servidor e o aviso da tela precisam da MESMA regra, e o frontend não pode importar o módulo\n * (carrega Drizzle). Duas implementações divergiriam, e a tela passaria a aprovar o que a rota\n * recusa.\n */\n\nimport { extractTemplatePlaceholders } from './templateRender'\n\n/**\n * `text` entra no corpo por interpolação; `attachment` NÃO — ele viaja ao lado da mensagem.\n *\n * A distinção existe porque as duas regras de validação são opostas: variável de texto declarada e\n * ausente do corpo é um aviso, e variável de anexo ausente do corpo é o normal. Sem o tipo, todo\n * anexo obrigatório apareceria eternamente como \"faltando no texto\".\n */\nexport const TEMPLATE_VARIABLE_KIND = {\n TEXT: 'text',\n ATTACHMENT: 'attachment',\n} as const\nexport type TemplateVariableKind = (typeof TEMPLATE_VARIABLE_KIND)[keyof typeof TEMPLATE_VARIABLE_KIND]\n\nexport type TemplateVariableDefinition = {\n readonly name: string\n /** Ausente é `text`: todo catálogo escrito antes disto continua valendo sem alteração. */\n readonly kind?: TemplateVariableKind\n /** Valor de exemplo — alimenta o preview. Só o produto sabe que `orderNumber` é \"QC-1042\". */\n readonly example: string\n /** `true` avisa quando o texto não usa a variável; nunca bloqueia (ver `diffTemplateVariables`). */\n readonly required: boolean\n /** Chave de i18n do rótulo na tela. Ausente, a tela mostra o próprio `name`. */\n readonly labelKey?: string\n}\n\n/** `templateKey` → variáveis que o produto promete enviar no payload daquela notificação. */\nexport type TemplateVariableCatalog = Readonly<Record<string, readonly TemplateVariableDefinition[]>>\n\nexport type TemplateVariableDiff = {\n /** Placeholders que o texto referencia, na ordem em que aparecem. */\n readonly used: readonly string[]\n /** Referenciados e não declarados — renderizariam vazio para sempre. */\n readonly unknown: readonly string[]\n /** Declarados como `required` e ausentes do texto. Só variáveis de texto entram aqui. */\n readonly missingRequired: readonly string[]\n /**\n * Anexos referenciados DENTRO do texto — quase sempre engano.\n *\n * `{{nota}}` no corpo de um anexo renderiza a URL crua no meio da frase, e não anexa nada. Se a\n * intenção era mandar o link, a variável devia ser de texto; se era anexar, ela não pertence ao\n * corpo. Aviso e não erro: link para o arquivo é uma escolha legítima, só não é esta.\n */\n readonly attachmentsInText: readonly string[]\n}\n\nexport type DiffTemplateVariablesParams = {\n readonly body: string\n readonly subject?: string | undefined\n /**\n * Ausente significa catálogo não declarado para esta `key`, e não catálogo vazio: nesse caso\n * nada é desconhecido. Fechar por omissão quebraria todo host que já usa o módulo sem catálogo.\n */\n readonly variables?: readonly TemplateVariableDefinition[] | undefined\n}\n\nexport function diffTemplateVariables(params: DiffTemplateVariablesParams): TemplateVariableDiff {\n const used = extractTemplatePlaceholders(`${params.subject ?? ''}\\n${params.body}`)\n\n if (!params.variables) return { used, unknown: [], missingRequired: [], attachmentsInText: [] }\n\n const declared = new Set(params.variables.map((variable) => variable.name))\n const usedSet = new Set(used)\n const attachments = new Set(\n params.variables\n .filter((variable) => variable.kind === TEMPLATE_VARIABLE_KIND.ATTACHMENT)\n .map((variable) => variable.name),\n )\n\n return {\n used,\n unknown: used.filter((name) => !declared.has(name)),\n missingRequired: params.variables\n .filter(\n (variable) =>\n variable.required && variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT && !usedSet.has(variable.name),\n )\n .map((variable) => variable.name),\n attachmentsInText: used.filter((name) => attachments.has(name)),\n }\n}\n\n/**\n * O payload de preview sai do próprio catálogo. Um mapa `key → exemplo` mantido em paralelo\n * divergiria do catálogo na primeira variável nova, e o preview voltaria a mentir.\n */\nexport function buildPreviewPayload(\n variables: readonly TemplateVariableDefinition[] | undefined,\n): Readonly<Record<string, string>> {\n if (!variables) return {}\n\n // Anexo não é interpolado: incluí-lo aqui faria o preview desenhar a URL no meio do texto de um\n // corpo que nunca vai conter essa URL.\n return Object.fromEntries(\n variables\n .filter((variable) => variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT)\n .map((variable) => [variable.name, variable.example]),\n )\n}\n"],"mappings":";;;;AAIO,IAAMA,uBAAuB;EAClCC,OAAO;EACPC,MAAM;EACNC,OAAO;EACPC,UAAU;EACVC,KAAK;AACP;AAIO,IAAMC,qBAAqD;EAChEN,qBAAqBE;EACrBF,qBAAqBI;EACrBJ,qBAAqBK;;AAahB,IAAME,sBAAsB;EACjCC,SAAS;EACTC,WAAW;EACXC,QAAQ;EACRC,YAAY;EACZC,kBAAkB;EAClBC,QAAQ;AACV;AAGO,IAAMC,kBAAkB;EAC7BJ,QAAQ;EACRK,MAAM;EACNC,WAAW;EACXH,QAAQ;EACRI,SAAS;EACTC,SAAS;AACX;AAGO,IAAMC,kBAAkB;EAC7BC,KAAK;EACLC,SAAS;EACTC,KAAK;AACP;AAGO,IAAMC,cAAc;EACzBC,MAAM;EACNC,KAAK;AACP;AAGO,IAAMC,eAAe;EAC1BC,MAAM;EACNC,QAAQ;EACRC,KAAK;AACP;AAGO,IAAMC,qBAAqB;EAChCC,QAAQ;EACRC,WAAW;EACXC,SAAS;AACX;AAQO,IAAMC,6BAA6B;EACxCC,cAAc;EACdC,SAAS;EACTC,UAAU;EACVC,WAAW;EACXC,QAAQ;AACV;;;ACrEO,IAAMC,6BAA6B,KAAK,OAAO;AAG/C,IAAMC,6BAA6B;AAoBnC,SAASC,qBAAqBC,YAA2B;AAC9D,MAAI,CAACA,WAAWC,SAASC,KAAI,EAAI,QAAO;AAIxC,MAAI,aAAaC,KAAKH,WAAWC,QAAQ,EAAG,QAAO;AAEnD,MAAI,CAACD,WAAWI,YAAYF,KAAI,EAAI,QAAO;AAI3C,MAAI,CAACF,WAAWK,IAAIC,WAAW,UAAA,EA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J,aAAaA,SAASK,SAASrB,uBAAuBE,UAAU,EACxEa,IAAI,CAACC,aAAaA,SAASC,IAAI,CAAA;AAGpC,SAAO;IACLZ;IACAK,SAASL,KAAKe,OAAO,CAACH,SAAS,CAACJ,SAASS,IAAIL,IAAAA,CAAAA;IAC7CN,iBAAiBP,OAAOK,UACrBW,OACC,CAACJ,aACCA,SAASO,YAAYP,SAASK,SAASrB,uBAAuBE,cAAc,CAACgB,QAAQI,IAAIN,SAASC,IAAI,CAAA,EAEzGF,IAAI,CAACC,aAAaA,SAASC,IAAI;IAClCL,mBAAmBP,KAAKe,OAAO,CAACH,SAASE,YAAYG,IAAIL,IAAAA,CAAAA;EAC3D;AACF;AAxBgBd;AA8BT,SAASqB,oBACdf,WAA4D;AAE5D,MAAI,CAACA,UAAW,QAAO,CAAC;AAIxB,SAAOgB,OAAOC,YACZjB,UACGW,OAAO,CAACJ,aAAaA,SAASK,SAASrB,uBAAuBE,UAAU,EACxEa,IAAI,CAACC,aAAa;IAACA,SAASC;IAAMD,SAASW;GAAQ,CAAA;AAE1D;AAZgBH;","names":["NOTIFICATION_CHANNEL","INBOX","PUSH","EMAIL","WHATSAPP","SMS","INTRUSIVE_CHANNELS","NOTIFICATION_STATUS","PENDING","SCHEDULED","QUEUED","DISPATCHED","PARTIALLY_FAILED","FAILED","DELIVERY_STATUS","SENT","DELIVERED","BOUNCED","SKIPPED","DEVICE_PLATFORM","IOS","ANDROID","WEB","PUSH_DRIVER","EXPO","FCM","EMAIL_DRIVER","SMTP","RESEND","SES","SUPPRESSION_REASON","BOUNCE","COMPLAINT","OPT_OUT","NOTIFICATION_CATEGORY_HINT","ORDER_STATUS","PAYMENT","SECURITY","MARKETING","SYSTEM","EMAIL_ATTACHMENT_MAX_BYTES","EMAIL_ATTACHMENT_MAX_COUNT","checkEmailAttachment","attachment","filename","trim","test","contentType","url","startsWith","undefined","z","HHMM","MAX_PER_PAGE","quietHoursShape","quietHoursStart","z","string","regex","optional","quietHoursEnd","timezone","min","sendNotificationSchema","object","recipientUserId","uuid","category","max","templateKey","payload","record","unknown","channels","array","nativeEnum","NOTIFICATION_CHANNEL","nonempty","dedupeKey","scheduledFor","coerce","date","locale","registerDeviceSchema","platform","DEVICE_PLATFORM","driver","PUSH_DRIVER","token","appVersion","preferenceEntrySchema","channel","enabled","boolean","updatePreferencesSchema","preferences","categoryPolicyEntrySchema","updateCategoryPoliciesSchema","policies","upsertTemplateSchema","key","subject","body","whatsappTemplateName","active","default","listNotificationsQuerySchema","read","enum","transform","value","cursor","perPage","number","int","deliveryWebhookSchema","providerMessageId","status","errorCode","occurredAt","suppressionReason","SUPPRESSION_REASON","NOTIFICATION_EVENT","CREATED","DISPATCHED","READ","DELIVERY_SENT","DELIVERY_FAILED","DELIVERY_BOUNCED","DEVICE_REGISTERED","DEVICE_INVALIDATED","PREFERENCES_UPDATED","NotificationError","Error","message","statusCode","code","details","name","NOTIFICATION_ERROR_CODES","TEMPLATE_NOT_FOUND","CHANNEL_NOT_CONFIGURED","RECIPIENT_UNRESOLVED","SUPPRESSED_TARGET","NOT_FOUND","INVALID_WEBHOOK_SIGNATURE","DUPLICATE_WEBHOOK_DELIVERY","DEVICE_NOT_FOUND","THROTTLED","CONFIG_MISSING","TEMPLATE_UNKNOWN_VARIABLE","TemplateIdNotFoundError","templateId","UnknownTemplateVariablesError","templateKey","fields","map","field","TemplateNotFoundError","channel","locale","ChannelNotConfiguredError","RecipientUnresolvedError","userId","SuppressedTargetError","reason","NotificationNotFoundError","notificationId","InvalidWebhookSignatureError","DuplicateWebhookDeliveryError","nonce","DeviceNotFoundError","deviceId","ThrottledError","retryAfterSeconds","ConfigMissingError","INVALID_TARGET_CODES","Set","PERMANENT_CODES","RETRIABLE_CODES","readNumericField","error","field","undefined","value","classifyError","metaCode","has","outcome","errorCode","suppressionReason","SUPPRESSION_REASON","BOUNCE","statusCode","createWhatsAppDriverFromChannel","channel","send","params","result","template","sendTemplate","to","templateName","languageCode","bodyParameters","sendText","body","providerMessageId","externalMessageId","PREVIEW_VIEWPORT","DESKTOP","MOBILE","viewport","width","PREVIEW_VIEWPORT_BY_CHANNEL","NOTIFICATION_CHANNEL","EMAIL","PUSH","WHATSAPP","INBOX","SMS","TEMPLATE_CONSTRAINTS_BY_CHANNEL","title","body","PLACEHOLDER_PATTERN","DEFAULT_TITLE_MAX_LENGTH","HTML_ESCAPE_MAP","escapeTemplateHtml","text","replace","character","interpolateTemplate","template","payload","_match","key","value","undefined","String","deriveTitleFromBody","body","firstLine","split","length","slice","extractTemplatePlaceholders","found","Set","match","matchAll","add","sanitizeTitle","title","trim","checkConstraints","params","limits","TEMPLATE_CONSTRAINTS_BY_CHANNEL","channel","checks","values","field","limit","actual","push","exceeded","renderTemplate","subject","constraints","html","TEMPLATE_VARIABLE_KIND","TEXT","ATTACHMENT","diffTemplateVariables","params","used","extractTemplatePlaceholders","subject","body","variables","unknown","missingRequired","attachmentsInText","declared","Set","map","variable","name","usedSet","attachments","filter","kind","has","required","buildPreviewPayload","Object","fromEntries","example"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adatechnology/notification-contracts",
3
- "version": "0.1.0-rc.2",
3
+ "version": "0.1.0-rc.4",
4
4
  "description": "Shared types, zod schemas, and port interfaces for the notification trio (contracts only — no runtime behavior)",
5
5
  "license": "MIT",
6
6
  "publishConfig": {