@dereekb/nestjs 12.7.0 → 13.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/LICENSE +1 -1
  2. package/index.cjs.js +292 -0
  3. package/index.d.ts +1 -0
  4. package/index.esm.js +270 -0
  5. package/mailgun/index.cjs.js +646 -0
  6. package/mailgun/index.d.ts +1 -0
  7. package/mailgun/index.esm.js +633 -0
  8. package/mailgun/package.json +24 -3
  9. package/mailgun/src/lib/mailgun.d.ts +2 -2
  10. package/mailgun/src/lib/mailgun.type.d.ts +1 -1
  11. package/mailgun/src/lib/mailgun.util.d.ts +22 -17
  12. package/openai/index.cjs.js +310 -0
  13. package/openai/index.d.ts +1 -0
  14. package/openai/index.esm.js +293 -0
  15. package/openai/package.json +24 -5
  16. package/openai/src/lib/index.d.ts +0 -1
  17. package/openai/src/lib/webhook/webhook.openai.controller.d.ts +1 -1
  18. package/openai/src/lib/webhook/webhook.openai.d.ts +2 -2
  19. package/openai/src/lib/webhook/webhook.openai.service.d.ts +1 -1
  20. package/package.json +58 -28
  21. package/stripe/index.cjs.js +223 -0
  22. package/stripe/index.d.ts +1 -0
  23. package/stripe/index.esm.js +215 -0
  24. package/stripe/package.json +24 -5
  25. package/stripe/src/lib/index.d.ts +1 -1
  26. package/stripe/src/lib/stripe.module.d.ts +2 -2
  27. package/stripe/src/lib/webhook/webhook.stripe.controller.d.ts +1 -1
  28. package/typeform/index.cjs.js +378 -0
  29. package/typeform/index.d.ts +1 -0
  30. package/typeform/index.esm.js +363 -0
  31. package/typeform/package.json +24 -5
  32. package/typeform/src/lib/index.d.ts +0 -1
  33. package/typeform/src/lib/webhook/webhook.typeform.controller.d.ts +1 -1
  34. package/vapiai/index.cjs.js +306 -0
  35. package/vapiai/index.d.ts +1 -0
  36. package/vapiai/index.esm.js +297 -0
  37. package/vapiai/package.json +24 -5
  38. package/vapiai/src/lib/index.d.ts +0 -1
  39. package/vapiai/src/lib/vapiai.type.d.ts +3 -1
  40. package/vapiai/src/lib/webhook/webhook.vapiai.controller.d.ts +1 -1
  41. package/vapiai/src/lib/webhook/webhook.vapiai.d.ts +1 -9
  42. package/vapiai/src/lib/webhook/webhook.vapiai.types.d.ts +6 -34
  43. package/CHANGELOG.md +0 -2001
  44. package/mailgun/LICENSE +0 -21
  45. package/mailgun/src/index.js +0 -5
  46. package/mailgun/src/index.js.map +0 -1
  47. package/mailgun/src/lib/index.js +0 -10
  48. package/mailgun/src/lib/index.js.map +0 -1
  49. package/mailgun/src/lib/mailgun.api.js +0 -37
  50. package/mailgun/src/lib/mailgun.api.js.map +0 -1
  51. package/mailgun/src/lib/mailgun.config.js +0 -45
  52. package/mailgun/src/lib/mailgun.config.js.map +0 -1
  53. package/mailgun/src/lib/mailgun.js +0 -205
  54. package/mailgun/src/lib/mailgun.js.map +0 -1
  55. package/mailgun/src/lib/mailgun.service.js +0 -53
  56. package/mailgun/src/lib/mailgun.service.js.map +0 -1
  57. package/mailgun/src/lib/mailgun.service.module.js +0 -84
  58. package/mailgun/src/lib/mailgun.service.module.js.map +0 -1
  59. package/mailgun/src/lib/mailgun.type.js +0 -3
  60. package/mailgun/src/lib/mailgun.type.js.map +0 -1
  61. package/mailgun/src/lib/mailgun.util.js +0 -206
  62. package/mailgun/src/lib/mailgun.util.js.map +0 -1
  63. package/openai/LICENSE +0 -21
  64. package/openai/src/index.js +0 -5
  65. package/openai/src/index.js.map +0 -1
  66. package/openai/src/lib/index.js +0 -11
  67. package/openai/src/lib/index.js.map +0 -1
  68. package/openai/src/lib/openai.api.js +0 -22
  69. package/openai/src/lib/openai.api.js.map +0 -1
  70. package/openai/src/lib/openai.config.js +0 -29
  71. package/openai/src/lib/openai.config.js.map +0 -1
  72. package/openai/src/lib/openai.module.js +0 -41
  73. package/openai/src/lib/openai.module.js.map +0 -1
  74. package/openai/src/lib/openai.type.js +0 -3
  75. package/openai/src/lib/openai.type.js.map +0 -1
  76. package/openai/src/lib/openai.util.js +0 -48
  77. package/openai/src/lib/openai.util.js.map +0 -1
  78. package/openai/src/lib/webhook/index.js +0 -10
  79. package/openai/src/lib/webhook/index.js.map +0 -1
  80. package/openai/src/lib/webhook/webhook.openai.config.js +0 -17
  81. package/openai/src/lib/webhook/webhook.openai.config.js.map +0 -1
  82. package/openai/src/lib/webhook/webhook.openai.controller.js +0 -30
  83. package/openai/src/lib/webhook/webhook.openai.controller.js.map +0 -1
  84. package/openai/src/lib/webhook/webhook.openai.js +0 -41
  85. package/openai/src/lib/webhook/webhook.openai.js.map +0 -1
  86. package/openai/src/lib/webhook/webhook.openai.module.js +0 -39
  87. package/openai/src/lib/webhook/webhook.openai.module.js.map +0 -1
  88. package/openai/src/lib/webhook/webhook.openai.service.js +0 -48
  89. package/openai/src/lib/webhook/webhook.openai.service.js.map +0 -1
  90. package/openai/src/lib/webhook/webhook.openai.verify.js +0 -37
  91. package/openai/src/lib/webhook/webhook.openai.verify.js.map +0 -1
  92. package/src/index.js +0 -5
  93. package/src/index.js.map +0 -1
  94. package/src/lib/decorators/index.js +0 -6
  95. package/src/lib/decorators/index.js.map +0 -1
  96. package/src/lib/decorators/local.decorator.js +0 -17
  97. package/src/lib/decorators/local.decorator.js.map +0 -1
  98. package/src/lib/decorators/rawbody.js +0 -44
  99. package/src/lib/decorators/rawbody.js.map +0 -1
  100. package/src/lib/index.js +0 -7
  101. package/src/lib/index.js.map +0 -1
  102. package/src/lib/middlewares/index.js +0 -7
  103. package/src/lib/middlewares/index.js.map +0 -1
  104. package/src/lib/middlewares/json.middleware.js +0 -16
  105. package/src/lib/middlewares/json.middleware.js.map +0 -1
  106. package/src/lib/middlewares/rawbody.middleware.js +0 -16
  107. package/src/lib/middlewares/rawbody.middleware.js.map +0 -1
  108. package/src/lib/middlewares/webhook.js +0 -51
  109. package/src/lib/middlewares/webhook.js.map +0 -1
  110. package/src/lib/module/client/client.config.js +0 -13
  111. package/src/lib/module/client/client.config.js.map +0 -1
  112. package/src/lib/module/client/client.js +0 -8
  113. package/src/lib/module/client/client.js.map +0 -1
  114. package/src/lib/module/client/client.module.js +0 -36
  115. package/src/lib/module/client/client.module.js.map +0 -1
  116. package/src/lib/module/client/client.service.js +0 -30
  117. package/src/lib/module/client/client.service.js.map +0 -1
  118. package/src/lib/module/client/index.js +0 -8
  119. package/src/lib/module/client/index.js.map +0 -1
  120. package/src/lib/module/env/env.config.js +0 -14
  121. package/src/lib/module/env/env.config.js.map +0 -1
  122. package/src/lib/module/env/env.js +0 -10
  123. package/src/lib/module/env/env.js.map +0 -1
  124. package/src/lib/module/env/env.nest.js +0 -16
  125. package/src/lib/module/env/env.nest.js.map +0 -1
  126. package/src/lib/module/env/env.service.js +0 -33
  127. package/src/lib/module/env/env.service.js.map +0 -1
  128. package/src/lib/module/env/index.js +0 -8
  129. package/src/lib/module/env/index.js.map +0 -1
  130. package/src/lib/module/index.js +0 -7
  131. package/src/lib/module/index.js.map +0 -1
  132. package/src/lib/module/module.js +0 -26
  133. package/src/lib/module/module.js.map +0 -1
  134. package/stripe/LICENSE +0 -21
  135. package/stripe/src/index.js +0 -5
  136. package/stripe/src/index.js.map +0 -1
  137. package/stripe/src/lib/index.js +0 -8
  138. package/stripe/src/lib/index.js.map +0 -1
  139. package/stripe/src/lib/stripe.api.js +0 -40
  140. package/stripe/src/lib/stripe.api.js.map +0 -1
  141. package/stripe/src/lib/stripe.config.js +0 -19
  142. package/stripe/src/lib/stripe.config.js.map +0 -1
  143. package/stripe/src/lib/stripe.module.js +0 -41
  144. package/stripe/src/lib/stripe.module.js.map +0 -1
  145. package/stripe/src/lib/stripe.type.js +0 -4
  146. package/stripe/src/lib/stripe.type.js.map +0 -1
  147. package/stripe/src/lib/webhook/index.js +0 -8
  148. package/stripe/src/lib/webhook/index.js.map +0 -1
  149. package/stripe/src/lib/webhook/webhook.stripe.controller.js +0 -30
  150. package/stripe/src/lib/webhook/webhook.stripe.controller.js.map +0 -1
  151. package/stripe/src/lib/webhook/webhook.stripe.js +0 -67
  152. package/stripe/src/lib/webhook/webhook.stripe.js.map +0 -1
  153. package/stripe/src/lib/webhook/webhook.stripe.module.js +0 -20
  154. package/stripe/src/lib/webhook/webhook.stripe.module.js.map +0 -1
  155. package/stripe/src/lib/webhook/webhook.stripe.service.js +0 -36
  156. package/stripe/src/lib/webhook/webhook.stripe.service.js.map +0 -1
  157. package/typeform/LICENSE +0 -21
  158. package/typeform/src/index.js +0 -5
  159. package/typeform/src/index.js.map +0 -1
  160. package/typeform/src/lib/index.js +0 -11
  161. package/typeform/src/lib/index.js.map +0 -1
  162. package/typeform/src/lib/typeform.api.js +0 -22
  163. package/typeform/src/lib/typeform.api.js.map +0 -1
  164. package/typeform/src/lib/typeform.config.js +0 -21
  165. package/typeform/src/lib/typeform.config.js.map +0 -1
  166. package/typeform/src/lib/typeform.module.js +0 -39
  167. package/typeform/src/lib/typeform.module.js.map +0 -1
  168. package/typeform/src/lib/typeform.type.js +0 -3
  169. package/typeform/src/lib/typeform.type.js.map +0 -1
  170. package/typeform/src/lib/typeform.util.js +0 -26
  171. package/typeform/src/lib/typeform.util.js.map +0 -1
  172. package/typeform/src/lib/webhook/index.js +0 -12
  173. package/typeform/src/lib/webhook/index.js.map +0 -1
  174. package/typeform/src/lib/webhook/webhook.typeform.config.js +0 -17
  175. package/typeform/src/lib/webhook/webhook.typeform.config.js.map +0 -1
  176. package/typeform/src/lib/webhook/webhook.typeform.controller.js +0 -30
  177. package/typeform/src/lib/webhook/webhook.typeform.controller.js.map +0 -1
  178. package/typeform/src/lib/webhook/webhook.typeform.form.js +0 -113
  179. package/typeform/src/lib/webhook/webhook.typeform.form.js.map +0 -1
  180. package/typeform/src/lib/webhook/webhook.typeform.js +0 -27
  181. package/typeform/src/lib/webhook/webhook.typeform.js.map +0 -1
  182. package/typeform/src/lib/webhook/webhook.typeform.module.js +0 -38
  183. package/typeform/src/lib/webhook/webhook.typeform.module.js.map +0 -1
  184. package/typeform/src/lib/webhook/webhook.typeform.service.js +0 -45
  185. package/typeform/src/lib/webhook/webhook.typeform.service.js.map +0 -1
  186. package/typeform/src/lib/webhook/webhook.typeform.type.js +0 -3
  187. package/typeform/src/lib/webhook/webhook.typeform.type.js.map +0 -1
  188. package/typeform/src/lib/webhook/webhook.typeform.verify.js +0 -28
  189. package/typeform/src/lib/webhook/webhook.typeform.verify.js.map +0 -1
  190. package/vapiai/LICENSE +0 -21
  191. package/vapiai/src/index.js +0 -5
  192. package/vapiai/src/index.js.map +0 -1
  193. package/vapiai/src/lib/index.js +0 -10
  194. package/vapiai/src/lib/index.js.map +0 -1
  195. package/vapiai/src/lib/vapiai.api.js +0 -32
  196. package/vapiai/src/lib/vapiai.api.js.map +0 -1
  197. package/vapiai/src/lib/vapiai.config.js +0 -17
  198. package/vapiai/src/lib/vapiai.config.js.map +0 -1
  199. package/vapiai/src/lib/vapiai.module.js +0 -38
  200. package/vapiai/src/lib/vapiai.module.js.map +0 -1
  201. package/vapiai/src/lib/vapiai.type.js +0 -3
  202. package/vapiai/src/lib/vapiai.type.js.map +0 -1
  203. package/vapiai/src/lib/webhook/index.js +0 -10
  204. package/vapiai/src/lib/webhook/index.js.map +0 -1
  205. package/vapiai/src/lib/webhook/webhook.vapi.config.js +0 -20
  206. package/vapiai/src/lib/webhook/webhook.vapi.config.js.map +0 -1
  207. package/vapiai/src/lib/webhook/webhook.vapiai.controller.js +0 -38
  208. package/vapiai/src/lib/webhook/webhook.vapiai.controller.js.map +0 -1
  209. package/vapiai/src/lib/webhook/webhook.vapiai.js +0 -42
  210. package/vapiai/src/lib/webhook/webhook.vapiai.js.map +0 -1
  211. package/vapiai/src/lib/webhook/webhook.vapiai.module.js +0 -41
  212. package/vapiai/src/lib/webhook/webhook.vapiai.module.js.map +0 -1
  213. package/vapiai/src/lib/webhook/webhook.vapiai.service.js +0 -52
  214. package/vapiai/src/lib/webhook/webhook.vapiai.service.js.map +0 -1
  215. package/vapiai/src/lib/webhook/webhook.vapiai.types.js +0 -25
  216. package/vapiai/src/lib/webhook/webhook.vapiai.types.js.map +0 -1
  217. package/vapiai/src/lib/webhook/webhook.vapiai.verify.js +0 -49
  218. package/vapiai/src/lib/webhook/webhook.vapiai.verify.js.map +0 -1
@@ -0,0 +1,646 @@
1
+ 'use strict';
2
+
3
+ var nestjs = require('@dereekb/nestjs');
4
+ var util = require('@dereekb/util');
5
+ var common = require('@nestjs/common');
6
+ var Mailgun = require('mailgun.js');
7
+ var FormData = require('form-data');
8
+ var config = require('@nestjs/config');
9
+
10
+ const DEFAULT_RECIPIENT_VARIABLE_PREFIX = 'recipient-';
11
+ const MAILGUN_REPLY_TO_EMAIL_HEADER_DATA_VARIABLE_KEY = `h:Reply-To`;
12
+ /**
13
+ * The maximum number of recipients allowed in a single batch send request.
14
+ */
15
+ const MAX_BATCH_SEND_RECIPIENTS = 1000;
16
+ /**
17
+ * Converts a MailgunTemplateEmailRequest to a MailgunMessageData.
18
+ *
19
+ * @param config
20
+ * @returns
21
+ */
22
+ function convertMailgunTemplateEmailRequestToMailgunMessageData(config) {
23
+ const {
24
+ request,
25
+ defaultSender,
26
+ isTestingEnvironment: testEnvironment,
27
+ recipientVariablePrefix: inputRecipientVariablePrefix = DEFAULT_RECIPIENT_VARIABLE_PREFIX,
28
+ addRecipientVariablePrefixToAllMergedGlobalVariables: inputAddRecipientVariablePrefixToAllMergedGlobalVariables = true,
29
+ addCopyOfMergedRecipientVariablesWithoutPrefixToGlobalVariables: inputAddCopyOfMergedRecipientVariablesWithoutPrefixToGlobalVariables = false,
30
+ addCopyOfTemplateVariablesWithRecipientVariablePrefix: inputAddCopyOfTemplateVariablesWithRecipientVariablePrefix = false
31
+ } = config;
32
+ const {
33
+ recipientVariablesConfig
34
+ } = request;
35
+ const recipientVariablePrefix = recipientVariablesConfig?.recipientVariablePrefix ?? inputRecipientVariablePrefix;
36
+ const addRecipientVariablePrefixToAllMergedGlobalVariables = recipientVariablesConfig?.addRecipientVariablePrefixToAllMergedGlobalVariables ?? inputAddRecipientVariablePrefixToAllMergedGlobalVariables;
37
+ const addCopyOfMergedRecipientVariablesWithoutPrefixToGlobalVariables = recipientVariablesConfig?.addCopyOfMergedRecipientVariablesWithoutPrefixToGlobalVariables ?? inputAddCopyOfMergedRecipientVariablesWithoutPrefixToGlobalVariables;
38
+ const addCopyOfTemplateVariablesWithRecipientVariablePrefix = recipientVariablesConfig?.addCopyOfTemplateVariablesWithRecipientVariablePrefix ?? inputAddCopyOfTemplateVariablesWithRecipientVariablePrefix;
39
+ const finalizeRecipientVariables = request.finalizeRecipientVariables ?? util.MAP_IDENTITY;
40
+ const allowBatchSending = request.batchSend ?? true;
41
+ const mergeRecipientVariablesIntoGlobalVariable = !allowBatchSending;
42
+ function mapEmailToLowercase(x) {
43
+ return {
44
+ ...x,
45
+ email: x.email.toLowerCase()
46
+ };
47
+ }
48
+ const toInput = util.asArray(request.to).map(mapEmailToLowercase);
49
+ const ccInput = request.cc ? util.asArray(request.cc).map(mapEmailToLowercase) : undefined;
50
+ const bccInput = request.bcc ? util.asArray(request.bcc).map(mapEmailToLowercase) : undefined;
51
+ const from = request.from ? convertMailgunRecipientToString(request.from) : defaultSender;
52
+ const to = convertMailgunRecipientsToStrings(toInput);
53
+ const cc = ccInput?.length ? convertMailgunRecipientsToStrings(ccInput) : undefined;
54
+ const bcc = bccInput?.length ? convertMailgunRecipientsToStrings(bccInput) : undefined;
55
+ // throw an error if batchSend is not defined and cc or bcc is defined
56
+ if (request.batchSend == null && (ccInput || bccInput)) {
57
+ throw new Error('convertMailgunTemplateEmailRequestToMailgunMessageData(): batchSend must be false when either "cc" or "bcc" is defined.');
58
+ }
59
+ if (allowBatchSending && to.length > MAX_BATCH_SEND_RECIPIENTS) {
60
+ throw new Error(`convertMailgunTemplateEmailRequestToMailgunMessageData(): Can only batch send to a maximum of ${MAX_BATCH_SEND_RECIPIENTS} recipients.`);
61
+ }
62
+ const data = {
63
+ from,
64
+ to,
65
+ cc,
66
+ bcc,
67
+ subject: request.subject,
68
+ template: request.template,
69
+ ...request.messageData
70
+ };
71
+ if (request.replyTo != null) {
72
+ data[MAILGUN_REPLY_TO_EMAIL_HEADER_DATA_VARIABLE_KEY] = convertMailgunRecipientToString(request.replyTo);
73
+ }
74
+ if (request.testEmail === true || (testEnvironment ?? nestjs.isTestNodeEnv()) && request.testEmail !== false) {
75
+ data['o:testmode'] = true;
76
+ }
77
+ if (request.templateVariables) {
78
+ util.forEachKeyValue(request.templateVariables, {
79
+ forEach: x => {
80
+ const [key, value] = x;
81
+ const encodedValue = encodeMailgunTemplateVariableValue(value);
82
+ if (encodedValue != null) {
83
+ data[`v:${key}`] = encodedValue;
84
+ if (recipientVariablePrefix && addCopyOfTemplateVariablesWithRecipientVariablePrefix) {
85
+ data[`v:${recipientVariablePrefix}${key}`] = encodedValue;
86
+ }
87
+ }
88
+ }
89
+ });
90
+ }
91
+ const hasUserVariables = Boolean(data['recipient-variables']) || toInput.findIndex(x => x.userVariables != null) !== -1;
92
+ if (hasUserVariables) {
93
+ let recipientVariables = {};
94
+ const allRecipientVariableKeys = new Set();
95
+ toInput.forEach(({
96
+ email,
97
+ userVariables
98
+ }) => {
99
+ if (userVariables != null && !util.objectIsEmpty(userVariables)) {
100
+ recipientVariables[email] = userVariables;
101
+ util.addToSet(allRecipientVariableKeys, Object.keys(userVariables));
102
+ }
103
+ });
104
+ if (data['recipient-variables']) {
105
+ const decoded = JSON.parse(data['recipient-variables']);
106
+ util.forEachKeyValue(decoded, {
107
+ forEach: x => {
108
+ const [recipientEmail, userVariables] = x;
109
+ const email = recipientEmail.toLowerCase();
110
+ if (recipientVariables[email] != null) {
111
+ util.overrideInObject(recipientVariables[email], {
112
+ from: [userVariables],
113
+ filter: {
114
+ valueFilter: util.KeyValueTypleValueFilter.UNDEFINED
115
+ }
116
+ });
117
+ } else {
118
+ recipientVariables[email] = userVariables;
119
+ }
120
+ util.addToSet(allRecipientVariableKeys, Object.keys(userVariables));
121
+ }
122
+ });
123
+ }
124
+ // Finalize the recipient variables before they are re-encoded back to JSON
125
+ recipientVariables = finalizeRecipientVariables(recipientVariables, {
126
+ messageData: data,
127
+ config
128
+ }) ?? recipientVariables;
129
+ if (mergeRecipientVariablesIntoGlobalVariable) {
130
+ const addRecipientPrefixVariable = recipientVariablePrefix && addRecipientVariablePrefixToAllMergedGlobalVariables;
131
+ // iterate all recipient variables and merge them into the global variables
132
+ util.forEachKeyValue(recipientVariables, {
133
+ forEach: x => {
134
+ const [email, userVariables] = x;
135
+ util.forEachKeyValue(userVariables, {
136
+ forEach: y => {
137
+ const [key, value] = y;
138
+ const encodedValue = encodeMailgunTemplateVariableValue(value);
139
+ if (encodedValue != null) {
140
+ if (addRecipientPrefixVariable) {
141
+ // also add the variable using the recipient variable prefix
142
+ const recipientVariableKey = `${recipientVariablePrefix}${key}`;
143
+ data[`v:${recipientVariableKey}`] = encodedValue;
144
+ }
145
+ // add if not adding the prefix variable, or if it was requested
146
+ if (!addRecipientPrefixVariable || addCopyOfMergedRecipientVariablesWithoutPrefixToGlobalVariables) {
147
+ data[`v:${key}`] = encodedValue;
148
+ }
149
+ }
150
+ }
151
+ });
152
+ }
153
+ });
154
+ } else {
155
+ // set back on the data object
156
+ data['recipient-variables'] = JSON.stringify(recipientVariables);
157
+ // add all recipient variable to the other variables so they can be used easily/directly in templates as variables too.
158
+ // https://documentation.mailgun.com/en/latest/user_manual.html#attaching-data-to-messages
159
+ if (recipientVariablePrefix) {
160
+ util.forEachInIterable(allRecipientVariableKeys, key => {
161
+ const recipientVariableKey = `${recipientVariablePrefix}${key}`;
162
+ // v:recipient-id=%recipient.id%
163
+ data[`v:${recipientVariableKey}`] = `%recipient.${key}%`;
164
+ });
165
+ }
166
+ }
167
+ }
168
+ // double check and remove the recipient variables if we merged them into the global variables
169
+ if (mergeRecipientVariablesIntoGlobalVariable) {
170
+ delete data['recipient-variables'];
171
+ }
172
+ const inputAttachments = request.attachments;
173
+ if (inputAttachments) {
174
+ if (data.attachment) {
175
+ throw new Error(`Cannot specify attachments in both messageData and in the request's attachments field.`);
176
+ }
177
+ data.attachment = inputAttachments;
178
+ }
179
+ return data;
180
+ }
181
+ function convertMailgunRecipientsToStrings(recipients) {
182
+ return recipients.map(x => convertMailgunRecipientToString(x));
183
+ }
184
+ function convertMailgunRecipientToString(recipient) {
185
+ let address = recipient.email;
186
+ if (recipient.name) {
187
+ address = `${recipient.name} <${address}>`;
188
+ }
189
+ return address;
190
+ }
191
+ /**
192
+ * Encodes a value to a string for use as a Mailgun template variable. Throws an error if the value is not supported.
193
+ *
194
+ * @param value The value to encode.
195
+ * @returns The encoded value, or undefined if the value is null or undefined.
196
+ */
197
+ function encodeMailgunTemplateVariableValue(value) {
198
+ let encodedValue;
199
+ switch (typeof value) {
200
+ case 'object':
201
+ if (value) {
202
+ if (value instanceof Date) {
203
+ encodedValue = value.toISOString();
204
+ } else {
205
+ encodedValue = JSON.stringify(value);
206
+ }
207
+ }
208
+ break;
209
+ case 'bigint':
210
+ case 'boolean':
211
+ case 'number':
212
+ case 'string':
213
+ encodedValue = String(value); // encoded as a string value
214
+ break;
215
+ default:
216
+ if (value) {
217
+ throw new Error(`Invalid value "${value}" passed to encodeMailgunTemplateVariableValue().`);
218
+ }
219
+ }
220
+ return encodedValue;
221
+ }
222
+
223
+ /******************************************************************************
224
+ Copyright (c) Microsoft Corporation.
225
+
226
+ Permission to use, copy, modify, and/or distribute this software for any
227
+ purpose with or without fee is hereby granted.
228
+
229
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
230
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
231
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
232
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
233
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
234
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
235
+ PERFORMANCE OF THIS SOFTWARE.
236
+ ***************************************************************************** */
237
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
238
+
239
+
240
+ function __decorate(decorators, target, key, desc) {
241
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
242
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
243
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
244
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
245
+ }
246
+
247
+ function __param(paramIndex, decorator) {
248
+ return function (target, key) { decorator(target, key, paramIndex); }
249
+ }
250
+
251
+ function __metadata(metadataKey, metadataValue) {
252
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
253
+ }
254
+
255
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
256
+ var e = new Error(message);
257
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
258
+ };
259
+
260
+ class MailgunServiceConfig {
261
+ // Mailgun Config
262
+ mailgun;
263
+ /**
264
+ * Base URL to the client.
265
+ */
266
+ clientUrl;
267
+ /**
268
+ * Main domain to send emails from.
269
+ */
270
+ domain;
271
+ /**
272
+ * Mailgun sender string.
273
+ */
274
+ sender;
275
+ /**
276
+ * Additional messages config
277
+ */
278
+ messages;
279
+ static assertValidConfig(config) {
280
+ if (!config.mailgun.username) {
281
+ throw new Error('No mailgun username specified.');
282
+ } else if (!config.mailgun.key) {
283
+ throw new Error('No mailgun key specified.');
284
+ } else if (!config.domain) {
285
+ throw new Error('No mailgun domain specified.');
286
+ } else if (!config.clientUrl) {
287
+ throw new Error('No client url specified.');
288
+ } else if (!config.sender) {
289
+ throw new Error('No mailgun sender specified.');
290
+ } else if (!config.messages) {
291
+ throw new Error('No mailgun messages config specified.');
292
+ }
293
+ }
294
+ }
295
+
296
+ exports.MailgunApi = class MailgunApi {
297
+ config;
298
+ client;
299
+ constructor(config) {
300
+ this.config = config;
301
+ this.client = new Mailgun(FormData).client({
302
+ ...config.mailgun
303
+ });
304
+ }
305
+ get messages() {
306
+ return this.client.messages;
307
+ }
308
+ get clientUrl() {
309
+ return this.config.clientUrl;
310
+ }
311
+ get domain() {
312
+ return this.config.domain;
313
+ }
314
+ get sender() {
315
+ return this.config.sender;
316
+ }
317
+ };
318
+ exports.MailgunApi = __decorate([common.Injectable(), __param(0, common.Inject(MailgunServiceConfig)), __metadata("design:paramtypes", [MailgunServiceConfig])], exports.MailgunApi);
319
+
320
+ exports.MailgunService = class MailgunService {
321
+ _mailgunApi;
322
+ _serverEnvironmentService;
323
+ constructor(mailgunApi, serverEnvironmentService) {
324
+ this._mailgunApi = mailgunApi;
325
+ this._serverEnvironmentService = serverEnvironmentService;
326
+ }
327
+ get mailgunApi() {
328
+ return this._mailgunApi;
329
+ }
330
+ get serverEnvironmentService() {
331
+ return this._serverEnvironmentService;
332
+ }
333
+ async sendTemplateEmail(request) {
334
+ const domain = this.mailgunApi.domain;
335
+ const sender = this.mailgunApi.sender;
336
+ const isTestingEnvironment = this.serverEnvironmentService.isTestingEnv;
337
+ const {
338
+ recipientVariablePrefix
339
+ } = this.mailgunApi.config.messages;
340
+ const data = convertMailgunTemplateEmailRequestToMailgunMessageData({
341
+ request,
342
+ defaultSender: sender,
343
+ recipientVariablePrefix,
344
+ isTestingEnvironment
345
+ });
346
+ let result;
347
+ const shouldSend = !isTestingEnvironment || request.sendTestEmails || this.mailgunApi.config.messages.sendTestEmails;
348
+ if (shouldSend) {
349
+ try {
350
+ result = await this.mailgunApi.messages.create(domain, data);
351
+ } catch (e) {
352
+ console.error('Failed sending email: ', e);
353
+ throw e;
354
+ }
355
+ } else {
356
+ result = {
357
+ status: 200,
358
+ message: 'Success. Env prevented sending email.'
359
+ };
360
+ }
361
+ return result;
362
+ }
363
+ };
364
+ exports.MailgunService = __decorate([common.Injectable(), __param(0, common.Inject(exports.MailgunApi)), __param(1, common.Inject(nestjs.ServerEnvironmentService)), __metadata("design:paramtypes", [exports.MailgunApi, nestjs.ServerEnvironmentService])], exports.MailgunService);
365
+
366
+ function mailgunServiceConfigFactory(configService, serverEnvironmentService) {
367
+ const isTestingEnv = serverEnvironmentService.isTestingEnv;
368
+ const useSandbox = configService.get('USE_MAILGUN_SANDBOX') === 'true' || isTestingEnv;
369
+ const sendTestEmails = configService.get('MAILGUN_SEND_TEST_EMAILS') === 'true';
370
+ let key = configService.get('MAILGUN_API_KEY');
371
+ let domain = configService.get('MAILGUN_DOMAIN');
372
+ if (useSandbox) {
373
+ key = configService.get('MAILGUN_SANDBOX_API_KEY');
374
+ domain = configService.get('MAILGUN_SANDBOX_DOMAIN');
375
+ if (!key || !domain) {
376
+ throw new Error('USE_MAILGUN_SANDBOX is set to "true" (or current environment is a testing environment), but no environment variables for the sandbox (MAILGUN_SANDBOX_API_KEY, MAILGUN_SANDBOX_DOMAIN) are provided.');
377
+ } else if (!serverEnvironmentService.isTestingEnv) {
378
+ console.log('Using Mailgun Sandbox Domain: ', domain);
379
+ }
380
+ } else if (!serverEnvironmentService.isTestingEnv) {
381
+ console.log('Using Mailgun Production Domain: ', domain);
382
+ }
383
+ const name = configService.get('MAILGUN_SENDER_NAME');
384
+ const email = configService.get('MAILGUN_SENDER_EMAIL');
385
+ const url = configService.get('MAILGUN_API_URL');
386
+ const recipientVariablePrefix = configService.get('MAILGUN_MESSAGES_RECIPIENT_VARIABLE_PREFIX') ?? undefined;
387
+ if (!email) {
388
+ throw new Error('MAILGUN_SENDER_EMAIL is required but was not configured.');
389
+ } else if (!key) {
390
+ throw new Error('MAILGUN_API_KEY (or MAILGUN_SANDBOX_API_KEY for tests) is required but was not configured.');
391
+ } else if (!domain) {
392
+ throw new Error('MAILGUN_DOMAIN (or MAILGUN_SANDBOX_DOMAIN for tests) is required but was not configured.');
393
+ }
394
+ const clientUrl = configService.get('CLIENT_APP_URL') ?? domain;
395
+ const config = {
396
+ mailgun: {
397
+ username: configService.get('MAILGUN_USERNAME') ?? 'api',
398
+ key,
399
+ url
400
+ },
401
+ domain,
402
+ clientUrl,
403
+ sender: convertMailgunRecipientToString({
404
+ name,
405
+ email
406
+ }),
407
+ messages: {
408
+ sendTestEmails,
409
+ recipientVariablePrefix
410
+ }
411
+ };
412
+ MailgunServiceConfig.assertValidConfig(config);
413
+ return config;
414
+ }
415
+ exports.MailgunServiceModule = class MailgunServiceModule {};
416
+ exports.MailgunServiceModule = __decorate([common.Module({
417
+ imports: [config.ConfigModule],
418
+ providers: [{
419
+ provide: MailgunServiceConfig,
420
+ inject: [config.ConfigService, nestjs.ServerEnvironmentService],
421
+ useFactory: mailgunServiceConfigFactory
422
+ }, exports.MailgunApi, exports.MailgunService],
423
+ exports: [exports.MailgunApi, exports.MailgunService]
424
+ })], exports.MailgunServiceModule);
425
+
426
+ /**
427
+ * The default template subject to use when batch sending emails.
428
+ *
429
+ * This pulls the subject from each recipient's user variables.
430
+ */
431
+ const MAILGUN_BATCH_SEND_RECIPIENT_SUBJECT_TEMPLATE = `%recipient.subject%`;
432
+ /**
433
+ * Creates a composite key from the from/replyTo email addresses used to group MailgunRecipientBatchSendTarget values.
434
+ */
435
+ function mailgunRecipientBatchSendTargetFromReplyToBatchGroupKey(recipient) {
436
+ const fromEmail = (recipient.from?.email ?? '').toLowerCase();
437
+ const replyToEmail = (recipient.replyTo?.email ?? '').toLowerCase();
438
+ return `f:${fromEmail}|r:${replyToEmail}`;
439
+ }
440
+ /**
441
+ * Creates a ExpandMailgunRecipientBatchSendTargetRequestFactory from the input config.
442
+ *
443
+ * @param config
444
+ * @returns
445
+ */
446
+ function expandMailgunRecipientBatchSendTargetRequestFactory(config) {
447
+ const {
448
+ request: inputBaseRequest,
449
+ useSubjectFromRecipientUserVariables,
450
+ allowSingleRecipientBatchSendRequests,
451
+ recipientVariablesConfig,
452
+ mailgunRecipientBatchSendTargetEntityKeyRecipientLookup,
453
+ overrideCarbonCopyVariablesWithCarbonCopyKeyRecipients
454
+ } = config;
455
+ const defaultSubject = inputBaseRequest.subject;
456
+ if (!defaultSubject && !useSubjectFromRecipientUserVariables) {
457
+ throw new Error('defaultSubject must be set when "useSubjectFromRecipientUserVariables" is false');
458
+ }
459
+ /**
460
+ * Returns the carbon copy recipients, based on the input.
461
+ *
462
+ * Will return undefined if the array would be empty.
463
+ *
464
+ * @param input
465
+ * @returns
466
+ */
467
+ function determineCarbonCopyRecipients(input) {
468
+ const {
469
+ baseRequestCarbonCopyRecipients,
470
+ carbonCopyRecipients,
471
+ carbonCopyRecipientsKeys
472
+ } = input;
473
+ let cc = carbonCopyRecipients ? util.asArray(carbonCopyRecipients) : baseRequestCarbonCopyRecipients;
474
+ const resolvedCc = mailgunRecipientBatchSendTargetEntityKeyRecipientLookup?.getRecipientsForKeys(carbonCopyRecipientsKeys);
475
+ if (resolvedCc?.length) {
476
+ if (overrideCarbonCopyVariablesWithCarbonCopyKeyRecipients) {
477
+ cc = resolvedCc;
478
+ } else {
479
+ cc = [...(cc ?? []), ...resolvedCc];
480
+ }
481
+ }
482
+ return cc?.length ? cc : undefined;
483
+ }
484
+ const baseRequestCc = determineCarbonCopyRecipients({
485
+ carbonCopyRecipients: inputBaseRequest.cc,
486
+ carbonCopyRecipientsKeys: inputBaseRequest.ccKeys
487
+ });
488
+ const baseRequestBcc = determineCarbonCopyRecipients({
489
+ carbonCopyRecipients: inputBaseRequest.bcc,
490
+ carbonCopyRecipientsKeys: inputBaseRequest.bccKeys
491
+ });
492
+ const baseRequestFrom = inputBaseRequest.from ?? mailgunRecipientBatchSendTargetEntityKeyRecipientLookup?.getRecipientOrDefaultForKey(inputBaseRequest.fromKey);
493
+ const baseRequestReplyTo = inputBaseRequest.replyTo ?? mailgunRecipientBatchSendTargetEntityKeyRecipientLookup?.getRecipientOrDefaultForKey(inputBaseRequest.replyToKey);
494
+ const baseRequest = {
495
+ ...inputBaseRequest,
496
+ from: baseRequestFrom,
497
+ replyTo: baseRequestReplyTo,
498
+ cc: baseRequestCc,
499
+ bcc: baseRequestBcc
500
+ };
501
+ delete baseRequest.fromKey;
502
+ delete baseRequest.replyToKey;
503
+ delete baseRequest.ccKeys;
504
+ delete baseRequest.bccKeys;
505
+ const configAllowBatchSend = baseRequest.batchSend !== false;
506
+ return inputRecipients => {
507
+ // Process recipients to resolve keys
508
+ const recipients = inputRecipients.map(recipient => {
509
+ let from = recipient.from;
510
+ let replyTo = recipient.replyTo;
511
+ if (mailgunRecipientBatchSendTargetEntityKeyRecipientLookup) {
512
+ // try the fromKey, otherwise use the baseRequest.from
513
+ if (!from) {
514
+ from = mailgunRecipientBatchSendTargetEntityKeyRecipientLookup.getRecipientOrDefaultForKey(recipient.fromKey, baseRequest.from);
515
+ }
516
+ // try the replyToKey, otherwise use the baseRequest.replyTo
517
+ if (!replyTo) {
518
+ replyTo = mailgunRecipientBatchSendTargetEntityKeyRecipientLookup.getRecipientOrDefaultForKey(recipient.replyToKey, baseRequest.replyTo);
519
+ }
520
+ } else {
521
+ // use defaults from base request
522
+ if (!from) {
523
+ from = baseRequest.from;
524
+ }
525
+ if (!replyTo) {
526
+ replyTo = baseRequest.replyTo;
527
+ }
528
+ }
529
+ const cc = determineCarbonCopyRecipients({
530
+ baseRequestCarbonCopyRecipients: baseRequestCc,
531
+ carbonCopyRecipients: recipient.cc,
532
+ carbonCopyRecipientsKeys: recipient.ccKeys
533
+ });
534
+ const bcc = determineCarbonCopyRecipients({
535
+ baseRequestCarbonCopyRecipients: baseRequestBcc,
536
+ carbonCopyRecipients: recipient.bcc,
537
+ carbonCopyRecipientsKeys: recipient.bccKeys
538
+ });
539
+ const result = {
540
+ ...recipient,
541
+ from,
542
+ replyTo,
543
+ cc,
544
+ bcc
545
+ };
546
+ return result;
547
+ });
548
+ const allowBatchSend = configAllowBatchSend && (allowSingleRecipientBatchSendRequests || recipients.length > 1);
549
+ const nonBatchSendRequests = [];
550
+ const batchSendRequestRecipients = [];
551
+ recipients.forEach(recipient => {
552
+ const recipientHasCarbonCopy = Boolean(recipient.cc?.length || recipient.bcc?.length);
553
+ if (allowBatchSend && !recipientHasCarbonCopy) {
554
+ // add to batch send recipients
555
+ batchSendRequestRecipients.push(recipient);
556
+ } else {
557
+ // add to non-batch send requests
558
+ // use the subject from the recipient's user variables if available as a default
559
+ const cc = recipient.cc;
560
+ const bcc = recipient.bcc;
561
+ const subject = (useSubjectFromRecipientUserVariables ? recipient.userVariables?.['subject'] : undefined) ?? defaultSubject ?? recipient.userVariables?.['subject'];
562
+ const request = {
563
+ ...baseRequest,
564
+ from: recipient.from ?? baseRequest.from,
565
+ replyTo: recipient.replyTo ?? baseRequest.replyTo,
566
+ recipientVariablesConfig: baseRequest.recipientVariablesConfig ?? recipientVariablesConfig,
567
+ to: recipient,
568
+ cc,
569
+ bcc,
570
+ subject,
571
+ batchSend: false // explicitly disable batch send for non-batch requests
572
+ };
573
+ nonBatchSendRequests.push(request);
574
+ }
575
+ });
576
+ // create batch send request(s)
577
+ const batchSendRequests = [];
578
+ if (batchSendRequestRecipients.length > 0) {
579
+ const subject = useSubjectFromRecipientUserVariables ? MAILGUN_BATCH_SEND_RECIPIENT_SUBJECT_TEMPLATE : defaultSubject;
580
+ // Group recipients by their from/replyTo values
581
+ const batchSendRecipientGroups = util.makeValuesGroupMap(batchSendRequestRecipients, mailgunRecipientBatchSendTargetFromReplyToBatchGroupKey);
582
+ batchSendRecipientGroups.forEach(groupRecipients => {
583
+ // All recipients in this group should share the same from/replyTo values
584
+ const firstRecipient = groupRecipients[0];
585
+ const batchRequest = {
586
+ ...baseRequest,
587
+ from: firstRecipient.from,
588
+ replyTo: firstRecipient.replyTo,
589
+ recipientVariablesConfig: baseRequest.recipientVariablesConfig ?? recipientVariablesConfig,
590
+ to: groupRecipients,
591
+ subject,
592
+ batchSend: true
593
+ };
594
+ batchSendRequests.push(batchRequest);
595
+ });
596
+ }
597
+ return util.filterMaybeArrayValues([...batchSendRequests, ...nonBatchSendRequests]);
598
+ };
599
+ }
600
+ /**
601
+ * Creates a MailgunRecipientBatchSendTargetEntityKeyRecipientLookup given the input configuration.
602
+ *
603
+ * @param config The configuration for the lookup.
604
+ * @returns The lookup.
605
+ */
606
+ function mailgunRecipientBatchSendTargetEntityKeyRecipientLookup(config) {
607
+ const {
608
+ recipientsMap
609
+ } = config;
610
+ function getRecipientOrDefaultForKey(input, defaultRecipient) {
611
+ let result = defaultRecipient;
612
+ if (input) {
613
+ result = recipientsMap.get(input) ?? defaultRecipient;
614
+ }
615
+ return result;
616
+ }
617
+ function getRecipientsForKeys(input) {
618
+ let result = undefined;
619
+ if (input) {
620
+ const keysArray = util.asArray(input);
621
+ const recipients = util.filterMaybeArrayValues(keysArray.map(key => recipientsMap.get(key)));
622
+ if (recipients.length > 0) {
623
+ result = recipients;
624
+ }
625
+ }
626
+ return result;
627
+ }
628
+ return {
629
+ recipientsMap,
630
+ getRecipientOrDefaultForKey,
631
+ getRecipientsForKeys
632
+ };
633
+ }
634
+
635
+ exports.DEFAULT_RECIPIENT_VARIABLE_PREFIX = DEFAULT_RECIPIENT_VARIABLE_PREFIX;
636
+ exports.MAILGUN_BATCH_SEND_RECIPIENT_SUBJECT_TEMPLATE = MAILGUN_BATCH_SEND_RECIPIENT_SUBJECT_TEMPLATE;
637
+ exports.MAILGUN_REPLY_TO_EMAIL_HEADER_DATA_VARIABLE_KEY = MAILGUN_REPLY_TO_EMAIL_HEADER_DATA_VARIABLE_KEY;
638
+ exports.MAX_BATCH_SEND_RECIPIENTS = MAX_BATCH_SEND_RECIPIENTS;
639
+ exports.convertMailgunRecipientToString = convertMailgunRecipientToString;
640
+ exports.convertMailgunRecipientsToStrings = convertMailgunRecipientsToStrings;
641
+ exports.convertMailgunTemplateEmailRequestToMailgunMessageData = convertMailgunTemplateEmailRequestToMailgunMessageData;
642
+ exports.encodeMailgunTemplateVariableValue = encodeMailgunTemplateVariableValue;
643
+ exports.expandMailgunRecipientBatchSendTargetRequestFactory = expandMailgunRecipientBatchSendTargetRequestFactory;
644
+ exports.mailgunRecipientBatchSendTargetEntityKeyRecipientLookup = mailgunRecipientBatchSendTargetEntityKeyRecipientLookup;
645
+ exports.mailgunRecipientBatchSendTargetFromReplyToBatchGroupKey = mailgunRecipientBatchSendTargetFromReplyToBatchGroupKey;
646
+ exports.mailgunServiceConfigFactory = mailgunServiceConfigFactory;
@@ -0,0 +1 @@
1
+ export * from "./src/index";