zupost 0.1.1 → 0.5.1

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,178 @@ var __async = (__this, __arguments, generator) => {
69
44
  };
70
45
 
71
46
  // package.json
72
- var version = "0.1.1";
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.5.1";
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;
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) {
266
73
  }
267
- onProgress == null ? void 0 : onProgress({ percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);
268
74
  }
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
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
+ });
288
84
  });
289
85
  }
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
86
  };
308
87
 
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 : []);
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;
337
100
  }
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
- }
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
111
+ });
373
112
  }
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 = [];
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());
119
+ }
120
+ const init = { method, headers };
121
+ if (body !== void 0) {
122
+ init.body = JSON.stringify(body);
386
123
  }
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);
124
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
125
+ let response;
126
+ try {
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);
392
131
  continue;
393
132
  }
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;
133
+ if (response.ok) {
134
+ return yield response.json();
402
135
  }
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
- }
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);
409
139
  continue;
410
140
  }
411
- if (isObject(value) && key in returnValue) {
412
- value = deepMerge(returnValue[key], value);
413
- }
414
- returnValue = __spreadProps(__spreadValues({}, returnValue), { [key]: value });
415
- }
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;
141
+ throw yield ZupostError.fromResponse(response);
423
142
  }
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
143
+ throw new Error("Zupost API: retries exhausted");
461
144
  });
462
145
  }
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
- };
483
-
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
- });
499
- }
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);
146
+ get(path) {
147
+ return __async(this, null, function* () {
148
+ return this.request(path, "GET");
517
149
  });
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
- }
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.");
636
- }
637
- this.request = __privateMethod(this, _Ky_instances, wrapRequestWithUploadProgress_fn).call(this, this.request, (_m = __privateGet(this, _options).body) != null ? _m : void 0);
638
- }
639
150
  }
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}`);
647
- }
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;
653
- 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) });
679
- }
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");
685
- }
686
- if (!supportsResponseStreams) {
687
- throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
688
- }
689
- const progressResponse = response.clone();
690
- __privateMethod(_l = ky2, _Ky_instances, cancelResponseBody_fn).call(_l, response);
691
- return streamResponse(progressResponse, __privateGet(ky2, _options).onDownloadProgress);
692
- }
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);
151
+ post(path, body) {
152
+ return __async(this, null, function* () {
153
+ return this.request(path, "POST", body);
700
154
  });
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
155
  }
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());
156
+ patch(path, body) {
157
+ return __async(this, null, function* () {
158
+ return this.request(path, "PATCH", body);
809
159
  });
810
160
  }
811
- return response;
812
- };
813
- cancelBody_fn = function(body) {
814
- if (!body) {
815
- return;
161
+ delete(path, body) {
162
+ return __async(this, null, function* () {
163
+ return this.request(path, "DELETE", body);
164
+ });
816
165
  }
817
- void body.cancel().catch(() => void 0);
818
166
  };
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
- };
823
- retry_fn = function(function_) {
167
+ _defaultHeaders = new WeakMap();
168
+ _baseUrl = new WeakMap();
169
+
170
+ // src/email/emails.ts
171
+ function loadReactRender() {
824
172
  return __async(this, null, function* () {
825
173
  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);
174
+ const mod = yield import("@react-email/render");
175
+ return mod.render;
176
+ } catch (e) {
177
+ throw new Error(
178
+ "Sending React-based emails requires '@react-email/render' to be installed. Run: npm install @react-email/render react"
179
+ );
882
180
  }
883
- return timeout(__privateGet(this, _originalRequest), nonRequestOptions, __privateGet(this, _abortController), __privateGet(this, _options));
884
181
  });
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";
182
+ }
929
183
  var Emails = class {
930
- constructor(zupost) {
931
- this.zupost = zupost;
184
+ constructor(http) {
185
+ this.http = http;
932
186
  }
933
187
  /**
934
- * Send an email using template, markdown or HTML content.
188
+ * Send an email.
189
+ *
190
+ * Zupost is template first: prefer sending by `templateId` with `variables`
191
+ * so your content lives in the Zupost dashboard and can be edited without a
192
+ * deploy. Inline `html`, `markdown`, or `react` content is supported as a
193
+ * fallback for ad-hoc or dynamically generated emails.
935
194
  *
936
195
  * @param options - Email options including recipient, sender, and content.
937
- * @returns A promise that resolves to the email response containing emailId.
196
+ * @returns A promise that resolves to the email response containing the email id.
938
197
  *
939
198
  * @example
940
199
  * ```typescript
941
200
  * const zupost = new Zupost('your-api-key');
942
201
  *
943
- * // Send with HTML content
944
- * const { emailId } = await zupost.emails.send({
202
+ * // Recommended: send with a template
203
+ * const { id } = await zupost.emails.send({
945
204
  * from: 'sender@example.com',
946
205
  * to: 'recipient@example.com',
947
- * subject: 'Hello World',
948
- * html: '<h1>Hello!</h1>',
206
+ * templateId: 'welcome-template',
207
+ * variables: { name: 'John' },
949
208
  * });
950
209
  *
951
- * // Send with a template
210
+ * // Fallback: inline HTML
952
211
  * await zupost.emails.send({
953
212
  * from: 'sender@example.com',
954
- * to: ['user1@example.com', 'user2@example.com'],
955
- * subject: 'Welcome!',
956
- * templateId: 'welcome-template',
957
- * variables: { name: 'John' },
213
+ * to: 'recipient@example.com',
214
+ * subject: 'Hello World',
215
+ * html: '<h1>Hello!</h1>',
958
216
  * });
959
217
  *
960
- * // Send with markdown
218
+ * // Fallback: inline markdown
961
219
  * await zupost.emails.send({
962
220
  * from: 'sender@example.com',
963
221
  * to: 'recipient@example.com',
@@ -968,29 +226,31 @@ var Emails = class {
968
226
  */
969
227
  send(options) {
970
228
  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;
975
- }
976
- if (!options.html && !options.markdown && !options.react && !options.templateId) {
977
- throw new Error("Either html, markdown, react or templateId must be provided");
229
+ const inlineCount = [options.html, options.markdown, options.react].filter(
230
+ (v) => v !== void 0 && v !== null
231
+ ).length;
232
+ if (inlineCount > 1) {
233
+ throw new Error("Provide only one of html, markdown, or react");
978
234
  }
979
- if (options.html && options.markdown) {
980
- throw new Error("Either html or markdown must be provided");
235
+ if (inlineCount === 0 && !options.templateId) {
236
+ throw new Error("Provide one of html, markdown, react, or templateId");
981
237
  }
982
- if (options.react && options.html) {
983
- throw new Error("Either react or html must be provided");
238
+ const payload = __spreadValues({}, options);
239
+ if (options.react) {
240
+ const render = yield loadReactRender();
241
+ payload.html = yield render(options.react, options.reactOptions);
242
+ delete payload.react;
243
+ delete payload.reactOptions;
984
244
  }
985
- return this.zupost.post("email/send", options);
245
+ return this.http.post("email/send", payload);
986
246
  });
987
247
  }
988
248
  };
989
249
 
990
250
  // src/campaign/campaigns.ts
991
251
  var Campaigns = class {
992
- constructor(zupost) {
993
- this.zupost = zupost;
252
+ constructor(http) {
253
+ this.http = http;
994
254
  }
995
255
  /**
996
256
  * Send a campaign to selected audiences.
@@ -1013,68 +273,293 @@ var Campaigns = class {
1013
273
  */
1014
274
  send(options) {
1015
275
  return __async(this, null, function* () {
1016
- return this.zupost.post("campaign/send", options);
276
+ return this.http.post("campaign/send", options);
1017
277
  });
1018
278
  }
1019
279
  };
1020
280
 
1021
- // src/zupost.ts
1022
- var Zupost = class {
1023
- constructor(apiKey, options) {
1024
- this.baseUrl = "https://api.zupost.com";
1025
- if (!apiKey) {
1026
- throw new Error("API key is required");
1027
- }
1028
- if (options == null ? void 0 : options.baseUrl) {
1029
- this.baseUrl = options.baseUrl;
281
+ // src/contact/contacts.ts
282
+ function buildQuery(params) {
283
+ const search = new URLSearchParams();
284
+ for (const [key, value] of Object.entries(params)) {
285
+ if (value === void 0) continue;
286
+ if (Array.isArray(value)) {
287
+ for (const v of value) search.append(key, String(v));
288
+ } else {
289
+ search.set(key, String(value));
1030
290
  }
1031
- this.headers = new Headers({
1032
- "Authorization": `Bearer ${apiKey}`,
1033
- "Content-Type": "application/json",
1034
- "User-Agent": `node-sdk@${version}`
291
+ }
292
+ const query = search.toString();
293
+ return query ? `?${query}` : "";
294
+ }
295
+ var Contacts = class {
296
+ constructor(http) {
297
+ this.http = http;
298
+ }
299
+ /**
300
+ * Create or upsert a contact by email. Idempotent on (project, email).
301
+ *
302
+ * @example
303
+ * ```typescript
304
+ * const contact = await zupost.contacts.create({
305
+ * email: 'user@example.com',
306
+ * name: 'Jane Doe',
307
+ * marketingConsent: true,
308
+ * marketingConsentSource: 'signup-form',
309
+ * tags: ['vip', 'beta'],
310
+ * });
311
+ * ```
312
+ */
313
+ create(options) {
314
+ return __async(this, null, function* () {
315
+ return this.http.post("/contact", options);
1035
316
  });
1036
- this.emails = new Emails(this);
1037
- this.campaigns = new Campaigns(this);
1038
317
  }
1039
318
  /**
1040
- * @internal
1041
- * Makes a request to the Zupost API.
319
+ * Get a contact by ID.
1042
320
  */
1043
- request(path, method, body) {
321
+ get(id) {
1044
322
  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();
323
+ return this.http.get(`/contact/${encodeURIComponent(id)}`);
1052
324
  });
1053
325
  }
1054
326
  /**
1055
- * @internal
1056
- * Makes a GET request to the Zupost API.
327
+ * List contacts with optional search, consent and tag filters.
1057
328
  */
1058
- get(path) {
329
+ list() {
330
+ return __async(this, arguments, function* (options = {}) {
331
+ const query = buildQuery({
332
+ skip: options.skip,
333
+ take: options.take,
334
+ search: options.search,
335
+ marketingConsent: options.marketingConsent === void 0 ? void 0 : String(options.marketingConsent),
336
+ tag: options.tag
337
+ });
338
+ return this.http.get(`/contact${query}`);
339
+ });
340
+ }
341
+ /**
342
+ * Update a contact. Pass only the fields that should change.
343
+ *
344
+ * Toggling `marketingConsent` or `trackingConsent` automatically records
345
+ * a corresponding ContactEvent for the audit trail.
346
+ */
347
+ update(id, patch) {
1059
348
  return __async(this, null, function* () {
1060
- return this.request(path, "GET");
349
+ return this.http.patch(`/contact/${encodeURIComponent(id)}`, patch);
1061
350
  });
1062
351
  }
1063
352
  /**
1064
- * @internal
1065
- * Makes a POST request to the Zupost API.
353
+ * GDPR right-to-be-forgotten. Anonymises the contact, sets `forgottenAt`
354
+ * and disables consent. Existing email events are anonymised in a
355
+ * follow-up cascade.
1066
356
  */
1067
- post(path, body) {
357
+ forget(id) {
1068
358
  return __async(this, null, function* () {
1069
- return this.request(path, "POST", body);
359
+ return this.http.delete(`/contact/${encodeURIComponent(id)}`);
360
+ });
361
+ }
362
+ /**
363
+ * Get the chronological event timeline for a contact.
364
+ */
365
+ events(_0) {
366
+ return __async(this, arguments, function* (id, options = {}) {
367
+ const query = buildQuery({
368
+ skip: options.skip,
369
+ take: options.take,
370
+ type: options.type
371
+ });
372
+ return this.http.get(`/contact/${encodeURIComponent(id)}/events${query}`);
373
+ });
374
+ }
375
+ /**
376
+ * GDPR data access export. Returns the complete record for a contact
377
+ * including all emails, events, subscriptions and tags.
378
+ */
379
+ export(id) {
380
+ return __async(this, null, function* () {
381
+ return this.http.get(`/contact/${encodeURIComponent(id)}/export`);
382
+ });
383
+ }
384
+ /**
385
+ * Add a tag to a contact (idempotent).
386
+ */
387
+ addTag(id, name) {
388
+ return __async(this, null, function* () {
389
+ return this.http.post(`/contact/${encodeURIComponent(id)}/tags`, { name });
390
+ });
391
+ }
392
+ /**
393
+ * Remove a tag from a contact.
394
+ */
395
+ removeTag(id, name) {
396
+ return __async(this, null, function* () {
397
+ return this.http.delete(
398
+ `/contact/${encodeURIComponent(id)}/tags/${encodeURIComponent(name)}`
399
+ );
1070
400
  });
1071
401
  }
1072
402
  };
1073
- export {
1074
- Zupost
403
+
404
+ // src/sequence/sequences.ts
405
+ function buildQuery2(params) {
406
+ const search = new URLSearchParams();
407
+ for (const [key, value] of Object.entries(params)) {
408
+ if (value === void 0) continue;
409
+ search.set(key, String(value));
410
+ }
411
+ const q = search.toString();
412
+ return q ? `?${q}` : "";
413
+ }
414
+ var Sequences = class {
415
+ constructor(http) {
416
+ this.http = http;
417
+ this.runs = {
418
+ list: (_0, ..._1) => __async(this, [_0, ..._1], function* (sequenceId, options = {}) {
419
+ const query = buildQuery2({
420
+ skip: options.skip,
421
+ take: options.take,
422
+ status: options.status,
423
+ contactId: options.contactId
424
+ });
425
+ return this.http.get(
426
+ `/sequence/${encodeURIComponent(sequenceId)}/runs${query}`
427
+ );
428
+ })
429
+ };
430
+ }
431
+ /**
432
+ * Create a new sequence (always starts in DRAFT). Pass `definition` to
433
+ * seed the first version, or omit it to create an empty placeholder you
434
+ * can later push versions into.
435
+ */
436
+ create(options) {
437
+ return __async(this, null, function* () {
438
+ return this.http.post("/sequence", options);
439
+ });
440
+ }
441
+ /**
442
+ * Get a sequence by ID.
443
+ */
444
+ get(id) {
445
+ return __async(this, null, function* () {
446
+ return this.http.get(`/sequence/${encodeURIComponent(id)}`);
447
+ });
448
+ }
449
+ /**
450
+ * List sequences with filters.
451
+ */
452
+ list() {
453
+ return __async(this, arguments, function* (options = {}) {
454
+ const query = buildQuery2({
455
+ skip: options.skip,
456
+ take: options.take,
457
+ type: options.type,
458
+ status: options.status,
459
+ search: options.search
460
+ });
461
+ return this.http.get(`/sequence${query}`);
462
+ });
463
+ }
464
+ /**
465
+ * Delete a sequence and all its versions and runs.
466
+ */
467
+ delete(id) {
468
+ return __async(this, null, function* () {
469
+ return this.http.delete(`/sequence/${encodeURIComponent(id)}`);
470
+ });
471
+ }
472
+ /**
473
+ * Change the lifecycle status: DRAFT, ACTIVE, PAUSED, ARCHIVED.
474
+ */
475
+ setStatus(id, status) {
476
+ return __async(this, null, function* () {
477
+ return this.http.post(`/sequence/${encodeURIComponent(id)}/status`, { status });
478
+ });
479
+ }
480
+ /**
481
+ * Save a new immutable version of the sequence definition. If `activate`
482
+ * is true (default), the new version becomes the active one for future
483
+ * triggered runs. Existing in-flight runs keep their pinned version.
484
+ */
485
+ saveVersion(id, options) {
486
+ return __async(this, null, function* () {
487
+ return this.http.post(`/sequence/${encodeURIComponent(id)}/versions`, options);
488
+ });
489
+ }
490
+ /**
491
+ * Trigger a sequence run for a contact or ad-hoc email. The sequence
492
+ * must be ACTIVE.
493
+ */
494
+ trigger(id, options) {
495
+ return __async(this, null, function* () {
496
+ if (!options.contactId && !options.email) {
497
+ throw new Error("trigger requires contactId or email");
498
+ }
499
+ return this.http.post(`/sequence/${encodeURIComponent(id)}/runs`, options);
500
+ });
501
+ }
1075
502
  };
1076
- /*! Bundled license information:
1077
503
 
1078
- ky/distribution/index.js:
1079
- (*! MIT License © Sindre Sorhus *)
1080
- */
504
+ // src/zupost.ts
505
+ var _client;
506
+ var Zupost = class {
507
+ constructor(apiKey, options) {
508
+ __privateAdd(this, _client);
509
+ var _a;
510
+ if (!apiKey) {
511
+ throw new Error("API key is required");
512
+ }
513
+ const baseUrl = (_a = options == null ? void 0 : options.baseUrl) != null ? _a : "https://api.zupost.com";
514
+ __privateSet(this, _client, new HttpClient(apiKey, baseUrl, `node-sdk@${version}`));
515
+ this.emails = new Emails(__privateGet(this, _client));
516
+ this.campaigns = new Campaigns(__privateGet(this, _client));
517
+ this.contacts = new Contacts(__privateGet(this, _client));
518
+ this.sequences = new Sequences(__privateGet(this, _client));
519
+ }
520
+ };
521
+ _client = new WeakMap();
522
+
523
+ // src/sequence/define.ts
524
+ function defineSequence(definition) {
525
+ const issues = [];
526
+ const stepKeys = Object.keys(definition.steps);
527
+ if (!definition.steps[definition.entry]) {
528
+ issues.push(`entry "${String(definition.entry)}" is not a defined step`);
529
+ }
530
+ if (stepKeys.length === 0) issues.push("steps must contain at least one step");
531
+ for (const key of stepKeys) {
532
+ const step = definition.steps[key];
533
+ if (step.key !== key) issues.push(`step.key "${step.key}" does not match object key "${key}"`);
534
+ const checkRef = (ref, where) => {
535
+ if (ref && !definition.steps[ref]) {
536
+ issues.push(`step "${key}" ${where} points at unknown step "${ref}"`);
537
+ }
538
+ };
539
+ switch (step.type) {
540
+ case "send_email":
541
+ case "wait":
542
+ case "tag_add":
543
+ case "tag_remove":
544
+ case "update_contact":
545
+ case "webhook":
546
+ checkRef(step.next, "next");
547
+ break;
548
+ case "branch":
549
+ checkRef(step.thenNext, "thenNext");
550
+ checkRef(step.elseNext, "elseNext");
551
+ break;
552
+ case "end":
553
+ break;
554
+ }
555
+ }
556
+ if (issues.length > 0) {
557
+ throw new Error(`Invalid sequence definition: ${issues.join("; ")}`);
558
+ }
559
+ return definition;
560
+ }
561
+ export {
562
+ Zupost,
563
+ ZupostError,
564
+ defineSequence
565
+ };