@usenadia/node 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,1701 @@
1
+ // src/index.ts
2
+ import { createHmac, timingSafeEqual } from "crypto";
3
+
4
+ // src/generated/core/bodySerializer.gen.ts
5
+ var serializeFormDataPair = (data, key, value) => {
6
+ if (typeof value === "string" || value instanceof Blob) {
7
+ data.append(key, value);
8
+ } else if (value instanceof Date) {
9
+ data.append(key, value.toISOString());
10
+ } else {
11
+ data.append(key, JSON.stringify(value));
12
+ }
13
+ };
14
+ var formDataBodySerializer = {
15
+ bodySerializer: (body) => {
16
+ const data = new FormData();
17
+ Object.entries(body).forEach(([key, value]) => {
18
+ if (value === void 0 || value === null) {
19
+ return;
20
+ }
21
+ if (Array.isArray(value)) {
22
+ value.forEach((v) => serializeFormDataPair(data, key, v));
23
+ } else {
24
+ serializeFormDataPair(data, key, value);
25
+ }
26
+ });
27
+ return data;
28
+ }
29
+ };
30
+ var jsonBodySerializer = {
31
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
32
+ };
33
+
34
+ // src/generated/core/params.gen.ts
35
+ var extraPrefixesMap = {
36
+ $body_: "body",
37
+ $headers_: "headers",
38
+ $path_: "path",
39
+ $query_: "query"
40
+ };
41
+ var extraPrefixes = Object.entries(extraPrefixesMap);
42
+
43
+ // src/generated/core/serverSentEvents.gen.ts
44
+ function createSseClient({
45
+ onRequest,
46
+ onSseError,
47
+ onSseEvent,
48
+ responseTransformer,
49
+ responseValidator,
50
+ sseDefaultRetryDelay,
51
+ sseMaxRetryAttempts,
52
+ sseMaxRetryDelay,
53
+ sseSleepFn,
54
+ url,
55
+ ...options
56
+ }) {
57
+ let lastEventId;
58
+ const sleep2 = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
59
+ const createStream = async function* () {
60
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
61
+ let attempt = 0;
62
+ const signal = options.signal ?? new AbortController().signal;
63
+ while (true) {
64
+ if (signal.aborted) break;
65
+ attempt++;
66
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
67
+ if (lastEventId !== void 0) {
68
+ headers.set("Last-Event-ID", lastEventId);
69
+ }
70
+ try {
71
+ const requestInit = {
72
+ redirect: "follow",
73
+ ...options,
74
+ body: options.serializedBody,
75
+ headers,
76
+ signal
77
+ };
78
+ let request = new Request(url, requestInit);
79
+ if (onRequest) {
80
+ request = await onRequest(url, requestInit);
81
+ }
82
+ const _fetch = options.fetch ?? globalThis.fetch;
83
+ const response = await _fetch(request);
84
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
85
+ if (!response.body) throw new Error("No body in SSE response");
86
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
87
+ let buffer = "";
88
+ const abortHandler = () => {
89
+ try {
90
+ reader.cancel();
91
+ } catch {
92
+ }
93
+ };
94
+ signal.addEventListener("abort", abortHandler);
95
+ try {
96
+ while (true) {
97
+ const { done, value } = await reader.read();
98
+ if (done) break;
99
+ buffer += value;
100
+ buffer = buffer.replace(/\r\n?/g, "\n");
101
+ const chunks = buffer.split("\n\n");
102
+ buffer = chunks.pop() ?? "";
103
+ for (const chunk of chunks) {
104
+ const lines = chunk.split("\n");
105
+ const dataLines = [];
106
+ let eventName;
107
+ for (const line of lines) {
108
+ if (line.startsWith("data:")) {
109
+ dataLines.push(line.replace(/^data:\s*/, ""));
110
+ } else if (line.startsWith("event:")) {
111
+ eventName = line.replace(/^event:\s*/, "");
112
+ } else if (line.startsWith("id:")) {
113
+ lastEventId = line.replace(/^id:\s*/, "");
114
+ } else if (line.startsWith("retry:")) {
115
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
116
+ if (!Number.isNaN(parsed)) {
117
+ retryDelay = parsed;
118
+ }
119
+ }
120
+ }
121
+ let data;
122
+ let parsedJson = false;
123
+ if (dataLines.length) {
124
+ const rawData = dataLines.join("\n");
125
+ try {
126
+ data = JSON.parse(rawData);
127
+ parsedJson = true;
128
+ } catch {
129
+ data = rawData;
130
+ }
131
+ }
132
+ if (parsedJson) {
133
+ if (responseValidator) {
134
+ await responseValidator(data);
135
+ }
136
+ if (responseTransformer) {
137
+ data = await responseTransformer(data);
138
+ }
139
+ }
140
+ onSseEvent?.({
141
+ data,
142
+ event: eventName,
143
+ id: lastEventId,
144
+ retry: retryDelay
145
+ });
146
+ if (dataLines.length) {
147
+ yield data;
148
+ }
149
+ }
150
+ }
151
+ } finally {
152
+ signal.removeEventListener("abort", abortHandler);
153
+ reader.releaseLock();
154
+ }
155
+ break;
156
+ } catch (error) {
157
+ onSseError?.(error);
158
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
159
+ break;
160
+ }
161
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
162
+ await sleep2(backoff);
163
+ }
164
+ }
165
+ };
166
+ const stream = createStream();
167
+ return { stream };
168
+ }
169
+
170
+ // src/generated/core/pathSerializer.gen.ts
171
+ var separatorArrayExplode = (style) => {
172
+ switch (style) {
173
+ case "label":
174
+ return ".";
175
+ case "matrix":
176
+ return ";";
177
+ case "simple":
178
+ return ",";
179
+ default:
180
+ return "&";
181
+ }
182
+ };
183
+ var separatorArrayNoExplode = (style) => {
184
+ switch (style) {
185
+ case "form":
186
+ return ",";
187
+ case "pipeDelimited":
188
+ return "|";
189
+ case "spaceDelimited":
190
+ return "%20";
191
+ default:
192
+ return ",";
193
+ }
194
+ };
195
+ var separatorObjectExplode = (style) => {
196
+ switch (style) {
197
+ case "label":
198
+ return ".";
199
+ case "matrix":
200
+ return ";";
201
+ case "simple":
202
+ return ",";
203
+ default:
204
+ return "&";
205
+ }
206
+ };
207
+ var serializeArrayParam = ({
208
+ allowReserved,
209
+ explode,
210
+ name,
211
+ style,
212
+ value
213
+ }) => {
214
+ if (!explode) {
215
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
216
+ switch (style) {
217
+ case "label":
218
+ return `.${joinedValues2}`;
219
+ case "matrix":
220
+ return `;${name}=${joinedValues2}`;
221
+ case "simple":
222
+ return joinedValues2;
223
+ default:
224
+ return `${name}=${joinedValues2}`;
225
+ }
226
+ }
227
+ const separator = separatorArrayExplode(style);
228
+ const joinedValues = value.map((v) => {
229
+ if (style === "label" || style === "simple") {
230
+ return allowReserved ? v : encodeURIComponent(v);
231
+ }
232
+ return serializePrimitiveParam({
233
+ allowReserved,
234
+ name,
235
+ value: v
236
+ });
237
+ }).join(separator);
238
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
239
+ };
240
+ var serializePrimitiveParam = ({
241
+ allowReserved,
242
+ name,
243
+ value
244
+ }) => {
245
+ if (value === void 0 || value === null) {
246
+ return "";
247
+ }
248
+ if (typeof value === "object") {
249
+ throw new Error(
250
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
251
+ );
252
+ }
253
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
254
+ };
255
+ var serializeObjectParam = ({
256
+ allowReserved,
257
+ explode,
258
+ name,
259
+ style,
260
+ value,
261
+ valueOnly
262
+ }) => {
263
+ if (value instanceof Date) {
264
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
265
+ }
266
+ if (style !== "deepObject" && !explode) {
267
+ let values = [];
268
+ Object.entries(value).forEach(([key, v]) => {
269
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
270
+ });
271
+ const joinedValues2 = values.join(",");
272
+ switch (style) {
273
+ case "form":
274
+ return `${name}=${joinedValues2}`;
275
+ case "label":
276
+ return `.${joinedValues2}`;
277
+ case "matrix":
278
+ return `;${name}=${joinedValues2}`;
279
+ default:
280
+ return joinedValues2;
281
+ }
282
+ }
283
+ const separator = separatorObjectExplode(style);
284
+ const joinedValues = Object.entries(value).map(
285
+ ([key, v]) => serializePrimitiveParam({
286
+ allowReserved,
287
+ name: style === "deepObject" ? `${name}[${key}]` : key,
288
+ value: v
289
+ })
290
+ ).join(separator);
291
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
292
+ };
293
+
294
+ // src/generated/core/utils.gen.ts
295
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
296
+ var defaultPathSerializer = ({ path, url: _url }) => {
297
+ let url = _url;
298
+ const matches = _url.match(PATH_PARAM_RE);
299
+ if (matches) {
300
+ for (const match of matches) {
301
+ let explode = false;
302
+ let name = match.substring(1, match.length - 1);
303
+ let style = "simple";
304
+ if (name.endsWith("*")) {
305
+ explode = true;
306
+ name = name.substring(0, name.length - 1);
307
+ }
308
+ if (name.startsWith(".")) {
309
+ name = name.substring(1);
310
+ style = "label";
311
+ } else if (name.startsWith(";")) {
312
+ name = name.substring(1);
313
+ style = "matrix";
314
+ }
315
+ const value = path[name];
316
+ if (value === void 0 || value === null) {
317
+ continue;
318
+ }
319
+ if (Array.isArray(value)) {
320
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
321
+ continue;
322
+ }
323
+ if (typeof value === "object") {
324
+ url = url.replace(
325
+ match,
326
+ serializeObjectParam({
327
+ explode,
328
+ name,
329
+ style,
330
+ value,
331
+ valueOnly: true
332
+ })
333
+ );
334
+ continue;
335
+ }
336
+ if (style === "matrix") {
337
+ url = url.replace(
338
+ match,
339
+ `;${serializePrimitiveParam({
340
+ name,
341
+ value
342
+ })}`
343
+ );
344
+ continue;
345
+ }
346
+ const replaceValue = encodeURIComponent(
347
+ style === "label" ? `.${value}` : value
348
+ );
349
+ url = url.replace(match, replaceValue);
350
+ }
351
+ }
352
+ return url;
353
+ };
354
+ var getUrl = ({
355
+ baseUrl,
356
+ path,
357
+ query,
358
+ querySerializer,
359
+ url: _url
360
+ }) => {
361
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
362
+ let url = (baseUrl ?? "") + pathUrl;
363
+ if (path) {
364
+ url = defaultPathSerializer({ path, url });
365
+ }
366
+ let search = query ? querySerializer(query) : "";
367
+ if (search.startsWith("?")) {
368
+ search = search.substring(1);
369
+ }
370
+ if (search) {
371
+ url += `?${search}`;
372
+ }
373
+ return url;
374
+ };
375
+ function getValidRequestBody(options) {
376
+ const hasBody = options.body !== void 0;
377
+ const isSerializedBody = hasBody && options.bodySerializer;
378
+ if (isSerializedBody) {
379
+ if ("serializedBody" in options) {
380
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
381
+ return hasSerializedBody ? options.serializedBody : null;
382
+ }
383
+ return options.body !== "" ? options.body : null;
384
+ }
385
+ if (hasBody) {
386
+ return options.body;
387
+ }
388
+ return void 0;
389
+ }
390
+
391
+ // src/generated/core/auth.gen.ts
392
+ var getAuthToken = async (auth, callback) => {
393
+ const token = typeof callback === "function" ? await callback(auth) : callback;
394
+ if (!token) {
395
+ return;
396
+ }
397
+ if (auth.scheme === "bearer") {
398
+ return `Bearer ${token}`;
399
+ }
400
+ if (auth.scheme === "basic") {
401
+ return `Basic ${btoa(token)}`;
402
+ }
403
+ return token;
404
+ };
405
+
406
+ // src/generated/client/utils.gen.ts
407
+ var createQuerySerializer = ({
408
+ parameters = {},
409
+ ...args
410
+ } = {}) => {
411
+ const querySerializer = (queryParams) => {
412
+ const search = [];
413
+ if (queryParams && typeof queryParams === "object") {
414
+ for (const name in queryParams) {
415
+ const value = queryParams[name];
416
+ if (value === void 0 || value === null) {
417
+ continue;
418
+ }
419
+ const options = parameters[name] || args;
420
+ if (Array.isArray(value)) {
421
+ const serializedArray = serializeArrayParam({
422
+ allowReserved: options.allowReserved,
423
+ explode: true,
424
+ name,
425
+ style: "form",
426
+ value,
427
+ ...options.array
428
+ });
429
+ if (serializedArray) search.push(serializedArray);
430
+ } else if (typeof value === "object") {
431
+ const serializedObject = serializeObjectParam({
432
+ allowReserved: options.allowReserved,
433
+ explode: true,
434
+ name,
435
+ style: "deepObject",
436
+ value,
437
+ ...options.object
438
+ });
439
+ if (serializedObject) search.push(serializedObject);
440
+ } else {
441
+ const serializedPrimitive = serializePrimitiveParam({
442
+ allowReserved: options.allowReserved,
443
+ name,
444
+ value
445
+ });
446
+ if (serializedPrimitive) search.push(serializedPrimitive);
447
+ }
448
+ }
449
+ }
450
+ return search.join("&");
451
+ };
452
+ return querySerializer;
453
+ };
454
+ var getParseAs = (contentType) => {
455
+ if (!contentType) {
456
+ return "stream";
457
+ }
458
+ const cleanContent = contentType.split(";")[0]?.trim();
459
+ if (!cleanContent) {
460
+ return;
461
+ }
462
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
463
+ return "json";
464
+ }
465
+ if (cleanContent === "multipart/form-data") {
466
+ return "formData";
467
+ }
468
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
469
+ return "blob";
470
+ }
471
+ if (cleanContent.startsWith("text/")) {
472
+ return "text";
473
+ }
474
+ return;
475
+ };
476
+ var checkForExistence = (options, name) => {
477
+ if (!name) {
478
+ return false;
479
+ }
480
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
481
+ return true;
482
+ }
483
+ return false;
484
+ };
485
+ async function setAuthParams(options) {
486
+ for (const auth of options.security ?? []) {
487
+ if (checkForExistence(options, auth.name)) {
488
+ continue;
489
+ }
490
+ const token = await getAuthToken(auth, options.auth);
491
+ if (!token) {
492
+ continue;
493
+ }
494
+ const name = auth.name ?? "Authorization";
495
+ switch (auth.in) {
496
+ case "query":
497
+ if (!options.query) {
498
+ options.query = {};
499
+ }
500
+ options.query[name] = token;
501
+ break;
502
+ case "cookie":
503
+ options.headers.append("Cookie", `${name}=${token}`);
504
+ break;
505
+ case "header":
506
+ default:
507
+ options.headers.set(name, token);
508
+ break;
509
+ }
510
+ }
511
+ }
512
+ var buildUrl = (options) => getUrl({
513
+ baseUrl: options.baseUrl,
514
+ path: options.path,
515
+ query: options.query,
516
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
517
+ url: options.url
518
+ });
519
+ var mergeConfigs = (a, b) => {
520
+ const config = { ...a, ...b };
521
+ if (config.baseUrl?.endsWith("/")) {
522
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
523
+ }
524
+ config.headers = mergeHeaders(a.headers, b.headers);
525
+ return config;
526
+ };
527
+ var headersEntries = (headers) => {
528
+ const entries = [];
529
+ headers.forEach((value, key) => {
530
+ entries.push([key, value]);
531
+ });
532
+ return entries;
533
+ };
534
+ var mergeHeaders = (...headers) => {
535
+ const mergedHeaders = new Headers();
536
+ for (const header of headers) {
537
+ if (!header) {
538
+ continue;
539
+ }
540
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
541
+ for (const [key, value] of iterator) {
542
+ if (value === null) {
543
+ mergedHeaders.delete(key);
544
+ } else if (Array.isArray(value)) {
545
+ for (const v of value) {
546
+ mergedHeaders.append(key, v);
547
+ }
548
+ } else if (value !== void 0) {
549
+ mergedHeaders.set(
550
+ key,
551
+ typeof value === "object" ? JSON.stringify(value) : value
552
+ );
553
+ }
554
+ }
555
+ }
556
+ return mergedHeaders;
557
+ };
558
+ var Interceptors = class {
559
+ fns = [];
560
+ clear() {
561
+ this.fns = [];
562
+ }
563
+ eject(id) {
564
+ const index = this.getInterceptorIndex(id);
565
+ if (this.fns[index]) {
566
+ this.fns[index] = null;
567
+ }
568
+ }
569
+ exists(id) {
570
+ const index = this.getInterceptorIndex(id);
571
+ return Boolean(this.fns[index]);
572
+ }
573
+ getInterceptorIndex(id) {
574
+ if (typeof id === "number") {
575
+ return this.fns[id] ? id : -1;
576
+ }
577
+ return this.fns.indexOf(id);
578
+ }
579
+ update(id, fn) {
580
+ const index = this.getInterceptorIndex(id);
581
+ if (this.fns[index]) {
582
+ this.fns[index] = fn;
583
+ return id;
584
+ }
585
+ return false;
586
+ }
587
+ use(fn) {
588
+ this.fns.push(fn);
589
+ return this.fns.length - 1;
590
+ }
591
+ };
592
+ var createInterceptors = () => ({
593
+ error: new Interceptors(),
594
+ request: new Interceptors(),
595
+ response: new Interceptors()
596
+ });
597
+ var defaultQuerySerializer = createQuerySerializer({
598
+ allowReserved: false,
599
+ array: {
600
+ explode: true,
601
+ style: "form"
602
+ },
603
+ object: {
604
+ explode: true,
605
+ style: "deepObject"
606
+ }
607
+ });
608
+ var defaultHeaders = {
609
+ "Content-Type": "application/json"
610
+ };
611
+ var createConfig = (override = {}) => ({
612
+ ...jsonBodySerializer,
613
+ headers: defaultHeaders,
614
+ parseAs: "auto",
615
+ querySerializer: defaultQuerySerializer,
616
+ ...override
617
+ });
618
+
619
+ // src/generated/client/client.gen.ts
620
+ var createClient = (config = {}) => {
621
+ let _config = mergeConfigs(createConfig(), config);
622
+ const getConfig = () => ({ ..._config });
623
+ const setConfig = (config2) => {
624
+ _config = mergeConfigs(_config, config2);
625
+ return getConfig();
626
+ };
627
+ const interceptors = createInterceptors();
628
+ const beforeRequest = async (options) => {
629
+ const opts = {
630
+ ..._config,
631
+ ...options,
632
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
633
+ headers: mergeHeaders(_config.headers, options.headers),
634
+ serializedBody: void 0
635
+ };
636
+ if (opts.security) {
637
+ await setAuthParams(opts);
638
+ }
639
+ if (opts.requestValidator) {
640
+ await opts.requestValidator(opts);
641
+ }
642
+ if (opts.body !== void 0 && opts.bodySerializer) {
643
+ opts.serializedBody = opts.bodySerializer(opts.body);
644
+ }
645
+ if (opts.body === void 0 || opts.serializedBody === "") {
646
+ opts.headers.delete("Content-Type");
647
+ }
648
+ const resolvedOpts = opts;
649
+ const url = buildUrl(resolvedOpts);
650
+ return { opts: resolvedOpts, url };
651
+ };
652
+ const request = async (options) => {
653
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
654
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
655
+ let request2;
656
+ let response;
657
+ try {
658
+ const { opts, url } = await beforeRequest(options);
659
+ const requestInit = {
660
+ redirect: "follow",
661
+ ...opts,
662
+ body: getValidRequestBody(opts)
663
+ };
664
+ request2 = new Request(url, requestInit);
665
+ for (const fn of interceptors.request.fns) {
666
+ if (fn) {
667
+ request2 = await fn(request2, opts);
668
+ }
669
+ }
670
+ const _fetch = opts.fetch;
671
+ response = await _fetch(request2);
672
+ for (const fn of interceptors.response.fns) {
673
+ if (fn) {
674
+ response = await fn(response, request2, opts);
675
+ }
676
+ }
677
+ const result = {
678
+ request: request2,
679
+ response
680
+ };
681
+ if (response.ok) {
682
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
683
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
684
+ let emptyData;
685
+ switch (parseAs) {
686
+ case "arrayBuffer":
687
+ case "blob":
688
+ case "text":
689
+ emptyData = await response[parseAs]();
690
+ break;
691
+ case "formData":
692
+ emptyData = new FormData();
693
+ break;
694
+ case "stream":
695
+ emptyData = response.body;
696
+ break;
697
+ case "json":
698
+ default:
699
+ emptyData = {};
700
+ break;
701
+ }
702
+ return opts.responseStyle === "data" ? emptyData : {
703
+ data: emptyData,
704
+ ...result
705
+ };
706
+ }
707
+ let data;
708
+ switch (parseAs) {
709
+ case "arrayBuffer":
710
+ case "blob":
711
+ case "formData":
712
+ case "text":
713
+ data = await response[parseAs]();
714
+ break;
715
+ case "json": {
716
+ const text = await response.text();
717
+ data = text ? JSON.parse(text) : {};
718
+ break;
719
+ }
720
+ case "stream":
721
+ return opts.responseStyle === "data" ? response.body : {
722
+ data: response.body,
723
+ ...result
724
+ };
725
+ }
726
+ if (parseAs === "json") {
727
+ if (opts.responseValidator) {
728
+ await opts.responseValidator(data);
729
+ }
730
+ if (opts.responseTransformer) {
731
+ data = await opts.responseTransformer(data);
732
+ }
733
+ }
734
+ return opts.responseStyle === "data" ? data : {
735
+ data,
736
+ ...result
737
+ };
738
+ }
739
+ const textError = await response.text();
740
+ let jsonError;
741
+ try {
742
+ jsonError = JSON.parse(textError);
743
+ } catch {
744
+ }
745
+ throw jsonError ?? textError;
746
+ } catch (error) {
747
+ let finalError = error;
748
+ for (const fn of interceptors.error.fns) {
749
+ if (fn) {
750
+ finalError = await fn(finalError, response, request2, options);
751
+ }
752
+ }
753
+ finalError = finalError || {};
754
+ if (throwOnError) {
755
+ throw finalError;
756
+ }
757
+ return responseStyle === "data" ? void 0 : {
758
+ error: finalError,
759
+ request: request2,
760
+ response
761
+ };
762
+ }
763
+ };
764
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
765
+ const makeSseFn = (method) => async (options) => {
766
+ const { opts, url } = await beforeRequest(options);
767
+ return createSseClient({
768
+ ...opts,
769
+ body: opts.body,
770
+ method,
771
+ onRequest: async (url2, init) => {
772
+ let request2 = new Request(url2, init);
773
+ for (const fn of interceptors.request.fns) {
774
+ if (fn) {
775
+ request2 = await fn(request2, opts);
776
+ }
777
+ }
778
+ return request2;
779
+ },
780
+ serializedBody: getValidRequestBody(opts),
781
+ url
782
+ });
783
+ };
784
+ const _buildUrl = (options) => buildUrl({ ..._config, ...options });
785
+ return {
786
+ buildUrl: _buildUrl,
787
+ connect: makeMethodFn("CONNECT"),
788
+ delete: makeMethodFn("DELETE"),
789
+ get: makeMethodFn("GET"),
790
+ getConfig,
791
+ head: makeMethodFn("HEAD"),
792
+ interceptors,
793
+ options: makeMethodFn("OPTIONS"),
794
+ patch: makeMethodFn("PATCH"),
795
+ post: makeMethodFn("POST"),
796
+ put: makeMethodFn("PUT"),
797
+ request,
798
+ setConfig,
799
+ sse: {
800
+ connect: makeSseFn("CONNECT"),
801
+ delete: makeSseFn("DELETE"),
802
+ get: makeSseFn("GET"),
803
+ head: makeSseFn("HEAD"),
804
+ options: makeSseFn("OPTIONS"),
805
+ patch: makeSseFn("PATCH"),
806
+ post: makeSseFn("POST"),
807
+ put: makeSseFn("PUT"),
808
+ trace: makeSseFn("TRACE")
809
+ },
810
+ trace: makeMethodFn("TRACE")
811
+ };
812
+ };
813
+
814
+ // src/generated/client.gen.ts
815
+ var client = createClient(createConfig({ baseUrl: "https://app.usenadia.com/api" }));
816
+
817
+ // src/generated/sdk.gen.ts
818
+ var uploadFile = (options) => (options.client ?? client).post({
819
+ ...formDataBodySerializer,
820
+ security: [{ name: "Authorization", type: "apiKey" }],
821
+ url: "/public/v1/upload",
822
+ ...options,
823
+ headers: {
824
+ "Content-Type": null,
825
+ ...options.headers
826
+ }
827
+ });
828
+ var uploadFromUrl = (options) => (options.client ?? client).post({
829
+ security: [{ name: "Authorization", type: "apiKey" }],
830
+ url: "/public/v1/upload-from-url",
831
+ ...options,
832
+ headers: {
833
+ "Content-Type": "application/json",
834
+ ...options.headers
835
+ }
836
+ });
837
+ var findSlot = (options) => (options.client ?? client).get({
838
+ security: [{ name: "Authorization", type: "apiKey" }],
839
+ url: "/public/v1/find-slot/{id}",
840
+ ...options
841
+ });
842
+ var listPosts = (options) => (options.client ?? client).get({
843
+ security: [{ name: "Authorization", type: "apiKey" }],
844
+ url: "/public/v1/posts",
845
+ ...options
846
+ });
847
+ var createPost = (options) => (options.client ?? client).post({
848
+ security: [{ name: "Authorization", type: "apiKey" }],
849
+ url: "/public/v1/posts",
850
+ ...options,
851
+ headers: {
852
+ "Content-Type": "application/json",
853
+ ...options.headers
854
+ }
855
+ });
856
+ var deletePost = (options) => (options.client ?? client).delete({
857
+ security: [{ name: "Authorization", type: "apiKey" }],
858
+ url: "/public/v1/posts/{id}",
859
+ ...options
860
+ });
861
+ var deletePostGroup = (options) => (options.client ?? client).delete({
862
+ security: [{ name: "Authorization", type: "apiKey" }],
863
+ url: "/public/v1/posts/group/{group}",
864
+ ...options
865
+ });
866
+ var checkConnection = (options) => (options?.client ?? client).get({
867
+ security: [{ name: "Authorization", type: "apiKey" }],
868
+ url: "/public/v1/is-connected",
869
+ ...options
870
+ });
871
+ var listGroups = (options) => (options?.client ?? client).get({
872
+ security: [{ name: "Authorization", type: "apiKey" }],
873
+ url: "/public/v1/groups",
874
+ ...options
875
+ });
876
+ var listChannels = (options) => (options?.client ?? client).get({
877
+ security: [{ name: "Authorization", type: "apiKey" }],
878
+ url: "/public/v1/integrations",
879
+ ...options
880
+ });
881
+ var startChannelConnection = (options) => (options.client ?? client).get({
882
+ security: [{ name: "Authorization", type: "apiKey" }],
883
+ url: "/public/v1/social/{integration}",
884
+ ...options
885
+ });
886
+ var listNotifications = (options) => (options?.client ?? client).get({
887
+ security: [{ name: "Authorization", type: "apiKey" }],
888
+ url: "/public/v1/notifications",
889
+ ...options
890
+ });
891
+ var generateVideo = (options) => (options.client ?? client).post({
892
+ security: [{ name: "Authorization", type: "apiKey" }],
893
+ url: "/public/v1/generate-video",
894
+ ...options,
895
+ headers: {
896
+ "Content-Type": "application/json",
897
+ ...options.headers
898
+ }
899
+ });
900
+ var callVideoFunction = (options) => (options.client ?? client).post({
901
+ security: [{ name: "Authorization", type: "apiKey" }],
902
+ url: "/public/v1/video/function",
903
+ ...options,
904
+ headers: {
905
+ "Content-Type": "application/json",
906
+ ...options.headers
907
+ }
908
+ });
909
+ var deleteChannel = (options) => (options.client ?? client).delete({
910
+ security: [{ name: "Authorization", type: "apiKey" }],
911
+ url: "/public/v1/integrations/{id}",
912
+ ...options
913
+ });
914
+ var getChannelSettings = (options) => (options.client ?? client).get({
915
+ security: [{ name: "Authorization", type: "apiKey" }],
916
+ url: "/public/v1/integration-settings/{id}",
917
+ ...options
918
+ });
919
+ var listMissingMedia = (options) => (options.client ?? client).get({
920
+ security: [{ name: "Authorization", type: "apiKey" }],
921
+ url: "/public/v1/posts/{id}/missing",
922
+ ...options
923
+ });
924
+ var changePostStatus = (options) => (options.client ?? client).put({
925
+ security: [{ name: "Authorization", type: "apiKey" }],
926
+ url: "/public/v1/posts/{id}/status",
927
+ ...options,
928
+ headers: {
929
+ "Content-Type": "application/json",
930
+ ...options.headers
931
+ }
932
+ });
933
+ var setPostReleaseId = (options) => (options.client ?? client).put({
934
+ security: [{ name: "Authorization", type: "apiKey" }],
935
+ url: "/public/v1/posts/{id}/release-id",
936
+ ...options,
937
+ headers: {
938
+ "Content-Type": "application/json",
939
+ ...options.headers
940
+ }
941
+ });
942
+ var getChannelAnalytics = (options) => (options.client ?? client).get({
943
+ security: [{ name: "Authorization", type: "apiKey" }],
944
+ url: "/public/v1/analytics/{integration}",
945
+ ...options
946
+ });
947
+ var listVideoPerformance = (options) => (options.client ?? client).get({
948
+ security: [{ name: "Authorization", type: "apiKey" }],
949
+ url: "/public/v1/video-list/{integrationId}",
950
+ ...options
951
+ });
952
+ var getAccountHistory = (options) => (options.client ?? client).get({
953
+ security: [{ name: "Authorization", type: "apiKey" }],
954
+ url: "/public/v1/analytics-history/{integrationId}",
955
+ ...options
956
+ });
957
+ var getVideoHistory = (options) => (options.client ?? client).get({
958
+ security: [{ name: "Authorization", type: "apiKey" }],
959
+ url: "/public/v1/video-history/{integrationId}",
960
+ ...options
961
+ });
962
+ var getPostAnalytics = (options) => (options.client ?? client).get({
963
+ security: [{ name: "Authorization", type: "apiKey" }],
964
+ url: "/public/v1/analytics/post/{postId}",
965
+ ...options
966
+ });
967
+ var runChannelTool = (options) => (options.client ?? client).post({
968
+ security: [{ name: "Authorization", type: "apiKey" }],
969
+ url: "/public/v1/integration-trigger/{id}",
970
+ ...options,
971
+ headers: {
972
+ "Content-Type": "application/json",
973
+ ...options.headers
974
+ }
975
+ });
976
+ var listChannelMedia = (options) => (options.client ?? client).get({
977
+ security: [{ name: "Authorization", type: "apiKey" }],
978
+ url: "/public/v1/inbox/media/{integrationId}",
979
+ ...options
980
+ });
981
+ var listChannelStories = (options) => (options.client ?? client).get({
982
+ security: [{ name: "Authorization", type: "apiKey" }],
983
+ url: "/public/v1/inbox/stories/{integrationId}",
984
+ ...options
985
+ });
986
+ var listMediaComments = (options) => (options.client ?? client).get({
987
+ security: [{ name: "Authorization", type: "apiKey" }],
988
+ url: "/public/v1/inbox/comments/{integrationId}/{mediaId}",
989
+ ...options
990
+ });
991
+ var replyToComment = (options) => (options.client ?? client).post({
992
+ security: [{ name: "Authorization", type: "apiKey" }],
993
+ url: "/public/v1/inbox/comments/{commentId}/reply",
994
+ ...options,
995
+ headers: {
996
+ "Content-Type": "application/json",
997
+ ...options.headers
998
+ }
999
+ });
1000
+ var hideComment = (options) => (options.client ?? client).post({
1001
+ security: [{ name: "Authorization", type: "apiKey" }],
1002
+ url: "/public/v1/inbox/comments/{integrationId}/{commentId}/hide",
1003
+ ...options,
1004
+ headers: {
1005
+ "Content-Type": "application/json",
1006
+ ...options.headers
1007
+ }
1008
+ });
1009
+ var deleteComment = (options) => (options.client ?? client).delete({
1010
+ security: [{ name: "Authorization", type: "apiKey" }],
1011
+ url: "/public/v1/inbox/comments/{integrationId}/{commentId}",
1012
+ ...options
1013
+ });
1014
+ var listConversations = (options) => (options.client ?? client).get({
1015
+ security: [{ name: "Authorization", type: "apiKey" }],
1016
+ url: "/public/v1/inbox/{integrationId}",
1017
+ ...options
1018
+ });
1019
+ var sendDirectMessage = (options) => (options.client ?? client).post({
1020
+ security: [{ name: "Authorization", type: "apiKey" }],
1021
+ url: "/public/v1/inbox/{integrationId}/send",
1022
+ ...options,
1023
+ headers: {
1024
+ "Content-Type": "application/json",
1025
+ ...options.headers
1026
+ }
1027
+ });
1028
+ var pollInbox = (options) => (options.client ?? client).post({
1029
+ security: [{ name: "Authorization", type: "apiKey" }],
1030
+ url: "/public/v1/inbox/{integrationId}/poll",
1031
+ ...options
1032
+ });
1033
+ var subscribeInboxWebhook = (options) => (options.client ?? client).post({
1034
+ security: [{ name: "Authorization", type: "apiKey" }],
1035
+ url: "/public/v1/inbox/{integrationId}/subscribe-webhook",
1036
+ ...options
1037
+ });
1038
+ var getConversation = (options) => (options.client ?? client).get({
1039
+ security: [{ name: "Authorization", type: "apiKey" }],
1040
+ url: "/public/v1/inbox/{integrationId}/{conversationId}",
1041
+ ...options
1042
+ });
1043
+ var listAutomationFlows = (options) => (options?.client ?? client).get({
1044
+ security: [{ name: "Authorization", type: "apiKey" }],
1045
+ url: "/public/v1/automation-flows",
1046
+ ...options
1047
+ });
1048
+ var createAutomationFlow = (options) => (options.client ?? client).post({
1049
+ security: [{ name: "Authorization", type: "apiKey" }],
1050
+ url: "/public/v1/automation-flows",
1051
+ ...options,
1052
+ headers: {
1053
+ "Content-Type": "application/json",
1054
+ ...options.headers
1055
+ }
1056
+ });
1057
+ var previewAutomationEmail = (options) => (options.client ?? client).post({
1058
+ security: [{ name: "Authorization", type: "apiKey" }],
1059
+ url: "/public/v1/automation-flows/email-preview",
1060
+ ...options,
1061
+ headers: {
1062
+ "Content-Type": "application/json",
1063
+ ...options.headers
1064
+ }
1065
+ });
1066
+ var sendAutomationTestEmail = (options) => (options.client ?? client).post({
1067
+ security: [{ name: "Authorization", type: "apiKey" }],
1068
+ url: "/public/v1/automation-flows/email-test",
1069
+ ...options,
1070
+ headers: {
1071
+ "Content-Type": "application/json",
1072
+ ...options.headers
1073
+ }
1074
+ });
1075
+ var deleteAutomationFlow = (options) => (options.client ?? client).delete({
1076
+ security: [{ name: "Authorization", type: "apiKey" }],
1077
+ url: "/public/v1/automation-flows/{id}",
1078
+ ...options
1079
+ });
1080
+ var getAutomationFlow = (options) => (options.client ?? client).get({
1081
+ security: [{ name: "Authorization", type: "apiKey" }],
1082
+ url: "/public/v1/automation-flows/{id}",
1083
+ ...options
1084
+ });
1085
+ var updateAutomationFlow = (options) => (options.client ?? client).put({
1086
+ security: [{ name: "Authorization", type: "apiKey" }],
1087
+ url: "/public/v1/automation-flows/{id}",
1088
+ ...options,
1089
+ headers: {
1090
+ "Content-Type": "application/json",
1091
+ ...options.headers
1092
+ }
1093
+ });
1094
+ var setAutomationFlowStatus = (options) => (options.client ?? client).put({
1095
+ security: [{ name: "Authorization", type: "apiKey" }],
1096
+ url: "/public/v1/automation-flows/{id}/status",
1097
+ ...options,
1098
+ headers: {
1099
+ "Content-Type": "application/json",
1100
+ ...options.headers
1101
+ }
1102
+ });
1103
+ var listAutomationFlowPoses = (options) => (options.client ?? client).get({
1104
+ security: [{ name: "Authorization", type: "apiKey" }],
1105
+ url: "/public/v1/automation-flows/{id}/poses",
1106
+ ...options
1107
+ });
1108
+ var poseAutomationFlow = (options) => (options.client ?? client).post({
1109
+ security: [{ name: "Authorization", type: "apiKey" }],
1110
+ url: "/public/v1/automation-flows/{id}/poses",
1111
+ ...options,
1112
+ headers: {
1113
+ "Content-Type": "application/json",
1114
+ ...options.headers
1115
+ }
1116
+ });
1117
+ var listChannelAutomationPoses = (options) => (options.client ?? client).get({
1118
+ security: [{ name: "Authorization", type: "apiKey" }],
1119
+ url: "/public/v1/automation-flow-poses",
1120
+ ...options
1121
+ });
1122
+ var deleteAutomationPose = (options) => (options.client ?? client).delete({
1123
+ security: [{ name: "Authorization", type: "apiKey" }],
1124
+ url: "/public/v1/automation-flow-poses/{id}",
1125
+ ...options
1126
+ });
1127
+ var getAutomationPose = (options) => (options.client ?? client).get({
1128
+ security: [{ name: "Authorization", type: "apiKey" }],
1129
+ url: "/public/v1/automation-flow-poses/{id}",
1130
+ ...options
1131
+ });
1132
+ var updateAutomationPose = (options) => (options.client ?? client).put({
1133
+ security: [{ name: "Authorization", type: "apiKey" }],
1134
+ url: "/public/v1/automation-flow-poses/{id}",
1135
+ ...options,
1136
+ headers: {
1137
+ "Content-Type": "application/json",
1138
+ ...options.headers
1139
+ }
1140
+ });
1141
+ var listAutomationPoseRuns = (options) => (options.client ?? client).get({
1142
+ security: [{ name: "Authorization", type: "apiKey" }],
1143
+ url: "/public/v1/automation-flow-poses/{id}/runs",
1144
+ ...options
1145
+ });
1146
+ var pollAutomationPose = (options) => (options.client ?? client).post({
1147
+ security: [{ name: "Authorization", type: "apiKey" }],
1148
+ url: "/public/v1/automation-flow-poses/{id}/poll",
1149
+ ...options
1150
+ });
1151
+ var replayAutomationPose = (options) => (options.client ?? client).post({
1152
+ security: [{ name: "Authorization", type: "apiKey" }],
1153
+ url: "/public/v1/automation-flow-poses/{id}/replay",
1154
+ ...options,
1155
+ headers: {
1156
+ "Content-Type": "application/json",
1157
+ ...options.headers
1158
+ }
1159
+ });
1160
+ var listWebhookEvents = (options) => (options?.client ?? client).get({
1161
+ security: [{ name: "Authorization", type: "apiKey" }],
1162
+ url: "/public/v1/webhooks/events",
1163
+ ...options
1164
+ });
1165
+ var listWebhooks = (options) => (options?.client ?? client).get({
1166
+ security: [{ name: "Authorization", type: "apiKey" }],
1167
+ url: "/public/v1/webhooks",
1168
+ ...options
1169
+ });
1170
+ var createWebhook = (options) => (options.client ?? client).post({
1171
+ security: [{ name: "Authorization", type: "apiKey" }],
1172
+ url: "/public/v1/webhooks",
1173
+ ...options,
1174
+ headers: {
1175
+ "Content-Type": "application/json",
1176
+ ...options.headers
1177
+ }
1178
+ });
1179
+ var deleteWebhook = (options) => (options.client ?? client).delete({
1180
+ security: [{ name: "Authorization", type: "apiKey" }],
1181
+ url: "/public/v1/webhooks/{id}",
1182
+ ...options
1183
+ });
1184
+ var getWebhook = (options) => (options.client ?? client).get({
1185
+ security: [{ name: "Authorization", type: "apiKey" }],
1186
+ url: "/public/v1/webhooks/{id}",
1187
+ ...options
1188
+ });
1189
+ var testWebhook = (options) => (options.client ?? client).post({
1190
+ security: [{ name: "Authorization", type: "apiKey" }],
1191
+ url: "/public/v1/webhooks/{id}/test",
1192
+ ...options,
1193
+ headers: {
1194
+ "Content-Type": "application/json",
1195
+ ...options.headers
1196
+ }
1197
+ });
1198
+ var listContents = (options) => (options?.client ?? client).get({
1199
+ security: [{ name: "Authorization", type: "apiKey" }],
1200
+ url: "/public/v1/contents",
1201
+ ...options
1202
+ });
1203
+ var createContent = (options) => (options.client ?? client).post({
1204
+ security: [{ name: "Authorization", type: "apiKey" }],
1205
+ url: "/public/v1/contents",
1206
+ ...options,
1207
+ headers: {
1208
+ "Content-Type": "application/json",
1209
+ ...options.headers
1210
+ }
1211
+ });
1212
+ var getContentsPerformance = (options) => (options?.client ?? client).get({
1213
+ security: [{ name: "Authorization", type: "apiKey" }],
1214
+ url: "/public/v1/contents/performance",
1215
+ ...options
1216
+ });
1217
+ var deleteContent = (options) => (options.client ?? client).delete({
1218
+ security: [{ name: "Authorization", type: "apiKey" }],
1219
+ url: "/public/v1/contents/{id}",
1220
+ ...options
1221
+ });
1222
+ var getContent = (options) => (options.client ?? client).get({
1223
+ security: [{ name: "Authorization", type: "apiKey" }],
1224
+ url: "/public/v1/contents/{id}",
1225
+ ...options
1226
+ });
1227
+ var updateContent = (options) => (options.client ?? client).put({
1228
+ security: [{ name: "Authorization", type: "apiKey" }],
1229
+ url: "/public/v1/contents/{id}",
1230
+ ...options,
1231
+ headers: {
1232
+ "Content-Type": "application/json",
1233
+ ...options.headers
1234
+ }
1235
+ });
1236
+ var upsertContent = (options) => (options.client ?? client).post({
1237
+ security: [{ name: "Authorization", type: "apiKey" }],
1238
+ url: "/public/v1/contents/upsert",
1239
+ ...options,
1240
+ headers: {
1241
+ "Content-Type": "application/json",
1242
+ ...options.headers
1243
+ }
1244
+ });
1245
+ var moveContent = (options) => (options.client ?? client).put({
1246
+ security: [{ name: "Authorization", type: "apiKey" }],
1247
+ url: "/public/v1/contents/{id}/move",
1248
+ ...options,
1249
+ headers: {
1250
+ "Content-Type": "application/json",
1251
+ ...options.headers
1252
+ }
1253
+ });
1254
+ var linkContentPost = (options) => (options.client ?? client).put({
1255
+ security: [{ name: "Authorization", type: "apiKey" }],
1256
+ url: "/public/v1/contents/{id}/post",
1257
+ ...options,
1258
+ headers: {
1259
+ "Content-Type": "application/json",
1260
+ ...options.headers
1261
+ }
1262
+ });
1263
+ var searchHooks = (options) => (options?.client ?? client).get({
1264
+ security: [{ name: "Authorization", type: "apiKey" }],
1265
+ url: "/public/v1/hooks",
1266
+ ...options
1267
+ });
1268
+ var getHookForms = (options) => (options?.client ?? client).get({
1269
+ security: [{ name: "Authorization", type: "apiKey" }],
1270
+ url: "/public/v1/hooks/forms",
1271
+ ...options
1272
+ });
1273
+ var listHookFamilies = (options) => (options?.client ?? client).get({
1274
+ security: [{ name: "Authorization", type: "apiKey" }],
1275
+ url: "/public/v1/hooks/families",
1276
+ ...options
1277
+ });
1278
+ var replaceHookFamilies = (options) => (options.client ?? client).put({
1279
+ security: [{ name: "Authorization", type: "apiKey" }],
1280
+ url: "/public/v1/hooks/families",
1281
+ ...options,
1282
+ headers: {
1283
+ "Content-Type": "application/json",
1284
+ ...options.headers
1285
+ }
1286
+ });
1287
+ var importHooks = (options) => (options.client ?? client).post({
1288
+ security: [{ name: "Authorization", type: "apiKey" }],
1289
+ url: "/public/v1/hooks/import",
1290
+ ...options,
1291
+ headers: {
1292
+ "Content-Type": "application/json",
1293
+ ...options.headers
1294
+ }
1295
+ });
1296
+ var listMusic = (options) => (options?.client ?? client).get({
1297
+ security: [{ name: "Authorization", type: "apiKey" }],
1298
+ url: "/public/v1/music",
1299
+ ...options
1300
+ });
1301
+ var listMusicPillars = (options) => (options?.client ?? client).get({
1302
+ security: [{ name: "Authorization", type: "apiKey" }],
1303
+ url: "/public/v1/music/pillars",
1304
+ ...options
1305
+ });
1306
+ var getMusicTrack = (options) => (options.client ?? client).get({
1307
+ security: [{ name: "Authorization", type: "apiKey" }],
1308
+ url: "/public/v1/music/{slug}",
1309
+ ...options
1310
+ });
1311
+ var importMusic = (options) => (options.client ?? client).post({
1312
+ security: [{ name: "Authorization", type: "apiKey" }],
1313
+ url: "/public/v1/music/import",
1314
+ ...options,
1315
+ headers: {
1316
+ "Content-Type": "application/json",
1317
+ ...options.headers
1318
+ }
1319
+ });
1320
+ var uploadMusicFile = (options) => (options.client ?? client).put({
1321
+ ...formDataBodySerializer,
1322
+ security: [{ name: "Authorization", type: "apiKey" }],
1323
+ url: "/public/v1/music/{slug}/file",
1324
+ ...options,
1325
+ headers: {
1326
+ "Content-Type": null,
1327
+ ...options.headers
1328
+ }
1329
+ });
1330
+
1331
+ // src/index.ts
1332
+ var DEFAULT_BASE_URL = "https://app.usenadia.com/api";
1333
+ var NadiaError = class _NadiaError extends Error {
1334
+ status;
1335
+ body;
1336
+ constructor(status, body, message) {
1337
+ super(message ?? `UseNadia API responded ${status}`);
1338
+ this.name = "NadiaError";
1339
+ this.status = status;
1340
+ this.body = body;
1341
+ Object.setPrototypeOf(this, _NadiaError.prototype);
1342
+ }
1343
+ /**
1344
+ * True when retrying later could plausibly work: a rate limit, a server
1345
+ * hiccup, or a request that never completed at all (status 0).
1346
+ */
1347
+ get isTransient() {
1348
+ return this.status === 0 || this.status === 429 || this.status >= 500;
1349
+ }
1350
+ };
1351
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1352
+ var messageOf = (body) => {
1353
+ if (!body || typeof body !== "object") return void 0;
1354
+ const { msg, message } = body;
1355
+ if (typeof msg === "string") return msg;
1356
+ if (typeof message === "string") return message;
1357
+ if (Array.isArray(message) && message.length && message.every((m) => typeof m === "string")) {
1358
+ return message.join("; ");
1359
+ }
1360
+ return void 0;
1361
+ };
1362
+ var Nadia = class {
1363
+ client;
1364
+ retries;
1365
+ constructor(apiKey, options = {}) {
1366
+ if (!apiKey) {
1367
+ throw new Error("An API key is required.");
1368
+ }
1369
+ const opts = typeof options === "string" ? { baseUrl: options } : options;
1370
+ this.retries = opts.retries ?? 2;
1371
+ this.client = client;
1372
+ this.client.setConfig({
1373
+ baseUrl: opts.baseUrl ?? DEFAULT_BASE_URL,
1374
+ headers: { Authorization: apiKey },
1375
+ ...opts.fetch ? { fetch: opts.fetch } : {}
1376
+ });
1377
+ }
1378
+ /**
1379
+ * Runs a generated operation, turns a non-2xx into a `NadiaError`, and
1380
+ * retries the transient ones. Every method below goes through here — that is
1381
+ * the whole point of the facade.
1382
+ */
1383
+ async call(operation) {
1384
+ let lastError;
1385
+ for (let attempt = 0; attempt <= this.retries; attempt++) {
1386
+ const { data, error, response } = await operation({ client: this.client });
1387
+ if (!response) {
1388
+ lastError = new NadiaError(0, error, "The request did not complete.");
1389
+ } else if (response.ok) {
1390
+ return data;
1391
+ } else {
1392
+ lastError = new NadiaError(response.status, error, messageOf(error));
1393
+ }
1394
+ if (!lastError.isTransient || attempt === this.retries) {
1395
+ throw lastError;
1396
+ }
1397
+ await sleep(2 ** attempt * 500);
1398
+ }
1399
+ throw lastError;
1400
+ }
1401
+ /* --------------------------------------------------------------- *
1402
+ * The five calls upstream had, same names, same shape
1403
+ * --------------------------------------------------------------- */
1404
+ /** Schedule, publish or draft a post on one or more channels. */
1405
+ post(body) {
1406
+ return this.call(
1407
+ (o) => createPost({ ...o, body })
1408
+ );
1409
+ }
1410
+ /** List posts in a date range. */
1411
+ postList(query) {
1412
+ return this.call(
1413
+ (o) => listPosts({ ...o, query })
1414
+ );
1415
+ }
1416
+ /** Upload a file and get a URL usable in a post. */
1417
+ upload(file, filename = "upload") {
1418
+ const form = new FormData();
1419
+ form.append("file", file, filename);
1420
+ return this.call(
1421
+ (o) => uploadFile({
1422
+ ...o,
1423
+ body: form,
1424
+ bodySerializer: (body) => body
1425
+ })
1426
+ );
1427
+ }
1428
+ /** List your connected channels. */
1429
+ integrations() {
1430
+ return this.call((o) => listChannels(o));
1431
+ }
1432
+ /** Delete a post and everything published with it. */
1433
+ deletePost(id) {
1434
+ return this.call(
1435
+ (o) => deletePost({ ...o, path: { id } })
1436
+ );
1437
+ }
1438
+ /* --------------------------------------------------------------- *
1439
+ * The rest of our surface, which upstream never had
1440
+ * --------------------------------------------------------------- */
1441
+ /** Check that the API key is valid. Throws `NadiaError` with status 401 if not. */
1442
+ async isConnected() {
1443
+ await this.call((o) => checkConnection(o));
1444
+ return true;
1445
+ }
1446
+ /** Next free slot in a channel's schedule. */
1447
+ findSlot(integrationId) {
1448
+ return this.call(
1449
+ (o) => findSlot({
1450
+ ...o,
1451
+ path: { id: integrationId }
1452
+ })
1453
+ );
1454
+ }
1455
+ /** List your groups (brands). */
1456
+ groups() {
1457
+ return this.call((o) => listGroups(o));
1458
+ }
1459
+ /** Direct message conversations of a channel. */
1460
+ inbox(integrationId, limit) {
1461
+ return this.call(
1462
+ (o) => listConversations({
1463
+ ...o,
1464
+ path: { integrationId },
1465
+ query: limit ? { limit: String(limit) } : void 0
1466
+ })
1467
+ );
1468
+ }
1469
+ /* --------------------------------------------------------------- *
1470
+ * The content board: one card per video, from the idea to the
1471
+ * numbers after publication
1472
+ * --------------------------------------------------------------- */
1473
+ /**
1474
+ * The cards of the board, with the posts scheduled from each. Filters
1475
+ * combine: `stage`, `tag`, `externalId`; `fields` (`'id,title,stage'`)
1476
+ * leaves the scripts out.
1477
+ */
1478
+ contents(query) {
1479
+ return this.call((o) => listContents({ ...o, query }));
1480
+ }
1481
+ /** One card. */
1482
+ content(id) {
1483
+ return this.call((o) => getContent({ ...o, path: { id } }));
1484
+ }
1485
+ /** Create a card — in IDEA unless `stage` says otherwise. */
1486
+ createContent(body) {
1487
+ return this.call((o) => createContent({ ...o, body }));
1488
+ }
1489
+ /**
1490
+ * Create or update the card holding `externalId` (your own id: a script
1491
+ * file path, a build id). Re-running an import never duplicates; an
1492
+ * existing card keeps its column.
1493
+ */
1494
+ upsertContent(body) {
1495
+ return this.call((o) => upsertContent({ ...o, body }));
1496
+ }
1497
+ /** Update a card: only the fields sent change, `null` clears one. */
1498
+ updateContent(id, body) {
1499
+ return this.call((o) => updateContent({ ...o, path: { id }, body }));
1500
+ }
1501
+ /** Move a card to another column (to the bottom unless `position` is given). */
1502
+ moveContent(id, stage, position) {
1503
+ return this.call(
1504
+ (o) => moveContent({
1505
+ ...o,
1506
+ path: { id },
1507
+ body: position === void 0 ? { stage } : { stage, position }
1508
+ })
1509
+ );
1510
+ }
1511
+ /**
1512
+ * Tie a card to a post scheduled from it — the `group` passed on
1513
+ * {@link Nadia.post}. A card holds several posts (a TikTok draft, an
1514
+ * Instagram post): each call adds one. The card moves to PUBLISHED when
1515
+ * the first of them goes live.
1516
+ */
1517
+ linkContentPost(id, postGroup) {
1518
+ return this.call(
1519
+ (o) => linkContentPost({ ...o, path: { id }, body: { postGroup } })
1520
+ );
1521
+ }
1522
+ /** Delete a card. */
1523
+ deleteContent(id) {
1524
+ return this.call((o) => deleteContent({ ...o, path: { id } }));
1525
+ }
1526
+ /** The numbers of the published cards, keyed by card id. */
1527
+ contentsPerformance() {
1528
+ return this.call((o) => getContentsPerformance(o));
1529
+ }
1530
+ /**
1531
+ * Runs any generated operation with the facade's guarantees — a non-2xx
1532
+ * throws a `NadiaError`, the transient ones are retried. The way to reach
1533
+ * what the facade does not sugar without giving those up.
1534
+ *
1535
+ * import { getChannelAnalytics } from '@usenadia/node';
1536
+ * await nadia.request((o) =>
1537
+ * getChannelAnalytics({ ...o, path: { integration: id }, query: { date: '7' } })
1538
+ * );
1539
+ */
1540
+ request(operation) {
1541
+ return this.call(operation);
1542
+ }
1543
+ /**
1544
+ * The generated client, configured with your key. Use it for any of the
1545
+ * operations the facade does not wrap — nothing here is a dead end.
1546
+ *
1547
+ * import { getChannelAnalytics } from '@usenadia/node';
1548
+ * await getChannelAnalytics({ client: nadia.raw, path: {...} });
1549
+ */
1550
+ get raw() {
1551
+ return this.client;
1552
+ }
1553
+ };
1554
+ var index_default = Nadia;
1555
+ var NadiaWebhookError = class _NadiaWebhookError extends Error {
1556
+ reason;
1557
+ constructor(reason, message) {
1558
+ super(message);
1559
+ this.name = "NadiaWebhookError";
1560
+ this.reason = reason;
1561
+ Object.setPrototypeOf(this, _NadiaWebhookError.prototype);
1562
+ }
1563
+ };
1564
+ function checkSignature(o) {
1565
+ const { secret, signature, timestamp, body } = o;
1566
+ if (!signature || timestamp === null || timestamp === void 0 || timestamp === "") {
1567
+ return { ok: false, reason: "missing_header", message: "X-Nadia-Signature or X-Nadia-Timestamp is missing." };
1568
+ }
1569
+ const ts = String(timestamp);
1570
+ if (o.tolerance !== void 0) {
1571
+ const seconds = Number(ts);
1572
+ const now = (o.now ?? Date.now()) / 1e3;
1573
+ if (!Number.isFinite(seconds) || Math.abs(now - seconds) > o.tolerance) {
1574
+ return { ok: false, reason: "stale", message: `Timestamp outside the ${o.tolerance}s tolerance.` };
1575
+ }
1576
+ }
1577
+ const expected = Buffer.from(
1578
+ "sha256=" + createHmac("sha256", secret).update(`${ts}.`).update(body).digest("hex")
1579
+ );
1580
+ const received = Buffer.from(signature);
1581
+ if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
1582
+ return { ok: false, reason: "bad_signature", message: "Signature does not match." };
1583
+ }
1584
+ return { ok: true };
1585
+ }
1586
+ function verifyWebhookSignature(options) {
1587
+ return checkSignature(options).ok;
1588
+ }
1589
+ function parseWebhook(options) {
1590
+ const header = (name) => {
1591
+ const h = options.headers;
1592
+ if (typeof h.get === "function") return h.get(name) ?? void 0;
1593
+ const record = h;
1594
+ const key = Object.keys(record).find((k) => k.toLowerCase() === name.toLowerCase());
1595
+ const value = key === void 0 ? void 0 : record[key];
1596
+ return Array.isArray(value) ? value[0] : value;
1597
+ };
1598
+ const check = checkSignature({
1599
+ secret: options.secret,
1600
+ signature: header("X-Nadia-Signature"),
1601
+ timestamp: header("X-Nadia-Timestamp"),
1602
+ body: options.body,
1603
+ tolerance: options.tolerance ?? 300,
1604
+ now: options.now
1605
+ });
1606
+ if (!check.ok) throw new NadiaWebhookError(check.reason, check.message);
1607
+ try {
1608
+ const text = typeof options.body === "string" ? options.body : new TextDecoder().decode(options.body);
1609
+ return JSON.parse(text);
1610
+ } catch {
1611
+ throw new NadiaWebhookError("bad_body", "The body is not JSON.");
1612
+ }
1613
+ }
1614
+ export {
1615
+ DEFAULT_BASE_URL,
1616
+ Nadia,
1617
+ NadiaError,
1618
+ NadiaWebhookError,
1619
+ callVideoFunction,
1620
+ changePostStatus,
1621
+ checkConnection,
1622
+ createAutomationFlow,
1623
+ createContent,
1624
+ createPost,
1625
+ createWebhook,
1626
+ index_default as default,
1627
+ deleteAutomationFlow,
1628
+ deleteAutomationPose,
1629
+ deleteChannel,
1630
+ deleteComment,
1631
+ deleteContent,
1632
+ deletePost,
1633
+ deletePostGroup,
1634
+ deleteWebhook,
1635
+ findSlot,
1636
+ generateVideo,
1637
+ getAccountHistory,
1638
+ getAutomationFlow,
1639
+ getAutomationPose,
1640
+ getChannelAnalytics,
1641
+ getChannelSettings,
1642
+ getContent,
1643
+ getContentsPerformance,
1644
+ getConversation,
1645
+ getHookForms,
1646
+ getMusicTrack,
1647
+ getPostAnalytics,
1648
+ getVideoHistory,
1649
+ getWebhook,
1650
+ hideComment,
1651
+ importHooks,
1652
+ importMusic,
1653
+ linkContentPost,
1654
+ listAutomationFlowPoses,
1655
+ listAutomationFlows,
1656
+ listAutomationPoseRuns,
1657
+ listChannelAutomationPoses,
1658
+ listChannelMedia,
1659
+ listChannelStories,
1660
+ listChannels,
1661
+ listContents,
1662
+ listConversations,
1663
+ listGroups,
1664
+ listHookFamilies,
1665
+ listMediaComments,
1666
+ listMissingMedia,
1667
+ listMusic,
1668
+ listMusicPillars,
1669
+ listNotifications,
1670
+ listPosts,
1671
+ listVideoPerformance,
1672
+ listWebhookEvents,
1673
+ listWebhooks,
1674
+ moveContent,
1675
+ parseWebhook,
1676
+ pollAutomationPose,
1677
+ pollInbox,
1678
+ poseAutomationFlow,
1679
+ previewAutomationEmail,
1680
+ replaceHookFamilies,
1681
+ replayAutomationPose,
1682
+ replyToComment,
1683
+ runChannelTool,
1684
+ searchHooks,
1685
+ sendAutomationTestEmail,
1686
+ sendDirectMessage,
1687
+ setAutomationFlowStatus,
1688
+ setPostReleaseId,
1689
+ startChannelConnection,
1690
+ subscribeInboxWebhook,
1691
+ testWebhook,
1692
+ updateAutomationFlow,
1693
+ updateAutomationPose,
1694
+ updateContent,
1695
+ uploadFile,
1696
+ uploadFromUrl,
1697
+ uploadMusicFile,
1698
+ upsertContent,
1699
+ verifyWebhookSignature
1700
+ };
1701
+ //# sourceMappingURL=index.mjs.map