@hintergrund/worker 0.1.6 → 0.1.7

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 (186) hide show
  1. package/dist/api/cms/handlers/admin-users.handler.d.ts +8 -0
  2. package/dist/api/cms/handlers/admin-users.handler.d.ts.map +1 -0
  3. package/dist/api/cms/handlers/admin-users.handler.js +121 -0
  4. package/dist/api/cms/handlers/agent-conversations.handler.d.ts +7 -0
  5. package/dist/api/cms/handlers/agent-conversations.handler.d.ts.map +1 -0
  6. package/dist/api/cms/handlers/agent-conversations.handler.js +94 -0
  7. package/dist/api/cms/handlers/auth.handler.d.ts +0 -3
  8. package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -1
  9. package/dist/api/cms/handlers/auth.handler.js +74 -153
  10. package/dist/api/cms/handlers/website-repo.handler.d.ts +8 -0
  11. package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -0
  12. package/dist/api/cms/handlers/website-repo.handler.js +148 -0
  13. package/dist/api/cms/routes/index.d.ts.map +1 -1
  14. package/dist/api/cms/routes/index.js +16 -4
  15. package/dist/api/emails/handlers/campaigns.handler.d.ts +10 -23
  16. package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
  17. package/dist/api/emails/handlers/campaigns.handler.js +164 -92
  18. package/dist/api/emails/handlers/invoice.handler.d.ts +5 -19
  19. package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -1
  20. package/dist/api/emails/handlers/invoice.handler.js +58 -340
  21. package/dist/api/emails/handlers/public.handler.d.ts +6 -29
  22. package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
  23. package/dist/api/emails/handlers/public.handler.js +150 -312
  24. package/dist/api/emails/handlers/send.handler.d.ts +5 -17
  25. package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
  26. package/dist/api/emails/handlers/send.handler.js +107 -92
  27. package/dist/api/emails/handlers/settings.handler.d.ts +28 -33
  28. package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
  29. package/dist/api/emails/handlers/settings.handler.js +96 -287
  30. package/dist/api/emails/handlers/subscribers.handler.d.ts +13 -0
  31. package/dist/api/emails/handlers/subscribers.handler.d.ts.map +1 -0
  32. package/dist/api/emails/handlers/subscribers.handler.js +125 -0
  33. package/dist/api/emails/handlers/webhook.handler.d.ts +1 -2
  34. package/dist/api/emails/handlers/webhook.handler.d.ts.map +1 -1
  35. package/dist/api/emails/handlers/webhook.handler.js +66 -166
  36. package/dist/api/emails/routes/admin.routes.d.ts +1 -3
  37. package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
  38. package/dist/api/emails/routes/admin.routes.js +19 -49
  39. package/dist/api/emails/routes/public.routes.d.ts +1 -3
  40. package/dist/api/emails/routes/public.routes.d.ts.map +1 -1
  41. package/dist/api/emails/routes/public.routes.js +2 -9
  42. package/dist/api/shop/handlers/prices.handler.d.ts +2 -15
  43. package/dist/api/shop/handlers/prices.handler.d.ts.map +1 -1
  44. package/dist/api/shop/handlers/prices.handler.js +2 -83
  45. package/dist/api/shop/handlers/products.handler.d.ts +29 -20
  46. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
  47. package/dist/api/shop/handlers/products.handler.js +195 -162
  48. package/dist/api/shop/handlers/public.handler.d.ts +24 -8
  49. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
  50. package/dist/api/shop/handlers/public.handler.js +525 -78
  51. package/dist/api/shop/routes.d.ts.map +1 -1
  52. package/dist/api/shop/routes.js +14 -9
  53. package/dist/hintergrund-assets.d.ts +3 -2
  54. package/dist/hintergrund-assets.d.ts.map +1 -1
  55. package/dist/hintergrund-assets.js +4 -2
  56. package/dist/index.d.ts +14 -7
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +44 -4
  59. package/dist/lib/auth/crypto.d.ts +2 -15
  60. package/dist/lib/auth/crypto.d.ts.map +1 -1
  61. package/dist/lib/auth/crypto.js +8 -95
  62. package/dist/lib/auth/jwt.d.ts +0 -4
  63. package/dist/lib/auth/jwt.d.ts.map +1 -1
  64. package/dist/lib/auth/jwt.js +0 -6
  65. package/dist/lib/config.d.ts +1 -1
  66. package/dist/lib/config.d.ts.map +1 -1
  67. package/dist/lib/config.js +42 -86
  68. package/dist/lib/email-template.d.ts +15 -0
  69. package/dist/lib/email-template.d.ts.map +1 -0
  70. package/dist/lib/email-template.js +58 -0
  71. package/dist/lib/email.d.ts +18 -8
  72. package/dist/lib/email.d.ts.map +1 -1
  73. package/dist/lib/email.js +59 -70
  74. package/dist/lib/github-config.d.ts +19 -0
  75. package/dist/lib/github-config.d.ts.map +1 -0
  76. package/dist/lib/github-config.js +23 -0
  77. package/dist/lib/github.d.ts +10 -0
  78. package/dist/lib/github.d.ts.map +1 -1
  79. package/dist/lib/github.js +20 -2
  80. package/dist/lib/project-db.d.ts +24 -0
  81. package/dist/lib/project-db.d.ts.map +1 -0
  82. package/dist/lib/project-db.js +172 -0
  83. package/dist/lib/template.js +4 -4
  84. package/dist/middleware/auth.d.ts +0 -2
  85. package/dist/middleware/auth.d.ts.map +1 -1
  86. package/dist/middleware/auth.js +21 -50
  87. package/package.json +3 -2
  88. package/dist/api/builder/handlers/generate.handler.d.ts +0 -12
  89. package/dist/api/builder/handlers/generate.handler.d.ts.map +0 -1
  90. package/dist/api/builder/handlers/generate.handler.js +0 -203
  91. package/dist/api/builder/handlers/template.handler.d.ts +0 -12
  92. package/dist/api/builder/handlers/template.handler.d.ts.map +0 -1
  93. package/dist/api/builder/handlers/template.handler.js +0 -208
  94. package/dist/api/builder/routes.d.ts +0 -7
  95. package/dist/api/builder/routes.d.ts.map +0 -1
  96. package/dist/api/builder/routes.js +0 -15
  97. package/dist/api/cms/handlers/assets.handler.d.ts +0 -31
  98. package/dist/api/cms/handlers/assets.handler.d.ts.map +0 -1
  99. package/dist/api/cms/handlers/assets.handler.js +0 -200
  100. package/dist/api/cms/handlers/config.handler.d.ts +0 -7
  101. package/dist/api/cms/handlers/config.handler.d.ts.map +0 -1
  102. package/dist/api/cms/handlers/config.handler.js +0 -37
  103. package/dist/api/cms/handlers/content.handler.d.ts +0 -21
  104. package/dist/api/cms/handlers/content.handler.d.ts.map +0 -1
  105. package/dist/api/cms/handlers/content.handler.js +0 -117
  106. package/dist/api/cms/routes/assets.routes.d.ts +0 -4
  107. package/dist/api/cms/routes/assets.routes.d.ts.map +0 -1
  108. package/dist/api/cms/routes/assets.routes.js +0 -13
  109. package/dist/api/cms/routes/content.routes.d.ts +0 -4
  110. package/dist/api/cms/routes/content.routes.d.ts.map +0 -1
  111. package/dist/api/cms/routes/content.routes.js +0 -11
  112. package/dist/api/emails/handlers/branding.handler.d.ts +0 -17
  113. package/dist/api/emails/handlers/branding.handler.d.ts.map +0 -1
  114. package/dist/api/emails/handlers/branding.handler.js +0 -120
  115. package/dist/api/emails/handlers/contacts.handler.d.ts +0 -37
  116. package/dist/api/emails/handlers/contacts.handler.d.ts.map +0 -1
  117. package/dist/api/emails/handlers/contacts.handler.js +0 -161
  118. package/dist/api/emails/handlers/templates.handler.d.ts +0 -32
  119. package/dist/api/emails/handlers/templates.handler.d.ts.map +0 -1
  120. package/dist/api/emails/handlers/templates.handler.js +0 -132
  121. package/dist/api/newsletter/handlers/email.handler.d.ts +0 -7
  122. package/dist/api/newsletter/handlers/email.handler.d.ts.map +0 -1
  123. package/dist/api/newsletter/handlers/email.handler.js +0 -102
  124. package/dist/api/newsletter/handlers/emails.handler.d.ts +0 -31
  125. package/dist/api/newsletter/handlers/emails.handler.d.ts.map +0 -1
  126. package/dist/api/newsletter/handlers/emails.handler.js +0 -262
  127. package/dist/api/newsletter/handlers/invoice.handler.d.ts +0 -22
  128. package/dist/api/newsletter/handlers/invoice.handler.d.ts.map +0 -1
  129. package/dist/api/newsletter/handlers/invoice.handler.js +0 -455
  130. package/dist/api/newsletter/handlers/public.handler.d.ts +0 -22
  131. package/dist/api/newsletter/handlers/public.handler.d.ts.map +0 -1
  132. package/dist/api/newsletter/handlers/public.handler.js +0 -300
  133. package/dist/api/newsletter/handlers/send.handler.d.ts +0 -12
  134. package/dist/api/newsletter/handlers/send.handler.d.ts.map +0 -1
  135. package/dist/api/newsletter/handlers/send.handler.js +0 -153
  136. package/dist/api/newsletter/handlers/subscribers.handler.d.ts +0 -22
  137. package/dist/api/newsletter/handlers/subscribers.handler.d.ts.map +0 -1
  138. package/dist/api/newsletter/handlers/subscribers.handler.js +0 -195
  139. package/dist/api/newsletter/routes/admin.routes.d.ts +0 -4
  140. package/dist/api/newsletter/routes/admin.routes.d.ts.map +0 -1
  141. package/dist/api/newsletter/routes/admin.routes.js +0 -28
  142. package/dist/api/newsletter/routes/index.d.ts +0 -4
  143. package/dist/api/newsletter/routes/index.d.ts.map +0 -1
  144. package/dist/api/newsletter/routes/index.js +0 -9
  145. package/dist/api/newsletter/routes/public.routes.d.ts +0 -4
  146. package/dist/api/newsletter/routes/public.routes.d.ts.map +0 -1
  147. package/dist/api/newsletter/routes/public.routes.js +0 -9
  148. package/dist/api/shop/handlers/assets.handler.d.ts +0 -3
  149. package/dist/api/shop/handlers/assets.handler.d.ts.map +0 -1
  150. package/dist/api/shop/handlers/assets.handler.js +0 -62
  151. package/dist/api/shop/handlers/checkout.handler.d.ts +0 -10
  152. package/dist/api/shop/handlers/checkout.handler.d.ts.map +0 -1
  153. package/dist/api/shop/handlers/checkout.handler.js +0 -50
  154. package/dist/api/shop/handlers/customers.handler.d.ts +0 -17
  155. package/dist/api/shop/handlers/customers.handler.d.ts.map +0 -1
  156. package/dist/api/shop/handlers/customers.handler.js +0 -89
  157. package/dist/api/shop/handlers/orders.handler.d.ts +0 -17
  158. package/dist/api/shop/handlers/orders.handler.d.ts.map +0 -1
  159. package/dist/api/shop/handlers/orders.handler.js +0 -84
  160. package/dist/api/shop/handlers/stats.handler.d.ts +0 -10
  161. package/dist/api/shop/handlers/stats.handler.d.ts.map +0 -1
  162. package/dist/api/shop/handlers/stats.handler.js +0 -71
  163. package/dist/api/shop/handlers/webhook.handler.d.ts +0 -10
  164. package/dist/api/shop/handlers/webhook.handler.d.ts.map +0 -1
  165. package/dist/api/shop/handlers/webhook.handler.js +0 -233
  166. package/dist/cms-assets.d.ts +0 -4
  167. package/dist/cms-assets.d.ts.map +0 -1
  168. package/dist/cms-assets.js +0 -5
  169. package/dist/cms-bundle.d.ts +0 -3
  170. package/dist/cms-bundle.d.ts.map +0 -1
  171. package/dist/cms-bundle.js +0 -4
  172. package/dist/config-loader.d.ts +0 -26
  173. package/dist/config-loader.d.ts.map +0 -1
  174. package/dist/config-loader.js +0 -98
  175. package/dist/jwt.d.ts +0 -26
  176. package/dist/jwt.d.ts.map +0 -1
  177. package/dist/jwt.js +0 -102
  178. package/dist/lib/plunk.d.ts +0 -204
  179. package/dist/lib/plunk.d.ts.map +0 -1
  180. package/dist/lib/plunk.js +0 -259
  181. package/dist/template.d.ts +0 -2
  182. package/dist/template.d.ts.map +0 -1
  183. package/dist/template.js +0 -61
  184. package/dist/utils.d.ts +0 -23
  185. package/dist/utils.d.ts.map +0 -1
  186. package/dist/utils.js +0 -110
@@ -1,300 +0,0 @@
1
- // Utility functions for token generation
2
- function generateToken() {
3
- const array = new Uint8Array(32);
4
- crypto.getRandomValues(array);
5
- return Array.from(array, (b) => b.toString(16).padStart(2, '0')).join('');
6
- }
7
- function generateId() {
8
- return Math.random().toString(36).substring(2, 14);
9
- }
10
- // Email validation
11
- function isValidEmail(email) {
12
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
13
- return emailRegex.test(email);
14
- }
15
- // Helper to get auto email template
16
- async function getAutoEmailTemplate(db, type) {
17
- const template = await db
18
- .prepare('SELECT subject, html_content FROM emails WHERE email_type = ? LIMIT 1')
19
- .bind(type)
20
- .first();
21
- return template;
22
- }
23
- // Send email via Resend
24
- async function sendEmailViaResend(apiKey, to, from, fromName, subject, html) {
25
- const response = await fetch('https://api.resend.com/emails', {
26
- method: 'POST',
27
- headers: {
28
- Authorization: `Bearer ${apiKey}`,
29
- 'Content-Type': 'application/json',
30
- },
31
- body: JSON.stringify({
32
- from: `${fromName} <${from}>`,
33
- to,
34
- subject,
35
- html,
36
- }),
37
- });
38
- if (!response.ok) {
39
- const error = await response.text();
40
- throw new Error(`Failed to send email: ${error}`);
41
- }
42
- }
43
- // Send confirmation email via Resend
44
- async function sendConfirmationEmail(db, email, token, apiKey, from, fromName, confirmationUrl) {
45
- const confirmLink = `${confirmationUrl}?token=${token}`;
46
- const template = await getAutoEmailTemplate(db, 'confirm');
47
- let html = '';
48
- let subject = 'Confirm your subscription';
49
- if (template) {
50
- subject = template.subject;
51
- html = template.html_content.replace(/{{confirm_url}}/g, confirmLink);
52
- }
53
- else {
54
- // Default template
55
- html = `
56
- <h2>Confirm your subscription</h2>
57
- <p>Thank you for subscribing! Please confirm your email address by clicking the link below:</p>
58
- <p><a href="${confirmLink}">${confirmLink}</a></p>
59
- <p>If you didn't request this, you can safely ignore this email.</p>
60
- `;
61
- }
62
- await sendEmailViaResend(apiKey, email, from, fromName, subject, html);
63
- }
64
- /**
65
- * POST /api/email/subscribe
66
- * Public endpoint to subscribe to newsletter
67
- */
68
- export async function subscribe(c) {
69
- try {
70
- const body = (await c.req.json());
71
- const { email, name } = body;
72
- // Validate email
73
- if (!email || !isValidEmail(email)) {
74
- return c.json({ success: false, message: 'Invalid email address' }, 400);
75
- }
76
- const normalizedEmail = email.toLowerCase().trim();
77
- // Get environment variables
78
- const db = c.env.DB;
79
- const apiKey = c.env.HG_NEWSLETTER_EMAIL_API_KEY;
80
- const fromEmail = c.env.HG_NEWSLETTER_FROM_EMAIL;
81
- const fromName = c.env.HG_NEWSLETTER_FROM_NAME;
82
- const confirmationUrl = c.env.HG_NEWSLETTER_CONFIRMATION_URL;
83
- if (!db || !apiKey || !fromEmail || !confirmationUrl) {
84
- return c.json({ success: false, message: 'Newsletter not configured' }, 500);
85
- }
86
- // Check if subscriber already exists
87
- const existing = await db
88
- .prepare('SELECT id, status FROM subscribers WHERE email = ?')
89
- .bind(normalizedEmail)
90
- .first();
91
- if (existing) {
92
- // If already subscribed, return success
93
- if (existing.status === 'subscribed') {
94
- return c.json({
95
- success: true,
96
- message: 'You are already subscribed!',
97
- });
98
- }
99
- // If pending, resend confirmation
100
- if (existing.status === 'pending') {
101
- // Generate new token
102
- const token = generateToken();
103
- const now = Date.now();
104
- await db
105
- .prepare(`UPDATE subscribers
106
- SET confirmation_token = ?, confirmation_sent_at = ?, updated_at = ?
107
- WHERE email = ?`)
108
- .bind(token, now, now, normalizedEmail)
109
- .run();
110
- // Send confirmation email
111
- await sendConfirmationEmail(db, normalizedEmail, token, apiKey, fromEmail, fromName || 'Newsletter', confirmationUrl);
112
- return c.json({
113
- success: true,
114
- message: 'Please check your email to confirm your subscription',
115
- });
116
- }
117
- // If unsubscribed, allow re-subscription
118
- if (existing.status === 'unsubscribed') {
119
- // Generate new confirmation token
120
- const token = generateToken();
121
- const now = Date.now();
122
- await db
123
- .prepare(`UPDATE subscribers
124
- SET status = 'pending', confirmation_token = ?, confirmation_sent_at = ?, updated_at = ?
125
- WHERE email = ?`)
126
- .bind(token, now, now, normalizedEmail)
127
- .run();
128
- // Send confirmation email
129
- await sendConfirmationEmail(db, normalizedEmail, token, apiKey, fromEmail, fromName || 'Newsletter', confirmationUrl);
130
- return c.json({
131
- success: true,
132
- message: 'Please check your email to confirm your subscription',
133
- });
134
- }
135
- }
136
- // Create new pending subscriber
137
- const id = generateId();
138
- const token = generateToken();
139
- const unsubscribeToken = generateToken();
140
- const now = Date.now();
141
- await db
142
- .prepare(`INSERT INTO subscribers
143
- (id, email, name, status, source, confirmation_token, unsubscribe_token, confirmation_sent_at, created_at, updated_at)
144
- VALUES (?, ?, ?, 'pending', 'website', ?, ?, ?, ?, ?)`)
145
- .bind(id, normalizedEmail, name || null, token, unsubscribeToken, now, now, now)
146
- .run();
147
- // Send confirmation email
148
- await sendConfirmationEmail(db, normalizedEmail, token, apiKey, fromEmail, fromName || 'Newsletter', confirmationUrl);
149
- return c.json({
150
- success: true,
151
- message: 'Please check your email to confirm your subscription',
152
- });
153
- }
154
- catch (error) {
155
- console.error('Subscribe error:', error);
156
- return c.json({
157
- success: false,
158
- message: error instanceof Error ? error.message : 'Failed to subscribe',
159
- }, 500);
160
- }
161
- }
162
- /**
163
- * GET /api/email/confirm?token=xxx
164
- * Public endpoint to confirm subscription
165
- */
166
- export async function confirm(c) {
167
- try {
168
- const token = c.req.query('token');
169
- if (!token) {
170
- return c.json({ success: false, message: 'Missing confirmation token' }, 400);
171
- }
172
- const db = c.env.DB;
173
- // Find subscriber by confirmation token
174
- const subscriber = await db
175
- .prepare('SELECT id, status, email FROM subscribers WHERE confirmation_token = ?')
176
- .bind(token)
177
- .first();
178
- if (!subscriber) {
179
- return c.json({ success: false, message: 'Invalid or expired confirmation token' }, 404);
180
- }
181
- // Update subscriber status
182
- const now = Date.now();
183
- await db
184
- .prepare(`UPDATE subscribers
185
- SET status = 'subscribed', confirmed_at = ?, subscribed_at = ?, confirmation_token = NULL, updated_at = ?
186
- WHERE id = ?`)
187
- .bind(now, now, now, subscriber.id)
188
- .run();
189
- // Send welcome email if configured
190
- try {
191
- const welcomeTemplate = await getAutoEmailTemplate(db, 'welcome');
192
- if (welcomeTemplate) {
193
- const apiKey = c.env.HG_NEWSLETTER_EMAIL_API_KEY;
194
- const fromEmail = c.env.HG_NEWSLETTER_FROM_EMAIL;
195
- const fromName = c.env.HG_NEWSLETTER_FROM_NAME;
196
- if (apiKey && fromEmail) {
197
- // We need unsubscribe link for welcome email usually, but public handler might not have easy access to generate it
198
- // without the unsubscribe token. Wait, we have the subscriber, we can get their unsubscribe token.
199
- // But we just updated the record. Let's fetch the unsubscribe token.
200
- const subData = await db
201
- .prepare('SELECT unsubscribe_token FROM subscribers WHERE id = ?')
202
- .bind(subscriber.id)
203
- .first();
204
- // If we can't get it easily, we might skip it or use a placeholder.
205
- // Assuming the template has {{unsubscribe_url}}.
206
- // The unsubscribe URL is likely /newsletter/unsubscribe?token=...
207
- // Base URL? We can use c.req.url origin or an env var.
208
- // The confirmation URL env var base can be used.
209
- const confirmationUrl = c.env.HG_NEWSLETTER_CONFIRMATION_URL;
210
- let unsubscribeUrl = '#';
211
- if (confirmationUrl && subData?.unsubscribe_token) {
212
- // Assuming confirmationUrl is .../newsletter/confirm
213
- const baseUrl = new URL(confirmationUrl).origin;
214
- unsubscribeUrl = `${baseUrl}/newsletter/unsubscribe?token=${subData.unsubscribe_token}`;
215
- }
216
- const html = welcomeTemplate.html_content.replace(/{{unsubscribe_url}}/g, unsubscribeUrl);
217
- await sendEmailViaResend(apiKey, subscriber.email, fromEmail, fromName || 'Newsletter', welcomeTemplate.subject, html);
218
- }
219
- }
220
- }
221
- catch (emailError) {
222
- console.error('Failed to send welcome email:', emailError);
223
- // Don't fail the confirmation request just because welcome email failed
224
- }
225
- return c.json({
226
- success: true,
227
- message: 'Your subscription has been confirmed! Thank you for subscribing.',
228
- });
229
- }
230
- catch (error) {
231
- console.error('Confirm error:', error);
232
- return c.json({
233
- success: false,
234
- message: error instanceof Error ? error.message : 'Failed to confirm subscription',
235
- }, 500);
236
- }
237
- }
238
- /**
239
- * GET /api/email/unsubscribe?token=xxx
240
- * Public endpoint to show unsubscribe confirmation page
241
- */
242
- export async function showUnsubscribePage(c) {
243
- const token = c.req.query('token');
244
- if (!token) {
245
- return c.text('Missing unsubscribe token', 400);
246
- }
247
- // Import template function
248
- const { getTemplate } = await import('../../../lib/template');
249
- // Pass token as a script variable
250
- const tokenScript = `const token = '${token}';`;
251
- return c.html(getTemplate('unsubscribe', '', tokenScript));
252
- }
253
- /**
254
- * POST /api/email/unsubscribe
255
- * Public endpoint to unsubscribe from newsletter
256
- */
257
- export async function unsubscribe(c) {
258
- try {
259
- const body = (await c.req.json());
260
- const { token, email } = body;
261
- if (!token && !email) {
262
- return c.json({ success: false, message: 'Missing token or email' }, 400);
263
- }
264
- const db = c.env.DB;
265
- let query;
266
- let param;
267
- if (token) {
268
- query = 'SELECT id FROM subscribers WHERE unsubscribe_token = ?';
269
- param = token;
270
- }
271
- else {
272
- const normalizedEmail = email.toLowerCase().trim();
273
- query = 'SELECT id FROM subscribers WHERE email = ?';
274
- param = normalizedEmail;
275
- }
276
- const subscriber = await db.prepare(query).bind(param).first();
277
- if (!subscriber) {
278
- return c.json({ success: false, message: 'Subscriber not found' }, 404);
279
- }
280
- // Soft-delete: set status to 'unsubscribed' instead of deleting
281
- const now = Date.now();
282
- await db
283
- .prepare(`UPDATE subscribers
284
- SET status = 'unsubscribed', unsubscribed_at = ?, updated_at = ?
285
- WHERE id = ?`)
286
- .bind(now, now, subscriber.id)
287
- .run();
288
- return c.json({
289
- success: true,
290
- message: 'You have been unsubscribed successfully',
291
- });
292
- }
293
- catch (error) {
294
- console.error('Unsubscribe error:', error);
295
- return c.json({
296
- success: false,
297
- message: error instanceof Error ? error.message : 'Failed to unsubscribe',
298
- }, 500);
299
- }
300
- }
@@ -1,12 +0,0 @@
1
- import { Context } from 'hono';
2
- /**
3
- * POST /api/email/admin/send
4
- * Send bulk email to all subscribed users (admin only)
5
- */
6
- export declare function sendBulkEmail(c: Context): Promise<Response>;
7
- /**
8
- * POST /api/email/admin/emails/test
9
- * Send test email to a single email address
10
- */
11
- export declare function sendTestEmail(c: Context): Promise<Response>;
12
- //# sourceMappingURL=send.handler.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"send.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/newsletter/handlers/send.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAqE/B;;;GAGG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA8FjE;AAED;;;GAGG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6DjE"}
@@ -1,153 +0,0 @@
1
- import { saveSentEmail } from './emails.handler';
2
- // Send email via Resend with optional inline attachments
3
- async function sendEmail(to, subject, html, apiKey, from, fromName, replyTo, attachments) {
4
- const payload = {
5
- from: `${fromName} <${from}>`,
6
- to,
7
- subject,
8
- html,
9
- reply_to: replyTo,
10
- };
11
- // Add attachments if present
12
- if (attachments && attachments.length > 0) {
13
- payload.attachments = attachments;
14
- }
15
- const response = await fetch('https://api.resend.com/emails', {
16
- method: 'POST',
17
- headers: {
18
- Authorization: `Bearer ${apiKey}`,
19
- 'Content-Type': 'application/json',
20
- },
21
- body: JSON.stringify(payload),
22
- });
23
- if (!response.ok) {
24
- const error = await response.text();
25
- throw new Error(`Failed to send email to ${to}: ${error}`);
26
- }
27
- }
28
- /**
29
- * Convert EmailAttachment array to Resend attachment format
30
- */
31
- function toResendAttachments(images) {
32
- if (!images || images.length === 0)
33
- return undefined;
34
- return images.map((img) => ({
35
- content: img.content,
36
- filename: img.filename,
37
- type: img.type,
38
- disposition: 'inline',
39
- id: img.id,
40
- }));
41
- }
42
- /**
43
- * POST /api/email/admin/send
44
- * Send bulk email to all subscribed users (admin only)
45
- */
46
- export async function sendBulkEmail(c) {
47
- try {
48
- const body = (await c.req.json());
49
- const { subject, html, images } = body;
50
- if (!subject || !html) {
51
- return c.json({ success: false, message: 'Subject and HTML content are required' }, 400);
52
- }
53
- const db = c.env.DB;
54
- const apiKey = c.env.HG_NEWSLETTER_EMAIL_API_KEY;
55
- const fromEmail = c.env.HG_NEWSLETTER_FROM_EMAIL;
56
- const fromName = c.env.HG_NEWSLETTER_FROM_NAME;
57
- const replyTo = c.env.HG_NEWSLETTER_REPLY_TO;
58
- if (!db || !apiKey || !fromEmail) {
59
- return c.json({ success: false, message: 'Newsletter not configured' }, 500);
60
- }
61
- // Fetch all subscribed users
62
- const result = await db.prepare('SELECT id, email, unsubscribe_token FROM subscribers WHERE status = \'subscribed\'').all();
63
- const subscribers = result.results;
64
- if (subscribers.length === 0) {
65
- return c.json({ success: true, sent: 0, message: 'No subscribed users found' });
66
- }
67
- // Convert images to Resend format
68
- const resendAttachments = toResendAttachments(images);
69
- // Send emails to all subscribers
70
- let sent = 0;
71
- const errors = [];
72
- for (const subscriber of subscribers) {
73
- try {
74
- // Append unsubscribe link to HTML
75
- const unsubscribeUrl = `${c.req.url.split('/api')[0]}/api/email/unsubscribe?token=${subscriber.unsubscribe_token}`;
76
- const htmlWithUnsubscribe = `
77
- ${html}
78
- <hr style="margin-top: 2rem; margin-bottom: 1rem; border: none; border-top: 1px solid #eee;">
79
- <p style="font-size: 0.875rem; color: #666;">
80
- <a href="${unsubscribeUrl}" style="color: #666;">Unsubscribe from this newsletter</a>
81
- </p>
82
- `;
83
- await sendEmail(subscriber.email, subject, htmlWithUnsubscribe, apiKey, fromEmail, fromName || 'Newsletter', replyTo, resendAttachments);
84
- sent++;
85
- }
86
- catch (error) {
87
- console.error(`Failed to send email to ${subscriber.email}:`, error);
88
- errors.push(subscriber.email);
89
- }
90
- }
91
- // Save sent email to database
92
- await saveSentEmail(db, subject, html, sent);
93
- if (errors.length > 0) {
94
- return c.json({
95
- success: true,
96
- sent,
97
- message: `Sent to ${sent} subscribers. Failed to send to: ${errors.join(', ')}`,
98
- });
99
- }
100
- return c.json({
101
- success: true,
102
- sent,
103
- message: `Successfully sent email to ${sent} subscriber${sent === 1 ? '' : 's'}`,
104
- });
105
- }
106
- catch (error) {
107
- console.error('Send bulk email error:', error);
108
- return c.json({
109
- success: false,
110
- message: error instanceof Error ? error.message : 'Failed to send emails',
111
- }, 500);
112
- }
113
- }
114
- /**
115
- * POST /api/email/admin/emails/test
116
- * Send test email to a single email address
117
- */
118
- export async function sendTestEmail(c) {
119
- try {
120
- const body = (await c.req.json());
121
- const { subject, html, testEmail, images } = body;
122
- if (!subject || !html || !testEmail) {
123
- return c.json({ success: false, message: 'Subject, HTML content, and test email are required' }, 400);
124
- }
125
- // Validate email
126
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
127
- if (!emailRegex.test(testEmail)) {
128
- return c.json({ success: false, message: 'Invalid test email address' }, 400);
129
- }
130
- const apiKey = c.env.HG_NEWSLETTER_EMAIL_API_KEY;
131
- const fromEmail = c.env.HG_NEWSLETTER_FROM_EMAIL;
132
- const fromName = c.env.HG_NEWSLETTER_FROM_NAME;
133
- const replyTo = c.env.HG_NEWSLETTER_REPLY_TO;
134
- if (!apiKey || !fromEmail) {
135
- return c.json({ success: false, message: 'Newsletter not configured' }, 500);
136
- }
137
- // Convert images to Resend format
138
- const resendAttachments = toResendAttachments(images);
139
- // Send test email with attachments
140
- await sendEmail(testEmail, subject, html, apiKey, fromEmail, fromName || 'Newsletter', replyTo, resendAttachments);
141
- return c.json({
142
- success: true,
143
- message: `Test email sent to ${testEmail}`,
144
- });
145
- }
146
- catch (error) {
147
- console.error('Send test email error:', error);
148
- return c.json({
149
- success: false,
150
- message: error instanceof Error ? error.message : 'Failed to send test email',
151
- }, 500);
152
- }
153
- }
@@ -1,22 +0,0 @@
1
- import { Context } from 'hono';
2
- /**
3
- * GET /api/email/admin/subscribers
4
- * Get all subscribers (admin only)
5
- */
6
- export declare function getSubscribers(c: Context): Promise<Response>;
7
- /**
8
- * POST /api/email/admin/subscribers
9
- * Manually add subscriber (admin only, bypasses confirmation)
10
- */
11
- export declare function addSubscriber(c: Context): Promise<Response>;
12
- /**
13
- * DELETE /api/email/admin/subscribers/:id
14
- * Delete subscriber by ID (admin only)
15
- */
16
- export declare function deleteSubscriber(c: Context): Promise<Response>;
17
- /**
18
- * PATCH /api/email/admin/subscribers/:id
19
- * Update subscriber (admin only)
20
- */
21
- export declare function updateSubscriber(c: Context): Promise<Response>;
22
- //# sourceMappingURL=subscribers.handler.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"subscribers.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/newsletter/handlers/subscribers.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAwC/B;;;GAGG;AACH,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmBlE;AAED;;;GAGG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6DjE;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA+BpE;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA+EpE"}