@hintergrund/worker 0.1.6 → 0.1.8

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 (190) 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/dashboard.handler.js +1 -1
  11. package/dist/api/cms/handlers/website-repo.handler.d.ts +8 -0
  12. package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -0
  13. package/dist/api/cms/handlers/website-repo.handler.js +148 -0
  14. package/dist/api/cms/routes/index.d.ts.map +1 -1
  15. package/dist/api/cms/routes/index.js +16 -4
  16. package/dist/api/emails/handlers/campaigns.handler.d.ts +10 -23
  17. package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
  18. package/dist/api/emails/handlers/campaigns.handler.js +164 -92
  19. package/dist/api/emails/handlers/invoice.handler.d.ts +5 -19
  20. package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -1
  21. package/dist/api/emails/handlers/invoice.handler.js +58 -340
  22. package/dist/api/emails/handlers/public.handler.d.ts +6 -29
  23. package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
  24. package/dist/api/emails/handlers/public.handler.js +150 -312
  25. package/dist/api/emails/handlers/send.handler.d.ts +5 -17
  26. package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
  27. package/dist/api/emails/handlers/send.handler.js +107 -92
  28. package/dist/api/emails/handlers/settings.handler.d.ts +28 -33
  29. package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
  30. package/dist/api/emails/handlers/settings.handler.js +96 -287
  31. package/dist/api/emails/handlers/subscribers.handler.d.ts +13 -0
  32. package/dist/api/emails/handlers/subscribers.handler.d.ts.map +1 -0
  33. package/dist/api/emails/handlers/subscribers.handler.js +125 -0
  34. package/dist/api/emails/handlers/webhook.handler.d.ts +1 -2
  35. package/dist/api/emails/handlers/webhook.handler.d.ts.map +1 -1
  36. package/dist/api/emails/handlers/webhook.handler.js +66 -166
  37. package/dist/api/emails/routes/admin.routes.d.ts +1 -3
  38. package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
  39. package/dist/api/emails/routes/admin.routes.js +19 -49
  40. package/dist/api/emails/routes/public.routes.d.ts +1 -3
  41. package/dist/api/emails/routes/public.routes.d.ts.map +1 -1
  42. package/dist/api/emails/routes/public.routes.js +2 -9
  43. package/dist/api/shop/handlers/prices.handler.d.ts +2 -15
  44. package/dist/api/shop/handlers/prices.handler.d.ts.map +1 -1
  45. package/dist/api/shop/handlers/prices.handler.js +2 -83
  46. package/dist/api/shop/handlers/products.handler.d.ts +29 -20
  47. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
  48. package/dist/api/shop/handlers/products.handler.js +195 -162
  49. package/dist/api/shop/handlers/public.handler.d.ts +24 -8
  50. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
  51. package/dist/api/shop/handlers/public.handler.js +525 -78
  52. package/dist/api/shop/routes.d.ts.map +1 -1
  53. package/dist/api/shop/routes.js +14 -9
  54. package/dist/hintergrund-assets.d.ts +3 -2
  55. package/dist/hintergrund-assets.d.ts.map +1 -1
  56. package/dist/hintergrund-assets.js +4 -2
  57. package/dist/index.d.ts +15 -8
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +44 -4
  60. package/dist/lib/auth/crypto.d.ts +2 -15
  61. package/dist/lib/auth/crypto.d.ts.map +1 -1
  62. package/dist/lib/auth/crypto.js +8 -95
  63. package/dist/lib/auth/jwt.d.ts +0 -4
  64. package/dist/lib/auth/jwt.d.ts.map +1 -1
  65. package/dist/lib/auth/jwt.js +0 -6
  66. package/dist/lib/config.d.ts +8 -10
  67. package/dist/lib/config.d.ts.map +1 -1
  68. package/dist/lib/config.js +30 -106
  69. package/dist/lib/email-template.d.ts +15 -0
  70. package/dist/lib/email-template.d.ts.map +1 -0
  71. package/dist/lib/email-template.js +58 -0
  72. package/dist/lib/email.d.ts +18 -8
  73. package/dist/lib/email.d.ts.map +1 -1
  74. package/dist/lib/email.js +59 -70
  75. package/dist/lib/github-app.d.ts +2 -0
  76. package/dist/lib/github-app.d.ts.map +1 -0
  77. package/dist/lib/github-app.js +49 -0
  78. package/dist/lib/github-config.d.ts +19 -0
  79. package/dist/lib/github-config.d.ts.map +1 -0
  80. package/dist/lib/github-config.js +23 -0
  81. package/dist/lib/github.d.ts +16 -3
  82. package/dist/lib/github.d.ts.map +1 -1
  83. package/dist/lib/github.js +38 -15
  84. package/dist/lib/project-db.d.ts +24 -0
  85. package/dist/lib/project-db.d.ts.map +1 -0
  86. package/dist/lib/project-db.js +172 -0
  87. package/dist/lib/template.js +4 -4
  88. package/dist/middleware/auth.d.ts +0 -2
  89. package/dist/middleware/auth.d.ts.map +1 -1
  90. package/dist/middleware/auth.js +21 -50
  91. package/package.json +3 -2
  92. package/dist/api/builder/handlers/generate.handler.d.ts +0 -12
  93. package/dist/api/builder/handlers/generate.handler.d.ts.map +0 -1
  94. package/dist/api/builder/handlers/generate.handler.js +0 -203
  95. package/dist/api/builder/handlers/template.handler.d.ts +0 -12
  96. package/dist/api/builder/handlers/template.handler.d.ts.map +0 -1
  97. package/dist/api/builder/handlers/template.handler.js +0 -208
  98. package/dist/api/builder/routes.d.ts +0 -7
  99. package/dist/api/builder/routes.d.ts.map +0 -1
  100. package/dist/api/builder/routes.js +0 -15
  101. package/dist/api/cms/handlers/assets.handler.d.ts +0 -31
  102. package/dist/api/cms/handlers/assets.handler.d.ts.map +0 -1
  103. package/dist/api/cms/handlers/assets.handler.js +0 -200
  104. package/dist/api/cms/handlers/config.handler.d.ts +0 -7
  105. package/dist/api/cms/handlers/config.handler.d.ts.map +0 -1
  106. package/dist/api/cms/handlers/config.handler.js +0 -37
  107. package/dist/api/cms/handlers/content.handler.d.ts +0 -21
  108. package/dist/api/cms/handlers/content.handler.d.ts.map +0 -1
  109. package/dist/api/cms/handlers/content.handler.js +0 -117
  110. package/dist/api/cms/routes/assets.routes.d.ts +0 -4
  111. package/dist/api/cms/routes/assets.routes.d.ts.map +0 -1
  112. package/dist/api/cms/routes/assets.routes.js +0 -13
  113. package/dist/api/cms/routes/content.routes.d.ts +0 -4
  114. package/dist/api/cms/routes/content.routes.d.ts.map +0 -1
  115. package/dist/api/cms/routes/content.routes.js +0 -11
  116. package/dist/api/emails/handlers/branding.handler.d.ts +0 -17
  117. package/dist/api/emails/handlers/branding.handler.d.ts.map +0 -1
  118. package/dist/api/emails/handlers/branding.handler.js +0 -120
  119. package/dist/api/emails/handlers/contacts.handler.d.ts +0 -37
  120. package/dist/api/emails/handlers/contacts.handler.d.ts.map +0 -1
  121. package/dist/api/emails/handlers/contacts.handler.js +0 -161
  122. package/dist/api/emails/handlers/templates.handler.d.ts +0 -32
  123. package/dist/api/emails/handlers/templates.handler.d.ts.map +0 -1
  124. package/dist/api/emails/handlers/templates.handler.js +0 -132
  125. package/dist/api/newsletter/handlers/email.handler.d.ts +0 -7
  126. package/dist/api/newsletter/handlers/email.handler.d.ts.map +0 -1
  127. package/dist/api/newsletter/handlers/email.handler.js +0 -102
  128. package/dist/api/newsletter/handlers/emails.handler.d.ts +0 -31
  129. package/dist/api/newsletter/handlers/emails.handler.d.ts.map +0 -1
  130. package/dist/api/newsletter/handlers/emails.handler.js +0 -262
  131. package/dist/api/newsletter/handlers/invoice.handler.d.ts +0 -22
  132. package/dist/api/newsletter/handlers/invoice.handler.d.ts.map +0 -1
  133. package/dist/api/newsletter/handlers/invoice.handler.js +0 -455
  134. package/dist/api/newsletter/handlers/public.handler.d.ts +0 -22
  135. package/dist/api/newsletter/handlers/public.handler.d.ts.map +0 -1
  136. package/dist/api/newsletter/handlers/public.handler.js +0 -300
  137. package/dist/api/newsletter/handlers/send.handler.d.ts +0 -12
  138. package/dist/api/newsletter/handlers/send.handler.d.ts.map +0 -1
  139. package/dist/api/newsletter/handlers/send.handler.js +0 -153
  140. package/dist/api/newsletter/handlers/subscribers.handler.d.ts +0 -22
  141. package/dist/api/newsletter/handlers/subscribers.handler.d.ts.map +0 -1
  142. package/dist/api/newsletter/handlers/subscribers.handler.js +0 -195
  143. package/dist/api/newsletter/routes/admin.routes.d.ts +0 -4
  144. package/dist/api/newsletter/routes/admin.routes.d.ts.map +0 -1
  145. package/dist/api/newsletter/routes/admin.routes.js +0 -28
  146. package/dist/api/newsletter/routes/index.d.ts +0 -4
  147. package/dist/api/newsletter/routes/index.d.ts.map +0 -1
  148. package/dist/api/newsletter/routes/index.js +0 -9
  149. package/dist/api/newsletter/routes/public.routes.d.ts +0 -4
  150. package/dist/api/newsletter/routes/public.routes.d.ts.map +0 -1
  151. package/dist/api/newsletter/routes/public.routes.js +0 -9
  152. package/dist/api/shop/handlers/assets.handler.d.ts +0 -3
  153. package/dist/api/shop/handlers/assets.handler.d.ts.map +0 -1
  154. package/dist/api/shop/handlers/assets.handler.js +0 -62
  155. package/dist/api/shop/handlers/checkout.handler.d.ts +0 -10
  156. package/dist/api/shop/handlers/checkout.handler.d.ts.map +0 -1
  157. package/dist/api/shop/handlers/checkout.handler.js +0 -50
  158. package/dist/api/shop/handlers/customers.handler.d.ts +0 -17
  159. package/dist/api/shop/handlers/customers.handler.d.ts.map +0 -1
  160. package/dist/api/shop/handlers/customers.handler.js +0 -89
  161. package/dist/api/shop/handlers/orders.handler.d.ts +0 -17
  162. package/dist/api/shop/handlers/orders.handler.d.ts.map +0 -1
  163. package/dist/api/shop/handlers/orders.handler.js +0 -84
  164. package/dist/api/shop/handlers/stats.handler.d.ts +0 -10
  165. package/dist/api/shop/handlers/stats.handler.d.ts.map +0 -1
  166. package/dist/api/shop/handlers/stats.handler.js +0 -71
  167. package/dist/api/shop/handlers/webhook.handler.d.ts +0 -10
  168. package/dist/api/shop/handlers/webhook.handler.d.ts.map +0 -1
  169. package/dist/api/shop/handlers/webhook.handler.js +0 -233
  170. package/dist/cms-assets.d.ts +0 -4
  171. package/dist/cms-assets.d.ts.map +0 -1
  172. package/dist/cms-assets.js +0 -5
  173. package/dist/cms-bundle.d.ts +0 -3
  174. package/dist/cms-bundle.d.ts.map +0 -1
  175. package/dist/cms-bundle.js +0 -4
  176. package/dist/config-loader.d.ts +0 -26
  177. package/dist/config-loader.d.ts.map +0 -1
  178. package/dist/config-loader.js +0 -98
  179. package/dist/jwt.d.ts +0 -26
  180. package/dist/jwt.d.ts.map +0 -1
  181. package/dist/jwt.js +0 -102
  182. package/dist/lib/plunk.d.ts +0 -204
  183. package/dist/lib/plunk.d.ts.map +0 -1
  184. package/dist/lib/plunk.js +0 -259
  185. package/dist/template.d.ts +0 -2
  186. package/dist/template.d.ts.map +0 -1
  187. package/dist/template.js +0 -61
  188. package/dist/utils.d.ts +0 -23
  189. package/dist/utils.d.ts.map +0 -1
  190. package/dist/utils.js +0 -110
@@ -1,350 +1,188 @@
1
1
  /**
2
- * Public Handler
3
- *
4
- * Handles public email subscription/unsubscription endpoints.
5
- * Uses Plunk for contact management.
6
- */
7
- import { createPlunkClient } from '../../../lib/plunk';
8
- import { getEmailsConfig } from '../../../lib/config';
9
- /**
10
- * POST /api/email/subscribe
11
- * Public endpoint for newsletter subscription
12
- *
13
- * Creates an unsubscribed contact in Plunk. Plunk's built-in double opt-in
14
- * will handle sending the confirmation email and updating the subscription status.
2
+ * Public Handler — D1-backed subscribe/unsubscribe/confirm, no Plunk
15
3
  */
4
+ import { getProjectDb, createId } from '../../../lib/project-db';
5
+ import { sendEmail } from '../../../lib/email';
6
+ import { renderEmailTemplate } from '../../../lib/email-template';
7
+ import { readEmailTemplateData } from './settings.handler';
8
+ const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
9
+ /** POST /api/email/subscribe */
16
10
  export async function subscribe(c) {
17
11
  try {
18
12
  const body = await c.req.json();
19
- if (!body.email) {
13
+ if (!body.email)
20
14
  return c.json({ success: false, message: 'Email is required' }, 400);
21
- }
22
- // Validate email format
23
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
24
- if (!emailRegex.test(body.email)) {
15
+ if (!EMAIL_REGEX.test(body.email))
25
16
  return c.json({ success: false, message: 'Invalid email format' }, 400);
26
- }
17
+ const db = getProjectDb(c.env);
27
18
  const email = body.email.toLowerCase().trim();
28
- const plunk = createPlunkClient(c.env);
29
- // Check if contact already exists
30
- const existingContact = await plunk.findContactByEmail(email);
31
- if (existingContact) {
32
- if (existingContact.subscribed) {
33
- return c.json({
34
- success: true,
35
- message: 'You are already subscribed to our newsletter.',
36
- });
19
+ const now = Date.now();
20
+ // Check for existing subscriber
21
+ const existing = await db
22
+ .prepare('SELECT * FROM subscribers WHERE email = ?')
23
+ .bind(email)
24
+ .first();
25
+ if (existing) {
26
+ if (existing.status === 'subscribed') {
27
+ return c.json({ success: true, message: 'You are already subscribed to updates from us.' });
37
28
  }
38
- // If they are pending, send them another confirmation email
39
- if (existingContact.data?.status === 'pending') {
40
- try {
41
- await sendConfirmationEmail(c, plunk, existingContact.id, email);
42
- }
43
- catch (error) {
44
- const message = error instanceof Error ? error.message : '';
45
- if (message.includes('verified') || message.includes('domain') || message.includes('identity')) {
46
- return c.json({
47
- success: false,
48
- message: 'Email sending failed: Your sending domain is not verified in Plunk. Please check your email settings.',
49
- }, 400);
50
- }
51
- throw error;
52
- }
53
- return c.json({
54
- success: true,
55
- message: 'Please check your email to confirm your subscription.',
56
- });
29
+ if (existing.status === 'pending') {
30
+ // Resend confirmation
31
+ await sendConfirmation(c, email, existing.confirmation_token);
32
+ return c.json({ success: true, message: 'Please check your email to confirm your subscription.' });
57
33
  }
58
- // Re-subscribe existing contact (e.g. if they previously unsubscribed)
59
- await plunk.updateContact(existingContact.id, {
60
- subscribed: true,
61
- data: {
62
- ...existingContact.data,
63
- status: 'confirmed',
64
- reSubscribedAt: new Date().toISOString()
65
- }
66
- });
67
- return c.json({
68
- success: true,
69
- message: 'Welcome back! You have been re-subscribed to our newsletter.',
70
- });
71
- }
72
- // Create new contact (subscribed = false for double opt-in)
73
- const contact = await plunk.createContact({
74
- email,
75
- subscribed: false,
76
- data: {
77
- ...(body.name ? { name: body.name } : {}),
78
- status: 'pending',
79
- subscribedAt: new Date().toISOString()
80
- }
81
- });
82
- // Send custom confirmation email
83
- try {
84
- await sendConfirmationEmail(c, plunk, contact.id, email);
34
+ // Re-subscribe (unsubscribed/bounced/complained)
35
+ const token = crypto.randomUUID();
36
+ await db.prepare(`UPDATE subscribers SET status = 'pending', confirmation_token = ?, confirmed_at = NULL, subscribed_at = NULL, updated_at = ? WHERE email = ?`).bind(token, now, email).run();
37
+ await sendConfirmation(c, email, token);
38
+ return c.json({ success: true, message: 'Please check your email to confirm your subscription.' });
85
39
  }
86
- catch (error) {
87
- const message = error instanceof Error ? error.message : '';
88
- if (message.includes('verified') || message.includes('domain') || message.includes('identity')) {
89
- return c.json({
90
- success: false,
91
- message: 'Email sending failed: Your sending domain is not verified in Plunk. Please check your email settings.',
92
- }, 400);
93
- }
94
- throw error; // Re-throw other errors to be caught by the outer catch
95
- }
96
- return c.json({
97
- success: true,
98
- message: 'Please check your email to confirm your subscription.',
99
- });
40
+ // New subscriber
41
+ const id = createId('sub');
42
+ const token = crypto.randomUUID();
43
+ await db.prepare(`INSERT INTO subscribers (id, email, name, status, source, data_json, confirmation_token, created_at, updated_at)
44
+ VALUES (?, ?, ?, 'pending', 'website', '{}', ?, ?, ?)`).bind(id, email, body.name ?? null, token, now, now).run();
45
+ await sendConfirmation(c, email, token);
46
+ return c.json({ success: true, message: 'Please check your email to confirm your subscription.' });
100
47
  }
101
48
  catch (error) {
102
49
  console.error('Subscribe error:', error);
103
- return c.json({
104
- success: false,
105
- message: error instanceof Error ? error.message : 'Failed to subscribe',
106
- }, 500);
50
+ return c.json({ success: false, message: 'Failed to subscribe' }, 500);
107
51
  }
108
52
  }
109
- /**
110
- * Helper to send a confirmation email using the 'Confirmation Email' template
111
- */
112
- async function sendConfirmationEmail(c, plunk, contactId, email) {
53
+ async function sendConfirmation(c, email, token) {
54
+ const origin = new URL(c.req.url).origin;
55
+ const confirmUrl = `${origin}/emails/confirm?token=${token}`;
113
56
  try {
114
- const config = getEmailsConfig(c.env);
115
- // 1. Fetch templates from Plunk
116
- const { templates } = await plunk.getTemplates();
117
- // 2. Find the "Confirmation Email" template
118
- const template = templates.find(t => t.name === 'Confirmation Email');
119
- if (!template) {
120
- console.warn('Confirmation Email template not found in Plunk');
121
- return;
122
- }
123
- // 3. Construct confirmation URL
124
- // The URL should point to the frontend confirm page which then calls our confirm API
125
- const origin = new URL(c.req.url).origin;
126
- const confirmUrl = `${origin}/newsletter/confirm?token=${contactId}`;
127
- // 4. Prepare email body (replace placeholders)
128
- let body = template.body || '';
129
- body = body.replace(/{{confirm_url}}/g, confirmUrl);
130
- // 5. Send transactional email
131
- await plunk.send({
132
- to: email,
133
- subject: template.subject,
134
- body: body,
135
- from: config.fromEmail,
136
- replyTo: config.replyTo,
57
+ const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
58
+ const automation = settings.automation;
59
+ const bodyHtml = (automation?.confirmation?.bodyHtml || `
60
+ <h2>Confirm your subscription</h2>
61
+ <p>Click the button below to confirm your subscription.</p>
62
+ <p><a href="{{confirm_url}}" style="display:inline-block;background:${settings.emailTemplate?.primaryColor ?? '#111827'};color:white;padding:12px 24px;border-radius:4px;text-decoration:none;">Confirm subscription</a></p>
63
+ <p style="font-size:12px;color:#888;">If you didn't subscribe, you can safely ignore this email.</p>`).replaceAll('{{confirm_url}}', confirmUrl);
64
+ const html = renderEmailTemplate({
65
+ bodyHtml,
66
+ template: settings.emailTemplate,
67
+ logoDataUrl,
137
68
  });
138
- console.log(`Confirmation email sent to ${email}`);
69
+ await sendEmail(c.env, { to: email, subject: automation?.confirmation?.subject || 'Confirm your subscription', html });
70
+ }
71
+ catch (err) {
72
+ console.error('Failed to send confirmation email:', err);
73
+ }
74
+ }
75
+ /** GET /api/email/confirm */
76
+ export async function confirm(c) {
77
+ try {
78
+ const token = c.req.query('token');
79
+ if (!token)
80
+ return c.json({ success: false, message: 'Token is required' }, 400);
81
+ const db = getProjectDb(c.env);
82
+ const now = Date.now();
83
+ const subscriber = await db
84
+ .prepare("SELECT * FROM subscribers WHERE confirmation_token = ? AND status = 'pending'")
85
+ .bind(token)
86
+ .first();
87
+ if (!subscriber) {
88
+ return c.json({ success: false, message: 'Invalid or expired confirmation token' }, 400);
89
+ }
90
+ await db.prepare(`UPDATE subscribers SET status = 'subscribed', confirmed_at = ?, subscribed_at = ?, confirmation_token = NULL, updated_at = ? WHERE id = ?`).bind(now, now, now, subscriber.id).run();
91
+ return c.json({ success: true, message: 'Your subscription has been confirmed!' });
139
92
  }
140
93
  catch (error) {
141
- console.error('Failed to send confirmation email:', error);
142
- throw error;
94
+ console.error('Confirm error:', error);
95
+ return c.json({ success: false, message: 'Failed to confirm subscription' }, 500);
143
96
  }
144
97
  }
145
- /**
146
- * POST /api/email/unsubscribe
147
- * Public endpoint for newsletter unsubscription
148
- */
98
+ /** POST /api/email/unsubscribe */
149
99
  export async function unsubscribe(c) {
150
100
  try {
151
101
  const body = await c.req.json();
152
- if (!body.email) {
153
- return c.json({ success: false, message: 'Email is required' }, 400);
102
+ const db = getProjectDb(c.env);
103
+ const now = Date.now();
104
+ let subscriber = null;
105
+ if (body.token) {
106
+ subscriber = await db
107
+ .prepare('SELECT * FROM subscribers WHERE unsubscribe_token = ?')
108
+ .bind(body.token)
109
+ .first();
154
110
  }
155
- // Validate email format
156
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
157
- if (!emailRegex.test(body.email)) {
158
- return c.json({ success: false, message: 'Invalid email format' }, 400);
111
+ else if (body.email) {
112
+ if (!EMAIL_REGEX.test(body.email))
113
+ return c.json({ success: false, message: 'Invalid email format' }, 400);
114
+ subscriber = await db
115
+ .prepare('SELECT * FROM subscribers WHERE email = ?')
116
+ .bind(body.email.toLowerCase().trim())
117
+ .first();
159
118
  }
160
- const email = body.email.toLowerCase().trim();
161
- const plunk = createPlunkClient(c.env);
162
- // Find contact by email
163
- const contact = await plunk.findContactByEmail(email);
164
- if (!contact) {
165
- // Don't reveal if email exists for privacy
166
- return c.json({
167
- success: true,
168
- message: 'If you were subscribed, you have been unsubscribed.',
169
- });
119
+ else {
120
+ return c.json({ success: false, message: 'email or token is required' }, 400);
170
121
  }
171
- // Unsubscribe the contact
172
- await plunk.unsubscribeContact(contact.id);
173
- // Also update status in data for tracking
174
- await plunk.updateContact(contact.id, {
175
- data: {
176
- status: 'unsubscribed',
177
- unsubscribedAt: new Date().toISOString()
178
- }
179
- });
180
- return c.json({
181
- success: true,
182
- message: 'You have been successfully unsubscribed.',
183
- });
122
+ if (!subscriber) {
123
+ return c.json({ success: true, message: 'If you were subscribed, you have been unsubscribed.' });
124
+ }
125
+ await db.prepare(`UPDATE subscribers SET status = 'unsubscribed', unsubscribed_at = ?, updated_at = ? WHERE id = ?`).bind(now, now, subscriber.id).run();
126
+ return c.json({ success: true, message: 'You have been successfully unsubscribed.' });
184
127
  }
185
128
  catch (error) {
186
129
  console.error('Unsubscribe error:', error);
187
- return c.json({
188
- success: false,
189
- message: error instanceof Error ? error.message : 'Failed to unsubscribe',
190
- }, 500);
130
+ return c.json({ success: false, message: 'Failed to unsubscribe' }, 500);
191
131
  }
192
132
  }
193
- /**
194
- * GET /api/email/unsubscribe
195
- * Show unsubscribe page (for links in emails)
196
- */
133
+ /** GET /api/email/unsubscribe — HTML unsubscribe page */
197
134
  export async function showUnsubscribePage(c) {
198
- const email = c.req.query('email') || '';
199
- const html = `
200
- <!DOCTYPE html>
201
- <html lang="en">
202
- <head>
203
- <meta charset="UTF-8">
204
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
205
- <title>Unsubscribe</title>
206
- <style>
207
- body {
208
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
209
- max-width: 400px;
210
- margin: 100px auto;
211
- padding: 20px;
212
- text-align: center;
213
- }
214
- h1 { font-size: 1.5rem; margin-bottom: 1rem; }
215
- p { color: #666; margin-bottom: 1.5rem; }
216
- input {
217
- width: 100%;
218
- padding: 12px;
219
- border: 1px solid #ddd;
220
- border-radius: 4px;
221
- margin-bottom: 12px;
222
- box-sizing: border-box;
223
- }
224
- button {
225
- width: 100%;
226
- padding: 12px;
227
- background: #e74c3c;
228
- color: white;
229
- border: none;
230
- border-radius: 4px;
231
- cursor: pointer;
232
- font-size: 1rem;
233
- }
234
- button:hover { background: #c0392b; }
235
- .message {
236
- padding: 12px;
237
- border-radius: 4px;
238
- margin-bottom: 1rem;
239
- display: none;
240
- }
241
- .message.success { background: #d4edda; color: #155724; display: block; }
242
- .message.error { background: #f8d7da; color: #721c24; display: block; }
243
- </style>
244
- </head>
245
- <body>
246
- <h1>Unsubscribe</h1>
247
- <p>Enter your email address to unsubscribe from our newsletter.</p>
248
- <div id="message" class="message"></div>
249
- <form id="unsubscribe-form">
250
- <input type="email" id="email" name="email" value="${email}" placeholder="your@email.com" required>
251
- <button type="submit">Unsubscribe</button>
252
- </form>
253
- <script>
254
- document.getElementById('unsubscribe-form').addEventListener('submit', async (e) => {
255
- e.preventDefault();
256
- const email = document.getElementById('email').value;
257
- const messageEl = document.getElementById('message');
258
-
259
- try {
260
- const response = await fetch('/api/email/unsubscribe', {
261
- method: 'POST',
262
- headers: { 'Content-Type': 'application/json' },
263
- body: JSON.stringify({ email })
264
- });
265
- const data = await response.json();
266
-
267
- messageEl.textContent = data.message;
268
- messageEl.className = 'message ' + (data.success ? 'success' : 'error');
269
- } catch (error) {
270
- messageEl.textContent = 'An error occurred. Please try again.';
271
- messageEl.className = 'message error';
272
- }
273
- });
274
- </script>
275
- </body>
276
- </html>
277
- `;
278
- return c.html(html);
279
- }
280
- /**
281
- * POST /api/email/track
282
- * Track an event for a contact (public endpoint using public key)
283
- */
284
- export async function trackEvent(c) {
285
- try {
286
- const body = await c.req.json();
287
- if (!body.email || !body.event) {
288
- return c.json({ success: false, message: 'email and event are required' }, 400);
135
+ const email = c.req.query('email') ?? '';
136
+ const token = c.req.query('token') ?? '';
137
+ // If token provided, handle unsubscribe directly
138
+ if (token) {
139
+ try {
140
+ const db = getProjectDb(c.env);
141
+ const now = Date.now();
142
+ const subscriber = await db
143
+ .prepare('SELECT id FROM subscribers WHERE unsubscribe_token = ?')
144
+ .bind(token)
145
+ .first();
146
+ if (subscriber) {
147
+ await db.prepare(`UPDATE subscribers SET status = 'unsubscribed', unsubscribed_at = ?, updated_at = ? WHERE id = ?`).bind(now, now, subscriber.id).run();
148
+ }
289
149
  }
290
- const plunk = createPlunkClient(c.env);
291
- await plunk.track({
292
- email: body.email.toLowerCase().trim(),
293
- event: body.event,
294
- data: body.data,
295
- });
296
- return c.json({ success: true });
297
- }
298
- catch (error) {
299
- console.error('Track event error:', error);
300
- return c.json({
301
- success: false,
302
- message: error instanceof Error ? error.message : 'Failed to track event',
303
- }, 500);
304
- }
305
- }
306
- /**
307
- * GET /api/email/confirm
308
- * Public endpoint to confirm subscription
309
- */
310
- export async function confirm(c) {
311
- try {
312
- const token = c.req.query('token');
313
- if (!token) {
314
- return c.json({ success: false, message: 'Token is required' }, 400);
150
+ catch (e) {
151
+ console.error('Token unsubscribe error:', e);
315
152
  }
316
- const plunk = createPlunkClient(c.env);
317
- // Plunk double opt-in handles the token verification if used via their links
318
- // But here we are building a custom confirmation flow
319
- // In a real scenario, the token would be used to find the contact or verify a JWT
320
- // For now, we assume the token IS the contact ID or we use Plunk's built-in confirmation if possible
321
- // If we use Plunk's built-in confirmation, we don't necessarily need this endpoint
322
- // unless we want to redirect to a success page or update local metadata.
323
- // However, many users prefer a custom flow.
324
- // Since Plunk's built-in confirmation link goes to their domain,
325
- // if the user wants a custom confirm page on their frontend, they need to:
326
- // 1. Set the confirmation URL in Plunk settings to their frontend /newsletter/confirm
327
- // 2. That page calls THIS endpoint with the token.
328
- // Assuming the token is the contact ID for simplicity in this implementation,
329
- // or Plunk provides a way to verify it.
330
- // Let's assume for this implementation we update the contact status
331
- await plunk.updateContact(token, {
332
- subscribed: true,
333
- data: {
334
- status: 'confirmed',
335
- confirmedAt: new Date().toISOString()
336
- }
337
- });
338
- return c.json({
339
- success: true,
340
- message: 'Your subscription has been confirmed!'
341
- });
342
- }
343
- catch (error) {
344
- console.error('Confirm error:', error);
345
- return c.json({
346
- success: false,
347
- message: error instanceof Error ? error.message : 'Failed to confirm subscription',
348
- }, 500);
349
153
  }
154
+ const html = `<!DOCTYPE html>
155
+ <html lang="en"><head>
156
+ <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
157
+ <title>Unsubscribe</title>
158
+ <style>body{font-family:-apple-system,sans-serif;max-width:400px;margin:100px auto;padding:20px;text-align:center}
159
+ h1{font-size:1.5rem;margin-bottom:1rem}p{color:#666;margin-bottom:1.5rem}
160
+ input{width:100%;padding:12px;border:1px solid #ddd;border-radius:4px;margin-bottom:12px;box-sizing:border-box}
161
+ button{width:100%;padding:12px;background:#e74c3c;color:white;border:none;border-radius:4px;cursor:pointer;font-size:1rem}
162
+ .message{padding:12px;border-radius:4px;margin-bottom:1rem;display:none}
163
+ .success{background:#d4edda;color:#155724;display:block}.error{background:#f8d7da;color:#721c24;display:block}
164
+ </style></head><body>
165
+ ${token ? '<p style="color:#155724;background:#d4edda;padding:12px;border-radius:4px;">You have been successfully unsubscribed.</p>' : `
166
+ <h1>Unsubscribe</h1>
167
+ <p>Enter your email address to unsubscribe from updates.</p>
168
+ <div id="message" class="message"></div>
169
+ <form id="form">
170
+ <input type="email" id="email" value="${email.replace(/"/g, '')}" placeholder="your@email.com" required>
171
+ <button type="submit">Unsubscribe</button>
172
+ </form>
173
+ <script>
174
+ document.getElementById('form').addEventListener('submit', async (e) => {
175
+ e.preventDefault();
176
+ const email = document.getElementById('email').value;
177
+ const msg = document.getElementById('message');
178
+ try {
179
+ const r = await fetch('/api/email/unsubscribe', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({email}) });
180
+ const d = await r.json();
181
+ msg.textContent = d.message;
182
+ msg.className = 'message ' + (d.success ? 'success' : 'error');
183
+ } catch { msg.textContent = 'An error occurred.'; msg.className = 'message error'; }
184
+ });
185
+ </script>`}
186
+ </body></html>`;
187
+ return c.html(html);
350
188
  }
@@ -1,23 +1,11 @@
1
1
  /**
2
- * Send Handler
3
- *
4
- * Handles transactional email sending via Plunk.
2
+ * Send Handler — transactional + bulk email, D1 send history, no Plunk
5
3
  */
6
4
  import { Context } from 'hono';
7
- /**
8
- * POST /api/email/admin/send
9
- * Send a transactional email
10
- */
5
+ /** GET /api/email/admin/sends */
6
+ export declare function getSends(c: Context): Promise<Response>;
7
+ /** POST /api/email/admin/send — transactional single email */
11
8
  export declare function sendTransactional(c: Context): Promise<Response>;
12
- /**
13
- * POST /api/email/admin/send/test
14
- * Send a test email (for previewing campaigns/templates)
15
- */
16
- export declare function sendTestEmail(c: Context): Promise<Response>;
17
- /**
18
- * POST /api/email/admin/send/bulk
19
- * Send an email to all subscribed contacts
20
- * Uses Plunk's campaign functionality under the hood
21
- */
9
+ /** POST /api/email/admin/send/bulk — send to all subscribed contacts */
22
10
  export declare function sendBulkEmail(c: Context): Promise<Response>;
23
11
  //# sourceMappingURL=send.handler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"send.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/send.handler.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAI/B;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgDrE;AAED;;;GAGG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA8CjE;AAED;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA4CjE"}
1
+ {"version":3,"file":"send.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/send.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAuB/B,iCAAiC;AACjC,wBAAsB,QAAQ,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAW5D;AAED,8DAA8D;AAC9D,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAyDrE;AAED,wEAAwE;AACxE,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAyDjE"}