@designsystemsinternational/email 0.0.2 → 0.0.3

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.
@@ -0,0 +1,631 @@
1
+ 'use strict';
2
+
3
+ var posthtml = require('posthtml');
4
+ var removeTags = require('posthtml-remove-tags');
5
+ var removeAttributes = require('posthtml-remove-attributes');
6
+ var matchHelper = require('posthtml-match-helper');
7
+ var colorConvert = require('color-convert');
8
+ var unescape = require('lodash.unescape');
9
+ var compressing = require('compressing');
10
+ var getStream = require('get-stream');
11
+ var mailchimpAPI = require('@mailchimp/mailchimp_marketing');
12
+ var AWS = require('aws-sdk');
13
+ var nodemailer = require('nodemailer');
14
+
15
+ /**
16
+ * Generates a deterministic random string based on the input string.
17
+ *
18
+ * @param {string} str Input string
19
+ * @return {string} hash of str
20
+ */
21
+ const hashFromString = (str) => {
22
+ let hash = 0;
23
+ for (let i = 0; i < str.length; i++) {
24
+ hash = str.charCodeAt(i) + ((hash << 5) - hash);
25
+ }
26
+ return hash.toString();
27
+ };
28
+
29
+ /**
30
+ * Formats a string to a filename by turning it into kebab case
31
+ *
32
+ * @param {string} text
33
+ * @return {string} formatted filename
34
+ */
35
+ const formatFilename = (text) => {
36
+ return text
37
+ .toLowerCase()
38
+ .replace(/[^a-z0-9-]+/g, ' ')
39
+ .trim()
40
+ .replace(/\s+/g, '-');
41
+ };
42
+
43
+ /**
44
+ * Converts all rgb defined colors with their hex equivalent
45
+ * as some email clients only support hex color format.
46
+ */
47
+ const convertRgbToHex = () => {
48
+ return (tree) => {
49
+ tree.match(matchHelper('[style]'), (node) => {
50
+ let styleBlock = node.attrs.style;
51
+ styleBlock = styleBlock.replace(
52
+ /rgb\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}\)/g,
53
+ (match) => {
54
+ const values = match
55
+ .replace(/[rgb() ]/g, '')
56
+ .split(',')
57
+ .map((n) => parseInt(n));
58
+ return '#' + colorConvert.rgb.hex(values);
59
+ },
60
+ );
61
+ node.attrs.style = styleBlock;
62
+ return node;
63
+ });
64
+
65
+ return tree;
66
+ };
67
+ };
68
+
69
+ /**
70
+ * Prepares HTML by only returning the body tag, to make sure
71
+ */
72
+ const onlyReturnBody = () => {
73
+ return (tree) => {
74
+ tree.match({ tag: 'body' }, (node) => {
75
+ return node.content;
76
+ });
77
+
78
+ return tree;
79
+ };
80
+ };
81
+
82
+ /**
83
+ * Rewrites the markup by turning all conditional comments returned from the
84
+ * <ConditionalComment> component into true conditional comments that can be
85
+ * picked up by Outlook.
86
+ */
87
+ const injectConditionalComments = () => {
88
+ return (tree) => {
89
+ tree.match(matchHelper('[data-conditional-comment]'), (node) => {
90
+ const comment = node.attrs['data-conditional-comment'];
91
+
92
+ // Remove HTML comment delimiters
93
+ const cleanedComment = unescape(comment).replace(/<!--|-->/g, '');
94
+
95
+ // Remove Line breaks from comment
96
+ const cleanedCommentLines = cleanedComment.split('\n').join('');
97
+
98
+ node = `<!--${cleanedCommentLines}-->`;
99
+ return node;
100
+ });
101
+ return tree;
102
+ };
103
+ };
104
+
105
+ /**
106
+ * Rewrites the markup by adding all styles defined in the data-mso-style
107
+ * attribute to the <style> tag. This is needed because the mso styles are
108
+ * non-standard CSS, so they cannot be added to React's style tag.
109
+ */
110
+ const injectMsoStyles = () => {
111
+ return (tree) => {
112
+ tree.match(matchHelper('[data-mso-style]'), (node) => {
113
+ if (node.attrs?.style == null) node.attrs.style = '';
114
+ node.attrs.style += node.attrs['data-mso-style'];
115
+ node.attrs['data-mso-style'] = null;
116
+ return node;
117
+ });
118
+ return tree;
119
+ };
120
+ };
121
+
122
+ /**
123
+ * Collects all inline styles defined in the components, de-dedupes them and
124
+ * moves them to a single unified style tag in the head of the document.
125
+ */
126
+ const moveInlineStylesToHead = () => {
127
+ let styles = {};
128
+
129
+ return (tree) => {
130
+ tree.match({ tag: 'style' }, (node) => {
131
+ if (!node.content) return '';
132
+ const styleBlock = node.content[0].trim();
133
+ const hash = hashFromString(styleBlock);
134
+
135
+ if (styleBlock) {
136
+ styles[hash] = styleBlock;
137
+ }
138
+
139
+ // Remove the inline style node
140
+ return '';
141
+ });
142
+
143
+ tree.match({ tag: 'head' }, (node) => {
144
+ node.content.push({
145
+ tag: 'style',
146
+ content: Object.values(styles).join(''),
147
+ });
148
+
149
+ return node;
150
+ });
151
+
152
+ return tree;
153
+ };
154
+ };
155
+
156
+ const prepareHtmlFactory = (plugins) => {
157
+ const htmlProcessor = posthtml();
158
+
159
+ plugins.forEach((plugin) => {
160
+ htmlProcessor.use(plugin);
161
+ });
162
+
163
+ return async (body, template = (str) => str) => {
164
+ const content = template(body);
165
+
166
+ const processed = await htmlProcessor.process(content);
167
+
168
+ return processed.html;
169
+ };
170
+ };
171
+
172
+ /**
173
+ * This default pipeline removes all script and link tags from the HTML,
174
+ * moves all inline styles to the head and wraps everything in the email template.
175
+ *
176
+ * @param {string} body - the html body
177
+ * @param {function} template - the template function, defaults to no template
178
+ */
179
+ const defaultPipeline = prepareHtmlFactory([
180
+ onlyReturnBody(),
181
+ removeTags({ tags: ['script', 'link'] }),
182
+ convertRgbToHex(),
183
+ moveInlineStylesToHead(),
184
+ injectMsoStyles(),
185
+ injectConditionalComments(),
186
+ removeAttributes(['data-reactid', 'data-reactroot']),
187
+ ]);
188
+
189
+ const BASE64_REGEX = /data:image\/([a-zA-Z]*);base64,(.*)/;
190
+
191
+ // NODE.JS packacking factory
192
+
193
+ /**
194
+ * Turns base64 inlined images into image buffers and updates their src
195
+ * attribute accordingly. Returns an object containing the updated html and
196
+ * an array of image buffers. Different adapters can then hook into this to
197
+ * process the email into a ZIP archive or pushing it to an API.
198
+ *
199
+ * @param {string} body - the prepared html body
200
+ * @return {object} the processed html and buffers for all images
201
+ */
202
+ const preparePackageFactory =
203
+ ({ urlPrefix = '', handlePackage }) =>
204
+ async (body, opts = {}) => {
205
+ let counter = 0;
206
+ const images = [];
207
+
208
+ const processed = await posthtml()
209
+ .use((tree) => {
210
+ tree.match({ tag: 'img' }, (node) => {
211
+ const { src, alt } = node.attrs;
212
+
213
+ if (BASE64_REGEX.test(src)) {
214
+ const [_, ext, data] = src.match(
215
+ /data:image\/([a-zA-Z]*);base64,(.*)/,
216
+ );
217
+
218
+ const hash = Math.random().toString(36).substring(2, 7);
219
+
220
+ const filename = alt
221
+ ? `${formatFilename(alt)}-text-${hash}.${ext}`
222
+ : `image-${counter}.${ext}`;
223
+
224
+ node.attrs.src = `${urlPrefix}${filename}`;
225
+
226
+ const imgBuffer = Buffer.from(data, 'base64');
227
+
228
+ images.push({
229
+ filename,
230
+ buffer: imgBuffer,
231
+ });
232
+
233
+ counter++;
234
+ }
235
+ return node;
236
+ });
237
+
238
+ return tree;
239
+ })
240
+ .process(body);
241
+
242
+ return await handlePackage(
243
+ {
244
+ html: processed.html,
245
+ images,
246
+ },
247
+ opts,
248
+ );
249
+ };
250
+
251
+ const makeDefaultTemplate =
252
+ ({ lang = 'en-US', dir = 'ltr' } = {}) =>
253
+ (body) =>
254
+ `<!doctype html>
255
+ <html
256
+ lang="${lang}"
257
+ xml:lang="${lang}"
258
+ dir="${dir}"
259
+ xmlns="http://www.w3.org/1999/xhtml"
260
+ xmlns:v="urn:schemas-microsoft-com:vml"
261
+ xmlns:o="urn:schemas-microsoft-com:office:office"
262
+ >
263
+ <head>
264
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
265
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
266
+ <title>Chief</title>
267
+ <!--[if mso]>
268
+ <style type="text/css">
269
+ table {
270
+ border-collapse: collapse;
271
+ border: 0;
272
+ border-spacing: 0;
273
+ margin: 0;
274
+ mso-table-lspace: 0pt !important;
275
+ mso-table-rspace: 0pt !important;
276
+ }
277
+
278
+ img {
279
+ display: block !important;
280
+ }
281
+
282
+ div, td {padding:0;}
283
+
284
+ div {margin:0 !important;}
285
+
286
+ .notMso {
287
+ display: none;
288
+ mso-hide: all;
289
+ }
290
+ </style>
291
+ <noscript>
292
+ <xml>
293
+ <o:OfficeDocumentSettings>
294
+ <o:PixelsPerInch>96</o:PixelsPerInch>
295
+ </o:OfficeDocumentSettings>
296
+ </xml>
297
+ </noscript>
298
+ <![endif]-->
299
+ <meta name="x-apple-disable-message-reformatting" />
300
+ <meta httpEquiv="Content-Type" content="text/html; charset=utf-8" />
301
+ <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
302
+ <meta name="viewport" content="width=device-width" />
303
+ <meta name="color-scheme" content="light" />
304
+ <meta name="supported-color-schemes" content="light" />
305
+
306
+ <meta name="format-detection" content="telephone=no">
307
+ <meta name="format-detection" content="date=no">
308
+ <meta name="format-detection" content="address=no">
309
+ <meta name="format-detection" content="email=no">
310
+
311
+ <style>
312
+ a[x-apple-data-detectors] {
313
+ color: inherit !important;
314
+
315
+ font-size: inherit !important;
316
+ font-family: inherit !important;
317
+ font-weight: inherit !important;
318
+ line-height: inherit !important;
319
+ text-decoration: inherit !important;
320
+ }
321
+
322
+ #MessageViewBody a:not([style]) {
323
+ color: inherit !important;
324
+ font-size: inherit !important;
325
+ font-family: inherit !important;
326
+ font-weight: inherit !important;
327
+ line-height: inherit !important;
328
+ text-decoration: inherit !important;
329
+ }
330
+ </style>
331
+ </head>
332
+ <body class="body" style="padding:0;">
333
+ ${body}
334
+ </body>
335
+ </html>`;
336
+
337
+ const defaultTemplate = makeDefaultTemplate();
338
+
339
+ /**
340
+ * Turns an HTML email into a ZIP package and saves that ZIP file to disk.
341
+ *
342
+ * @param {string} body - the prepared html body
343
+ * @return {Buffer} the zip file buffer
344
+ */
345
+ const packageToZip = preparePackageFactory({
346
+ urlPrefix: '',
347
+ handlePackage: async ({ html, images }) => {
348
+ const zipStream = new compressing.zip.Stream();
349
+ const htmlEntry = Buffer.from(html, 'utf8');
350
+ zipStream.addEntry(htmlEntry, { relativePath: `./index.html` });
351
+
352
+ images.forEach(({ filename, buffer }) => {
353
+ zipStream.addEntry(buffer, { relativePath: `./${filename}` });
354
+ });
355
+
356
+ const zipBuffer = await getStream.buffer(zipStream);
357
+ return zipBuffer;
358
+ },
359
+ });
360
+
361
+ const defaultOptions = {
362
+ mailchimpId: null,
363
+ mailchimpAPIKey: null,
364
+ mailchimpServerPrefix: null,
365
+ };
366
+
367
+ const getIdForCampaign = async (campaignId, mailchimpApi, offset = 0) => {
368
+ if (!campaignId) throw new Error('No campaign ID provided');
369
+
370
+ const count = 100;
371
+
372
+ try {
373
+ const response = await mailchimpApi.campaigns.list({
374
+ count,
375
+ offset,
376
+ sortField: 'create_time',
377
+ sortDir: 'DESC',
378
+ });
379
+
380
+ const campaign = response.campaigns.find(
381
+ (campaign) => campaign.web_id == campaignId,
382
+ );
383
+
384
+ if (!campaign && response.total_items > count + offset) {
385
+ return await getIdForCampaign(campaignId, offset + count);
386
+ }
387
+ if (!campaign) {
388
+ throw new Error(`No mailchimp campaign found for ${campaignId}`);
389
+ }
390
+ if (['sending', 'sent'].includes(campaign.status)) {
391
+ throw new Error("Campaign already sent. Can't update content ¯_(ツ)_/¯");
392
+ }
393
+
394
+ return { campaignId: campaign?.id };
395
+ } catch (e) {
396
+ throw new Error(e.message);
397
+ }
398
+ };
399
+
400
+ const publish = async (campaignId, zipFile, mailchimpApi) => {
401
+ if (!campaignId) throw new Error('No campaign ID provided');
402
+ if (!zipFile) throw new Error('No zip file provided');
403
+
404
+ try {
405
+ const response = await mailchimpApi.campaigns.setContent(campaignId, {
406
+ archive: {
407
+ archive_type: 'tar',
408
+ archive_content: zipFile,
409
+ },
410
+ });
411
+
412
+ return response;
413
+ } catch (e) {
414
+ throw new Error(e.message);
415
+ }
416
+ };
417
+
418
+ const prepareEmailToTarBuffer = async (html, images) => {
419
+ const tarStream = new compressing.tar.Stream();
420
+
421
+ const htmlEntry = Buffer.from(html, 'utf8');
422
+ tarStream.addEntry(htmlEntry, { relativePath: `./index.html` });
423
+
424
+ images.forEach(({ filename, buffer }) => {
425
+ tarStream.addEntry(buffer, { relativePath: `./${filename}` });
426
+ });
427
+
428
+ const tarBuffer = await getStream.buffer(tarStream);
429
+
430
+ return tarBuffer.toString('base64');
431
+ };
432
+
433
+ /**
434
+ * Publishes the eamil to mailchimp
435
+ *
436
+ * @param {string} body - the prepared html body
437
+ * @param {object} options - the options object containing { mailchimpId, mailchimpAPIKey, mailchimpServerPrefix }
438
+ */
439
+ const packageToMailchimp = preparePackageFactory({
440
+ urlPrefix: '',
441
+ handlePackage: async ({ html, images }, opts) => {
442
+ const config = Object.assign({}, defaultOptions, opts);
443
+
444
+ const { mailchimpId, mailchimpAPIKey } = config;
445
+ if (mailchimpId === null) throw new Error('mailchimpId is required');
446
+ if (mailchimpAPIKey === null) throw new Error('mailchimpAPIKey is quired');
447
+
448
+ const mailchimpServerPrefix =
449
+ config.mailchimpServerPrefix || mailchimpAPIKey.split('-').pop();
450
+
451
+ mailchimpAPI.setConfig({
452
+ apiKey: mailchimpAPIKey,
453
+ server: mailchimpServerPrefix,
454
+ });
455
+
456
+ const { campaignId } = await getIdForCampaign(mailchimpId, mailchimpAPI);
457
+ const tarBuffer = await prepareEmailToTarBuffer(html, images);
458
+ await publish(campaignId, tarBuffer, mailchimpAPI);
459
+
460
+ return campaignId;
461
+ },
462
+ });
463
+
464
+ /**
465
+ * Extracts the images from the HTML and publishes the package to S3
466
+ * Returns the HTML with all image URLs updated to point to S3
467
+ *
468
+ * @param {string} body - the prepared html body
469
+ * @param {object} options - the options object containing { awsAccessKeyId, awsSecretAccessKey, awsBucket, url, prefix }
470
+ * @return {string} HTML of the mail with all image URLs updated to point to S3
471
+ */
472
+ const packageToS3 = async (body, opts = {}) => {
473
+ const {
474
+ awsAccessKeyId,
475
+ awsSecretAccessKey,
476
+ awsBucket,
477
+ url,
478
+ prefix = '',
479
+ } = opts;
480
+
481
+ if (!awsAccessKeyId) throw new Error('awsAccessKeyId is required');
482
+ if (!awsSecretAccessKey) throw new Error('awsSecretAccessKey is required');
483
+ if (!awsBucket) throw new Error('awsBucket is required');
484
+
485
+ const s3 = new AWS.S3({
486
+ accessKeyId: awsAccessKeyId,
487
+ secretAccessKey: awsSecretAccessKey,
488
+ });
489
+
490
+ const uploadFileToS3 = async (buffer, filename) => {
491
+ await s3
492
+ .upload({
493
+ Bucket: awsBucket,
494
+ Key: `${prefix}${filename}`,
495
+ Body: buffer,
496
+ ACL: 'public-read',
497
+ CacheControl: 'no-store',
498
+ })
499
+ .promise();
500
+ };
501
+
502
+ const runUpload = preparePackageFactory({
503
+ urlPrefix: `${url}${prefix}`,
504
+ handlePackage: async ({ html, images }) => {
505
+ const htmlBuffer = Buffer.from(html, 'utf8');
506
+ await uploadFileToS3(htmlBuffer, 'index.html');
507
+
508
+ for (const image of images) {
509
+ await uploadFileToS3(image.buffer, image.filename);
510
+ }
511
+
512
+ return html;
513
+ },
514
+ });
515
+
516
+ return await runUpload(body);
517
+ };
518
+
519
+ const sendEmailSes = async (
520
+ { fromName, fromEmail, toName, toEmail, subject, plainBody, htmlBody },
521
+ opts = {},
522
+ ) => {
523
+ const { awsAccessKeyId, awsSecretAccessKey } = opts;
524
+
525
+ if (!awsAccessKeyId) throw new Error('awsAccessKeyId is required');
526
+ if (!awsSecretAccessKey) throw new Error('awsSecretAccessKey is required');
527
+
528
+ const fromAddress = fromName ? `"${fromName}" <${fromEmail}>` : fromEmail;
529
+ const toAddress = toName ? `"${toName}" <${toEmail}>` : toEmail;
530
+
531
+ const ses = new AWS.SES({
532
+ accessKeyId: awsAccessKeyId,
533
+ secretAccessKey: awsSecretAccessKey,
534
+ region: 'us-east-1',
535
+ httpOptions: { timeout: 5000 },
536
+ });
537
+
538
+ const emailRes = await ses
539
+ .sendEmail({
540
+ Source: fromAddress,
541
+ Destination: {
542
+ ToAddresses: [toAddress],
543
+ },
544
+ Message: {
545
+ Subject: {
546
+ Charset: 'UTF-8',
547
+ Data: subject,
548
+ },
549
+ Body: {
550
+ Html: {
551
+ Charset: 'UTF-8',
552
+ Data: htmlBody,
553
+ },
554
+ Text: {
555
+ Charset: 'UTF-8',
556
+ Data: plainBody,
557
+ },
558
+ },
559
+ },
560
+ })
561
+ .promise();
562
+ if (!emailRes.MessageId) {
563
+ throw new Error('Failed to send email');
564
+ } else {
565
+ return true;
566
+ }
567
+ };
568
+
569
+ /**
570
+ * Turns nodemailer's callback style API into a promise
571
+ */
572
+ const performSend = async (transporter, message) => {
573
+ return new Promise((resolve, reject) => {
574
+ transporter.sendMail(message, (error, info) => {
575
+ if (error) {
576
+ reject(error);
577
+ } else {
578
+ resolve(info);
579
+ }
580
+ });
581
+ });
582
+ };
583
+
584
+ /**
585
+ * Sends an email via SMTP
586
+ *
587
+ * @param {object} email - The email object { fromName, fromEmail, toName, toEmail, subject, plainBody, htmlBody }
588
+ * @param {object} options - The options object { smtpHost, smtpPort, smtpUser, smtpPass, useTLS }
589
+ */
590
+ const sendEmailSMTP = async (
591
+ { fromName, fromEmail, toName, toEmail, subject, plainBody, htmlBody },
592
+ { smtpHost, smtpPort = 25, smtpUser, smtpPass, useTLS = true } = {},
593
+ ) => {
594
+ if (!smtpHost) throw new Error('SMTP host is required');
595
+ if (!smtpUser) throw new Error('SMTP user is required');
596
+ if (!smtpPass) throw new Error('SMTP pass is required');
597
+
598
+ const fromAddress = fromName ? `"${fromName}" <${fromEmail}>` : fromEmail;
599
+ const toAddress = toName ? `"${toName}" <${toEmail}>` : toEmail;
600
+
601
+ const transporter = nodemailer.createTransport({
602
+ host: smtpHost,
603
+ port: smtpPort,
604
+ secure: useTLS,
605
+ auth: {
606
+ user: smtpUser,
607
+ pass: smtpPass,
608
+ },
609
+ });
610
+
611
+ const message = {
612
+ from: fromAddress,
613
+ to: toAddress,
614
+ subject,
615
+ text: plainBody,
616
+ html: htmlBody,
617
+ };
618
+
619
+ await performSend(transporter, message);
620
+ };
621
+
622
+ exports.defaultTemplate = defaultTemplate;
623
+ exports.makeDefaultTemplate = makeDefaultTemplate;
624
+ exports.packageToMailchimp = packageToMailchimp;
625
+ exports.packageToS3 = packageToS3;
626
+ exports.packageToZip = packageToZip;
627
+ exports.prepareHtml = defaultPipeline;
628
+ exports.prepareHtmlFactory = prepareHtmlFactory;
629
+ exports.preparePackageFactory = preparePackageFactory;
630
+ exports.sendEmailSMTP = sendEmailSMTP;
631
+ exports.sendEmailSes = sendEmailSes;