@hintergrund/worker 0.2.2 → 0.3.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 (120) hide show
  1. package/dist/api/cms/handlers/admin-users.handler.d.ts +1 -0
  2. package/dist/api/cms/handlers/admin-users.handler.d.ts.map +1 -1
  3. package/dist/api/cms/handlers/admin-users.handler.js +60 -74
  4. package/dist/api/cms/handlers/agent-conversations.handler.d.ts +0 -1
  5. package/dist/api/cms/handlers/agent-conversations.handler.d.ts.map +1 -1
  6. package/dist/api/cms/handlers/agent-conversations.handler.js +0 -7
  7. package/dist/api/cms/handlers/agent-provider.handler.d.ts +12 -0
  8. package/dist/api/cms/handlers/agent-provider.handler.d.ts.map +1 -0
  9. package/dist/api/cms/handlers/agent-provider.handler.js +64 -0
  10. package/dist/api/cms/handlers/auth.handler.d.ts +1 -1
  11. package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -1
  12. package/dist/api/cms/handlers/auth.handler.js +13 -62
  13. package/dist/api/cms/handlers/dashboard.handler.d.ts +1 -1
  14. package/dist/api/cms/handlers/dashboard.handler.d.ts.map +1 -1
  15. package/dist/api/cms/handlers/dashboard.handler.js +3 -4
  16. package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
  17. package/dist/api/cms/handlers/github-secrets.handler.js +12 -1
  18. package/dist/api/cms/handlers/integrations.handler.d.ts +5 -0
  19. package/dist/api/cms/handlers/integrations.handler.d.ts.map +1 -0
  20. package/dist/api/cms/handlers/integrations.handler.js +24 -0
  21. package/dist/api/cms/handlers/recovery.handler.d.ts +5 -0
  22. package/dist/api/cms/handlers/recovery.handler.d.ts.map +1 -0
  23. package/dist/api/cms/handlers/recovery.handler.js +53 -0
  24. package/dist/api/cms/handlers/setup.handler.d.ts.map +1 -1
  25. package/dist/api/cms/handlers/setup.handler.js +159 -29
  26. package/dist/api/cms/handlers/website-repo.handler.d.ts +2 -0
  27. package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
  28. package/dist/api/cms/handlers/website-repo.handler.js +124 -16
  29. package/dist/api/cms/handlers/website-templates.handler.d.ts +2 -0
  30. package/dist/api/cms/handlers/website-templates.handler.d.ts.map +1 -1
  31. package/dist/api/cms/handlers/website-templates.handler.js +22 -2
  32. package/dist/api/cms/routes/auth.routes.d.ts +1 -1
  33. package/dist/api/cms/routes/auth.routes.d.ts.map +1 -1
  34. package/dist/api/cms/routes/auth.routes.js +7 -2
  35. package/dist/api/cms/routes/index.d.ts +1 -1
  36. package/dist/api/cms/routes/index.d.ts.map +1 -1
  37. package/dist/api/cms/routes/index.js +14 -9
  38. package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
  39. package/dist/api/emails/handlers/campaigns.handler.js +3 -4
  40. package/dist/api/emails/handlers/invoice.handler.d.ts +8 -15
  41. package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -1
  42. package/dist/api/emails/handlers/invoice.handler.js +142 -170
  43. package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
  44. package/dist/api/emails/handlers/public.handler.js +27 -8
  45. package/dist/api/emails/handlers/send.handler.d.ts +1 -3
  46. package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
  47. package/dist/api/emails/handlers/send.handler.js +18 -65
  48. package/dist/api/emails/handlers/settings.handler.d.ts +60 -12
  49. package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
  50. package/dist/api/emails/handlers/settings.handler.js +38 -94
  51. package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
  52. package/dist/api/emails/routes/admin.routes.js +5 -6
  53. package/dist/api/emails/routes/mail-events.routes.d.ts +5 -0
  54. package/dist/api/emails/routes/mail-events.routes.d.ts.map +1 -0
  55. package/dist/api/emails/routes/mail-events.routes.js +29 -0
  56. package/dist/api/emails/routes/mail.routes.d.ts +5 -0
  57. package/dist/api/emails/routes/mail.routes.d.ts.map +1 -0
  58. package/dist/api/emails/routes/mail.routes.js +188 -0
  59. package/dist/api/shop/handlers/products.handler.d.ts +2 -2
  60. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
  61. package/dist/api/shop/handlers/products.handler.js +30 -8
  62. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
  63. package/dist/api/shop/handlers/public.handler.js +17 -66
  64. package/dist/index.d.ts +11 -1
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +30 -22
  67. package/dist/lib/brand.d.ts +6 -0
  68. package/dist/lib/brand.d.ts.map +1 -0
  69. package/dist/lib/brand.js +29 -0
  70. package/dist/lib/config.d.ts +5 -11
  71. package/dist/lib/config.d.ts.map +1 -1
  72. package/dist/lib/config.js +21 -39
  73. package/dist/lib/email-template.d.ts +2 -5
  74. package/dist/lib/email-template.d.ts.map +1 -1
  75. package/dist/lib/email-template.js +6 -27
  76. package/dist/lib/email.d.ts +20 -11
  77. package/dist/lib/email.d.ts.map +1 -1
  78. package/dist/lib/email.js +29 -19
  79. package/dist/lib/github.d.ts +1 -1
  80. package/dist/lib/github.d.ts.map +1 -1
  81. package/dist/lib/github.js +13 -4
  82. package/dist/lib/integration-health.d.ts +18 -0
  83. package/dist/lib/integration-health.d.ts.map +1 -0
  84. package/dist/lib/integration-health.js +51 -0
  85. package/dist/lib/invoice.d.ts +13 -0
  86. package/dist/lib/invoice.d.ts.map +1 -0
  87. package/dist/lib/invoice.js +41 -0
  88. package/dist/lib/launch-draft.d.ts +14 -0
  89. package/dist/lib/launch-draft.d.ts.map +1 -0
  90. package/dist/lib/launch-draft.js +45 -0
  91. package/dist/lib/launch.d.ts +3 -0
  92. package/dist/lib/launch.d.ts.map +1 -0
  93. package/dist/lib/launch.js +18 -0
  94. package/dist/lib/mail-schema.d.ts +5 -0
  95. package/dist/lib/mail-schema.d.ts.map +1 -0
  96. package/dist/lib/mail-schema.js +62 -0
  97. package/dist/lib/mail.d.ts +83 -0
  98. package/dist/lib/mail.d.ts.map +1 -0
  99. package/dist/lib/mail.js +211 -0
  100. package/dist/lib/project-db.d.ts +5 -4
  101. package/dist/lib/project-db.d.ts.map +1 -1
  102. package/dist/lib/project-db.js +27 -42
  103. package/dist/lib/template-installer.d.ts +9 -0
  104. package/dist/lib/template-installer.d.ts.map +1 -0
  105. package/dist/lib/template-installer.js +97 -0
  106. package/dist/lib/template.d.ts.map +1 -1
  107. package/dist/lib/template.js +28 -0
  108. package/dist/lib/user-recovery.d.ts +9 -0
  109. package/dist/lib/user-recovery.d.ts.map +1 -0
  110. package/dist/lib/user-recovery.js +42 -0
  111. package/dist/lib/website-i18n.d.ts +10 -0
  112. package/dist/lib/website-i18n.d.ts.map +1 -0
  113. package/dist/lib/website-i18n.js +195 -0
  114. package/dist/middleware/auth.d.ts +3 -1
  115. package/dist/middleware/auth.d.ts.map +1 -1
  116. package/dist/middleware/auth.js +8 -4
  117. package/package.json +5 -3
  118. package/dist/hintergrund-assets.d.ts +0 -5
  119. package/dist/hintergrund-assets.d.ts.map +0 -1
  120. package/dist/hintergrund-assets.js +0 -11
@@ -0,0 +1 @@
1
+ {"version":3,"file":"brand.d.ts","sourceRoot":"","sources":["../../src/lib/brand.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAKzC,wBAAsB,SAAS,CAAC,GAAG,EAAE,QAAQ,2DAI5C;AACD,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,mEAIpD;AACD,wBAAsB,cAAc,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAMrF;AACD,wBAAgB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAIhD"}
@@ -0,0 +1,29 @@
1
+ import { BRAND_PATH, DEFAULT_BRAND, validateBrand, INVOICE_DESIGN_PATH, DEFAULT_INVOICE_DESIGN, validateInvoiceDesign, publicAssetPath } from '@hintergrund/runtime-contracts';
2
+ import { createGitHubClient } from './github';
3
+ import { getGitHubConfig } from './config';
4
+ import { readJsonConfig } from './github-config';
5
+ export async function readBrand(env) {
6
+ const github = createGitHubClient(getGitHubConfig(env));
7
+ const { data } = await readJsonConfig(github, BRAND_PATH, DEFAULT_BRAND);
8
+ return validateBrand(data);
9
+ }
10
+ export async function readInvoiceDesign(env) {
11
+ const github = createGitHubClient(getGitHubConfig(env));
12
+ const { data } = await readJsonConfig(github, INVOICE_DESIGN_PATH, DEFAULT_INVOICE_DESIGN);
13
+ return validateInvoiceDesign(data);
14
+ }
15
+ export async function readBrandAsset(env, path) {
16
+ publicAssetPath(path);
17
+ const file = await createGitHubClient(getGitHubConfig(env)).readFileBinary(path);
18
+ if (!file)
19
+ throw new Error(`Brand asset not found: ${path}`);
20
+ if (file.content.length > 8 * 1024 * 1024)
21
+ throw new Error('Brand asset exceeds 6 MB.');
22
+ return Uint8Array.from(atob(file.content), char => char.charCodeAt(0));
23
+ }
24
+ export function base64(bytes) {
25
+ let result = '';
26
+ for (let i = 0; i < bytes.length; i += 8192)
27
+ result += String.fromCharCode(...bytes.subarray(i, i + 8192));
28
+ return btoa(result);
29
+ }
@@ -5,19 +5,13 @@ import type { AppConfig, AdminConfig, EmailsModuleConfig, ShopModuleConfig } fro
5
5
  */
6
6
  export declare function loadConfig(env: Record<string, string | undefined> | any): AppConfig;
7
7
  /**
8
- * Get admin UI configuration.
9
- * All product modules are always active; the newsletter is toggled in email settings.
10
- */
11
- export declare function getAdminConfig(_appConfig: AppConfig): AdminConfig;
12
- /**
13
- * Get Emails module configuration
14
- * @throws Error if Emails module is not enabled
8
+ * Get admin UI configuration. Every module ships with provisioning; the newsletter
9
+ * is toggled in email settings.
15
10
  */
11
+ export declare function getAdminConfig(): AdminConfig;
12
+ /** Get Emails module configuration. */
16
13
  export declare function getEmailsConfig(env: Record<string, string | undefined> | any): EmailsModuleConfig;
17
- /**
18
- * Get Shop module configuration
19
- * @throws Error if Shop module is not enabled
20
- */
14
+ /** Get Shop module configuration. */
21
15
  export declare function getShopConfig(env: Record<string, string | undefined> | any): ShopModuleConfig;
22
16
  /**
23
17
  * Get GitHub configuration from environment variables
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/lib/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,kBAAkB,EAAE,gBAAgB,EAAe,MAAM,gCAAgC,CAAC;AAEhI;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG,GAAG,SAAS,CAOnF;AA6CD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,SAAS,GAAG,WAAW,CAIjE;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG,GAAG,kBAAkB,CAQjG;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG,GAAG,gBAAgB,CAQ7F;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG;oBAUX,MAAM;mBAA+B,MAAM;cANhF,MAAM;aACR,MAAM;;;iBAWG,MAAM;0BACY,MAAM;sBACV,MAAM;cAd3B,MAAM;aACR,MAAM;;EAehC"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/lib/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAEnH;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG,GAAG,SAAS,CAOnF;AAwCD;;;GAGG;AACH,wBAAgB,cAAc,IAAI,WAAW,CAE5C;AAED,uCAAuC;AACvC,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG,GAAG,kBAAkB,CAEjG;AAED,qCAAqC;AACrC,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG,GAAG,gBAAgB,CAE7F;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG;oBAUX,MAAM;mBAA+B,MAAM;cANhF,MAAM;aACR,MAAM;;;iBAWG,MAAM;0BACY,MAAM;sBACV,MAAM;cAd3B,MAAM;aACR,MAAM;;EAehC"}
@@ -26,56 +26,38 @@ function getMissingVars(env, requiredVars) {
26
26
  const GIT_REPOSITORY_VARS = ['GIT_OWNER', 'GIT_REPO'];
27
27
  const GITHUB_APP_VARS = ['GITHUB_APP_ID', 'GITHUB_INSTALLATION_ID', 'GITHUB_APP_PRIVATE_KEY'];
28
28
  function loadFromEnvVars(env) {
29
- const config = {
29
+ return {
30
30
  global: {
31
31
  hgSecret: env.SECRET || '',
32
32
  },
33
+ emails: {
34
+ emailProvider: 'plunk',
35
+ emailApiKey: env.API_KEY || env.PLUNK_SECRET_KEY || '',
36
+ fromEmail: '',
37
+ fromName: '',
38
+ replyTo: undefined,
39
+ },
40
+ shop: {
41
+ paymentProvider: env.STRIPE_SECRET_KEY ? 'stripe' : 'bank_transfer',
42
+ stripeSecretKey: env.STRIPE_SECRET_KEY,
43
+ stripeWebhookSecret: env.STRIPE_WEBHOOK_SECRET,
44
+ },
33
45
  };
34
- config.emails = {
35
- emailProvider: 'plunk',
36
- emailApiKey: env.API_KEY || env.PLUNK_SECRET_KEY || '',
37
- fromEmail: '',
38
- fromName: '',
39
- replyTo: undefined,
40
- };
41
- config.shop = {
42
- paymentProvider: env.STRIPE_SECRET_KEY ? 'stripe' : 'bank_transfer',
43
- stripeSecretKey: env.STRIPE_SECRET_KEY,
44
- stripeWebhookSecret: env.STRIPE_WEBHOOK_SECRET,
45
- stripePublishableKey: env.STRIPE_PUBLISHABLE_KEY,
46
- };
47
- return config;
48
46
  }
49
47
  /**
50
- * Get admin UI configuration.
51
- * All product modules are always active; the newsletter is toggled in email settings.
48
+ * Get admin UI configuration. Every module ships with provisioning; the newsletter
49
+ * is toggled in email settings.
52
50
  */
53
- export function getAdminConfig(_appConfig) {
54
- return {
55
- loginMethod: 'password',
56
- };
51
+ export function getAdminConfig() {
52
+ return {};
57
53
  }
58
- /**
59
- * Get Emails module configuration
60
- * @throws Error if Emails module is not enabled
61
- */
54
+ /** Get Emails module configuration. */
62
55
  export function getEmailsConfig(env) {
63
- const config = loadConfig(env);
64
- if (!config.emails) {
65
- throw new Error('Emails module is not enabled');
66
- }
67
- return config.emails;
56
+ return loadConfig(env).emails;
68
57
  }
69
- /**
70
- * Get Shop module configuration
71
- * @throws Error if Shop module is not enabled
72
- */
58
+ /** Get Shop module configuration. */
73
59
  export function getShopConfig(env) {
74
- const config = loadConfig(env);
75
- if (!config.shop) {
76
- throw new Error('Shop module is not enabled');
77
- }
78
- return config.shop;
60
+ return loadConfig(env).shop;
79
61
  }
80
62
  /**
81
63
  * Get GitHub configuration from environment variables
@@ -1,3 +1,4 @@
1
+ import { type EmailTemplateConfig } from '@hintergrund/runtime-contracts';
1
2
  export interface RenderEmailTemplateOptions {
2
3
  bodyHtml: string;
3
4
  template?: Partial<EmailTemplateConfig>;
@@ -5,11 +6,7 @@ export interface RenderEmailTemplateOptions {
5
6
  unsubscribeUrl?: string;
6
7
  footerHtml?: string;
7
8
  }
8
- export interface EmailTemplateConfig {
9
- html: string;
10
- primaryColor: string;
11
- footerHtml: string;
12
- }
9
+ export type { EmailTemplateConfig } from '@hintergrund/runtime-contracts';
13
10
  export declare const DEFAULT_EMAIL_TEMPLATE: EmailTemplateConfig;
14
11
  export declare function renderEmailTemplate(options: RenderEmailTemplateOptions): string;
15
12
  //# sourceMappingURL=email-template.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"email-template.d.ts","sourceRoot":"","sources":["../../src/lib/email-template.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACxC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;CACnB;AAED,eAAO,MAAM,sBAAsB,EAAE,mBAsBpC,CAAC;AAoBF,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,MAAM,CAkB/E"}
1
+ {"version":3,"file":"email-template.d.ts","sourceRoot":"","sources":["../../src/lib/email-template.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyC,KAAK,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAEjH,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACxC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,YAAY,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAE1E,eAAO,MAAM,sBAAsB,EAAE,mBAA2D,CAAC;AAoBjG,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,MAAM,CAkB/E"}
@@ -1,36 +1,15 @@
1
- export const DEFAULT_EMAIL_TEMPLATE = {
2
- primaryColor: '#111827',
3
- footerHtml: '<p>You are receiving this email because you subscribed to updates from us.</p>',
4
- html: `<!doctype html>
5
- <html>
6
- <head>
7
- <meta charset="utf-8">
8
- <meta name="viewport" content="width=device-width,initial-scale=1">
9
- </head>
10
- <body style="margin:0;padding:0;background:#f6f8fa;">
11
- <div style="background:#f6f8fa;padding:40px 0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;font-size:14px;line-height:1.5;color:#24292f;">
12
- <div style="max-width:580px;margin:0 auto;background:#ffffff;border:1px solid #d0d7de;border-radius:8px;padding:32px;">
13
- {{logo}}
14
- {{content}}
15
- </div>
16
- <div style="max-width:580px;margin:20px auto 0;padding:0 32px;font-size:12px;color:#6e7781;text-align:center;">
17
- {{footer}}
18
- {{unsubscribe}}
19
- </div>
20
- </div>
21
- </body>
22
- </html>`,
23
- };
1
+ import { DEFAULT_BRAND, emailTemplateFromBrand } from '@hintergrund/runtime-contracts';
2
+ export const DEFAULT_EMAIL_TEMPLATE = emailTemplateFromBrand(DEFAULT_BRAND);
24
3
  function cleanCssValue(value, fallback) {
25
4
  return value && !/[<>"']/.test(value) ? value : fallback;
26
5
  }
27
- function styleEmailBody(bodyHtml, primaryColor) {
6
+ function styleEmailBody(bodyHtml, primaryColor, headingFont) {
28
7
  return bodyHtml
29
8
  .replace(/<(h[1-4])([^>]*)>/gi, (match, tag, attributes) => {
30
9
  if (/style=/i.test(attributes)) {
31
- return match.replace(/style=(["'])(.*?)\1/i, `style=$1color:${primaryColor};$2$1`);
10
+ return match.replace(/style=(["'])(.*?)\1/i, `style=$1color:${primaryColor};font-family:${headingFont.replaceAll("'", '')};$2$1`);
32
11
  }
33
- return `<${tag}${attributes} style="color:${primaryColor};">`;
12
+ return `<${tag}${attributes} style="color:${primaryColor};font-family:${headingFont};">`;
34
13
  })
35
14
  .replace(/<img([^>]*)>/gi, (match) => {
36
15
  if (/style=/i.test(match))
@@ -41,7 +20,7 @@ function styleEmailBody(bodyHtml, primaryColor) {
41
20
  export function renderEmailTemplate(options) {
42
21
  const template = { ...DEFAULT_EMAIL_TEMPLATE, ...(options.template ?? {}) };
43
22
  const primaryColor = cleanCssValue(template.primaryColor, DEFAULT_EMAIL_TEMPLATE.primaryColor);
44
- const bodyHtml = styleEmailBody(options.bodyHtml, primaryColor);
23
+ const bodyHtml = styleEmailBody(options.bodyHtml, primaryColor, template.headingFont);
45
24
  const logoHtml = options.logoDataUrl
46
25
  ? `<div style="text-align:center;margin:0 0 20px 0;"><img src="${options.logoDataUrl}" alt="Logo" style="max-width:120px;max-height:80px;height:auto;"></div>`
47
26
  : '';
@@ -2,7 +2,14 @@
2
2
  * Provider-agnostic email sending utility using Plunk.
3
3
  * Reads the API key from the Worker and sender details from GitHub-backed email settings.
4
4
  */
5
- interface SendEmailParams {
5
+ import type { Bindings } from '../index';
6
+ export interface SendEmailParams {
7
+ attachments?: Array<{
8
+ filename: string;
9
+ content: string;
10
+ contentType: string;
11
+ disposition?: 'attachment' | 'inline';
12
+ }>;
6
13
  to: string;
7
14
  toName?: string;
8
15
  subject: string;
@@ -10,15 +17,17 @@ interface SendEmailParams {
10
17
  from?: string;
11
18
  fromName?: string;
12
19
  replyTo?: string;
20
+ text?: string;
21
+ headers?: Record<string, string>;
22
+ idempotencyKey?: string;
13
23
  }
14
- export declare function sendEmail(env: Record<string, string | undefined>, params: SendEmailParams): Promise<void>;
15
- /** Send a one-time email code for passwordless admin authentication. */
16
- export declare function sendEmailOtp(params: {
17
- to: string;
18
- apiKey: string;
19
- fromEmail: string;
20
- fromName?: string;
21
- code: string;
22
- }): Promise<void>;
23
- export {};
24
+ export declare class EmailProviderError extends Error {
25
+ status: number;
26
+ reason?: string;
27
+ constructor(status: number, reason?: string);
28
+ }
29
+ export interface EmailReceipt {
30
+ providerId?: string;
31
+ }
32
+ export declare function sendEmail(env: Bindings, params: SendEmailParams): Promise<EmailReceipt>;
24
33
  //# sourceMappingURL=email.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"email.d.ts","sourceRoot":"","sources":["../../src/lib/email.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAMH,UAAU,eAAe;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,wBAAsB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,EAAE,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAW/G;AAkCD,wEAAwE;AACxE,wBAAsB,YAAY,CAAC,MAAM,EAAE;IAC1C,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACb,GAAG,OAAO,CAAC,IAAI,CAAC,CAahB"}
1
+ {"version":3,"file":"email.d.ts","sourceRoot":"","sources":["../../src/lib/email.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAGzC,MAAM,WAAW,eAAe;IAC/B,WAAW,CAAC,EAAE,KAAK,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,YAAY,GAAG,QAAQ,CAAA;KAAE,CAAC,CAAC;IACvH,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,qBAAa,kBAAmB,SAAQ,KAAK;IAC5C,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;gBACJ,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM;CAI3C;AACD,MAAM,WAAW,YAAY;IAAG,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE;AAErD,wBAAsB,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,YAAY,CAAC,CAW7F"}
package/dist/lib/email.js CHANGED
@@ -3,7 +3,13 @@
3
3
  * Reads the API key from the Worker and sender details from GitHub-backed email settings.
4
4
  */
5
5
  import { readEmailSettings } from '../api/emails/handlers/settings.handler';
6
- import { renderEmailTemplate } from './email-template';
6
+ export class EmailProviderError extends Error {
7
+ constructor(status, reason) {
8
+ super(reason ? `Email provider returned ${status}: ${reason}` : `Email provider returned ${status}`);
9
+ this.status = status;
10
+ this.reason = reason;
11
+ }
12
+ }
7
13
  export async function sendEmail(env, params) {
8
14
  const apiKey = env.API_KEY || env.PLUNK_SECRET_KEY;
9
15
  const { settings } = await readEmailSettings(env);
@@ -14,7 +20,7 @@ export async function sendEmail(env, params) {
14
20
  throw new Error('Plunk API key (API_KEY or PLUNK_SECRET_KEY) is not configured');
15
21
  if (!fromEmail)
16
22
  throw new Error('Email sender address is not configured');
17
- await sendViaPlunk(apiKey, fromEmail, fromName, { ...params, replyTo });
23
+ return sendViaPlunk(apiKey, fromEmail, fromName, { ...params, replyTo });
18
24
  }
19
25
  async function sendViaPlunk(apiKey, fromEmail, fromName, params) {
20
26
  const body = {
@@ -22,35 +28,39 @@ async function sendViaPlunk(apiKey, fromEmail, fromName, params) {
22
28
  subject: params.subject,
23
29
  body: params.html,
24
30
  type: 'html',
25
- subscribed: true,
26
- from: fromName ? `${fromName} <${fromEmail}>` : fromEmail,
31
+ // Transactional messages must not change the recipient's marketing consent.
32
+ from: fromName ? { name: fromName, email: fromEmail } : fromEmail,
27
33
  };
28
34
  if (params.toName)
29
- body.name = params.toName;
35
+ body.to = { name: params.toName, email: params.to };
36
+ if (params.attachments?.length)
37
+ body.attachments = params.attachments;
30
38
  if (params.replyTo)
31
39
  body.reply = params.replyTo;
40
+ if (params.headers)
41
+ body.headers = params.headers;
32
42
  const response = await fetch('https://next-api.useplunk.com/v1/send', {
33
43
  method: 'POST',
34
44
  headers: {
35
45
  Authorization: `Bearer ${apiKey}`,
36
46
  'Content-Type': 'application/json',
47
+ ...(params.idempotencyKey ? { 'Idempotency-Key': params.idempotencyKey } : {}),
37
48
  },
49
+ signal: AbortSignal.timeout(20000),
38
50
  body: JSON.stringify(body),
39
51
  });
40
52
  if (!response.ok) {
41
- const error = await response.text();
42
- throw new Error(`Plunk API error ${response.status}: ${error}`);
53
+ // Rejection reasons (e.g. suppressed or unsubscribed recipient) are small API
54
+ // error bodies. Bound the read so a misbehaving upstream cannot exhaust memory.
55
+ let reason;
56
+ if (Number(response.headers.get('content-length') || 0) <= 8192) {
57
+ reason = (await response.text()).slice(0, 300) || undefined;
58
+ }
59
+ else {
60
+ await response.body?.cancel();
61
+ }
62
+ throw new EmailProviderError(response.status, reason);
43
63
  }
44
- }
45
- /** Send a one-time email code for passwordless admin authentication. */
46
- export async function sendEmailOtp(params) {
47
- const html = renderEmailTemplate({
48
- bodyHtml: `
49
- <h1 style="font-size:24px;font-weight:600;text-align:center;margin-bottom:24px;">Sign in to Hintergrund</h1>
50
- <p style="margin-bottom:16px;text-align:center;color:#57606a;">Enter this one-time code to sign in. It expires in 15 minutes.</p>
51
- <p style="margin:0 0 32px;text-align:center;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:32px;font-weight:700;letter-spacing:0.2em;color:#1f2328;">${params.code}</p>
52
- <p style="font-size:14px;color:#57606a;text-align:center;">If you didn't request this code, you can safely ignore this email.</p>`,
53
- template: { primaryColor: '#1f883d', footerHtml: '' },
54
- });
55
- await sendEmail({ API_KEY: params.apiKey, FROM_EMAIL: params.fromEmail, FROM_NAME: params.fromName }, { to: params.to, subject: `${params.code} is your Hintergrund sign-in code`, html });
64
+ const result = await response.json();
65
+ return { providerId: result.data?.emails?.[0]?.email };
56
66
  }
@@ -76,7 +76,7 @@ export declare class GitHubClient {
76
76
  * Use this for images, videos, and other binary files
77
77
  * Returns null if file doesn't exist
78
78
  */
79
- readFileBinary(path: string): Promise<{
79
+ readFileBinary(path: string, maxBytes?: number): Promise<{
80
80
  content: string;
81
81
  sha: string;
82
82
  } | null>;
@@ -1 +1 @@
1
- {"version":3,"file":"github.d.ts","sourceRoot":"","sources":["../../src/lib/github.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAMxC;;GAEG;AACH,KAAK,sBAAsB,GAAG;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG,sBAAsB,GAAG,CACjD;IACD,cAAc,EAAE,MAAM,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;CACtB,GACC;IACD,WAAW,EAAE,MAAM,CAAC;IACpB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,gBAAgB,EAAE,MAAM,CAAC;CACzB,CACD,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,SAAS;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,M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AAC;IAQ/E;;;OAGG;IACG,gBAAgB,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,EAAE,SAAS,GAAE,MAAM,EAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IA4E9H;;OAEG;IACG,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAgB9D;;OAEG;IACG,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAyBpD;;;OAGG;IACG,eAAe,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAK5D;;OAEG;IACH,UAAU,IAAI,OAAO,CAAC,OAAO,CAAC;IAI9B,wFAAwF;IAClF,kBAAkB,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IAanD,qDAAqD;IAC/C,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAY5D,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQtD;;OAEG;IACH,WAAW;;;;;CAOX;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,YAAY,GAAG,YAAY,CAErE"}
@@ -115,7 +115,7 @@ export class GitHubClient {
115
115
  * Use this for images, videos, and other binary files
116
116
  * Returns null if file doesn't exist
117
117
  */
118
- async readFileBinary(path) {
118
+ async readFileBinary(path, maxBytes = 10 * 1024 * 1024) {
119
119
  try {
120
120
  const response = await (await this.octokit()).rest.repos.getContent({
121
121
  owner: this.owner,
@@ -126,9 +126,18 @@ export class GitHubClient {
126
126
  if (Array.isArray(response.data) || !('content' in response.data)) {
127
127
  return null;
128
128
  }
129
- // Return raw base64 content without decoding (for binary files)
130
- // GitHub returns base64 with newlines, so we need to clean it
131
- const rawContent = (response.data.content || '').replace(/\n/g, '');
129
+ if (response.data.size > maxBytes)
130
+ throw new RangeError('Binary file exceeds size limit');
131
+ // The Contents API omits bytes for files larger than 1 MB. Fetch the
132
+ // blob by SHA instead; an empty data URL would silently break images.
133
+ let content = response.data.content;
134
+ if (response.data.encoding === 'none') {
135
+ const blob = await (await this.octokit()).rest.git.getBlob({
136
+ owner: this.owner, repo: this.repo, file_sha: response.data.sha
137
+ });
138
+ content = blob.data.content;
139
+ }
140
+ const rawContent = (content || '').replace(/\s/g, '');
132
141
  return {
133
142
  content: rawContent,
134
143
  sha: response.data.sha
@@ -0,0 +1,18 @@
1
+ export declare const INTEGRATION_SECRETS: {
2
+ readonly stripe: "STRIPE_SECRET_KEY";
3
+ readonly plunk: "API_KEY";
4
+ readonly google: "GEMINI_API_KEY";
5
+ readonly deepseek: "DEEPSEEK_API_KEY";
6
+ };
7
+ export type IntegrationProvider = keyof typeof INTEGRATION_SECRETS;
8
+ export interface IntegrationHealth {
9
+ status: 'healthy' | 'warning' | 'invalid' | 'unavailable' | 'missing';
10
+ valid: boolean;
11
+ message: string;
12
+ }
13
+ export declare function isIntegrationProvider(value: string): value is IntegrationProvider;
14
+ /** Read-only probes: never send mail, create a charge, or run billable inference.
15
+ * Provider response bodies/errors and credentials must never be returned to callers.
16
+ */
17
+ export declare function checkIntegrationKey(provider: IntegrationProvider, rawKey: string): Promise<IntegrationHealth>;
18
+ //# sourceMappingURL=integration-health.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integration-health.d.ts","sourceRoot":"","sources":["../../src/lib/integration-health.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,mBAAmB;;;;;CAEtB,CAAC;AACX,MAAM,MAAM,mBAAmB,GAAG,MAAM,OAAO,mBAAmB,CAAC;AACnE,MAAM,WAAW,iBAAiB;IACjC,MAAM,EAAE,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG,aAAa,GAAG,SAAS,CAAC;IACtE,KAAK,EAAE,OAAO,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CAChB;AACD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,mBAAmB,CAEjF;AAED;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,QAAQ,EAAE,mBAAmB,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAqCnH"}
@@ -0,0 +1,51 @@
1
+ export const INTEGRATION_SECRETS = {
2
+ stripe: 'STRIPE_SECRET_KEY', plunk: 'API_KEY', google: 'GEMINI_API_KEY', deepseek: 'DEEPSEEK_API_KEY',
3
+ };
4
+ export function isIntegrationProvider(value) {
5
+ return Object.prototype.hasOwnProperty.call(INTEGRATION_SECRETS, value);
6
+ }
7
+ /** Read-only probes: never send mail, create a charge, or run billable inference.
8
+ * Provider response bodies/errors and credentials must never be returned to callers.
9
+ */
10
+ export async function checkIntegrationKey(provider, rawKey) {
11
+ const key = rawKey.trim();
12
+ if (!key || key === 'NOT_CONFIGURED')
13
+ return { status: 'missing', valid: false, message: 'No key is configured.' };
14
+ if (key.length > 4096 || /[\r\n]/.test(key))
15
+ return { status: 'invalid', valid: false, message: 'Invalid API key format.' };
16
+ const endpoints = {
17
+ stripe: 'https://api.stripe.com/v1/account',
18
+ plunk: 'https://next-api.useplunk.com/contacts?limit=1',
19
+ google: 'https://generativelanguage.googleapis.com/v1beta/models?pageSize=1',
20
+ deepseek: 'https://api.deepseek.com/models',
21
+ };
22
+ try {
23
+ const response = await fetch(endpoints[provider], {
24
+ headers: provider === 'google' ? { 'x-goog-api-key': key } : { Authorization: `Bearer ${key}` },
25
+ signal: AbortSignal.timeout(10000), redirect: 'error',
26
+ });
27
+ if (!response.ok) {
28
+ await response.body?.cancel();
29
+ const invalid = [400, 401, 403].includes(response.status);
30
+ return { status: invalid ? 'invalid' : 'unavailable', valid: false, message: invalid
31
+ ? 'The provider rejected this key or its permissions. Check the secret key and try again.'
32
+ : 'The provider is temporarily unavailable or rate-limiting requests. Try again later.' };
33
+ }
34
+ if (provider === 'stripe') {
35
+ const account = await response.json();
36
+ if (!account.charges_enabled || !account.payouts_enabled)
37
+ return {
38
+ status: 'warning', valid: true,
39
+ message: 'Key accepted. Payments or payouts are not enabled yet; finish account setup in Stripe. Webhook delivery is not tested.',
40
+ };
41
+ return { status: 'healthy', valid: true, message: 'Key accepted; Stripe API is reachable and payments/payouts are enabled. Webhook delivery is not tested.' };
42
+ }
43
+ await response.body?.cancel();
44
+ return { status: 'healthy', valid: true, message: provider === 'plunk'
45
+ ? 'Secret key accepted; Plunk API is reachable. Verify your sender domain in Plunk before sending. No email was sent.'
46
+ : 'Key accepted; model API is reachable. Inference quota and billing are not tested.' };
47
+ }
48
+ catch {
49
+ return { status: 'unavailable', valid: false, message: 'Could not reach the provider within 10 seconds. Try again.' };
50
+ }
51
+ }
@@ -0,0 +1,13 @@
1
+ import type { Context } from 'hono';
2
+ import { type Brand, type InvoiceDesign, type InvoiceData } from '@hintergrund/runtime-contracts';
3
+ import type { Bindings } from '../index';
4
+ export declare function renderInvoice(env: Bindings, data: InvoiceData, draft?: {
5
+ brand: Brand;
6
+ design: InvoiceDesign;
7
+ assets?: Partial<Record<'logo' | 'bodyFont' | 'displayFont', Uint8Array>>;
8
+ }): Promise<Uint8Array<ArrayBufferLike>>;
9
+ /** Authenticated, side-effect-free preview. Only presentation can be supplied. */
10
+ export declare function previewInvoice(c: Context<{
11
+ Bindings: Bindings;
12
+ }>): Promise<Response>;
13
+ //# sourceMappingURL=invoice.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invoice.d.ts","sourceRoot":"","sources":["../../src/lib/invoice.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAwC,KAAK,KAAK,EAAE,KAAK,aAAa,EAAE,KAAK,WAAW,EAAE,MAAM,gCAAgC,CAAC;AACxI,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAKzC,wBAAsB,aAAa,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,KAAK,CAAC,EAAE;IAAE,KAAK,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,aAAa,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,GAAG,UAAU,GAAG,aAAa,EAAE,UAAU,CAAC,CAAC,CAAA;CAAE,wCAU/L;AAED,kFAAkF;AAClF,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqB1F"}
@@ -0,0 +1,41 @@
1
+ import { validateBrand, validateInvoiceDesign } from '@hintergrund/runtime-contracts';
2
+ import { readBrand, readInvoiceDesign, readBrandAsset } from './brand';
3
+ import { readEmailSettings } from '../api/emails/handlers/settings.handler';
4
+ import { generateInvoicePdf } from '../api/emails/handlers/invoice.handler';
5
+ export async function renderInvoice(env, data, draft) {
6
+ const brand = draft?.brand ?? await readBrand(env);
7
+ const design = draft?.design ?? await readInvoiceDesign(env);
8
+ const { settings } = await readEmailSettings(env);
9
+ const [logo, bodyFont, displayFont] = await Promise.all([
10
+ design.showLogo && brand.logoPath ? draft?.assets?.logo ?? readBrandAsset(env, brand.logoPath) : undefined,
11
+ brand.bodyFontPath ? draft?.assets?.bodyFont ?? readBrandAsset(env, brand.bodyFontPath) : undefined,
12
+ brand.displayFontPath ? draft?.assets?.displayFont ?? readBrandAsset(env, brand.displayFontPath) : undefined,
13
+ ]);
14
+ return generateInvoicePdf(settings.invoice, data, brand, design, { logo, bodyFont, displayFont });
15
+ }
16
+ /** Authenticated, side-effect-free preview. Only presentation can be supplied. */
17
+ export async function previewInvoice(c) {
18
+ try {
19
+ const input = await c.req.json();
20
+ const brand = validateBrand(input.brand), design = validateInvoiceDesign(input.design);
21
+ const assets = {};
22
+ for (const key of ['logo', 'bodyFont', 'displayFont']) {
23
+ const content = input.assets?.[key];
24
+ if (content === undefined)
25
+ continue;
26
+ if (typeof content !== 'string' || content.length > 8 * 1024 * 1024 || !/^[A-Za-z0-9+/]*={0,2}$/.test(content))
27
+ throw new Error('Invalid preview asset.');
28
+ assets[key] = Uint8Array.from(atob(content), char => char.charCodeAt(0));
29
+ }
30
+ const pdf = await renderInvoice(c.env, {
31
+ invoiceNumber: 'PREVIEW-001', invoiceDate: '2026-01-15', dueDate: '2026-01-29',
32
+ customerName: 'Sample Customer', customerEmail: 'sample@example.com', customerAddress: 'Example Street 12\n12345 Example City',
33
+ items: [{ description: 'Sample product', quantity: 2, unitPrice: 25, total: 50 }, { description: 'A longer service description to demonstrate wrapping in the invoice table', quantity: 1, unitPrice: 100, total: 100 }],
34
+ subtotal: 150, tax: 28.5, total: 178.5, currency: 'EUR', notes: 'PREVIEW ONLY — not a financial document.',
35
+ }, { brand, design, assets });
36
+ return new Response(pdf, { headers: { 'Content-Type': 'application/pdf', 'Cache-Control': 'no-store', 'Content-Disposition': 'inline; filename="invoice-preview.pdf"' } });
37
+ }
38
+ catch (error) {
39
+ return c.json({ error: error instanceof Error ? error.message : 'Invoice preview failed.' }, 400);
40
+ }
41
+ }
@@ -0,0 +1,14 @@
1
+ import type { Bindings } from '../index';
2
+ import type { FileEntry } from './github';
3
+ export interface LaunchDraft {
4
+ files: FileEntry[];
5
+ deletions: string[];
6
+ baseCommitSha: string;
7
+ }
8
+ export declare function launchPending(env: Bindings): Promise<boolean>;
9
+ export declare function storeLaunchDraft(env: Bindings, draft: LaunchDraft): Promise<void>;
10
+ export declare function readLaunchDraft(env: Bindings): Promise<LaunchDraft | null>;
11
+ export declare function lockLaunch(env: Bindings): Promise<boolean>;
12
+ export declare function finishLaunch(env: Bindings, success: boolean): Promise<void>;
13
+ export declare function clearLaunchDraft(env: Bindings): Promise<void>;
14
+ //# sourceMappingURL=launch-draft.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"launch-draft.d.ts","sourceRoot":"","sources":["../../src/lib/launch-draft.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAS1C,MAAM,WAAW,WAAW;IAAG,KAAK,EAAE,SAAS,EAAE,CAAC;IAAC,SAAS,EAAE,MAAM,EAAE,CAAC;IAAC,aAAa,EAAE,MAAM,CAAA;CAAE;AAC/F,wBAAsB,aAAa,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,CAInE;AACD,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,QAAQ,EAAE,KAAK,EAAE,WAAW,iBAUvE;AACD,wBAAsB,eAAe,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAKhF;AACD,wBAAsB,UAAU,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,CAIhE;AACD,wBAAsB,YAAY,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,iBAGjE;AACD,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,QAAQ,iBAGnD"}
@@ -0,0 +1,45 @@
1
+ import { getProjectDb } from './project-db';
2
+ async function database(env) {
3
+ const db = getProjectDb(env);
4
+ await db.prepare('CREATE TABLE IF NOT EXISTS launch_state (id INTEGER PRIMARY KEY CHECK(id = 1), phase TEXT NOT NULL, metadata TEXT NOT NULL)').run();
5
+ await db.prepare('CREATE TABLE IF NOT EXISTS launch_draft_chunks (id INTEGER PRIMARY KEY, content TEXT NOT NULL)').run();
6
+ return db;
7
+ }
8
+ export async function launchPending(env) {
9
+ const db = await database(env);
10
+ const row = await db.prepare('SELECT phase FROM launch_state WHERE id = 1').first();
11
+ return !!row && row.phase !== 'live';
12
+ }
13
+ export async function storeLaunchDraft(env, draft) {
14
+ const db = await database(env);
15
+ const files = [...new Map(draft.files.map(file => [file.path, file])).values()];
16
+ const paths = new Set(files.map(file => file.path));
17
+ const json = JSON.stringify({ ...draft, files, deletions: draft.deletions.filter(path => !paths.has(path)) });
18
+ const statements = [db.prepare('DELETE FROM launch_draft_chunks')];
19
+ for (let offset = 0, id = 0; offset < json.length; offset += 64000, id++)
20
+ statements.push(db.prepare('INSERT INTO launch_draft_chunks (id, content) VALUES (?, ?)').bind(id, json.slice(offset, offset + 64000)));
21
+ // Publish the pending marker only after all chunks exist. A failed setup can safely retry.
22
+ for (let i = 0; i < statements.length; i += 40)
23
+ await db.batch(statements.slice(i, i + 40));
24
+ await db.prepare("INSERT OR REPLACE INTO launch_state (id, phase, metadata) VALUES (1, 'pending', '{}')").run();
25
+ }
26
+ export async function readLaunchDraft(env) {
27
+ if (!await launchPending(env))
28
+ return null;
29
+ const db = await database(env);
30
+ const rows = await db.prepare('SELECT content FROM launch_draft_chunks ORDER BY id').all();
31
+ return JSON.parse(rows.results.map(row => row.content).join(''));
32
+ }
33
+ export async function lockLaunch(env) {
34
+ const db = await database(env);
35
+ const result = await db.prepare("UPDATE launch_state SET phase = 'publishing', metadata = ? WHERE id = 1 AND (phase = 'pending' OR (phase = 'publishing' AND json_extract(metadata, '$.startedAt') < ?))").bind(JSON.stringify({ startedAt: Date.now() }), Date.now() - 10 * 60 * 1000).run();
36
+ return result.meta.changes === 1;
37
+ }
38
+ export async function finishLaunch(env, success) {
39
+ const db = await database(env);
40
+ await db.prepare('UPDATE launch_state SET phase = ? WHERE id = 1').bind(success ? 'live' : 'pending').run();
41
+ }
42
+ export async function clearLaunchDraft(env) {
43
+ const db = await database(env);
44
+ await db.batch([db.prepare('DELETE FROM launch_state'), db.prepare('DELETE FROM launch_draft_chunks')]);
45
+ }
@@ -0,0 +1,3 @@
1
+ import type { GitHubClient } from './github';
2
+ export declare function isLaunchPending(client: GitHubClient): Promise<boolean>;
3
+ //# sourceMappingURL=launch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"launch.d.ts","sourceRoot":"","sources":["../../src/lib/launch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAG7C,wBAAsB,eAAe,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC,CAa5E"}