@sinnu-dev/sdk 0.0.0-stage → 0.2.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.js ADDED
@@ -0,0 +1,850 @@
1
+ // node_modules/openapi-fetch/dist/index.js
2
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
3
+ var supportsRequestInitExt = () => {
4
+ return typeof process === "object" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;
5
+ };
6
+ function randomID() {
7
+ return Math.random().toString(36).slice(2, 11);
8
+ }
9
+ function createClient(clientOptions) {
10
+ let {
11
+ baseUrl = "",
12
+ Request: CustomRequest = globalThis.Request,
13
+ fetch: baseFetch = globalThis.fetch,
14
+ querySerializer: globalQuerySerializer,
15
+ bodySerializer: globalBodySerializer,
16
+ headers: baseHeaders,
17
+ requestInitExt = void 0,
18
+ ...baseOptions
19
+ } = { ...clientOptions };
20
+ requestInitExt = supportsRequestInitExt() ? requestInitExt : void 0;
21
+ baseUrl = removeTrailingSlash(baseUrl);
22
+ const middlewares = [];
23
+ async function coreFetch(schemaPath, fetchOptions) {
24
+ const {
25
+ baseUrl: localBaseUrl,
26
+ fetch: fetch2 = baseFetch,
27
+ Request = CustomRequest,
28
+ headers,
29
+ params = {},
30
+ parseAs = "json",
31
+ querySerializer: requestQuerySerializer,
32
+ bodySerializer = globalBodySerializer ?? defaultBodySerializer,
33
+ body,
34
+ ...init
35
+ } = fetchOptions || {};
36
+ let finalBaseUrl = baseUrl;
37
+ if (localBaseUrl) {
38
+ finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;
39
+ }
40
+ let querySerializer = typeof globalQuerySerializer === "function" ? globalQuerySerializer : createQuerySerializer(globalQuerySerializer);
41
+ if (requestQuerySerializer) {
42
+ querySerializer = typeof requestQuerySerializer === "function" ? requestQuerySerializer : createQuerySerializer({
43
+ ...typeof globalQuerySerializer === "object" ? globalQuerySerializer : {},
44
+ ...requestQuerySerializer
45
+ });
46
+ }
47
+ const serializedBody = body === void 0 ? void 0 : bodySerializer(
48
+ body,
49
+ // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:
50
+ // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,
51
+ // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,
52
+ // setting the content-type at the very beginning to be overwritten.
53
+ // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.
54
+ mergeHeaders(baseHeaders, headers, params.header)
55
+ );
56
+ const finalHeaders = mergeHeaders(
57
+ // with no body, we should not to set Content-Type
58
+ serializedBody === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
59
+ serializedBody instanceof FormData ? {} : {
60
+ "Content-Type": "application/json"
61
+ },
62
+ baseHeaders,
63
+ headers,
64
+ params.header
65
+ );
66
+ const requestInit = {
67
+ redirect: "follow",
68
+ ...baseOptions,
69
+ ...init,
70
+ body: serializedBody,
71
+ headers: finalHeaders
72
+ };
73
+ let id;
74
+ let options;
75
+ let request = new CustomRequest(
76
+ createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer }),
77
+ requestInit
78
+ );
79
+ let response;
80
+ for (const key in init) {
81
+ if (!(key in request)) {
82
+ request[key] = init[key];
83
+ }
84
+ }
85
+ if (middlewares.length) {
86
+ id = randomID();
87
+ options = Object.freeze({
88
+ baseUrl: finalBaseUrl,
89
+ fetch: fetch2,
90
+ parseAs,
91
+ querySerializer,
92
+ bodySerializer
93
+ });
94
+ for (const m of middlewares) {
95
+ if (m && typeof m === "object" && typeof m.onRequest === "function") {
96
+ const result = await m.onRequest({
97
+ request,
98
+ schemaPath,
99
+ params,
100
+ options,
101
+ id
102
+ });
103
+ if (result) {
104
+ if (result instanceof CustomRequest) {
105
+ request = result;
106
+ } else if (result instanceof Response) {
107
+ response = result;
108
+ break;
109
+ } else {
110
+ throw new Error("onRequest: must return new Request() or Response() when modifying the request");
111
+ }
112
+ }
113
+ }
114
+ }
115
+ }
116
+ if (!response) {
117
+ try {
118
+ response = await fetch2(request, requestInitExt);
119
+ } catch (error2) {
120
+ let errorAfterMiddleware = error2;
121
+ if (middlewares.length) {
122
+ for (let i = middlewares.length - 1; i >= 0; i--) {
123
+ const m = middlewares[i];
124
+ if (m && typeof m === "object" && typeof m.onError === "function") {
125
+ const result = await m.onError({
126
+ request,
127
+ error: errorAfterMiddleware,
128
+ schemaPath,
129
+ params,
130
+ options,
131
+ id
132
+ });
133
+ if (result) {
134
+ if (result instanceof Response) {
135
+ errorAfterMiddleware = void 0;
136
+ response = result;
137
+ break;
138
+ }
139
+ if (result instanceof Error) {
140
+ errorAfterMiddleware = result;
141
+ continue;
142
+ }
143
+ throw new Error("onError: must return new Response() or instance of Error");
144
+ }
145
+ }
146
+ }
147
+ }
148
+ if (errorAfterMiddleware) {
149
+ throw errorAfterMiddleware;
150
+ }
151
+ }
152
+ if (middlewares.length) {
153
+ for (let i = middlewares.length - 1; i >= 0; i--) {
154
+ const m = middlewares[i];
155
+ if (m && typeof m === "object" && typeof m.onResponse === "function") {
156
+ const result = await m.onResponse({
157
+ request,
158
+ response,
159
+ schemaPath,
160
+ params,
161
+ options,
162
+ id
163
+ });
164
+ if (result) {
165
+ if (!(result instanceof Response)) {
166
+ throw new Error("onResponse: must return new Response() when modifying the response");
167
+ }
168
+ response = result;
169
+ }
170
+ }
171
+ }
172
+ }
173
+ }
174
+ if (response.status === 204 || request.method === "HEAD" || response.headers.get("Content-Length") === "0") {
175
+ return response.ok ? { data: void 0, response } : { error: void 0, response };
176
+ }
177
+ if (response.ok) {
178
+ if (parseAs === "stream") {
179
+ return { data: response.body, response };
180
+ }
181
+ return { data: await response[parseAs](), response };
182
+ }
183
+ let error = await response.text();
184
+ try {
185
+ error = JSON.parse(error);
186
+ } catch {
187
+ }
188
+ return { error, response };
189
+ }
190
+ return {
191
+ request(method, url, init) {
192
+ return coreFetch(url, { ...init, method: method.toUpperCase() });
193
+ },
194
+ /** Call a GET endpoint */
195
+ GET(url, init) {
196
+ return coreFetch(url, { ...init, method: "GET" });
197
+ },
198
+ /** Call a PUT endpoint */
199
+ PUT(url, init) {
200
+ return coreFetch(url, { ...init, method: "PUT" });
201
+ },
202
+ /** Call a POST endpoint */
203
+ POST(url, init) {
204
+ return coreFetch(url, { ...init, method: "POST" });
205
+ },
206
+ /** Call a DELETE endpoint */
207
+ DELETE(url, init) {
208
+ return coreFetch(url, { ...init, method: "DELETE" });
209
+ },
210
+ /** Call a OPTIONS endpoint */
211
+ OPTIONS(url, init) {
212
+ return coreFetch(url, { ...init, method: "OPTIONS" });
213
+ },
214
+ /** Call a HEAD endpoint */
215
+ HEAD(url, init) {
216
+ return coreFetch(url, { ...init, method: "HEAD" });
217
+ },
218
+ /** Call a PATCH endpoint */
219
+ PATCH(url, init) {
220
+ return coreFetch(url, { ...init, method: "PATCH" });
221
+ },
222
+ /** Call a TRACE endpoint */
223
+ TRACE(url, init) {
224
+ return coreFetch(url, { ...init, method: "TRACE" });
225
+ },
226
+ /** Register middleware */
227
+ use(...middleware) {
228
+ for (const m of middleware) {
229
+ if (!m) {
230
+ continue;
231
+ }
232
+ if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) {
233
+ throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
234
+ }
235
+ middlewares.push(m);
236
+ }
237
+ },
238
+ /** Unregister middleware */
239
+ eject(...middleware) {
240
+ for (const m of middleware) {
241
+ const i = middlewares.indexOf(m);
242
+ if (i !== -1) {
243
+ middlewares.splice(i, 1);
244
+ }
245
+ }
246
+ }
247
+ };
248
+ }
249
+ function serializePrimitiveParam(name, value, options) {
250
+ if (value === void 0 || value === null) {
251
+ return "";
252
+ }
253
+ if (typeof value === "object") {
254
+ throw new Error(
255
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
256
+ );
257
+ }
258
+ return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
259
+ }
260
+ function serializeObjectParam(name, value, options) {
261
+ if (!value || typeof value !== "object") {
262
+ return "";
263
+ }
264
+ const values = [];
265
+ const joiner = {
266
+ simple: ",",
267
+ label: ".",
268
+ matrix: ";"
269
+ }[options.style] || "&";
270
+ if (options.style !== "deepObject" && options.explode === false) {
271
+ for (const k in value) {
272
+ values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));
273
+ }
274
+ const final2 = values.join(",");
275
+ switch (options.style) {
276
+ case "form": {
277
+ return `${name}=${final2}`;
278
+ }
279
+ case "label": {
280
+ return `.${final2}`;
281
+ }
282
+ case "matrix": {
283
+ return `;${name}=${final2}`;
284
+ }
285
+ default: {
286
+ return final2;
287
+ }
288
+ }
289
+ }
290
+ for (const k in value) {
291
+ const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
292
+ values.push(serializePrimitiveParam(finalName, value[k], options));
293
+ }
294
+ const final = values.join(joiner);
295
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
296
+ }
297
+ function serializeArrayParam(name, value, options) {
298
+ if (!Array.isArray(value)) {
299
+ return "";
300
+ }
301
+ if (options.explode === false) {
302
+ const joiner2 = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[options.style] || ",";
303
+ const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner2);
304
+ switch (options.style) {
305
+ case "simple": {
306
+ return final;
307
+ }
308
+ case "label": {
309
+ return `.${final}`;
310
+ }
311
+ case "matrix": {
312
+ return `;${name}=${final}`;
313
+ }
314
+ // case "spaceDelimited":
315
+ // case "pipeDelimited":
316
+ default: {
317
+ return `${name}=${final}`;
318
+ }
319
+ }
320
+ }
321
+ const joiner = { simple: ",", label: ".", matrix: ";" }[options.style] || "&";
322
+ const values = [];
323
+ for (const v of value) {
324
+ if (options.style === "simple" || options.style === "label") {
325
+ values.push(options.allowReserved === true ? v : encodeURIComponent(v));
326
+ } else {
327
+ values.push(serializePrimitiveParam(name, v, options));
328
+ }
329
+ }
330
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${values.join(joiner)}` : values.join(joiner);
331
+ }
332
+ function createQuerySerializer(options) {
333
+ return function querySerializer(queryParams) {
334
+ const search = [];
335
+ if (queryParams && typeof queryParams === "object") {
336
+ for (const name in queryParams) {
337
+ const value = queryParams[name];
338
+ if (value === void 0 || value === null) {
339
+ continue;
340
+ }
341
+ if (Array.isArray(value)) {
342
+ if (value.length === 0) {
343
+ continue;
344
+ }
345
+ search.push(
346
+ serializeArrayParam(name, value, {
347
+ style: "form",
348
+ explode: true,
349
+ ...options?.array,
350
+ allowReserved: options?.allowReserved || false
351
+ })
352
+ );
353
+ continue;
354
+ }
355
+ if (typeof value === "object") {
356
+ search.push(
357
+ serializeObjectParam(name, value, {
358
+ style: "deepObject",
359
+ explode: true,
360
+ ...options?.object,
361
+ allowReserved: options?.allowReserved || false
362
+ })
363
+ );
364
+ continue;
365
+ }
366
+ search.push(serializePrimitiveParam(name, value, options));
367
+ }
368
+ }
369
+ return search.join("&");
370
+ };
371
+ }
372
+ function defaultPathSerializer(pathname, pathParams) {
373
+ let nextURL = pathname;
374
+ for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
375
+ let name = match.substring(1, match.length - 1);
376
+ let explode = false;
377
+ let style = "simple";
378
+ if (name.endsWith("*")) {
379
+ explode = true;
380
+ name = name.substring(0, name.length - 1);
381
+ }
382
+ if (name.startsWith(".")) {
383
+ style = "label";
384
+ name = name.substring(1);
385
+ } else if (name.startsWith(";")) {
386
+ style = "matrix";
387
+ name = name.substring(1);
388
+ }
389
+ if (!pathParams || pathParams[name] === void 0 || pathParams[name] === null) {
390
+ continue;
391
+ }
392
+ const value = pathParams[name];
393
+ if (Array.isArray(value)) {
394
+ nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));
395
+ continue;
396
+ }
397
+ if (typeof value === "object") {
398
+ nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));
399
+ continue;
400
+ }
401
+ if (style === "matrix") {
402
+ nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
403
+ continue;
404
+ }
405
+ nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
406
+ }
407
+ return nextURL;
408
+ }
409
+ function defaultBodySerializer(body, headers) {
410
+ if (body instanceof FormData) {
411
+ return body;
412
+ }
413
+ if (headers) {
414
+ const contentType = headers.get instanceof Function ? headers.get("Content-Type") ?? headers.get("content-type") : headers["Content-Type"] ?? headers["content-type"];
415
+ if (contentType === "application/x-www-form-urlencoded") {
416
+ return new URLSearchParams(body).toString();
417
+ }
418
+ }
419
+ return JSON.stringify(body);
420
+ }
421
+ function createFinalURL(pathname, options) {
422
+ let finalURL = `${options.baseUrl}${pathname}`;
423
+ if (options.params?.path) {
424
+ finalURL = defaultPathSerializer(finalURL, options.params.path);
425
+ }
426
+ let search = options.querySerializer(options.params.query ?? {});
427
+ if (search.startsWith("?")) {
428
+ search = search.substring(1);
429
+ }
430
+ if (search) {
431
+ finalURL += `?${search}`;
432
+ }
433
+ return finalURL;
434
+ }
435
+ function mergeHeaders(...allHeaders) {
436
+ const finalHeaders = new Headers();
437
+ for (const h of allHeaders) {
438
+ if (!h || typeof h !== "object") {
439
+ continue;
440
+ }
441
+ const iterator = h instanceof Headers ? h.entries() : Object.entries(h);
442
+ for (const [k, v] of iterator) {
443
+ if (v === null) {
444
+ finalHeaders.delete(k);
445
+ } else if (Array.isArray(v)) {
446
+ for (const v2 of v) {
447
+ finalHeaders.append(k, v2);
448
+ }
449
+ } else if (v !== void 0) {
450
+ finalHeaders.set(k, v);
451
+ }
452
+ }
453
+ }
454
+ return finalHeaders;
455
+ }
456
+ function removeTrailingSlash(url) {
457
+ if (url.endsWith("/")) {
458
+ return url.substring(0, url.length - 1);
459
+ }
460
+ return url;
461
+ }
462
+
463
+ // src/errors.ts
464
+ var SinnuError = class extends Error {
465
+ constructor(message, statusCode, body, response) {
466
+ super(message);
467
+ this.name = "SinnuError";
468
+ this.statusCode = statusCode;
469
+ this.body = body;
470
+ this.response = response;
471
+ }
472
+ };
473
+ var SinnuAuthError = class extends SinnuError {
474
+ constructor(message, statusCode = 401, body, response) {
475
+ super(message, statusCode, body, response);
476
+ this.name = "SinnuAuthError";
477
+ }
478
+ };
479
+ var SinnuNotFoundError = class extends SinnuError {
480
+ constructor(message, body, response) {
481
+ super(message, 404, body, response);
482
+ this.name = "SinnuNotFoundError";
483
+ }
484
+ };
485
+ var SinnuValidationError = class extends SinnuError {
486
+ constructor(message, statusCode, body, response) {
487
+ super(message, statusCode, body, response);
488
+ this.name = "SinnuValidationError";
489
+ }
490
+ };
491
+ var SinnuRateLimitError = class extends SinnuError {
492
+ constructor(message, body, response) {
493
+ super(message, 429, body, response);
494
+ this.name = "SinnuRateLimitError";
495
+ }
496
+ };
497
+ function toSinnuError(statusCode, body, response) {
498
+ const message = body?.message ?? `Requisi\xE7\xE3o falhou com status ${statusCode}`;
499
+ switch (statusCode) {
500
+ case 401:
501
+ case 403:
502
+ return new SinnuAuthError(message, statusCode, body, response);
503
+ case 404:
504
+ return new SinnuNotFoundError(message, body, response);
505
+ case 400:
506
+ case 422:
507
+ return new SinnuValidationError(message, statusCode, body, response);
508
+ case 429:
509
+ return new SinnuRateLimitError(message, body, response);
510
+ default:
511
+ return new SinnuError(message, statusCode, body, response);
512
+ }
513
+ }
514
+
515
+ // src/client.ts
516
+ var DEFAULT_BASE_URL = "https://api.sinnu.com.br";
517
+ var API_KEY_PREFIXES = ["sk_live_"];
518
+ function assertApiKey(apiKey) {
519
+ if (!apiKey || typeof apiKey !== "string") {
520
+ throw new Error(
521
+ "[@sinnu-dev/sdk] apiKey \xE9 obrigat\xF3ria. Gere uma chave secreta no painel sinnu (Integra\xE7\xF5es)."
522
+ );
523
+ }
524
+ if (!API_KEY_PREFIXES.some((p) => apiKey.startsWith(p))) {
525
+ console.warn(
526
+ "[@sinnu-dev/sdk] apiKey n\xE3o come\xE7a com 'sk_live_'. Use a chave secreta no backend, nunca uma chave no cliente."
527
+ );
528
+ }
529
+ }
530
+ function createTypedClient(options) {
531
+ assertApiKey(options.apiKey);
532
+ return createClient({
533
+ baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
534
+ fetch: options.fetch,
535
+ headers: {
536
+ Authorization: `Bearer ${options.apiKey}`,
537
+ "Content-Type": "application/json",
538
+ ...options.headers
539
+ }
540
+ });
541
+ }
542
+ async function unwrap(p) {
543
+ const { data, error, response } = await p;
544
+ if (error || !response.ok) {
545
+ throw toSinnuError(
546
+ response.status,
547
+ error ?? void 0,
548
+ response
549
+ );
550
+ }
551
+ if (data === void 0 || data === null) {
552
+ throw toSinnuError(response.status, { message: "Resposta sem corpo" }, response);
553
+ }
554
+ return data;
555
+ }
556
+ var RawHttp = class {
557
+ constructor(baseUrl, apiKey, extraHeaders, fetchImpl) {
558
+ this.baseUrl = baseUrl;
559
+ this.apiKey = apiKey;
560
+ this.extraHeaders = extraHeaders;
561
+ this.fetchImpl = fetchImpl;
562
+ }
563
+ async request(path, options = {}) {
564
+ const url = new URL(path.replace(/^\//, ""), ensureTrailingSlash(this.baseUrl));
565
+ if (options.query) {
566
+ for (const [key, value] of Object.entries(options.query)) {
567
+ if (value !== void 0) {
568
+ url.searchParams.set(key, String(value));
569
+ }
570
+ }
571
+ }
572
+ const response = await this.fetchImpl(url.toString(), {
573
+ method: options.method ?? "GET",
574
+ headers: {
575
+ Authorization: `Bearer ${this.apiKey}`,
576
+ "Content-Type": "application/json",
577
+ Accept: "application/json",
578
+ ...this.extraHeaders
579
+ },
580
+ body: options.body !== void 0 ? JSON.stringify(options.body) : void 0
581
+ });
582
+ const text = await response.text();
583
+ const parsed = text ? safeJsonParse(text) : void 0;
584
+ if (!response.ok) {
585
+ throw toSinnuError(response.status, parsed, response);
586
+ }
587
+ return parsed;
588
+ }
589
+ };
590
+ function ensureTrailingSlash(url) {
591
+ return url.endsWith("/") ? url : `${url}/`;
592
+ }
593
+ function safeJsonParse(text) {
594
+ try {
595
+ return JSON.parse(text);
596
+ } catch {
597
+ return text;
598
+ }
599
+ }
600
+
601
+ // src/resources/checkout.ts
602
+ var DEFAULT_CHECKOUT_BASE_URL = "https://pay.sinnu.com.br";
603
+ var Checkout = class {
604
+ constructor(options = {}) {
605
+ this.options = options;
606
+ }
607
+ /**
608
+ * Monta a URL pública do checkout hosted para um `slug` (8 chars) gerado
609
+ * ao criar um link (`sinnu.links.create(...).url` já vem pronto; este
610
+ * helper é útil quando você só tem o slug).
611
+ *
612
+ * @example
613
+ * const url = sinnu.checkout.url("abcd1234", { reference: "pedido-123" });
614
+ * // => "https://pay.sinnu.com.br/abcd1234?ref=pedido-123"
615
+ */
616
+ url(slug, options = {}) {
617
+ if (!slug || typeof slug !== "string") {
618
+ throw new Error("[@sinnu-dev/sdk] slug do checkout \xE9 obrigat\xF3rio.");
619
+ }
620
+ const base = options.checkoutBaseUrl ?? this.options.checkoutBaseUrl ?? DEFAULT_CHECKOUT_BASE_URL;
621
+ const url = new URL(encodeURIComponent(slug), ensureTrailingSlash2(base));
622
+ const query = { ...this.options.query, ...options.query };
623
+ for (const [key, value] of Object.entries(query)) {
624
+ if (value !== void 0) {
625
+ url.searchParams.set(key, String(value));
626
+ }
627
+ }
628
+ if (options.reference !== void 0) {
629
+ if (options.reference.length > 255) {
630
+ throw new Error("[@sinnu-dev/sdk] reference tem no m\xE1ximo 255 caracteres.");
631
+ }
632
+ url.searchParams.set("ref", options.reference);
633
+ }
634
+ return url.toString();
635
+ }
636
+ };
637
+ function ensureTrailingSlash2(url) {
638
+ return url.endsWith("/") ? url : `${url}/`;
639
+ }
640
+
641
+ // src/pagination.ts
642
+ async function* paginate(fetchPage) {
643
+ let page = 1;
644
+ let seen = 0;
645
+ while (true) {
646
+ const result = await fetchPage(page);
647
+ for (const item of result.data) {
648
+ yield item;
649
+ }
650
+ seen += result.data.length;
651
+ const pageSize = result.pageSize || result.data.length;
652
+ if (result.data.length === 0 || seen >= result.total || pageSize === 0) {
653
+ return;
654
+ }
655
+ page += 1;
656
+ }
657
+ }
658
+ async function collectAll(fetchPage) {
659
+ const out = [];
660
+ for await (const item of paginate(fetchPage)) {
661
+ out.push(item);
662
+ }
663
+ return out;
664
+ }
665
+
666
+ // src/resources/links.ts
667
+ var Links = class {
668
+ constructor(http) {
669
+ this.http = http;
670
+ }
671
+ /** Cria um link de pagamento (valor em centavos). */
672
+ async create(body) {
673
+ return this.http.request("/api/payment-links", {
674
+ method: "POST",
675
+ body
676
+ });
677
+ }
678
+ /** Busca um link de pagamento pelo id. */
679
+ async get(id) {
680
+ return this.http.request(`/api/payment-links/${encodeURIComponent(id)}`);
681
+ }
682
+ /** Atualiza parcialmente um link de pagamento. */
683
+ async update(id, body) {
684
+ return this.http.request(`/api/payment-links/${encodeURIComponent(id)}`, {
685
+ method: "PATCH",
686
+ body
687
+ });
688
+ }
689
+ /** Arquiva um link de pagamento. */
690
+ async archive(id) {
691
+ await this.http.request(`/api/payment-links/${encodeURIComponent(id)}`, {
692
+ method: "DELETE"
693
+ });
694
+ }
695
+ /** Lista links de pagamento (paginado). */
696
+ async list(params = {}) {
697
+ return this.http.request("/api/payment-links", {
698
+ query: { page: params.page, pageSize: params.pageSize }
699
+ });
700
+ }
701
+ /** Lista transações de um link de pagamento (paginado). */
702
+ async transactions(id, params = {}) {
703
+ return this.http.request(
704
+ `/api/payment-links/${encodeURIComponent(id)}/transactions`,
705
+ { query: { page: params.page, pageSize: params.pageSize } }
706
+ );
707
+ }
708
+ /** Itera todos os links de pagamento, página a página. */
709
+ listAll(params = {}) {
710
+ return paginate((page) => this.list({ ...params, page }));
711
+ }
712
+ };
713
+
714
+ // src/resources/transactions.ts
715
+ var Transactions = class {
716
+ constructor(http) {
717
+ this.http = http;
718
+ }
719
+ /** Lista transações (paginado, com filtro opcional por status). */
720
+ async list(params = {}) {
721
+ return this.http.request("/api/transactions/", {
722
+ query: {
723
+ status: params.status,
724
+ search: params.search,
725
+ customer: params.customer,
726
+ page: params.page,
727
+ pageSize: params.pageSize
728
+ }
729
+ });
730
+ }
731
+ /** Busca uma transação pelo id. */
732
+ async get(id) {
733
+ return this.http.request(`/api/transactions/${encodeURIComponent(id)}/`);
734
+ }
735
+ /** Estorna (refund) uma transação, sempre pelo valor total. Exige o escopo `transactions:refund` na chave. */
736
+ async refund(id, body = {}) {
737
+ return this.http.request(
738
+ `/api/transactions/${encodeURIComponent(id)}/refund/`,
739
+ { method: "POST", body }
740
+ );
741
+ }
742
+ /** Itera todas as transações, página a página. */
743
+ listAll(params = {}) {
744
+ return paginate((page) => this.list({ ...params, page }));
745
+ }
746
+ };
747
+
748
+ // src/webhooks.ts
749
+ import { createHmac, timingSafeEqual } from "crypto";
750
+ var SINNU_SIGNATURE_HEADER = "x-sinnu-signature";
751
+ var SinnuWebhookSignatureError = class extends SinnuError {
752
+ constructor(message) {
753
+ super(message, 0);
754
+ this.name = "SinnuWebhookSignatureError";
755
+ }
756
+ };
757
+ function normalizeSignature(signature) {
758
+ if (signature === void 0) {
759
+ throw new SinnuWebhookSignatureError(
760
+ "[@sinnu-dev/sdk] header de assinatura ausente. Esperado 'X-Sinnu-Signature'."
761
+ );
762
+ }
763
+ const value = Array.isArray(signature) ? signature[0] : signature;
764
+ if (!value) {
765
+ throw new SinnuWebhookSignatureError("[@sinnu-dev/sdk] header de assinatura vazio.");
766
+ }
767
+ return value.startsWith("sha256=") ? value.slice("sha256=".length) : value;
768
+ }
769
+ function toBuffer(payload) {
770
+ return typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
771
+ }
772
+ function computeSignature(payload, secret) {
773
+ return createHmac("sha256", secret).update(toBuffer(payload)).digest("hex");
774
+ }
775
+ function verifySignature(options) {
776
+ const { payload, signature, secret } = options;
777
+ if (!secret) {
778
+ throw new SinnuWebhookSignatureError(
779
+ "[@sinnu-dev/sdk] webhook secret \xE9 obrigat\xF3rio para verificar a assinatura."
780
+ );
781
+ }
782
+ const provided = normalizeSignature(signature);
783
+ const expected = computeSignature(payload, secret);
784
+ const providedBuf = Buffer.from(provided, "hex");
785
+ const expectedBuf = Buffer.from(expected, "hex");
786
+ if (providedBuf.length !== expectedBuf.length) {
787
+ return false;
788
+ }
789
+ return timingSafeEqual(providedBuf, expectedBuf);
790
+ }
791
+ function constructEvent(options) {
792
+ if (!verifySignature(options)) {
793
+ throw new SinnuWebhookSignatureError(
794
+ "[@sinnu-dev/sdk] assinatura de webhook inv\xE1lida. Requisi\xE7\xE3o rejeitada."
795
+ );
796
+ }
797
+ const text = typeof options.payload === "string" ? options.payload : options.payload.toString("utf8");
798
+ try {
799
+ return JSON.parse(text);
800
+ } catch {
801
+ throw new SinnuWebhookSignatureError("[@sinnu-dev/sdk] corpo do webhook n\xE3o \xE9 um JSON v\xE1lido.");
802
+ }
803
+ }
804
+ var webhooks = {
805
+ signatureHeader: SINNU_SIGNATURE_HEADER,
806
+ computeSignature,
807
+ verifySignature,
808
+ constructEvent
809
+ };
810
+
811
+ // src/index.ts
812
+ var Sinnu = class {
813
+ constructor(options) {
814
+ /** Verificação de webhooks (HMAC SHA-256): não faz requisições. */
815
+ this.webhooks = webhooks;
816
+ this.http = createTypedClient(options);
817
+ const raw = new RawHttp(
818
+ options.baseUrl ?? DEFAULT_BASE_URL,
819
+ options.apiKey,
820
+ options.headers ?? {},
821
+ options.fetch ?? fetch
822
+ );
823
+ this.links = new Links(raw);
824
+ this.transactions = new Transactions(raw);
825
+ this.checkout = new Checkout({ checkoutBaseUrl: options.checkoutBaseUrl });
826
+ }
827
+ };
828
+ var index_default = Sinnu;
829
+ export {
830
+ Checkout,
831
+ DEFAULT_BASE_URL,
832
+ DEFAULT_CHECKOUT_BASE_URL,
833
+ SINNU_SIGNATURE_HEADER,
834
+ Sinnu,
835
+ SinnuAuthError,
836
+ SinnuError,
837
+ SinnuNotFoundError,
838
+ SinnuRateLimitError,
839
+ SinnuValidationError,
840
+ SinnuWebhookSignatureError,
841
+ collectAll,
842
+ computeSignature,
843
+ constructEvent,
844
+ createTypedClient,
845
+ index_default as default,
846
+ paginate,
847
+ unwrap,
848
+ verifySignature,
849
+ webhooks
850
+ };