@sendery/sdk 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - Send published templates and retrieve delivery status from JavaScript or TypeScript on the server.
6
+ - Prepare requests with an idempotency key and opt in to bounded retries.
7
+ - Inspect API failures through `SenderyError`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sendery contributors
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,97 @@
1
+ # Sendery for JavaScript and TypeScript
2
+
3
+ Send published Sendery templates from JavaScript and TypeScript.
4
+
5
+ [Documentation](https://sendery.co/en/docs/javascript) · [API reference](https://sendery.co/en/docs/send-email) · [Changelog](CHANGELOG.md)
6
+
7
+ ## Requirements
8
+
9
+ Node.js 22.12+. The package uses ES module imports and includes TypeScript types.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install @sendery/sdk
15
+ ```
16
+
17
+ ## Set up
18
+
19
+ Publish a `welcome` template with `name` and `action_url` variables, and create a [project API key](https://sendery.co/en/docs/authentication). Store it as `SENDERY_API_KEY` on your server. Use the SDK only on the server.
20
+
21
+ ```bash
22
+ export SENDERY_API_KEY="your_project_api_key"
23
+ ```
24
+
25
+ ## Send an email
26
+
27
+ The response contains the accepted email’s `id` and `status`.
28
+
29
+ ```javascript
30
+ import { Sendery } from '@sendery/sdk';
31
+
32
+ const apiKey = process.env.SENDERY_API_KEY;
33
+ if (!apiKey) throw new Error('Set SENDERY_API_KEY on your server.');
34
+
35
+ const sendery = new Sendery(apiKey);
36
+ const receipt = await sendery.send({
37
+ to: 'alex@example.com',
38
+ template: 'welcome',
39
+ data: { name: 'Alex', action_url: 'https://example.com/start' },
40
+ });
41
+
42
+ console.log(receipt.id);
43
+ ```
44
+
45
+ ## Retrieve an email
46
+
47
+ Use the returned ID to [check delivery status](https://sendery.co/en/docs/get-email).
48
+
49
+ ```javascript
50
+ const message = await sendery.get(receipt.id);
51
+ console.log(message.status);
52
+ ```
53
+
54
+ ## Retry a send
55
+
56
+ Use a key such as `welcome-123` for one email, and [keep the payload unchanged on retries](https://sendery.co/en/docs/idempotency). `retry(3)` allows up to three additional attempts for temporary failures; `send()` alone makes one attempt.
57
+
58
+ ```javascript
59
+ const email = sendery.prepare({
60
+ to: 'alex@example.com',
61
+ template: 'welcome',
62
+ data: { name: 'Alex', action_url: 'https://example.com/start' },
63
+ }, 'welcome-123');
64
+
65
+ const receipt = await email.retry(3).send();
66
+ ```
67
+
68
+ ## Handle errors
69
+
70
+ Catch the SDK exception to inspect the [status and code](https://sendery.co/en/docs/errors). Retry delays are in seconds. The example uses the prepared `email` from the [retry example above](#retry-a-send).
71
+
72
+ ```javascript
73
+ import { SenderyError } from '@sendery/sdk';
74
+
75
+ try {
76
+ const receipt = await email.retry(3).send();
77
+ console.log(receipt.id);
78
+ } catch (error) {
79
+ if (error instanceof SenderyError) {
80
+ console.error(error.status, error.code, error.errors);
81
+ // error.retryAfter is a delay in seconds, when provided.
82
+ }
83
+ throw error;
84
+ }
85
+ ```
86
+
87
+ ## Frameworks
88
+
89
+ Follow the server setup for [Next.js](https://sendery.co/en/docs/next) or [Nuxt](https://sendery.co/en/docs/nuxt).
90
+
91
+ ## More
92
+
93
+ See [idempotency and retries](https://sendery.co/en/docs/idempotency) for retry conditions, delays, and reusing a key across attempts.
94
+
95
+ ## License
96
+
97
+ [MIT](LICENSE).
@@ -0,0 +1,40 @@
1
+ export type Variables = Record<string, string | number | boolean | Record<string, string | number | boolean>[]>;
2
+ export interface SendEmailInput {
3
+ to: string;
4
+ template: string;
5
+ data: Variables;
6
+ locale?: string;
7
+ }
8
+ export interface SendReceipt {
9
+ id: string;
10
+ status: string;
11
+ error_code?: string | null;
12
+ created_at?: string;
13
+ submitted_at?: string | null;
14
+ }
15
+ export declare class SenderyError extends Error {
16
+ status: number;
17
+ code: string;
18
+ errors: Record<string, string[]>;
19
+ retryAfter?: number;
20
+ constructor(status: number, code?: string, errors?: Record<string, string[]>, retryAfter?: number);
21
+ get retryable(): boolean;
22
+ }
23
+ export declare class PendingEmail {
24
+ readonly idempotencyKey: string;
25
+ private readonly body;
26
+ private readonly client;
27
+ private retries;
28
+ constructor(client: Sendery, input: SendEmailInput, key: string);
29
+ retry(retries?: number): this;
30
+ send(): Promise<SendReceipt>;
31
+ }
32
+ export declare class Sendery {
33
+ private apiKey;
34
+ private baseUrl;
35
+ constructor(apiKey: string, baseUrl?: string);
36
+ prepare(input: SendEmailInput, idempotencyKey?: string): PendingEmail;
37
+ send(input: SendEmailInput, idempotencyKey?: string): Promise<SendReceipt>;
38
+ get(id: string): Promise<SendReceipt>;
39
+ request(method: string, path: string, body?: string, key?: string): Promise<SendReceipt>;
40
+ }
package/dist/index.js ADDED
@@ -0,0 +1,127 @@
1
+ export class SenderyError extends Error {
2
+ status;
3
+ code;
4
+ errors;
5
+ retryAfter;
6
+ constructor(status, code = "request_error", errors = {}, retryAfter) {
7
+ super(`Sendery API error: ${code}`);
8
+ this.name = "SenderyError";
9
+ this.status = status;
10
+ this.code = code;
11
+ this.errors = errors;
12
+ this.retryAfter = retryAfter;
13
+ }
14
+ get retryable() {
15
+ return ([0, 500, 502, 503, 504].includes(this.status) ||
16
+ (this.status === 429 && this.code === "rate_limited"));
17
+ }
18
+ }
19
+ export class PendingEmail {
20
+ idempotencyKey;
21
+ body;
22
+ client;
23
+ retries = 0;
24
+ constructor(client, input, key) {
25
+ if (!/^[a-zA-Z0-9_.:-]{1,128}$/.test(key))
26
+ throw new Error("Invalid idempotency key.");
27
+ this.client = client;
28
+ this.idempotencyKey = key;
29
+ this.body = JSON.stringify({
30
+ to: input.to,
31
+ template: input.template,
32
+ data: input.data,
33
+ ...(input.locale ? { locale: input.locale } : {}),
34
+ });
35
+ }
36
+ retry(retries = 3) {
37
+ if (!Number.isInteger(retries) || retries < 0 || retries > 5)
38
+ throw new Error("Choose 0 to 5 retries.");
39
+ this.retries = retries;
40
+ return this;
41
+ }
42
+ async send() {
43
+ for (let attempt = 0;; attempt++) {
44
+ try {
45
+ return await this.client.request("POST", "/api/v1/emails", this.body, this.idempotencyKey);
46
+ }
47
+ catch (error) {
48
+ if (!(error instanceof SenderyError) ||
49
+ !error.retryable ||
50
+ attempt >= this.retries)
51
+ throw error;
52
+ const delay = error.retryAfter ??
53
+ Math.min(8, 0.25 * 2 ** attempt + Math.random() * 0.1);
54
+ if (delay > 30)
55
+ throw error;
56
+ await new Promise((resolve) => setTimeout(resolve, delay * 1000));
57
+ }
58
+ }
59
+ }
60
+ }
61
+ export class Sendery {
62
+ apiKey;
63
+ baseUrl;
64
+ constructor(apiKey, baseUrl = "https://sendery.co") {
65
+ if (typeof window !== "undefined")
66
+ throw new Error("Sendery API keys must remain on the server.");
67
+ const url = new URL(baseUrl);
68
+ if (!apiKey ||
69
+ url.username ||
70
+ url.password ||
71
+ url.search ||
72
+ url.hash ||
73
+ (url.protocol !== "https:" &&
74
+ !(url.protocol === "http:" &&
75
+ ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))))
76
+ throw new Error("Provide an API key and an HTTPS URL (HTTP allowed only on loopback).");
77
+ this.apiKey = apiKey;
78
+ this.baseUrl = baseUrl.replace(/\/$/, "");
79
+ }
80
+ prepare(input, idempotencyKey = crypto.randomUUID()) {
81
+ return new PendingEmail(this, input, idempotencyKey);
82
+ }
83
+ send(input, idempotencyKey) {
84
+ return this.prepare(input, idempotencyKey).send();
85
+ }
86
+ get(id) {
87
+ return this.request("GET", `/api/v1/emails/${encodeURIComponent(id)}`);
88
+ }
89
+ async request(method, path, body, key) {
90
+ let response;
91
+ try {
92
+ response = await fetch(`${this.baseUrl}${path}`, {
93
+ method,
94
+ redirect: "error",
95
+ signal: AbortSignal.timeout(10_000),
96
+ headers: {
97
+ Authorization: `Bearer ${this.apiKey}`,
98
+ Accept: "application/json",
99
+ "Content-Type": "application/json",
100
+ ...(key ? { "Idempotency-Key": key } : {}),
101
+ },
102
+ body,
103
+ });
104
+ }
105
+ catch {
106
+ throw new SenderyError(0, "connection_error");
107
+ }
108
+ const parsed = await response.json().catch(() => ({}));
109
+ const data = parsed && typeof parsed === "object" && !Array.isArray(parsed)
110
+ ? parsed
111
+ : {};
112
+ if (!response.ok) {
113
+ const header = response.headers.get("Retry-After");
114
+ const seconds = header === null
115
+ ? undefined
116
+ : /^\d+(\.\d+)?$/.test(header)
117
+ ? Number(header)
118
+ : (Date.parse(header) - Date.now()) / 1000;
119
+ throw new SenderyError(response.status, data.code, data.errors, seconds !== undefined && Number.isFinite(seconds)
120
+ ? Math.max(0, seconds)
121
+ : undefined);
122
+ }
123
+ if (typeof data.id !== "string" || typeof data.status !== "string")
124
+ throw new SenderyError(0, "invalid_response");
125
+ return data;
126
+ }
127
+ }
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@sendery/sdk",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Server-side Sendery template email SDK for JavaScript and TypeScript",
6
+ "license": "MIT",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE",
19
+ "CHANGELOG.md"
20
+ ],
21
+ "engines": {
22
+ "node": ">=22.12.0"
23
+ },
24
+ "scripts": {
25
+ "build": "tsc -p tsconfig.json",
26
+ "prepack": "npm run build",
27
+ "test": "npm run build && node --test tests/*.mjs"
28
+ },
29
+ "devDependencies": {
30
+ "typescript": "^5.9.0"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/sendery-co/sendery-javascript.git"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ }
39
+ }