@hiveku-apps/email 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hiveku
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,110 @@
1
+ # @hiveku/email
2
+
3
+ Official Node.js / TypeScript SDK for the **Hiveku Transactional Email Service**.
4
+
5
+ Send transactional emails, manage sending domains, and track delivery stats — all through a simple API.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @hiveku/email
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ ```typescript
16
+ import HivekuEmail from '@hiveku/email';
17
+
18
+ const email = new HivekuEmail('hk_live_YOUR_KEY');
19
+
20
+ await email.send({
21
+ from: 'Acme <hello@acme.com>',
22
+ to: 'user@example.com',
23
+ subject: 'Welcome to Acme!',
24
+ html: '<p>Thanks for signing up.</p>',
25
+ });
26
+ ```
27
+
28
+ Or set `HIVEKU_EMAIL_API_KEY` in your environment and call the module-level helper:
29
+
30
+ ```typescript
31
+ import { sendEmail } from '@hiveku/email';
32
+
33
+ await sendEmail({
34
+ from: 'hello@yourdomain.com',
35
+ to: 'user@example.com',
36
+ subject: 'Hello World',
37
+ html: '<p>Welcome!</p>',
38
+ });
39
+ ```
40
+
41
+ ## Usage with curl
42
+
43
+ ```bash
44
+ curl -X POST https://api.hiveku.com/v1/email/send \
45
+ -H "Authorization: Bearer hk_live_YOUR_KEY" \
46
+ -H "Content-Type: application/json" \
47
+ -d '{
48
+ "from": "hello@yourdomain.com",
49
+ "to": ["user@example.com"],
50
+ "subject": "Hello World",
51
+ "html": "<p>Welcome!</p>"
52
+ }'
53
+ ```
54
+
55
+ ## API
56
+
57
+ ### `new HivekuEmail(apiKeyOrConfig?)`
58
+
59
+ | Parameter | Type | Description |
60
+ |-----------|------|-------------|
61
+ | `apiKey` | `string` | Your Hiveku API key (`hk_live_...` or `hk_test_...`) |
62
+ | `baseUrl` | `string` | Override the API base URL |
63
+ | `timeout` | `number` | Request timeout in ms (default: `30000`) |
64
+
65
+ ### Methods
66
+
67
+ | Method | Description |
68
+ |--------|-------------|
69
+ | `send(options)` | Send a single email |
70
+ | `sendBatch(emails[])` | Send up to 50 emails in one request |
71
+ | `listDomains()` | List all sending domains |
72
+ | `addDomain(domain)` | Add a domain and get DNS records |
73
+ | `verifyDomain(domainId)` | Re-check domain DNS verification |
74
+ | `deleteDomain(domainId)` | Remove a domain |
75
+ | `getUsage(options?)` | Get delivery stats |
76
+ | `generateSmtpCredentials()` | Generate SMTP credentials |
77
+
78
+ ### `send(options)` options
79
+
80
+ | Field | Type | Required | Description |
81
+ |-------|------|----------|-------------|
82
+ | `from` | `string` | ✓ | Sender — `"Name <email>"` or plain address |
83
+ | `to` | `string \| string[]` | ✓ | Recipient(s) |
84
+ | `subject` | `string` | ✓ | Subject line |
85
+ | `html` | `string` | | HTML body |
86
+ | `text` | `string` | | Plain-text body |
87
+ | `replyTo` | `string` | | Reply-to address |
88
+ | `cc` | `string[]` | | CC recipients |
89
+ | `bcc` | `string[]` | | BCC recipients |
90
+ | `headers` | `Record<string,string>` | | Custom headers |
91
+ | `tags` | `Record<string,string>` | | Tracking tags |
92
+ | `attachments` | `Attachment[]` | | File attachments (base64) |
93
+ | `scheduledAt` | `string` | | Schedule delivery (ISO 8601) |
94
+
95
+ ## Environment variables
96
+
97
+ | Variable | Description |
98
+ |----------|-------------|
99
+ | `HIVEKU_EMAIL_API_KEY` | API key used by the default client |
100
+ | `HIVEKU_API_URL` | Override the API base URL |
101
+
102
+ ## Links
103
+
104
+ - Dashboard: [app.hiveku.com](https://app.hiveku.com)
105
+ - API Docs: [app.hiveku.com/docs](https://app.hiveku.com/docs)
106
+ - Status: [status.hiveku.com](https://status.hiveku.com)
107
+
108
+ ## License
109
+
110
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,164 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ // src/index.ts
6
+ var HivekuEmailError = class extends Error {
7
+ constructor(message, status, code) {
8
+ super(message);
9
+ this.name = "HivekuEmailError";
10
+ this.status = status;
11
+ this.code = code;
12
+ }
13
+ };
14
+ var HivekuEmail = class {
15
+ constructor(apiKeyOrConfig) {
16
+ if (typeof apiKeyOrConfig === "string") {
17
+ this.apiKey = apiKeyOrConfig;
18
+ this.baseUrl = "https://api.hiveku.com";
19
+ this.timeout = 3e4;
20
+ } else {
21
+ this.apiKey = apiKeyOrConfig?.apiKey || (typeof process !== "undefined" ? process.env.HIVEKU_EMAIL_API_KEY ?? "" : "");
22
+ this.baseUrl = apiKeyOrConfig?.baseUrl || (typeof process !== "undefined" ? process.env.HIVEKU_API_URL ?? "https://api.hiveku.com" : "https://api.hiveku.com");
23
+ this.timeout = apiKeyOrConfig?.timeout ?? 3e4;
24
+ }
25
+ if (!this.apiKey) {
26
+ throw new Error(
27
+ "Hiveku Email API key is required. Pass it to the constructor or set the HIVEKU_EMAIL_API_KEY environment variable."
28
+ );
29
+ }
30
+ }
31
+ // --------------------------------------------------------------------------
32
+ async request(method, path, body) {
33
+ const controller = new AbortController();
34
+ const timer = setTimeout(() => controller.abort(), this.timeout);
35
+ try {
36
+ const res = await fetch(`${this.baseUrl}${path}`, {
37
+ method,
38
+ headers: {
39
+ Authorization: `Bearer ${this.apiKey}`,
40
+ "Content-Type": "application/json",
41
+ "User-Agent": `hiveku-email-sdk/1.0.0`
42
+ },
43
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
44
+ signal: controller.signal
45
+ });
46
+ const data = await res.json();
47
+ if (!res.ok) {
48
+ throw new HivekuEmailError(
49
+ data.error || `Request failed with status ${res.status}`,
50
+ res.status,
51
+ data.code || "UNKNOWN_ERROR"
52
+ );
53
+ }
54
+ return data;
55
+ } finally {
56
+ clearTimeout(timer);
57
+ }
58
+ }
59
+ // ── Sending ──────────────────────────────────────────────────────────────
60
+ /**
61
+ * Send a single transactional email.
62
+ *
63
+ * @example
64
+ * await email.send({
65
+ * from: 'Acme <hello@acme.com>',
66
+ * to: 'user@example.com',
67
+ * subject: 'Welcome!',
68
+ * html: '<p>Thanks for signing up.</p>',
69
+ * });
70
+ */
71
+ async send(options) {
72
+ return this.request("POST", "/api/v1/email/send", {
73
+ from: options.from,
74
+ to: Array.isArray(options.to) ? options.to : [options.to],
75
+ subject: options.subject,
76
+ html: options.html,
77
+ text: options.text,
78
+ reply_to: options.replyTo,
79
+ cc: options.cc,
80
+ bcc: options.bcc,
81
+ headers: options.headers,
82
+ tags: options.tags,
83
+ attachments: options.attachments,
84
+ scheduled_at: options.scheduledAt
85
+ });
86
+ }
87
+ /**
88
+ * Send up to 50 emails in a single request.
89
+ */
90
+ async sendBatch(emails) {
91
+ if (emails.length > 50) throw new Error("Maximum 50 emails per batch.");
92
+ return this.request("POST", "/api/v1/email/batch", {
93
+ emails: emails.map((e) => ({
94
+ from: e.from,
95
+ to: Array.isArray(e.to) ? e.to : [e.to],
96
+ subject: e.subject,
97
+ html: e.html,
98
+ text: e.text,
99
+ reply_to: e.replyTo,
100
+ cc: e.cc,
101
+ bcc: e.bcc,
102
+ tags: e.tags,
103
+ attachments: e.attachments,
104
+ scheduled_at: e.scheduledAt
105
+ }))
106
+ });
107
+ }
108
+ // ── Domains ───────────────────────────────────────────────────────────────
109
+ /** List all domains on this account. */
110
+ async listDomains() {
111
+ return this.request("GET", "/api/v1/email/domains");
112
+ }
113
+ /** Add a domain and get the DNS records to configure. */
114
+ async addDomain(domain) {
115
+ return this.request("POST", "/api/v1/email/domains", { domain });
116
+ }
117
+ /** Trigger re-verification of a domain's DNS records. */
118
+ async verifyDomain(domainId) {
119
+ return this.request("POST", `/api/v1/email/domains/${domainId}`);
120
+ }
121
+ /** Remove a domain from the account. */
122
+ async deleteDomain(domainId) {
123
+ return this.request("DELETE", `/api/v1/email/domains/${domainId}`);
124
+ }
125
+ // ── Usage ─────────────────────────────────────────────────────────────────
126
+ /** Get send/delivery stats for a date range. */
127
+ async getUsage(options) {
128
+ const params = new URLSearchParams();
129
+ if (options?.startDate) params.set("start_date", options.startDate);
130
+ if (options?.endDate) params.set("end_date", options.endDate);
131
+ const qs = params.toString();
132
+ return this.request("GET", `/api/v1/email/usage${qs ? `?${qs}` : ""}`);
133
+ }
134
+ // ── SMTP ──────────────────────────────────────────────────────────────────
135
+ /**
136
+ * Generate SMTP credentials — useful for services like Supabase Auth or
137
+ * any system that only supports SMTP.
138
+ */
139
+ async generateSmtpCredentials() {
140
+ return this.request("POST", "/api/v1/email/smtp-credentials");
141
+ }
142
+ };
143
+ var _defaultClient = null;
144
+ function init(apiKey, config) {
145
+ _defaultClient = new HivekuEmail({ apiKey, ...config });
146
+ }
147
+ function getDefault() {
148
+ if (!_defaultClient) {
149
+ _defaultClient = new HivekuEmail();
150
+ }
151
+ return _defaultClient;
152
+ }
153
+ function sendEmail(options) {
154
+ return getDefault().send(options);
155
+ }
156
+ var index_default = HivekuEmail;
157
+
158
+ exports.HivekuEmail = HivekuEmail;
159
+ exports.HivekuEmailError = HivekuEmailError;
160
+ exports.default = index_default;
161
+ exports.init = init;
162
+ exports.sendEmail = sendEmail;
163
+ //# sourceMappingURL=index.cjs.map
164
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAmGO,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAI1C,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAgB,IAAA,EAAc;AACzD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAMO,IAAM,cAAN,MAAkB;AAAA,EAKvB,YAAY,cAAA,EAA6C;AACvD,IAAA,IAAI,OAAO,mBAAmB,QAAA,EAAU;AACtC,MAAA,IAAA,CAAK,MAAA,GAAS,cAAA;AACd,MAAA,IAAA,CAAK,OAAA,GAAU,wBAAA;AACf,MAAA,IAAA,CAAK,OAAA,GAAU,GAAA;AAAA,IACjB,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,MAAA,GACH,gBAAgB,MAAA,KACf,OAAO,YAAY,WAAA,GAAc,OAAA,CAAQ,GAAA,CAAI,oBAAA,IAAwB,EAAA,GAAK,EAAA,CAAA;AAC7E,MAAA,IAAA,CAAK,OAAA,GACH,gBAAgB,OAAA,KACf,OAAO,YAAY,WAAA,GAChB,OAAA,CAAQ,GAAA,CAAI,cAAA,IAAkB,wBAAA,GAC9B,wBAAA,CAAA;AACN,MAAA,IAAA,CAAK,OAAA,GAAU,gBAAgB,OAAA,IAAW,GAAA;AAAA,IAC5C;AAEA,IAAA,IAAI,CAAC,KAAK,MAAA,EAAQ;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AI,EAAE,CAAA,CAAA,GAAK,EAAE,CAAA,CAAE,CAAA;AAAA,EACvE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,uBAAA,GAAoD;AACxD,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,MAAA,EAAQ,gCAAgC,CAAA;AAAA,EAC9D;AACF;AAMA,IAAI,cAAA,GAAqC,IAAA;AAGlC,SAAS,IAAA,CAAK,QAAgB,MAAA,EAAkD;AACrF,EAAA,cAAA,GAAiB,IAAI,WAAA,CAAY,EAAE,MAAA,EAAQ,GAAG,QAAQ,CAAA;AACxD;AAEA,SAAS,UAAA,GAA0B;AACjC,EAAA,IAAI,CAAC,cAAA,EAAgB;AACnB,IAAA,cAAA,GAAiB,IAAI,WAAA,EAAY;AAAA,EACnC;AACA,EAAA,OAAO,cAAA;AACT;AAGO,SAAS,UAAU,OAAA,EAAuD;AAC/E,EAAA,OAAO,UAAA,EAAW,CAAE,IAAA,CAAK,OAAO,CAAA;AAClC;AAEA,IAAO,aAAA,GAAQ","file":"index.cjs","sourcesContent":["/**\n * @hiveku/email — Official Hiveku Transactional Email SDK\n * https://hiveku.com\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface SendEmailOptions {\n /** Sender address. Supports \"Name <email>\" format. */\n from: string;\n /** One or more recipient addresses. */\n to: string | string[];\n /** Email subject line. */\n subject: string;\n /** HTML body content. */\n html?: string;\n /** Plain text body content. */\n text?: string;\n /** Reply-to address. */\n replyTo?: string;\n /** CC recipients. */\n cc?: string[];\n /** BCC recipients. */\n bcc?: string[];\n /** Custom headers. */\n headers?: Record<string, string>;\n /** Tags for tracking / filtering (key-value pairs). */\n tags?: Record<string, string>;\n /** File attachments. */\n attachments?: Array<{\n filename: string;\n /** Base64-encoded file content. */\n content: string;\n contentType?: string;\n }>;\n /** Schedule delivery (ISO 8601). */\n scheduledAt?: string;\n}\n\nexport interface SendEmailResponse {\n id: string;\n status: 'queued' | 'sent' | 'failed';\n}\n\nexport interface BatchSendResponse {\n results: SendEmailResponse[];\n}\n\nexport interface EmailDomain {\n id: string;\n domain: string;\n status: 'pending' | 'verified' | 'failed';\n dnsRecords?: Array<{\n type: string;\n name: string;\n value: string;\n priority?: number;\n }>;\n createdAt: string;\n}\n\nexport interface UsageStats {\n sent: number;\n delivered: number;\n bounced: number;\n complained: number;\n opened: number;\n clicked: number;\n period: {\n start: string;\n end: string;\n };\n limits: {\n daily: number;\n monthly: number;\n dailyUsed: number;\n monthlyUsed: number;\n };\n}\n\nexport interface SmtpCredentials {\n host: string;\n port: number;\n username: string;\n password: string;\n secure: boolean;\n}\n\nexport interface HivekuEmailConfig {\n /** Your Hiveku API key (hk_live_... or hk_test_...). */\n apiKey?: string;\n /** Override the base URL (default: https://api.hiveku.com). */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000). */\n timeout?: number;\n}\n\nexport class HivekuEmailError extends Error {\n status: number;\n code: string;\n\n constructor(message: string, status: number, code: string) {\n super(message);\n this.name = 'HivekuEmailError';\n this.status = status;\n this.code = code;\n }\n}\n\n// ============================================================================\n// Client\n// ============================================================================\n\nexport class HivekuEmail {\n private apiKey: string;\n private baseUrl: string;\n private timeout: number;\n\n constructor(apiKeyOrConfig?: string | HivekuEmailConfig) {\n if (typeof apiKeyOrConfig === 'string') {\n this.apiKey = apiKeyOrConfig;\n this.baseUrl = 'https://api.hiveku.com';\n this.timeout = 30_000;\n } else {\n this.apiKey =\n apiKeyOrConfig?.apiKey ||\n (typeof process !== 'undefined' ? process.env.HIVEKU_EMAIL_API_KEY ?? '' : '');\n this.baseUrl =\n apiKeyOrConfig?.baseUrl ||\n (typeof process !== 'undefined'\n ? process.env.HIVEKU_API_URL ?? 'https://api.hiveku.com'\n : 'https://api.hiveku.com');\n this.timeout = apiKeyOrConfig?.timeout ?? 30_000;\n }\n\n if (!this.apiKey) {\n throw new Error(\n 'Hiveku Email API key is required. Pass it to the constructor or set the HIVEKU_EMAIL_API_KEY environment variable.'\n );\n }\n }\n\n // --------------------------------------------------------------------------\n\n private async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const res = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n 'User-Agent': `hiveku-email-sdk/1.0.0`,\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n const data = (await res.json()) as Record<string, unknown>;\n\n if (!res.ok) {\n throw new HivekuEmailError(\n (data.error as string) || `Request failed with status ${res.status}`,\n res.status,\n (data.code as string) || 'UNKNOWN_ERROR'\n );\n }\n\n return data as T;\n } finally {\n clearTimeout(timer);\n }\n }\n\n // ── Sending ──────────────────────────────────────────────────────────────\n\n /**\n * Send a single transactional email.\n *\n * @example\n * await email.send({\n * from: 'Acme <hello@acme.com>',\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * html: '<p>Thanks for signing up.</p>',\n * });\n */\n async send(options: SendEmailOptions): Promise<SendEmailResponse> {\n return this.request<SendEmailResponse>('POST', '/api/v1/email/send', {\n from: options.from,\n to: Array.isArray(options.to) ? options.to : [options.to],\n subject: options.subject,\n html: options.html,\n text: options.text,\n reply_to: options.replyTo,\n cc: options.cc,\n bcc: options.bcc,\n headers: options.headers,\n tags: options.tags,\n attachments: options.attachments,\n scheduled_at: options.scheduledAt,\n });\n }\n\n /**\n * Send up to 50 emails in a single request.\n */\n async sendBatch(emails: SendEmailOptions[]): Promise<BatchSendResponse> {\n if (emails.length > 50) throw new Error('Maximum 50 emails per batch.');\n\n return this.request<BatchSendResponse>('POST', '/api/v1/email/batch', {\n emails: emails.map((e) => ({\n from: e.from,\n to: Array.isArray(e.to) ? e.to : [e.to],\n subject: e.subject,\n html: e.html,\n text: e.text,\n reply_to: e.replyTo,\n cc: e.cc,\n bcc: e.bcc,\n tags: e.tags,\n attachments: e.attachments,\n scheduled_at: e.scheduledAt,\n })),\n });\n }\n\n // ── Domains ───────────────────────────────────────────────────────────────\n\n /** List all domains on this account. */\n async listDomains(): Promise<{ domains: EmailDomain[] }> {\n return this.request('GET', '/api/v1/email/domains');\n }\n\n /** Add a domain and get the DNS records to configure. */\n async addDomain(domain: string): Promise<EmailDomain> {\n return this.request('POST', '/api/v1/email/domains', { domain });\n }\n\n /** Trigger re-verification of a domain's DNS records. */\n async verifyDomain(domainId: string): Promise<EmailDomain> {\n return this.request('POST', `/api/v1/email/domains/${domainId}`);\n }\n\n /** Remove a domain from the account. */\n async deleteDomain(domainId: string): Promise<{ success: boolean }> {\n return this.request('DELETE', `/api/v1/email/domains/${domainId}`);\n }\n\n // ── Usage ─────────────────────────────────────────────────────────────────\n\n /** Get send/delivery stats for a date range. */\n async getUsage(options?: { startDate?: string; endDate?: string }): Promise<UsageStats> {\n const params = new URLSearchParams();\n if (options?.startDate) params.set('start_date', options.startDate);\n if (options?.endDate) params.set('end_date', options.endDate);\n const qs = params.toString();\n return this.request('GET', `/api/v1/email/usage${qs ? `?${qs}` : ''}`);\n }\n\n // ── SMTP ──────────────────────────────────────────────────────────────────\n\n /**\n * Generate SMTP credentials — useful for services like Supabase Auth or\n * any system that only supports SMTP.\n */\n async generateSmtpCredentials(): Promise<SmtpCredentials> {\n return this.request('POST', '/api/v1/email/smtp-credentials');\n }\n}\n\n// ============================================================================\n// Module-level convenience\n// ============================================================================\n\nlet _defaultClient: HivekuEmail | null = null;\n\n/** Initialize the default module-level client. */\nexport function init(apiKey: string, config?: Omit<HivekuEmailConfig, 'apiKey'>): void {\n _defaultClient = new HivekuEmail({ apiKey, ...config });\n}\n\nfunction getDefault(): HivekuEmail {\n if (!_defaultClient) {\n _defaultClient = new HivekuEmail();\n }\n return _defaultClient;\n}\n\n/** Send an email using the module-level default client. */\nexport function sendEmail(options: SendEmailOptions): Promise<SendEmailResponse> {\n return getDefault().send(options);\n}\n\nexport default HivekuEmail;\n"]}
@@ -0,0 +1,143 @@
1
+ /**
2
+ * @hiveku/email — Official Hiveku Transactional Email SDK
3
+ * https://hiveku.com
4
+ */
5
+ interface SendEmailOptions {
6
+ /** Sender address. Supports "Name <email>" format. */
7
+ from: string;
8
+ /** One or more recipient addresses. */
9
+ to: string | string[];
10
+ /** Email subject line. */
11
+ subject: string;
12
+ /** HTML body content. */
13
+ html?: string;
14
+ /** Plain text body content. */
15
+ text?: string;
16
+ /** Reply-to address. */
17
+ replyTo?: string;
18
+ /** CC recipients. */
19
+ cc?: string[];
20
+ /** BCC recipients. */
21
+ bcc?: string[];
22
+ /** Custom headers. */
23
+ headers?: Record<string, string>;
24
+ /** Tags for tracking / filtering (key-value pairs). */
25
+ tags?: Record<string, string>;
26
+ /** File attachments. */
27
+ attachments?: Array<{
28
+ filename: string;
29
+ /** Base64-encoded file content. */
30
+ content: string;
31
+ contentType?: string;
32
+ }>;
33
+ /** Schedule delivery (ISO 8601). */
34
+ scheduledAt?: string;
35
+ }
36
+ interface SendEmailResponse {
37
+ id: string;
38
+ status: 'queued' | 'sent' | 'failed';
39
+ }
40
+ interface BatchSendResponse {
41
+ results: SendEmailResponse[];
42
+ }
43
+ interface EmailDomain {
44
+ id: string;
45
+ domain: string;
46
+ status: 'pending' | 'verified' | 'failed';
47
+ dnsRecords?: Array<{
48
+ type: string;
49
+ name: string;
50
+ value: string;
51
+ priority?: number;
52
+ }>;
53
+ createdAt: string;
54
+ }
55
+ interface UsageStats {
56
+ sent: number;
57
+ delivered: number;
58
+ bounced: number;
59
+ complained: number;
60
+ opened: number;
61
+ clicked: number;
62
+ period: {
63
+ start: string;
64
+ end: string;
65
+ };
66
+ limits: {
67
+ daily: number;
68
+ monthly: number;
69
+ dailyUsed: number;
70
+ monthlyUsed: number;
71
+ };
72
+ }
73
+ interface SmtpCredentials {
74
+ host: string;
75
+ port: number;
76
+ username: string;
77
+ password: string;
78
+ secure: boolean;
79
+ }
80
+ interface HivekuEmailConfig {
81
+ /** Your Hiveku API key (hk_live_... or hk_test_...). */
82
+ apiKey?: string;
83
+ /** Override the base URL (default: https://api.hiveku.com). */
84
+ baseUrl?: string;
85
+ /** Request timeout in milliseconds (default: 30000). */
86
+ timeout?: number;
87
+ }
88
+ declare class HivekuEmailError extends Error {
89
+ status: number;
90
+ code: string;
91
+ constructor(message: string, status: number, code: string);
92
+ }
93
+ declare class HivekuEmail {
94
+ private apiKey;
95
+ private baseUrl;
96
+ private timeout;
97
+ constructor(apiKeyOrConfig?: string | HivekuEmailConfig);
98
+ private request;
99
+ /**
100
+ * Send a single transactional email.
101
+ *
102
+ * @example
103
+ * await email.send({
104
+ * from: 'Acme <hello@acme.com>',
105
+ * to: 'user@example.com',
106
+ * subject: 'Welcome!',
107
+ * html: '<p>Thanks for signing up.</p>',
108
+ * });
109
+ */
110
+ send(options: SendEmailOptions): Promise<SendEmailResponse>;
111
+ /**
112
+ * Send up to 50 emails in a single request.
113
+ */
114
+ sendBatch(emails: SendEmailOptions[]): Promise<BatchSendResponse>;
115
+ /** List all domains on this account. */
116
+ listDomains(): Promise<{
117
+ domains: EmailDomain[];
118
+ }>;
119
+ /** Add a domain and get the DNS records to configure. */
120
+ addDomain(domain: string): Promise<EmailDomain>;
121
+ /** Trigger re-verification of a domain's DNS records. */
122
+ verifyDomain(domainId: string): Promise<EmailDomain>;
123
+ /** Remove a domain from the account. */
124
+ deleteDomain(domainId: string): Promise<{
125
+ success: boolean;
126
+ }>;
127
+ /** Get send/delivery stats for a date range. */
128
+ getUsage(options?: {
129
+ startDate?: string;
130
+ endDate?: string;
131
+ }): Promise<UsageStats>;
132
+ /**
133
+ * Generate SMTP credentials — useful for services like Supabase Auth or
134
+ * any system that only supports SMTP.
135
+ */
136
+ generateSmtpCredentials(): Promise<SmtpCredentials>;
137
+ }
138
+ /** Initialize the default module-level client. */
139
+ declare function init(apiKey: string, config?: Omit<HivekuEmailConfig, 'apiKey'>): void;
140
+ /** Send an email using the module-level default client. */
141
+ declare function sendEmail(options: SendEmailOptions): Promise<SendEmailResponse>;
142
+
143
+ export { type BatchSendResponse, type EmailDomain, HivekuEmail, type HivekuEmailConfig, HivekuEmailError, type SendEmailOptions, type SendEmailResponse, type SmtpCredentials, type UsageStats, HivekuEmail as default, init, sendEmail };
@@ -0,0 +1,143 @@
1
+ /**
2
+ * @hiveku/email — Official Hiveku Transactional Email SDK
3
+ * https://hiveku.com
4
+ */
5
+ interface SendEmailOptions {
6
+ /** Sender address. Supports "Name <email>" format. */
7
+ from: string;
8
+ /** One or more recipient addresses. */
9
+ to: string | string[];
10
+ /** Email subject line. */
11
+ subject: string;
12
+ /** HTML body content. */
13
+ html?: string;
14
+ /** Plain text body content. */
15
+ text?: string;
16
+ /** Reply-to address. */
17
+ replyTo?: string;
18
+ /** CC recipients. */
19
+ cc?: string[];
20
+ /** BCC recipients. */
21
+ bcc?: string[];
22
+ /** Custom headers. */
23
+ headers?: Record<string, string>;
24
+ /** Tags for tracking / filtering (key-value pairs). */
25
+ tags?: Record<string, string>;
26
+ /** File attachments. */
27
+ attachments?: Array<{
28
+ filename: string;
29
+ /** Base64-encoded file content. */
30
+ content: string;
31
+ contentType?: string;
32
+ }>;
33
+ /** Schedule delivery (ISO 8601). */
34
+ scheduledAt?: string;
35
+ }
36
+ interface SendEmailResponse {
37
+ id: string;
38
+ status: 'queued' | 'sent' | 'failed';
39
+ }
40
+ interface BatchSendResponse {
41
+ results: SendEmailResponse[];
42
+ }
43
+ interface EmailDomain {
44
+ id: string;
45
+ domain: string;
46
+ status: 'pending' | 'verified' | 'failed';
47
+ dnsRecords?: Array<{
48
+ type: string;
49
+ name: string;
50
+ value: string;
51
+ priority?: number;
52
+ }>;
53
+ createdAt: string;
54
+ }
55
+ interface UsageStats {
56
+ sent: number;
57
+ delivered: number;
58
+ bounced: number;
59
+ complained: number;
60
+ opened: number;
61
+ clicked: number;
62
+ period: {
63
+ start: string;
64
+ end: string;
65
+ };
66
+ limits: {
67
+ daily: number;
68
+ monthly: number;
69
+ dailyUsed: number;
70
+ monthlyUsed: number;
71
+ };
72
+ }
73
+ interface SmtpCredentials {
74
+ host: string;
75
+ port: number;
76
+ username: string;
77
+ password: string;
78
+ secure: boolean;
79
+ }
80
+ interface HivekuEmailConfig {
81
+ /** Your Hiveku API key (hk_live_... or hk_test_...). */
82
+ apiKey?: string;
83
+ /** Override the base URL (default: https://api.hiveku.com). */
84
+ baseUrl?: string;
85
+ /** Request timeout in milliseconds (default: 30000). */
86
+ timeout?: number;
87
+ }
88
+ declare class HivekuEmailError extends Error {
89
+ status: number;
90
+ code: string;
91
+ constructor(message: string, status: number, code: string);
92
+ }
93
+ declare class HivekuEmail {
94
+ private apiKey;
95
+ private baseUrl;
96
+ private timeout;
97
+ constructor(apiKeyOrConfig?: string | HivekuEmailConfig);
98
+ private request;
99
+ /**
100
+ * Send a single transactional email.
101
+ *
102
+ * @example
103
+ * await email.send({
104
+ * from: 'Acme <hello@acme.com>',
105
+ * to: 'user@example.com',
106
+ * subject: 'Welcome!',
107
+ * html: '<p>Thanks for signing up.</p>',
108
+ * });
109
+ */
110
+ send(options: SendEmailOptions): Promise<SendEmailResponse>;
111
+ /**
112
+ * Send up to 50 emails in a single request.
113
+ */
114
+ sendBatch(emails: SendEmailOptions[]): Promise<BatchSendResponse>;
115
+ /** List all domains on this account. */
116
+ listDomains(): Promise<{
117
+ domains: EmailDomain[];
118
+ }>;
119
+ /** Add a domain and get the DNS records to configure. */
120
+ addDomain(domain: string): Promise<EmailDomain>;
121
+ /** Trigger re-verification of a domain's DNS records. */
122
+ verifyDomain(domainId: string): Promise<EmailDomain>;
123
+ /** Remove a domain from the account. */
124
+ deleteDomain(domainId: string): Promise<{
125
+ success: boolean;
126
+ }>;
127
+ /** Get send/delivery stats for a date range. */
128
+ getUsage(options?: {
129
+ startDate?: string;
130
+ endDate?: string;
131
+ }): Promise<UsageStats>;
132
+ /**
133
+ * Generate SMTP credentials — useful for services like Supabase Auth or
134
+ * any system that only supports SMTP.
135
+ */
136
+ generateSmtpCredentials(): Promise<SmtpCredentials>;
137
+ }
138
+ /** Initialize the default module-level client. */
139
+ declare function init(apiKey: string, config?: Omit<HivekuEmailConfig, 'apiKey'>): void;
140
+ /** Send an email using the module-level default client. */
141
+ declare function sendEmail(options: SendEmailOptions): Promise<SendEmailResponse>;
142
+
143
+ export { type BatchSendResponse, type EmailDomain, HivekuEmail, type HivekuEmailConfig, HivekuEmailError, type SendEmailOptions, type SendEmailResponse, type SmtpCredentials, type UsageStats, HivekuEmail as default, init, sendEmail };
package/dist/index.js ADDED
@@ -0,0 +1,156 @@
1
+ // src/index.ts
2
+ var HivekuEmailError = class extends Error {
3
+ constructor(message, status, code) {
4
+ super(message);
5
+ this.name = "HivekuEmailError";
6
+ this.status = status;
7
+ this.code = code;
8
+ }
9
+ };
10
+ var HivekuEmail = class {
11
+ constructor(apiKeyOrConfig) {
12
+ if (typeof apiKeyOrConfig === "string") {
13
+ this.apiKey = apiKeyOrConfig;
14
+ this.baseUrl = "https://api.hiveku.com";
15
+ this.timeout = 3e4;
16
+ } else {
17
+ this.apiKey = apiKeyOrConfig?.apiKey || (typeof process !== "undefined" ? process.env.HIVEKU_EMAIL_API_KEY ?? "" : "");
18
+ this.baseUrl = apiKeyOrConfig?.baseUrl || (typeof process !== "undefined" ? process.env.HIVEKU_API_URL ?? "https://api.hiveku.com" : "https://api.hiveku.com");
19
+ this.timeout = apiKeyOrConfig?.timeout ?? 3e4;
20
+ }
21
+ if (!this.apiKey) {
22
+ throw new Error(
23
+ "Hiveku Email API key is required. Pass it to the constructor or set the HIVEKU_EMAIL_API_KEY environment variable."
24
+ );
25
+ }
26
+ }
27
+ // --------------------------------------------------------------------------
28
+ async request(method, path, body) {
29
+ const controller = new AbortController();
30
+ const timer = setTimeout(() => controller.abort(), this.timeout);
31
+ try {
32
+ const res = await fetch(`${this.baseUrl}${path}`, {
33
+ method,
34
+ headers: {
35
+ Authorization: `Bearer ${this.apiKey}`,
36
+ "Content-Type": "application/json",
37
+ "User-Agent": `hiveku-email-sdk/1.0.0`
38
+ },
39
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
40
+ signal: controller.signal
41
+ });
42
+ const data = await res.json();
43
+ if (!res.ok) {
44
+ throw new HivekuEmailError(
45
+ data.error || `Request failed with status ${res.status}`,
46
+ res.status,
47
+ data.code || "UNKNOWN_ERROR"
48
+ );
49
+ }
50
+ return data;
51
+ } finally {
52
+ clearTimeout(timer);
53
+ }
54
+ }
55
+ // ── Sending ──────────────────────────────────────────────────────────────
56
+ /**
57
+ * Send a single transactional email.
58
+ *
59
+ * @example
60
+ * await email.send({
61
+ * from: 'Acme <hello@acme.com>',
62
+ * to: 'user@example.com',
63
+ * subject: 'Welcome!',
64
+ * html: '<p>Thanks for signing up.</p>',
65
+ * });
66
+ */
67
+ async send(options) {
68
+ return this.request("POST", "/api/v1/email/send", {
69
+ from: options.from,
70
+ to: Array.isArray(options.to) ? options.to : [options.to],
71
+ subject: options.subject,
72
+ html: options.html,
73
+ text: options.text,
74
+ reply_to: options.replyTo,
75
+ cc: options.cc,
76
+ bcc: options.bcc,
77
+ headers: options.headers,
78
+ tags: options.tags,
79
+ attachments: options.attachments,
80
+ scheduled_at: options.scheduledAt
81
+ });
82
+ }
83
+ /**
84
+ * Send up to 50 emails in a single request.
85
+ */
86
+ async sendBatch(emails) {
87
+ if (emails.length > 50) throw new Error("Maximum 50 emails per batch.");
88
+ return this.request("POST", "/api/v1/email/batch", {
89
+ emails: emails.map((e) => ({
90
+ from: e.from,
91
+ to: Array.isArray(e.to) ? e.to : [e.to],
92
+ subject: e.subject,
93
+ html: e.html,
94
+ text: e.text,
95
+ reply_to: e.replyTo,
96
+ cc: e.cc,
97
+ bcc: e.bcc,
98
+ tags: e.tags,
99
+ attachments: e.attachments,
100
+ scheduled_at: e.scheduledAt
101
+ }))
102
+ });
103
+ }
104
+ // ── Domains ───────────────────────────────────────────────────────────────
105
+ /** List all domains on this account. */
106
+ async listDomains() {
107
+ return this.request("GET", "/api/v1/email/domains");
108
+ }
109
+ /** Add a domain and get the DNS records to configure. */
110
+ async addDomain(domain) {
111
+ return this.request("POST", "/api/v1/email/domains", { domain });
112
+ }
113
+ /** Trigger re-verification of a domain's DNS records. */
114
+ async verifyDomain(domainId) {
115
+ return this.request("POST", `/api/v1/email/domains/${domainId}`);
116
+ }
117
+ /** Remove a domain from the account. */
118
+ async deleteDomain(domainId) {
119
+ return this.request("DELETE", `/api/v1/email/domains/${domainId}`);
120
+ }
121
+ // ── Usage ─────────────────────────────────────────────────────────────────
122
+ /** Get send/delivery stats for a date range. */
123
+ async getUsage(options) {
124
+ const params = new URLSearchParams();
125
+ if (options?.startDate) params.set("start_date", options.startDate);
126
+ if (options?.endDate) params.set("end_date", options.endDate);
127
+ const qs = params.toString();
128
+ return this.request("GET", `/api/v1/email/usage${qs ? `?${qs}` : ""}`);
129
+ }
130
+ // ── SMTP ──────────────────────────────────────────────────────────────────
131
+ /**
132
+ * Generate SMTP credentials — useful for services like Supabase Auth or
133
+ * any system that only supports SMTP.
134
+ */
135
+ async generateSmtpCredentials() {
136
+ return this.request("POST", "/api/v1/email/smtp-credentials");
137
+ }
138
+ };
139
+ var _defaultClient = null;
140
+ function init(apiKey, config) {
141
+ _defaultClient = new HivekuEmail({ apiKey, ...config });
142
+ }
143
+ function getDefault() {
144
+ if (!_defaultClient) {
145
+ _defaultClient = new HivekuEmail();
146
+ }
147
+ return _defaultClient;
148
+ }
149
+ function sendEmail(options) {
150
+ return getDefault().send(options);
151
+ }
152
+ var index_default = HivekuEmail;
153
+
154
+ export { HivekuEmail, HivekuEmailError, index_default as default, init, sendEmail };
155
+ //# sourceMappingURL=index.js.map
156
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";AAmGO,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAI1C,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAgB,IAAA,EAAc;AACzD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA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AA,cAAA,GAAiB,IAAI,WAAA,EAAY;AAAA,EACnC;AACA,EAAA,OAAO,cAAA;AACT;AAGO,SAAS,UAAU,OAAA,EAAuD;AAC/E,EAAA,OAAO,UAAA,EAAW,CAAE,IAAA,CAAK,OAAO,CAAA;AAClC;AAEA,IAAO,aAAA,GAAQ","file":"index.js","sourcesContent":["/**\n * @hiveku/email — Official Hiveku Transactional Email SDK\n * https://hiveku.com\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface SendEmailOptions {\n /** Sender address. Supports \"Name <email>\" format. */\n from: string;\n /** One or more recipient addresses. */\n to: string | string[];\n /** Email subject line. */\n subject: string;\n /** HTML body content. */\n html?: string;\n /** Plain text body content. */\n text?: string;\n /** Reply-to address. */\n replyTo?: string;\n /** CC recipients. */\n cc?: string[];\n /** BCC recipients. */\n bcc?: string[];\n /** Custom headers. */\n headers?: Record<string, string>;\n /** Tags for tracking / filtering (key-value pairs). */\n tags?: Record<string, string>;\n /** File attachments. */\n attachments?: Array<{\n filename: string;\n /** Base64-encoded file content. */\n content: string;\n contentType?: string;\n }>;\n /** Schedule delivery (ISO 8601). */\n scheduledAt?: string;\n}\n\nexport interface SendEmailResponse {\n id: string;\n status: 'queued' | 'sent' | 'failed';\n}\n\nexport interface BatchSendResponse {\n results: SendEmailResponse[];\n}\n\nexport interface EmailDomain {\n id: string;\n domain: string;\n status: 'pending' | 'verified' | 'failed';\n dnsRecords?: Array<{\n type: string;\n name: string;\n value: string;\n priority?: number;\n }>;\n createdAt: string;\n}\n\nexport interface UsageStats {\n sent: number;\n delivered: number;\n bounced: number;\n complained: number;\n opened: number;\n clicked: number;\n period: {\n start: string;\n end: string;\n };\n limits: {\n daily: number;\n monthly: number;\n dailyUsed: number;\n monthlyUsed: number;\n };\n}\n\nexport interface SmtpCredentials {\n host: string;\n port: number;\n username: string;\n password: string;\n secure: boolean;\n}\n\nexport interface HivekuEmailConfig {\n /** Your Hiveku API key (hk_live_... or hk_test_...). */\n apiKey?: string;\n /** Override the base URL (default: https://api.hiveku.com). */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000). */\n timeout?: number;\n}\n\nexport class HivekuEmailError extends Error {\n status: number;\n code: string;\n\n constructor(message: string, status: number, code: string) {\n super(message);\n this.name = 'HivekuEmailError';\n this.status = status;\n this.code = code;\n }\n}\n\n// ============================================================================\n// Client\n// ============================================================================\n\nexport class HivekuEmail {\n private apiKey: string;\n private baseUrl: string;\n private timeout: number;\n\n constructor(apiKeyOrConfig?: string | HivekuEmailConfig) {\n if (typeof apiKeyOrConfig === 'string') {\n this.apiKey = apiKeyOrConfig;\n this.baseUrl = 'https://api.hiveku.com';\n this.timeout = 30_000;\n } else {\n this.apiKey =\n apiKeyOrConfig?.apiKey ||\n (typeof process !== 'undefined' ? process.env.HIVEKU_EMAIL_API_KEY ?? '' : '');\n this.baseUrl =\n apiKeyOrConfig?.baseUrl ||\n (typeof process !== 'undefined'\n ? process.env.HIVEKU_API_URL ?? 'https://api.hiveku.com'\n : 'https://api.hiveku.com');\n this.timeout = apiKeyOrConfig?.timeout ?? 30_000;\n }\n\n if (!this.apiKey) {\n throw new Error(\n 'Hiveku Email API key is required. Pass it to the constructor or set the HIVEKU_EMAIL_API_KEY environment variable.'\n );\n }\n }\n\n // --------------------------------------------------------------------------\n\n private async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const res = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n 'User-Agent': `hiveku-email-sdk/1.0.0`,\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n const data = (await res.json()) as Record<string, unknown>;\n\n if (!res.ok) {\n throw new HivekuEmailError(\n (data.error as string) || `Request failed with status ${res.status}`,\n res.status,\n (data.code as string) || 'UNKNOWN_ERROR'\n );\n }\n\n return data as T;\n } finally {\n clearTimeout(timer);\n }\n }\n\n // ── Sending ──────────────────────────────────────────────────────────────\n\n /**\n * Send a single transactional email.\n *\n * @example\n * await email.send({\n * from: 'Acme <hello@acme.com>',\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * html: '<p>Thanks for signing up.</p>',\n * });\n */\n async send(options: SendEmailOptions): Promise<SendEmailResponse> {\n return this.request<SendEmailResponse>('POST', '/api/v1/email/send', {\n from: options.from,\n to: Array.isArray(options.to) ? options.to : [options.to],\n subject: options.subject,\n html: options.html,\n text: options.text,\n reply_to: options.replyTo,\n cc: options.cc,\n bcc: options.bcc,\n headers: options.headers,\n tags: options.tags,\n attachments: options.attachments,\n scheduled_at: options.scheduledAt,\n });\n }\n\n /**\n * Send up to 50 emails in a single request.\n */\n async sendBatch(emails: SendEmailOptions[]): Promise<BatchSendResponse> {\n if (emails.length > 50) throw new Error('Maximum 50 emails per batch.');\n\n return this.request<BatchSendResponse>('POST', '/api/v1/email/batch', {\n emails: emails.map((e) => ({\n from: e.from,\n to: Array.isArray(e.to) ? e.to : [e.to],\n subject: e.subject,\n html: e.html,\n text: e.text,\n reply_to: e.replyTo,\n cc: e.cc,\n bcc: e.bcc,\n tags: e.tags,\n attachments: e.attachments,\n scheduled_at: e.scheduledAt,\n })),\n });\n }\n\n // ── Domains ───────────────────────────────────────────────────────────────\n\n /** List all domains on this account. */\n async listDomains(): Promise<{ domains: EmailDomain[] }> {\n return this.request('GET', '/api/v1/email/domains');\n }\n\n /** Add a domain and get the DNS records to configure. */\n async addDomain(domain: string): Promise<EmailDomain> {\n return this.request('POST', '/api/v1/email/domains', { domain });\n }\n\n /** Trigger re-verification of a domain's DNS records. */\n async verifyDomain(domainId: string): Promise<EmailDomain> {\n return this.request('POST', `/api/v1/email/domains/${domainId}`);\n }\n\n /** Remove a domain from the account. */\n async deleteDomain(domainId: string): Promise<{ success: boolean }> {\n return this.request('DELETE', `/api/v1/email/domains/${domainId}`);\n }\n\n // ── Usage ─────────────────────────────────────────────────────────────────\n\n /** Get send/delivery stats for a date range. */\n async getUsage(options?: { startDate?: string; endDate?: string }): Promise<UsageStats> {\n const params = new URLSearchParams();\n if (options?.startDate) params.set('start_date', options.startDate);\n if (options?.endDate) params.set('end_date', options.endDate);\n const qs = params.toString();\n return this.request('GET', `/api/v1/email/usage${qs ? `?${qs}` : ''}`);\n }\n\n // ── SMTP ──────────────────────────────────────────────────────────────────\n\n /**\n * Generate SMTP credentials — useful for services like Supabase Auth or\n * any system that only supports SMTP.\n */\n async generateSmtpCredentials(): Promise<SmtpCredentials> {\n return this.request('POST', '/api/v1/email/smtp-credentials');\n }\n}\n\n// ============================================================================\n// Module-level convenience\n// ============================================================================\n\nlet _defaultClient: HivekuEmail | null = null;\n\n/** Initialize the default module-level client. */\nexport function init(apiKey: string, config?: Omit<HivekuEmailConfig, 'apiKey'>): void {\n _defaultClient = new HivekuEmail({ apiKey, ...config });\n}\n\nfunction getDefault(): HivekuEmail {\n if (!_defaultClient) {\n _defaultClient = new HivekuEmail();\n }\n return _defaultClient;\n}\n\n/** Send an email using the module-level default client. */\nexport function sendEmail(options: SendEmailOptions): Promise<SendEmailResponse> {\n return getDefault().send(options);\n}\n\nexport default HivekuEmail;\n"]}
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@hiveku-apps/email",
3
+ "version": "1.0.0",
4
+ "description": "Official Node.js SDK for the Hiveku Transactional Email Service",
5
+ "keywords": ["email", "transactional", "hiveku", "sdk", "smtp"],
6
+ "homepage": "https://hiveku.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/locus2012/hiveku_builder.git",
10
+ "directory": "packages/email"
11
+ },
12
+ "license": "MIT",
13
+ "author": "Hiveku",
14
+ "type": "module",
15
+ "main": "./dist/index.cjs",
16
+ "module": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "import": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "require": {
25
+ "types": "./dist/index.d.cts",
26
+ "default": "./dist/index.cjs"
27
+ }
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "scripts": {
36
+ "build": "tsup",
37
+ "dev": "tsup --watch",
38
+ "prepublishOnly": "npm run build",
39
+ "typecheck": "tsc --noEmit"
40
+ },
41
+ "devDependencies": {
42
+ "tsup": "^8.0.0",
43
+ "typescript": "^5.4.0"
44
+ },
45
+ "engines": {
46
+ "node": ">=18"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }