zupost 0.1.0 → 0.2.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/dist/index.mjs CHANGED
@@ -1,6 +1,4 @@
1
1
  var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
2
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
3
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
4
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -20,33 +18,10 @@ var __spreadValues = (a, b) => {
20
18
  }
21
19
  return a;
22
20
  };
23
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
- var __objRest = (source, exclude) => {
25
- var target = {};
26
- for (var prop in source)
27
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
28
- target[prop] = source[prop];
29
- if (source != null && __getOwnPropSymbols)
30
- for (var prop of __getOwnPropSymbols(source)) {
31
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
32
- target[prop] = source[prop];
33
- }
34
- return target;
35
- };
36
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
37
21
  var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
38
22
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
39
23
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
40
24
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
41
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
42
- var __privateWrapper = (obj, member, setter, getter) => ({
43
- set _(value) {
44
- __privateSet(obj, member, value, setter);
45
- },
46
- get _() {
47
- return __privateGet(obj, member, getter);
48
- }
49
- });
50
25
  var __async = (__this, __arguments, generator) => {
51
26
  return new Promise((resolve, reject) => {
52
27
  var fulfilled = (value) => {
@@ -69,895 +44,168 @@ var __async = (__this, __arguments, generator) => {
69
44
  };
70
45
 
71
46
  // package.json
72
- var version = "0.1.0";
73
-
74
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/errors/HTTPError.js
75
- var HTTPError = class extends Error {
76
- constructor(response, request, options) {
77
- var _a;
78
- const code = response.status || response.status === 0 ? response.status : "";
79
- const title = (_a = response.statusText) != null ? _a : "";
80
- const status = `${code} ${title}`.trim();
81
- const reason = status ? `status code ${status}` : "an unknown error";
82
- super(`Request failed with ${reason}: ${request.method} ${request.url}`);
83
- __publicField(this, "response");
84
- __publicField(this, "request");
85
- __publicField(this, "options");
86
- this.name = "HTTPError";
87
- this.response = response;
88
- this.request = request;
89
- this.options = options;
90
- }
91
- };
92
-
93
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/errors/NonError.js
94
- var NonError = class extends Error {
95
- constructor(value) {
96
- let message = "Non-error value was thrown";
97
- try {
98
- if (typeof value === "string") {
99
- message = value;
100
- } else if (value && typeof value === "object" && "message" in value && typeof value.message === "string") {
101
- message = value.message;
102
- }
103
- } catch (e) {
104
- }
105
- super(message);
106
- __publicField(this, "name", "NonError");
107
- __publicField(this, "value");
108
- this.value = value;
109
- }
110
- };
111
-
112
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/errors/ForceRetryError.js
113
- var ForceRetryError = class extends Error {
114
- constructor(options) {
115
- const cause = (options == null ? void 0 : options.cause) ? options.cause instanceof Error ? options.cause : new NonError(options.cause) : void 0;
116
- super((options == null ? void 0 : options.code) ? `Forced retry: ${options.code}` : "Forced retry", cause ? { cause } : void 0);
117
- __publicField(this, "name", "ForceRetryError");
118
- __publicField(this, "customDelay");
119
- __publicField(this, "code");
120
- __publicField(this, "customRequest");
121
- this.customDelay = options == null ? void 0 : options.delay;
122
- this.code = options == null ? void 0 : options.code;
123
- this.customRequest = options == null ? void 0 : options.request;
124
- }
125
- };
126
-
127
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/core/constants.js
128
- var supportsRequestStreams = (() => {
129
- let duplexAccessed = false;
130
- let hasContentType = false;
131
- const supportsReadableStream = typeof globalThis.ReadableStream === "function";
132
- const supportsRequest = typeof globalThis.Request === "function";
133
- if (supportsReadableStream && supportsRequest) {
134
- try {
135
- hasContentType = new globalThis.Request("https://empty.invalid", {
136
- body: new globalThis.ReadableStream(),
137
- method: "POST",
138
- // @ts-expect-error - Types are outdated.
139
- get duplex() {
140
- duplexAccessed = true;
141
- return "half";
142
- }
143
- }).headers.has("Content-Type");
144
- } catch (error) {
145
- if (error instanceof Error && error.message === "unsupported BodyInit type") {
146
- return false;
147
- }
148
- throw error;
149
- }
150
- }
151
- return duplexAccessed && !hasContentType;
152
- })();
153
- var supportsAbortController = typeof globalThis.AbortController === "function";
154
- var supportsAbortSignal = typeof globalThis.AbortSignal === "function" && typeof globalThis.AbortSignal.any === "function";
155
- var supportsResponseStreams = typeof globalThis.ReadableStream === "function";
156
- var supportsFormData = typeof globalThis.FormData === "function";
157
- var requestMethods = ["get", "post", "put", "patch", "head", "delete"];
158
- var validate = () => void 0;
159
- validate();
160
- var responseTypes = {
161
- json: "application/json",
162
- text: "text/*",
163
- formData: "multipart/form-data",
164
- arrayBuffer: "*/*",
165
- blob: "*/*",
166
- // Supported in modern Fetch implementations (for example, browsers and recent Node.js/undici).
167
- // We still feature-check at runtime before exposing the shortcut.
168
- bytes: "*/*"
169
- };
170
- var maxSafeTimeout = 2147483647;
171
- var usualFormBoundarySize = new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length;
172
- var stop = /* @__PURE__ */ Symbol("stop");
173
- var RetryMarker = class {
174
- constructor(options) {
175
- __publicField(this, "options");
176
- this.options = options;
177
- }
178
- };
179
- var retry = (options) => new RetryMarker(options);
180
- var kyOptionKeys = {
181
- json: true,
182
- parseJson: true,
183
- stringifyJson: true,
184
- searchParams: true,
185
- prefixUrl: true,
186
- retry: true,
187
- timeout: true,
188
- hooks: true,
189
- throwHttpErrors: true,
190
- onDownloadProgress: true,
191
- onUploadProgress: true,
192
- fetch: true,
193
- context: true
194
- };
195
- var vendorSpecificOptions = {
196
- next: true
197
- // Next.js cache revalidation (revalidate, tags)
198
- };
199
- var requestOptionsRegistry = {
200
- method: true,
201
- headers: true,
202
- body: true,
203
- mode: true,
204
- credentials: true,
205
- cache: true,
206
- redirect: true,
207
- referrer: true,
208
- referrerPolicy: true,
209
- integrity: true,
210
- keepalive: true,
211
- signal: true,
212
- window: true,
213
- duplex: true
214
- };
47
+ var version = "0.2.0";
215
48
 
216
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/body.js
217
- var getBodySize = (body) => {
218
- if (!body) {
219
- return 0;
220
- }
221
- if (body instanceof FormData) {
222
- let size = 0;
223
- for (const [key, value] of body) {
224
- size += usualFormBoundarySize;
225
- size += new TextEncoder().encode(`Content-Disposition: form-data; name="${key}"`).length;
226
- size += typeof value === "string" ? new TextEncoder().encode(value).length : value.size;
227
- }
228
- return size;
229
- }
230
- if (body instanceof Blob) {
231
- return body.size;
232
- }
233
- if (body instanceof ArrayBuffer) {
234
- return body.byteLength;
235
- }
236
- if (typeof body === "string") {
237
- return new TextEncoder().encode(body).length;
238
- }
239
- if (body instanceof URLSearchParams) {
240
- return new TextEncoder().encode(body.toString()).length;
241
- }
242
- if ("byteLength" in body) {
243
- return body.byteLength;
244
- }
245
- if (typeof body === "object" && body !== null) {
246
- try {
247
- const jsonString = JSON.stringify(body);
248
- return new TextEncoder().encode(jsonString).length;
249
- } catch (e) {
250
- return 0;
251
- }
252
- }
253
- return 0;
254
- };
255
- var withProgress = (stream, totalBytes, onProgress) => {
256
- let previousChunk;
257
- let transferredBytes = 0;
258
- return stream.pipeThrough(new TransformStream({
259
- transform(currentChunk, controller) {
260
- controller.enqueue(currentChunk);
261
- if (previousChunk) {
262
- transferredBytes += previousChunk.byteLength;
263
- let percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
264
- if (percent >= 1) {
265
- percent = 1 - Number.EPSILON;
266
- }
267
- onProgress == null ? void 0 : onProgress({ percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);
268
- }
269
- previousChunk = currentChunk;
270
- },
271
- flush() {
272
- if (previousChunk) {
273
- transferredBytes += previousChunk.byteLength;
274
- onProgress == null ? void 0 : onProgress({ percent: 1, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);
275
- }
276
- }
277
- }));
278
- };
279
- var streamResponse = (response, onDownloadProgress) => {
280
- if (!response.body) {
281
- return response;
282
- }
283
- if (response.status === 204) {
284
- return new Response(null, {
285
- status: response.status,
286
- statusText: response.statusText,
287
- headers: response.headers
288
- });
289
- }
290
- const totalBytes = Math.max(0, Number(response.headers.get("content-length")) || 0);
291
- return new Response(withProgress(response.body, totalBytes, onDownloadProgress), {
292
- status: response.status,
293
- statusText: response.statusText,
294
- headers: response.headers
295
- });
296
- };
297
- var streamRequest = (request, onUploadProgress, originalBody) => {
298
- if (!request.body) {
299
- return request;
300
- }
301
- const totalBytes = getBodySize(originalBody != null ? originalBody : request.body);
302
- return new Request(request, {
303
- // @ts-expect-error - Types are outdated.
304
- duplex: "half",
305
- body: withProgress(request.body, totalBytes, onUploadProgress)
306
- });
307
- };
308
-
309
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/is.js
310
- var isObject = (value) => value !== null && typeof value === "object";
311
-
312
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/merge.js
313
- var validateAndMerge = (...sources) => {
314
- for (const source of sources) {
315
- if ((!isObject(source) || Array.isArray(source)) && source !== void 0) {
316
- throw new TypeError("The `options` argument must be an object");
317
- }
318
- }
319
- return deepMerge({}, ...sources);
320
- };
321
- var mergeHeaders = (source1 = {}, source2 = {}) => {
322
- const result = new globalThis.Headers(source1);
323
- const isHeadersInstance = source2 instanceof globalThis.Headers;
324
- const source = new globalThis.Headers(source2);
325
- for (const [key, value] of source.entries()) {
326
- if (isHeadersInstance && value === "undefined" || value === void 0) {
327
- result.delete(key);
328
- } else {
329
- result.set(key, value);
330
- }
331
- }
332
- return result;
333
- };
334
- function newHookValue(original, incoming, property) {
335
- var _a, _b;
336
- return Object.hasOwn(incoming, property) && incoming[property] === void 0 ? [] : deepMerge((_a = original[property]) != null ? _a : [], (_b = incoming[property]) != null ? _b : []);
337
- }
338
- var mergeHooks = (original = {}, incoming = {}) => ({
339
- beforeRequest: newHookValue(original, incoming, "beforeRequest"),
340
- beforeRetry: newHookValue(original, incoming, "beforeRetry"),
341
- afterResponse: newHookValue(original, incoming, "afterResponse"),
342
- beforeError: newHookValue(original, incoming, "beforeError")
343
- });
344
- var appendSearchParameters = (target, source) => {
345
- const result = new URLSearchParams();
346
- for (const input of [target, source]) {
347
- if (input === void 0) {
348
- continue;
349
- }
350
- if (input instanceof URLSearchParams) {
351
- for (const [key, value] of input.entries()) {
352
- result.append(key, value);
353
- }
354
- } else if (Array.isArray(input)) {
355
- for (const pair of input) {
356
- if (!Array.isArray(pair) || pair.length !== 2) {
357
- throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");
358
- }
359
- result.append(String(pair[0]), String(pair[1]));
360
- }
361
- } else if (isObject(input)) {
362
- for (const [key, value] of Object.entries(input)) {
363
- if (value !== void 0) {
364
- result.append(key, String(value));
365
- }
366
- }
367
- } else {
368
- const parameters = new URLSearchParams(input);
369
- for (const [key, value] of parameters.entries()) {
370
- result.append(key, value);
371
- }
372
- }
373
- }
374
- return result;
375
- };
376
- var deepMerge = (...sources) => {
377
- let returnValue = {};
378
- let headers = {};
379
- let hooks = {};
380
- let searchParameters;
381
- const signals = [];
382
- for (const source of sources) {
383
- if (Array.isArray(source)) {
384
- if (!Array.isArray(returnValue)) {
385
- returnValue = [];
386
- }
387
- returnValue = [...returnValue, ...source];
388
- } else if (isObject(source)) {
389
- for (let [key, value] of Object.entries(source)) {
390
- if (key === "signal" && value instanceof globalThis.AbortSignal) {
391
- signals.push(value);
392
- continue;
393
- }
394
- if (key === "context") {
395
- if (value !== void 0 && value !== null && (!isObject(value) || Array.isArray(value))) {
396
- throw new TypeError("The `context` option must be an object");
397
- }
398
- returnValue = __spreadProps(__spreadValues({}, returnValue), {
399
- context: value === void 0 || value === null ? {} : __spreadValues(__spreadValues({}, returnValue.context), value)
400
- });
401
- continue;
402
- }
403
- if (key === "searchParams") {
404
- if (value === void 0 || value === null) {
405
- searchParameters = void 0;
406
- } else {
407
- searchParameters = searchParameters === void 0 ? value : appendSearchParameters(searchParameters, value);
408
- }
409
- continue;
410
- }
411
- if (isObject(value) && key in returnValue) {
412
- value = deepMerge(returnValue[key], value);
49
+ // src/errors.ts
50
+ var ZupostError = class _ZupostError extends Error {
51
+ constructor(args) {
52
+ super(args.message);
53
+ this.name = "ZupostError";
54
+ this.status = args.status;
55
+ this.statusText = args.statusText;
56
+ this.body = args.body;
57
+ this.requestId = args.requestId;
58
+ this.code = args.code;
59
+ }
60
+ /** @internal */
61
+ static fromResponse(response) {
62
+ return __async(this, null, function* () {
63
+ var _a, _b, _c;
64
+ const body = yield response.text().catch(() => "");
65
+ let parsedMessage;
66
+ let code;
67
+ if (body) {
68
+ try {
69
+ const parsed = JSON.parse(body);
70
+ parsedMessage = (_a = parsed.message) != null ? _a : parsed.error;
71
+ code = parsed.code;
72
+ } catch (e) {
413
73
  }
414
- returnValue = __spreadProps(__spreadValues({}, returnValue), { [key]: value });
415
74
  }
416
- if (isObject(source.hooks)) {
417
- hooks = mergeHooks(hooks, source.hooks);
418
- returnValue.hooks = hooks;
419
- }
420
- if (isObject(source.headers)) {
421
- headers = mergeHeaders(headers, source.headers);
422
- returnValue.headers = headers;
423
- }
424
- }
425
- }
426
- if (searchParameters !== void 0) {
427
- returnValue.searchParams = searchParameters;
428
- }
429
- if (signals.length > 0) {
430
- if (signals.length === 1) {
431
- returnValue.signal = signals[0];
432
- } else if (supportsAbortSignal) {
433
- returnValue.signal = AbortSignal.any(signals);
434
- } else {
435
- returnValue.signal = signals.at(-1);
436
- }
437
- }
438
- return returnValue;
439
- };
440
-
441
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/normalize.js
442
- var normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
443
- var retryMethods = ["get", "put", "head", "delete", "options", "trace"];
444
- var retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
445
- var retryAfterStatusCodes = [413, 429, 503];
446
- var defaultRetryOptions = {
447
- limit: 2,
448
- methods: retryMethods,
449
- statusCodes: retryStatusCodes,
450
- afterStatusCodes: retryAfterStatusCodes,
451
- maxRetryAfter: Number.POSITIVE_INFINITY,
452
- backoffLimit: Number.POSITIVE_INFINITY,
453
- delay: (attemptCount) => 0.3 * __pow(2, attemptCount - 1) * 1e3,
454
- jitter: void 0,
455
- retryOnTimeout: false
456
- };
457
- var normalizeRetryOptions = (retry2 = {}) => {
458
- if (typeof retry2 === "number") {
459
- return __spreadProps(__spreadValues({}, defaultRetryOptions), {
460
- limit: retry2
75
+ const detail = parsedMessage || response.statusText || body || "unknown error";
76
+ return new _ZupostError({
77
+ message: `Zupost API error ${response.status}: ${detail}`,
78
+ status: response.status,
79
+ statusText: response.statusText,
80
+ body,
81
+ requestId: (_c = (_b = response.headers.get("x-request-id")) != null ? _b : response.headers.get("x-zupost-request-id")) != null ? _c : void 0,
82
+ code
83
+ });
461
84
  });
462
85
  }
463
- if (retry2.methods && !Array.isArray(retry2.methods)) {
464
- throw new Error("retry.methods must be an array");
465
- }
466
- retry2.methods && (retry2.methods = retry2.methods.map((method) => method.toLowerCase()));
467
- if (retry2.statusCodes && !Array.isArray(retry2.statusCodes)) {
468
- throw new Error("retry.statusCodes must be an array");
469
- }
470
- const normalizedRetry = Object.fromEntries(Object.entries(retry2).filter(([, value]) => value !== void 0));
471
- return __spreadValues(__spreadValues({}, defaultRetryOptions), normalizedRetry);
472
- };
473
-
474
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/errors/TimeoutError.js
475
- var TimeoutError = class extends Error {
476
- constructor(request) {
477
- super(`Request timed out: ${request.method} ${request.url}`);
478
- __publicField(this, "request");
479
- this.name = "TimeoutError";
480
- this.request = request;
481
- }
482
86
  };
483
87
 
484
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/timeout.js
485
- function timeout(request, init, abortController, options) {
486
- return __async(this, null, function* () {
487
- return new Promise((resolve, reject) => {
488
- const timeoutId = setTimeout(() => {
489
- if (abortController) {
490
- abortController.abort();
491
- }
492
- reject(new TimeoutError(request));
493
- }, options.timeout);
494
- void options.fetch(request, init).then(resolve).catch(reject).then(() => {
495
- clearTimeout(timeoutId);
496
- });
497
- });
498
- });
88
+ // src/http-client.ts
89
+ var RETRIABLE_STATUSES = /* @__PURE__ */ new Set([408, 413, 429, 500, 502, 503, 504]);
90
+ var MAX_RETRIES = 3;
91
+ var BACKOFF_BASE_MS = 300;
92
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
93
+ function parseRetryAfter(value) {
94
+ if (!value) return null;
95
+ const seconds = Number(value);
96
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
97
+ const date = Date.parse(value);
98
+ if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
99
+ return null;
499
100
  }
500
-
501
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/delay.js
502
- function delay(_0, _1) {
503
- return __async(this, arguments, function* (ms, { signal }) {
504
- return new Promise((resolve, reject) => {
505
- if (signal) {
506
- signal.throwIfAborted();
507
- signal.addEventListener("abort", abortHandler, { once: true });
508
- }
509
- function abortHandler() {
510
- clearTimeout(timeoutId);
511
- reject(signal.reason);
512
- }
513
- const timeoutId = setTimeout(() => {
514
- signal == null ? void 0 : signal.removeEventListener("abort", abortHandler);
515
- resolve();
516
- }, ms);
101
+ var _defaultHeaders, _baseUrl;
102
+ var HttpClient = class {
103
+ constructor(apiKey, baseUrl, userAgent) {
104
+ __privateAdd(this, _defaultHeaders);
105
+ __privateAdd(this, _baseUrl);
106
+ __privateSet(this, _baseUrl, baseUrl.replace(/\/$/, ""));
107
+ __privateSet(this, _defaultHeaders, {
108
+ Authorization: `Bearer ${apiKey}`,
109
+ "Content-Type": "application/json",
110
+ "User-Agent": userAgent
517
111
  });
518
- });
519
- }
520
-
521
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/options.js
522
- var findUnknownOptions = (request, options) => {
523
- const unknownOptions = {};
524
- for (const key in options) {
525
- if (!Object.hasOwn(options, key)) {
526
- continue;
527
- }
528
- if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && (!(key in request) || key in vendorSpecificOptions)) {
529
- unknownOptions[key] = options[key];
530
- }
531
- }
532
- return unknownOptions;
533
- };
534
- var hasSearchParameters = (search) => {
535
- if (search === void 0) {
536
- return false;
537
- }
538
- if (Array.isArray(search)) {
539
- return search.length > 0;
540
- }
541
- if (search instanceof URLSearchParams) {
542
- return search.size > 0;
543
- }
544
- if (typeof search === "object") {
545
- return Object.keys(search).length > 0;
546
112
  }
547
- if (typeof search === "string") {
548
- return search.trim().length > 0;
549
- }
550
- return Boolean(search);
551
- };
552
-
553
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/type-guards.js
554
- function isHTTPError(error) {
555
- return error instanceof HTTPError || (error == null ? void 0 : error.name) === HTTPError.name;
556
- }
557
- function isTimeoutError(error) {
558
- return error instanceof TimeoutError || (error == null ? void 0 : error.name) === TimeoutError.name;
559
- }
560
-
561
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/core/Ky.js
562
- var _Ky_static, normalizeSearchParams_fn, _abortController, _retryCount, _input, _options, _originalRequest, _userProvidedAbortSignal, _cachedNormalizedOptions, _Ky_instances, calculateDelay_fn, calculateRetryDelay_fn, decorateResponse_fn, cancelBody_fn, cancelResponseBody_fn, retry_fn, fetch_fn, getNormalizedOptions_fn, assignRequest_fn, wrapRequestWithUploadProgress_fn;
563
- var _Ky = class _Ky {
564
- // eslint-disable-next-line complexity
565
- constructor(input, options = {}) {
566
- __privateAdd(this, _Ky_instances);
567
- __publicField(this, "request");
568
- __privateAdd(this, _abortController);
569
- __privateAdd(this, _retryCount, 0);
570
- // eslint-disable-next-line @typescript-eslint/prefer-readonly -- False positive: #input is reassigned on line 202
571
- __privateAdd(this, _input);
572
- __privateAdd(this, _options);
573
- __privateAdd(this, _originalRequest);
574
- __privateAdd(this, _userProvidedAbortSignal);
575
- __privateAdd(this, _cachedNormalizedOptions);
576
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
577
- __privateSet(this, _input, input);
578
- __privateSet(this, _options, __spreadProps(__spreadValues({}, options), {
579
- headers: mergeHeaders(__privateGet(this, _input).headers, options.headers),
580
- hooks: mergeHooks({
581
- beforeRequest: [],
582
- beforeRetry: [],
583
- beforeError: [],
584
- afterResponse: []
585
- }, options.hooks),
586
- method: normalizeRequestMethod((_b = (_a = options.method) != null ? _a : __privateGet(this, _input).method) != null ? _b : "GET"),
587
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
588
- prefixUrl: String(options.prefixUrl || ""),
589
- retry: normalizeRetryOptions(options.retry),
590
- throwHttpErrors: (_c = options.throwHttpErrors) != null ? _c : true,
591
- timeout: (_d = options.timeout) != null ? _d : 1e4,
592
- fetch: (_e = options.fetch) != null ? _e : globalThis.fetch.bind(globalThis),
593
- context: (_f = options.context) != null ? _f : {}
594
- }));
595
- if (typeof __privateGet(this, _input) !== "string" && !(__privateGet(this, _input) instanceof URL || __privateGet(this, _input) instanceof globalThis.Request)) {
596
- throw new TypeError("`input` must be a string, URL, or Request");
597
- }
598
- if (__privateGet(this, _options).prefixUrl && typeof __privateGet(this, _input) === "string") {
599
- if (__privateGet(this, _input).startsWith("/")) {
600
- throw new Error("`input` must not begin with a slash when using `prefixUrl`");
601
- }
602
- if (!__privateGet(this, _options).prefixUrl.endsWith("/")) {
603
- __privateGet(this, _options).prefixUrl += "/";
604
- }
605
- __privateSet(this, _input, __privateGet(this, _options).prefixUrl + __privateGet(this, _input));
606
- }
607
- if (supportsAbortController && supportsAbortSignal) {
608
- __privateSet(this, _userProvidedAbortSignal, (_g = __privateGet(this, _options).signal) != null ? _g : __privateGet(this, _input).signal);
609
- __privateSet(this, _abortController, new globalThis.AbortController());
610
- __privateGet(this, _options).signal = __privateGet(this, _userProvidedAbortSignal) ? AbortSignal.any([__privateGet(this, _userProvidedAbortSignal), __privateGet(this, _abortController).signal]) : __privateGet(this, _abortController).signal;
611
- }
612
- if (supportsRequestStreams) {
613
- __privateGet(this, _options).duplex = "half";
614
- }
615
- if (__privateGet(this, _options).json !== void 0) {
616
- __privateGet(this, _options).body = (_j = (_i = (_h = __privateGet(this, _options)).stringifyJson) == null ? void 0 : _i.call(_h, __privateGet(this, _options).json)) != null ? _j : JSON.stringify(__privateGet(this, _options).json);
617
- __privateGet(this, _options).headers.set("content-type", (_k = __privateGet(this, _options).headers.get("content-type")) != null ? _k : "application/json");
618
- }
619
- const userProvidedContentType = options.headers && new globalThis.Headers(options.headers).has("content-type");
620
- if (__privateGet(this, _input) instanceof globalThis.Request && (supportsFormData && __privateGet(this, _options).body instanceof globalThis.FormData || __privateGet(this, _options).body instanceof URLSearchParams) && !userProvidedContentType) {
621
- __privateGet(this, _options).headers.delete("content-type");
622
- }
623
- this.request = new globalThis.Request(__privateGet(this, _input), __privateGet(this, _options));
624
- if (hasSearchParameters(__privateGet(this, _options).searchParams)) {
625
- const textSearchParams = typeof __privateGet(this, _options).searchParams === "string" ? __privateGet(this, _options).searchParams.replace(/^\?/, "") : new URLSearchParams(__privateMethod(_l = _Ky, _Ky_static, normalizeSearchParams_fn).call(_l, __privateGet(this, _options).searchParams)).toString();
626
- const searchParams = "?" + textSearchParams;
627
- const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
628
- this.request = new globalThis.Request(url, __privateGet(this, _options));
629
- }
630
- if (__privateGet(this, _options).onUploadProgress) {
631
- if (typeof __privateGet(this, _options).onUploadProgress !== "function") {
632
- throw new TypeError("The `onUploadProgress` option must be a function");
633
- }
634
- if (!supportsRequestStreams) {
635
- throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");
113
+ request(path, method, body) {
114
+ return __async(this, null, function* () {
115
+ const url = `${__privateGet(this, _baseUrl)}/${path.replace(/^\//, "")}`;
116
+ const headers = new Headers(__privateGet(this, _defaultHeaders));
117
+ if (method !== "GET") {
118
+ headers.set("Idempotency-Key", crypto.randomUUID());
636
119
  }
637
- this.request = __privateMethod(this, _Ky_instances, wrapRequestWithUploadProgress_fn).call(this, this.request, (_m = __privateGet(this, _options).body) != null ? _m : void 0);
638
- }
639
- }
640
- static create(input, options) {
641
- var _a, _b, _c;
642
- const ky2 = new _Ky(input, options);
643
- const function_ = () => __async(null, null, function* () {
644
- var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l;
645
- if (typeof __privateGet(ky2, _options).timeout === "number" && __privateGet(ky2, _options).timeout > maxSafeTimeout) {
646
- throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
120
+ const init = { method, headers };
121
+ if (body !== void 0) {
122
+ init.body = JSON.stringify(body);
647
123
  }
648
- yield Promise.resolve();
649
- let response = yield __privateMethod(_a2 = ky2, _Ky_instances, fetch_fn).call(_a2);
650
- for (const hook of __privateGet(ky2, _options).hooks.afterResponse) {
651
- const clonedResponse = __privateMethod(_b2 = ky2, _Ky_instances, decorateResponse_fn).call(_b2, response.clone());
652
- let modifiedResponse;
124
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
125
+ let response;
653
126
  try {
654
- modifiedResponse = yield hook(ky2.request, __privateMethod(_c2 = ky2, _Ky_instances, getNormalizedOptions_fn).call(_c2), clonedResponse, { retryCount: __privateGet(ky2, _retryCount) });
655
- } catch (error) {
656
- __privateMethod(_d = ky2, _Ky_instances, cancelResponseBody_fn).call(_d, clonedResponse);
657
- __privateMethod(_e = ky2, _Ky_instances, cancelResponseBody_fn).call(_e, response);
658
- throw error;
659
- }
660
- if (modifiedResponse instanceof RetryMarker) {
661
- __privateMethod(_f = ky2, _Ky_instances, cancelResponseBody_fn).call(_f, clonedResponse);
662
- __privateMethod(_g = ky2, _Ky_instances, cancelResponseBody_fn).call(_g, response);
663
- throw new ForceRetryError(modifiedResponse.options);
664
- }
665
- const nextResponse = modifiedResponse instanceof globalThis.Response ? modifiedResponse : response;
666
- if (clonedResponse !== nextResponse) {
667
- __privateMethod(_h = ky2, _Ky_instances, cancelResponseBody_fn).call(_h, clonedResponse);
668
- }
669
- if (response !== nextResponse) {
670
- __privateMethod(_i = ky2, _Ky_instances, cancelResponseBody_fn).call(_i, response);
671
- }
672
- response = nextResponse;
673
- }
674
- __privateMethod(_j = ky2, _Ky_instances, decorateResponse_fn).call(_j, response);
675
- if (!response.ok && (typeof __privateGet(ky2, _options).throwHttpErrors === "function" ? __privateGet(ky2, _options).throwHttpErrors(response.status) : __privateGet(ky2, _options).throwHttpErrors)) {
676
- let error = new HTTPError(response, ky2.request, __privateMethod(_k = ky2, _Ky_instances, getNormalizedOptions_fn).call(_k));
677
- for (const hook of __privateGet(ky2, _options).hooks.beforeError) {
678
- error = yield hook(error, { retryCount: __privateGet(ky2, _retryCount) });
127
+ response = yield fetch(url, init);
128
+ } catch (err) {
129
+ if (attempt === MAX_RETRIES) throw err;
130
+ yield sleep(__pow(2, attempt) * BACKOFF_BASE_MS);
131
+ continue;
679
132
  }
680
- throw error;
681
- }
682
- if (__privateGet(ky2, _options).onDownloadProgress) {
683
- if (typeof __privateGet(ky2, _options).onDownloadProgress !== "function") {
684
- throw new TypeError("The `onDownloadProgress` option must be a function");
133
+ if (response.ok) {
134
+ return yield response.json();
685
135
  }
686
- if (!supportsResponseStreams) {
687
- throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
136
+ if (attempt < MAX_RETRIES && RETRIABLE_STATUSES.has(response.status)) {
137
+ const retryAfter = parseRetryAfter(response.headers.get("Retry-After"));
138
+ yield sleep(retryAfter != null ? retryAfter : __pow(2, attempt) * BACKOFF_BASE_MS);
139
+ continue;
688
140
  }
689
- const progressResponse = response.clone();
690
- __privateMethod(_l = ky2, _Ky_instances, cancelResponseBody_fn).call(_l, response);
691
- return streamResponse(progressResponse, __privateGet(ky2, _options).onDownloadProgress);
141
+ throw yield ZupostError.fromResponse(response);
692
142
  }
693
- return response;
694
- });
695
- const result = __privateMethod(_a = ky2, _Ky_instances, retry_fn).call(_a, function_).finally(() => {
696
- var _a2, _b2, _c2, _d;
697
- const originalRequest = __privateGet(ky2, _originalRequest);
698
- __privateMethod(_b2 = ky2, _Ky_instances, cancelBody_fn).call(_b2, (_a2 = originalRequest == null ? void 0 : originalRequest.body) != null ? _a2 : void 0);
699
- __privateMethod(_d = ky2, _Ky_instances, cancelBody_fn).call(_d, (_c2 = ky2.request.body) != null ? _c2 : void 0);
143
+ throw new Error("Zupost API: retries exhausted");
700
144
  });
701
- for (const [type, mimeType] of Object.entries(responseTypes)) {
702
- if (type === "bytes" && typeof ((_c = (_b = globalThis.Response) == null ? void 0 : _b.prototype) == null ? void 0 : _c.bytes) !== "function") {
703
- continue;
704
- }
705
- result[type] = () => __async(null, null, function* () {
706
- ky2.request.headers.set("accept", ky2.request.headers.get("accept") || mimeType);
707
- const response = yield result;
708
- if (type === "json") {
709
- if (response.status === 204) {
710
- return "";
711
- }
712
- const text = yield response.text();
713
- if (text === "") {
714
- return "";
715
- }
716
- if (options.parseJson) {
717
- return options.parseJson(text);
718
- }
719
- return JSON.parse(text);
720
- }
721
- return response[type]();
722
- });
723
- }
724
- return result;
725
- }
726
- };
727
- _Ky_static = new WeakSet();
728
- normalizeSearchParams_fn = function(searchParams) {
729
- if (searchParams && typeof searchParams === "object" && !Array.isArray(searchParams) && !(searchParams instanceof URLSearchParams)) {
730
- return Object.fromEntries(Object.entries(searchParams).filter(([, value]) => value !== void 0));
731
145
  }
732
- return searchParams;
733
- };
734
- _abortController = new WeakMap();
735
- _retryCount = new WeakMap();
736
- _input = new WeakMap();
737
- _options = new WeakMap();
738
- _originalRequest = new WeakMap();
739
- _userProvidedAbortSignal = new WeakMap();
740
- _cachedNormalizedOptions = new WeakMap();
741
- _Ky_instances = new WeakSet();
742
- calculateDelay_fn = function() {
743
- var _a;
744
- const retryDelay = __privateGet(this, _options).retry.delay(__privateGet(this, _retryCount));
745
- let jitteredDelay = retryDelay;
746
- if (__privateGet(this, _options).retry.jitter === true) {
747
- jitteredDelay = Math.random() * retryDelay;
748
- } else if (typeof __privateGet(this, _options).retry.jitter === "function") {
749
- jitteredDelay = __privateGet(this, _options).retry.jitter(retryDelay);
750
- if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {
751
- jitteredDelay = retryDelay;
752
- }
753
- }
754
- const backoffLimit = (_a = __privateGet(this, _options).retry.backoffLimit) != null ? _a : Number.POSITIVE_INFINITY;
755
- return Math.min(backoffLimit, jitteredDelay);
756
- };
757
- calculateRetryDelay_fn = function(error) {
758
- return __async(this, null, function* () {
759
- var _a, _b, _c, _d, _e, _f;
760
- __privateWrapper(this, _retryCount)._++;
761
- if (__privateGet(this, _retryCount) > __privateGet(this, _options).retry.limit) {
762
- throw error;
763
- }
764
- const errorObject = error instanceof Error ? error : new NonError(error);
765
- if (errorObject instanceof ForceRetryError) {
766
- return (_a = errorObject.customDelay) != null ? _a : __privateMethod(this, _Ky_instances, calculateDelay_fn).call(this);
767
- }
768
- if (!__privateGet(this, _options).retry.methods.includes(this.request.method.toLowerCase())) {
769
- throw error;
770
- }
771
- if (__privateGet(this, _options).retry.shouldRetry !== void 0) {
772
- const result = yield __privateGet(this, _options).retry.shouldRetry({ error: errorObject, retryCount: __privateGet(this, _retryCount) });
773
- if (result === false) {
774
- throw error;
775
- }
776
- if (result === true) {
777
- return __privateMethod(this, _Ky_instances, calculateDelay_fn).call(this);
778
- }
779
- }
780
- if (isTimeoutError(error) && !__privateGet(this, _options).retry.retryOnTimeout) {
781
- throw error;
782
- }
783
- if (isHTTPError(error)) {
784
- if (!__privateGet(this, _options).retry.statusCodes.includes(error.response.status)) {
785
- throw error;
786
- }
787
- const retryAfter = (_e = (_d = (_c = (_b = error.response.headers.get("Retry-After")) != null ? _b : error.response.headers.get("RateLimit-Reset")) != null ? _c : error.response.headers.get("X-RateLimit-Retry-After")) != null ? _d : error.response.headers.get("X-RateLimit-Reset")) != null ? _e : error.response.headers.get("X-Rate-Limit-Reset");
788
- if (retryAfter && __privateGet(this, _options).retry.afterStatusCodes.includes(error.response.status)) {
789
- let after = Number(retryAfter) * 1e3;
790
- if (Number.isNaN(after)) {
791
- after = Date.parse(retryAfter) - Date.now();
792
- } else if (after >= Date.parse("2024-01-01")) {
793
- after -= Date.now();
794
- }
795
- const max = (_f = __privateGet(this, _options).retry.maxRetryAfter) != null ? _f : after;
796
- return after < max ? after : max;
797
- }
798
- if (error.response.status === 413) {
799
- throw error;
800
- }
801
- }
802
- return __privateMethod(this, _Ky_instances, calculateDelay_fn).call(this);
803
- });
804
- };
805
- decorateResponse_fn = function(response) {
806
- if (__privateGet(this, _options).parseJson) {
807
- response.json = () => __async(this, null, function* () {
808
- return __privateGet(this, _options).parseJson(yield response.text());
146
+ get(path) {
147
+ return __async(this, null, function* () {
148
+ return this.request(path, "GET");
809
149
  });
810
150
  }
811
- return response;
812
- };
813
- cancelBody_fn = function(body) {
814
- if (!body) {
815
- return;
151
+ post(path, body) {
152
+ return __async(this, null, function* () {
153
+ return this.request(path, "POST", body);
154
+ });
816
155
  }
817
- void body.cancel().catch(() => void 0);
818
- };
819
- cancelResponseBody_fn = function(response) {
820
- var _a;
821
- __privateMethod(this, _Ky_instances, cancelBody_fn).call(this, (_a = response.body) != null ? _a : void 0);
822
156
  };
823
- retry_fn = function(function_) {
157
+ _defaultHeaders = new WeakMap();
158
+ _baseUrl = new WeakMap();
159
+
160
+ // src/email/emails.ts
161
+ function loadReactRender() {
824
162
  return __async(this, null, function* () {
825
163
  try {
826
- return yield function_();
827
- } catch (error) {
828
- const ms = Math.min(yield __privateMethod(this, _Ky_instances, calculateRetryDelay_fn).call(this, error), maxSafeTimeout);
829
- if (__privateGet(this, _retryCount) < 1) {
830
- throw error;
831
- }
832
- yield delay(ms, __privateGet(this, _userProvidedAbortSignal) ? { signal: __privateGet(this, _userProvidedAbortSignal) } : {});
833
- if (error instanceof ForceRetryError && error.customRequest) {
834
- const managedRequest = __privateGet(this, _options).signal ? new globalThis.Request(error.customRequest, { signal: __privateGet(this, _options).signal }) : new globalThis.Request(error.customRequest);
835
- __privateMethod(this, _Ky_instances, assignRequest_fn).call(this, managedRequest);
836
- }
837
- for (const hook of __privateGet(this, _options).hooks.beforeRetry) {
838
- const hookResult = yield hook({
839
- request: this.request,
840
- options: __privateMethod(this, _Ky_instances, getNormalizedOptions_fn).call(this),
841
- error,
842
- retryCount: __privateGet(this, _retryCount)
843
- });
844
- if (hookResult instanceof globalThis.Request) {
845
- __privateMethod(this, _Ky_instances, assignRequest_fn).call(this, hookResult);
846
- break;
847
- }
848
- if (hookResult instanceof globalThis.Response) {
849
- return hookResult;
850
- }
851
- if (hookResult === stop) {
852
- return;
853
- }
854
- }
855
- return __privateMethod(this, _Ky_instances, retry_fn).call(this, function_);
856
- }
857
- });
858
- };
859
- fetch_fn = function() {
860
- return __async(this, null, function* () {
861
- var _a;
862
- if ((_a = __privateGet(this, _abortController)) == null ? void 0 : _a.signal.aborted) {
863
- __privateSet(this, _abortController, new globalThis.AbortController());
864
- __privateGet(this, _options).signal = __privateGet(this, _userProvidedAbortSignal) ? AbortSignal.any([__privateGet(this, _userProvidedAbortSignal), __privateGet(this, _abortController).signal]) : __privateGet(this, _abortController).signal;
865
- this.request = new globalThis.Request(this.request, { signal: __privateGet(this, _options).signal });
866
- }
867
- for (const hook of __privateGet(this, _options).hooks.beforeRequest) {
868
- const result = yield hook(this.request, __privateMethod(this, _Ky_instances, getNormalizedOptions_fn).call(this), { retryCount: __privateGet(this, _retryCount) });
869
- if (result instanceof Response) {
870
- return result;
871
- }
872
- if (result instanceof globalThis.Request) {
873
- __privateMethod(this, _Ky_instances, assignRequest_fn).call(this, result);
874
- break;
875
- }
876
- }
877
- const nonRequestOptions = findUnknownOptions(this.request, __privateGet(this, _options));
878
- __privateSet(this, _originalRequest, this.request);
879
- this.request = __privateGet(this, _originalRequest).clone();
880
- if (__privateGet(this, _options).timeout === false) {
881
- return __privateGet(this, _options).fetch(__privateGet(this, _originalRequest), nonRequestOptions);
164
+ const mod = yield import("@react-email/render");
165
+ return mod.render;
166
+ } catch (e) {
167
+ throw new Error(
168
+ "Sending React-based emails requires '@react-email/render' to be installed. Run: npm install @react-email/render react"
169
+ );
882
170
  }
883
- return timeout(__privateGet(this, _originalRequest), nonRequestOptions, __privateGet(this, _abortController), __privateGet(this, _options));
884
171
  });
885
- };
886
- getNormalizedOptions_fn = function() {
887
- if (!__privateGet(this, _cachedNormalizedOptions)) {
888
- const _a = __privateGet(this, _options), { hooks } = _a, normalizedOptions = __objRest(_a, ["hooks"]);
889
- __privateSet(this, _cachedNormalizedOptions, Object.freeze(normalizedOptions));
890
- }
891
- return __privateGet(this, _cachedNormalizedOptions);
892
- };
893
- assignRequest_fn = function(request) {
894
- __privateSet(this, _cachedNormalizedOptions, void 0);
895
- this.request = __privateMethod(this, _Ky_instances, wrapRequestWithUploadProgress_fn).call(this, request);
896
- };
897
- wrapRequestWithUploadProgress_fn = function(request, originalBody) {
898
- var _a;
899
- if (!__privateGet(this, _options).onUploadProgress || !request.body) {
900
- return request;
901
- }
902
- return streamRequest(request, __privateGet(this, _options).onUploadProgress, (_a = originalBody != null ? originalBody : __privateGet(this, _options).body) != null ? _a : void 0);
903
- };
904
- __privateAdd(_Ky, _Ky_static);
905
- var Ky = _Ky;
906
-
907
- // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/index.js
908
- var createInstance = (defaults) => {
909
- const ky2 = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
910
- for (const method of requestMethods) {
911
- ky2[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
912
- }
913
- ky2.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
914
- ky2.extend = (newDefaults) => {
915
- if (typeof newDefaults === "function") {
916
- newDefaults = newDefaults(defaults != null ? defaults : {});
917
- }
918
- return createInstance(validateAndMerge(defaults, newDefaults));
919
- };
920
- ky2.stop = stop;
921
- ky2.retry = retry;
922
- return ky2;
923
- };
924
- var ky = createInstance();
925
- var distribution_default = ky;
926
-
927
- // src/email/emails.ts
928
- import { render } from "@react-email/render";
172
+ }
929
173
  var Emails = class {
930
- constructor(zupost) {
931
- this.zupost = zupost;
174
+ constructor(http) {
175
+ this.http = http;
932
176
  }
933
177
  /**
934
- * Send an email using template, markdown or HTML content.
178
+ * Send an email.
179
+ *
180
+ * Zupost is template first: prefer sending by `templateId` with `variables`
181
+ * so your content lives in the Zupost dashboard and can be edited without a
182
+ * deploy. Inline `html`, `markdown`, or `react` content is supported as a
183
+ * fallback for ad-hoc or dynamically generated emails.
935
184
  *
936
185
  * @param options - Email options including recipient, sender, and content.
937
- * @returns A promise that resolves to the email response containing emailId.
186
+ * @returns A promise that resolves to the email response containing the email id.
938
187
  *
939
188
  * @example
940
189
  * ```typescript
941
190
  * const zupost = new Zupost('your-api-key');
942
191
  *
943
- * // Send with HTML content
944
- * const { emailId } = await zupost.emails.send({
192
+ * // Recommended: send with a template
193
+ * const { id } = await zupost.emails.send({
945
194
  * from: 'sender@example.com',
946
195
  * to: 'recipient@example.com',
947
- * subject: 'Hello World',
948
- * html: '<h1>Hello!</h1>',
196
+ * templateId: 'welcome-template',
197
+ * variables: { name: 'John' },
949
198
  * });
950
199
  *
951
- * // Send with a template
200
+ * // Fallback: inline HTML
952
201
  * await zupost.emails.send({
953
202
  * from: 'sender@example.com',
954
- * to: ['user1@example.com', 'user2@example.com'],
955
- * subject: 'Welcome!',
956
- * templateId: 'welcome-template',
957
- * variables: { name: 'John' },
203
+ * to: 'recipient@example.com',
204
+ * subject: 'Hello World',
205
+ * html: '<h1>Hello!</h1>',
958
206
  * });
959
207
  *
960
- * // Send with markdown
208
+ * // Fallback: inline markdown
961
209
  * await zupost.emails.send({
962
210
  * from: 'sender@example.com',
963
211
  * to: 'recipient@example.com',
@@ -968,29 +216,31 @@ var Emails = class {
968
216
  */
969
217
  send(options) {
970
218
  return __async(this, null, function* () {
971
- if (options.react) {
972
- options.html = yield render(options.react, options.reactOptions);
973
- delete options.react;
974
- delete options.reactOptions;
219
+ const inlineCount = [options.html, options.markdown, options.react].filter(
220
+ (v) => v !== void 0 && v !== null
221
+ ).length;
222
+ if (inlineCount > 1) {
223
+ throw new Error("Provide only one of html, markdown, or react");
975
224
  }
976
- if (!options.html && !options.markdown && !options.react) {
977
- throw new Error("Either html, markdown or react must be provided");
225
+ if (inlineCount === 0 && !options.templateId) {
226
+ throw new Error("Provide one of html, markdown, react, or templateId");
978
227
  }
979
- if (options.html && options.markdown) {
980
- throw new Error("Either html or markdown must be provided");
981
- }
982
- if (options.react && options.html) {
983
- throw new Error("Either react or html must be provided");
228
+ const payload = __spreadValues({}, options);
229
+ if (options.react) {
230
+ const render = yield loadReactRender();
231
+ payload.html = yield render(options.react, options.reactOptions);
232
+ delete payload.react;
233
+ delete payload.reactOptions;
984
234
  }
985
- return this.zupost.post("email/send", options);
235
+ return this.http.post("email/send", payload);
986
236
  });
987
237
  }
988
238
  };
989
239
 
990
240
  // src/campaign/campaigns.ts
991
241
  var Campaigns = class {
992
- constructor(zupost) {
993
- this.zupost = zupost;
242
+ constructor(http) {
243
+ this.http = http;
994
244
  }
995
245
  /**
996
246
  * Send a campaign to selected audiences.
@@ -1013,68 +263,28 @@ var Campaigns = class {
1013
263
  */
1014
264
  send(options) {
1015
265
  return __async(this, null, function* () {
1016
- return this.zupost.post("campaign/send", options);
266
+ return this.http.post("campaign/send", options);
1017
267
  });
1018
268
  }
1019
269
  };
1020
270
 
1021
271
  // src/zupost.ts
272
+ var _client;
1022
273
  var Zupost = class {
1023
274
  constructor(apiKey, options) {
1024
- this.baseUrl = "https://api.zupost.com";
275
+ __privateAdd(this, _client);
276
+ var _a;
1025
277
  if (!apiKey) {
1026
278
  throw new Error("API key is required");
1027
279
  }
1028
- if (options == null ? void 0 : options.baseUrl) {
1029
- this.baseUrl = options.baseUrl;
1030
- }
1031
- this.headers = new Headers({
1032
- "Authorization": `Bearer ${apiKey}`,
1033
- "Content-Type": "application/json",
1034
- "User-Agent": `node-sdk@${version}`
1035
- });
1036
- this.emails = new Emails(this);
1037
- this.campaigns = new Campaigns(this);
1038
- }
1039
- /**
1040
- * @internal
1041
- * Makes a request to the Zupost API.
1042
- */
1043
- request(path, method, body) {
1044
- return __async(this, null, function* () {
1045
- return distribution_default(path, {
1046
- headers: this.headers,
1047
- method,
1048
- retry: 3,
1049
- prefixUrl: this.baseUrl,
1050
- json: body
1051
- }).json();
1052
- });
1053
- }
1054
- /**
1055
- * @internal
1056
- * Makes a GET request to the Zupost API.
1057
- */
1058
- get(path) {
1059
- return __async(this, null, function* () {
1060
- return this.request(path, "GET");
1061
- });
1062
- }
1063
- /**
1064
- * @internal
1065
- * Makes a POST request to the Zupost API.
1066
- */
1067
- post(path, body) {
1068
- return __async(this, null, function* () {
1069
- return this.request(path, "POST", body);
1070
- });
280
+ const baseUrl = (_a = options == null ? void 0 : options.baseUrl) != null ? _a : "https://api.zupost.com";
281
+ __privateSet(this, _client, new HttpClient(apiKey, baseUrl, `node-sdk@${version}`));
282
+ this.emails = new Emails(__privateGet(this, _client));
283
+ this.campaigns = new Campaigns(__privateGet(this, _client));
1071
284
  }
1072
285
  };
286
+ _client = new WeakMap();
1073
287
  export {
1074
- Zupost
288
+ Zupost,
289
+ ZupostError
1075
290
  };
1076
- /*! Bundled license information:
1077
-
1078
- ky/distribution/index.js:
1079
- (*! MIT License © Sindre Sorhus *)
1080
- */