brisa-sdk 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/LICENSE +21 -0
- package/README.md +90 -2
- package/dist/index.cjs +621 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +928 -0
- package/dist/index.d.ts +928 -0
- package/dist/index.js +590 -0
- package/dist/index.js.map +1 -0
- package/docs/01-primeiros-passos.md +106 -0
- package/docs/02-autenticacao.md +55 -0
- package/docs/03-documentos.md +80 -0
- package/docs/04-pagamentos.md +69 -0
- package/docs/05-impressao.md +44 -0
- package/docs/06-dados-bancarios.md +42 -0
- package/docs/07-clientes-e-extrato.md +61 -0
- package/docs/08-artigos-e-stock.md +38 -0
- package/docs/09-saft.md +23 -0
- package/docs/10-webhooks.md +42 -0
- package/docs/11-erros.md +52 -0
- package/docs/12-idempotencia-e-limites.md +29 -0
- package/docs/13-sandbox-e-producao.md +25 -0
- package/docs/README.md +35 -0
- package/docs/openapi.json +16772 -0
- package/docs/upgrade.md +23 -0
- package/package.json +67 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/errors.ts
|
|
4
|
+
var BrisaError = class extends Error {
|
|
5
|
+
constructor(message, options) {
|
|
6
|
+
super(message, options);
|
|
7
|
+
this.name = new.target.name;
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var BrisaApiError = class extends BrisaError {
|
|
11
|
+
/** O estado HTTP. */
|
|
12
|
+
status;
|
|
13
|
+
/** `urn:brisa:...`: identificador estável do tipo de problema. */
|
|
14
|
+
type;
|
|
15
|
+
title;
|
|
16
|
+
detail;
|
|
17
|
+
instance;
|
|
18
|
+
/** O campo que causou o erro (regras fiscais, `422`). */
|
|
19
|
+
field;
|
|
20
|
+
/** Erros de validação (`400`): `campo: mensagem`. */
|
|
21
|
+
errors;
|
|
22
|
+
/** O documento de erro completo, incluindo membros que o SDK não conhece. */
|
|
23
|
+
problem;
|
|
24
|
+
/** Segundos a esperar (`Retry-After`), quando a API os indicou. */
|
|
25
|
+
retryAfter;
|
|
26
|
+
headers;
|
|
27
|
+
constructor(problem, headers, retryAfter) {
|
|
28
|
+
super(`${problem.status} ${problem.title}${problem.detail ? `: ${problem.detail}` : ""}`);
|
|
29
|
+
this.status = problem.status;
|
|
30
|
+
this.type = problem.type;
|
|
31
|
+
this.title = problem.title;
|
|
32
|
+
this.detail = problem.detail;
|
|
33
|
+
this.instance = problem.instance;
|
|
34
|
+
this.field = problem.field;
|
|
35
|
+
this.errors = problem.errors;
|
|
36
|
+
this.problem = problem;
|
|
37
|
+
this.headers = headers;
|
|
38
|
+
this.retryAfter = retryAfter;
|
|
39
|
+
}
|
|
40
|
+
/** `true` para `429`, `502` e `503`: repetir mais tarde (com o mesmo `Idempotency-Key`). */
|
|
41
|
+
get retryable() {
|
|
42
|
+
return this.status === 429 || this.status === 502 || this.status === 503;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
var BrisaValidationError = class extends BrisaApiError {
|
|
46
|
+
};
|
|
47
|
+
var BrisaAuthenticationError = class extends BrisaApiError {
|
|
48
|
+
};
|
|
49
|
+
var BrisaPlanError = class extends BrisaApiError {
|
|
50
|
+
/** O que se esgotou (`invoices`, `clients`, `products`, `users`), nos erros de limite do plano. */
|
|
51
|
+
get metric() {
|
|
52
|
+
return this.problem.metric;
|
|
53
|
+
}
|
|
54
|
+
/** O máximo do plano. */
|
|
55
|
+
get limit() {
|
|
56
|
+
return this.problem.limit;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
var BrisaPermissionError = class extends BrisaApiError {
|
|
60
|
+
};
|
|
61
|
+
var BrisaNotFoundError = class extends BrisaApiError {
|
|
62
|
+
};
|
|
63
|
+
var BrisaConflictError = class extends BrisaApiError {
|
|
64
|
+
};
|
|
65
|
+
var BrisaRuleError = class extends BrisaApiError {
|
|
66
|
+
};
|
|
67
|
+
var BrisaRateLimitError = class extends BrisaApiError {
|
|
68
|
+
};
|
|
69
|
+
var BrisaServerError = class extends BrisaApiError {
|
|
70
|
+
};
|
|
71
|
+
var BrisaConnectionError = class extends BrisaError {
|
|
72
|
+
};
|
|
73
|
+
var BrisaTimeoutError = class extends BrisaConnectionError {
|
|
74
|
+
};
|
|
75
|
+
var BrisaWebhookSignatureError = class extends BrisaError {
|
|
76
|
+
};
|
|
77
|
+
function errorFor(problem, headers, retryAfter) {
|
|
78
|
+
const s = problem.status;
|
|
79
|
+
const C = s === 400 ? BrisaValidationError : s === 401 ? BrisaAuthenticationError : s === 402 ? BrisaPlanError : s === 403 ? BrisaPermissionError : s === 404 ? BrisaNotFoundError : s === 409 ? BrisaConflictError : s === 422 ? BrisaRuleError : s === 429 ? BrisaRateLimitError : s >= 500 ? BrisaServerError : BrisaApiError;
|
|
80
|
+
return new C(problem, headers, retryAfter);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/version.ts
|
|
84
|
+
var VERSION = "0.2.0";
|
|
85
|
+
|
|
86
|
+
// src/http.ts
|
|
87
|
+
var DEFAULT_BASE_URL = "https://api.brisa.ao";
|
|
88
|
+
var RETRYABLE = /* @__PURE__ */ new Set([429, 502, 503]);
|
|
89
|
+
function env(name) {
|
|
90
|
+
const p = globalThis.process;
|
|
91
|
+
return p?.env?.[name];
|
|
92
|
+
}
|
|
93
|
+
function idempotencyKey() {
|
|
94
|
+
const c = globalThis.crypto;
|
|
95
|
+
if (c?.randomUUID) return `brisa-js-${c.randomUUID()}`;
|
|
96
|
+
const bytes = new Uint8Array(16);
|
|
97
|
+
if (c?.getRandomValues) c.getRandomValues(bytes);
|
|
98
|
+
else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
99
|
+
return `brisa-js-${Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
100
|
+
}
|
|
101
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
102
|
+
if (!value) return void 0;
|
|
103
|
+
const n = Number(value);
|
|
104
|
+
if (Number.isFinite(n)) return Math.max(0, n);
|
|
105
|
+
const t = Date.parse(value);
|
|
106
|
+
return Number.isNaN(t) ? void 0 : Math.max(0, Math.ceil((t - now) / 1e3));
|
|
107
|
+
}
|
|
108
|
+
function rateLimitOf(h) {
|
|
109
|
+
const limit = h.get("x-ratelimit-limit");
|
|
110
|
+
if (limit === null) return void 0;
|
|
111
|
+
return { limit: Number(limit), remaining: Number(h.get("x-ratelimit-remaining") ?? 0), reset: Number(h.get("x-ratelimit-reset") ?? 0) };
|
|
112
|
+
}
|
|
113
|
+
var sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
114
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
115
|
+
const t = setTimeout(resolve, ms);
|
|
116
|
+
signal?.addEventListener(
|
|
117
|
+
"abort",
|
|
118
|
+
() => {
|
|
119
|
+
clearTimeout(t);
|
|
120
|
+
reject(signal.reason);
|
|
121
|
+
},
|
|
122
|
+
{ once: true }
|
|
123
|
+
);
|
|
124
|
+
});
|
|
125
|
+
var HttpClient = class {
|
|
126
|
+
baseUrl;
|
|
127
|
+
apiKey;
|
|
128
|
+
timeoutMs;
|
|
129
|
+
maxRetries;
|
|
130
|
+
maxRetryDelayMs;
|
|
131
|
+
fetchImpl;
|
|
132
|
+
headers;
|
|
133
|
+
/** Os limites de pedidos da última resposta. */
|
|
134
|
+
lastRateLimit;
|
|
135
|
+
constructor(options = {}) {
|
|
136
|
+
const apiKey = options.apiKey ?? env("BRISA_API_KEY");
|
|
137
|
+
if (!apiKey) throw new BrisaError("Falta a chave de API: passe { apiKey } ou defina BRISA_API_KEY.");
|
|
138
|
+
this.apiKey = apiKey;
|
|
139
|
+
this.baseUrl = (options.baseUrl ?? env("BRISA_API_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
140
|
+
this.timeoutMs = options.timeoutMs ?? 3e4;
|
|
141
|
+
this.maxRetries = options.maxRetries ?? 2;
|
|
142
|
+
this.maxRetryDelayMs = options.maxRetryDelayMs ?? 6e4;
|
|
143
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
144
|
+
if (!f) throw new BrisaError("N\xE3o h\xE1 fetch neste ambiente: use Node.js 18+ ou passe { fetch }.");
|
|
145
|
+
this.fetchImpl = f;
|
|
146
|
+
this.headers = options.headers ?? {};
|
|
147
|
+
}
|
|
148
|
+
url(path, query) {
|
|
149
|
+
const u = new URL(this.baseUrl + path);
|
|
150
|
+
if (query) {
|
|
151
|
+
for (const [k, v] of Object.entries(query)) {
|
|
152
|
+
if (v === void 0 || v === null) continue;
|
|
153
|
+
if (Array.isArray(v)) for (const x of v) u.searchParams.append(k, String(x));
|
|
154
|
+
else u.searchParams.set(k, String(v));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return u.toString();
|
|
158
|
+
}
|
|
159
|
+
async request(req, options = {}) {
|
|
160
|
+
const url = this.url(req.path, req.query);
|
|
161
|
+
const headers = {
|
|
162
|
+
Accept: req.accept ?? "application/json",
|
|
163
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
164
|
+
...this.headers,
|
|
165
|
+
...options.headers
|
|
166
|
+
};
|
|
167
|
+
if (!globalThis.window) headers["User-Agent"] = `brisa-sdk-js/${VERSION}`;
|
|
168
|
+
if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;
|
|
169
|
+
let body;
|
|
170
|
+
if (req.body !== void 0) {
|
|
171
|
+
headers["Content-Type"] = "application/json";
|
|
172
|
+
body = JSON.stringify(req.body);
|
|
173
|
+
}
|
|
174
|
+
const safeToRepeat = req.method !== "POST" || options.idempotencyKey !== void 0;
|
|
175
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
176
|
+
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
|
|
177
|
+
for (let attempt = 0; ; attempt++) {
|
|
178
|
+
let res;
|
|
179
|
+
const timeout = new AbortController();
|
|
180
|
+
const timer = setTimeout(() => timeout.abort(), timeoutMs);
|
|
181
|
+
const onAbort = () => timeout.abort();
|
|
182
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
183
|
+
try {
|
|
184
|
+
res = await this.fetchImpl(url, { method: req.method, headers, body, signal: timeout.signal });
|
|
185
|
+
} catch (e) {
|
|
186
|
+
clearTimeout(timer);
|
|
187
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
188
|
+
if (options.signal?.aborted) throw e;
|
|
189
|
+
const err = timeout.signal.aborted ? new BrisaTimeoutError(`A API n\xE3o respondeu em ${timeoutMs} ms (${req.method} ${req.path}).`, { cause: e }) : new BrisaConnectionError(`N\xE3o foi poss\xEDvel falar com a API (${req.method} ${req.path}): ${e?.message ?? e}`, { cause: e });
|
|
190
|
+
if (safeToRepeat && attempt < maxRetries) {
|
|
191
|
+
await sleep(backoff(attempt), options.signal);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
throw err;
|
|
195
|
+
}
|
|
196
|
+
try {
|
|
197
|
+
this.lastRateLimit = rateLimitOf(res.headers) ?? this.lastRateLimit;
|
|
198
|
+
if (res.ok) {
|
|
199
|
+
const data = await read(res, req.as ?? "json");
|
|
200
|
+
return {
|
|
201
|
+
data,
|
|
202
|
+
status: res.status,
|
|
203
|
+
headers: res.headers,
|
|
204
|
+
replayed: res.headers.get("idempotent-replayed") === "true",
|
|
205
|
+
rateLimit: rateLimitOf(res.headers)
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
209
|
+
const problem = await problemOf(res, req);
|
|
210
|
+
if (RETRYABLE.has(res.status) && attempt < maxRetries) {
|
|
211
|
+
const wait = retryAfter !== void 0 ? retryAfter * 1e3 : backoff(attempt);
|
|
212
|
+
if (wait <= this.maxRetryDelayMs) {
|
|
213
|
+
await sleep(wait, options.signal);
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
throw errorFor(problem, res.headers, retryAfter);
|
|
218
|
+
} finally {
|
|
219
|
+
clearTimeout(timer);
|
|
220
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
function backoff(attempt) {
|
|
226
|
+
const base = Math.min(8e3, 500 * 2 ** attempt);
|
|
227
|
+
return Math.round(base / 2 + Math.random() * (base / 2));
|
|
228
|
+
}
|
|
229
|
+
async function read(res, as) {
|
|
230
|
+
if (res.status === 204) return void 0;
|
|
231
|
+
if (as === "bytes") return new Uint8Array(await res.arrayBuffer());
|
|
232
|
+
const text2 = await res.text();
|
|
233
|
+
if (as === "text") return text2;
|
|
234
|
+
if (!text2) return void 0;
|
|
235
|
+
return JSON.parse(text2);
|
|
236
|
+
}
|
|
237
|
+
async function problemOf(res, req) {
|
|
238
|
+
const text2 = await res.text().catch(() => "");
|
|
239
|
+
try {
|
|
240
|
+
const p = JSON.parse(text2);
|
|
241
|
+
if (p && typeof p === "object") return { ...p, status: typeof p.status === "number" ? p.status : res.status, type: p.type ?? "about:blank", title: p.title ?? res.statusText };
|
|
242
|
+
} catch {
|
|
243
|
+
}
|
|
244
|
+
return { type: "about:blank", title: res.statusText || `HTTP ${res.status}`, status: res.status, detail: text2.slice(0, 500) || void 0, instance: req.path };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// src/pagination.ts
|
|
248
|
+
async function* paginate(fetchPage, params) {
|
|
249
|
+
let page = params.page ?? 0;
|
|
250
|
+
const size = params.size ?? 100;
|
|
251
|
+
let seen = 0;
|
|
252
|
+
for (; ; ) {
|
|
253
|
+
const p = await fetchPage({ ...params, page, size });
|
|
254
|
+
for (const item of p.items) yield item;
|
|
255
|
+
seen += p.items.length;
|
|
256
|
+
if (p.items.length === 0 || p.items.length < p.size || seen + (params.page ?? 0) * size >= p.total) return;
|
|
257
|
+
page++;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
async function collect(it, max = Number.POSITIVE_INFINITY) {
|
|
261
|
+
const out = [];
|
|
262
|
+
for await (const x of it) {
|
|
263
|
+
out.push(x);
|
|
264
|
+
if (out.length >= max) break;
|
|
265
|
+
}
|
|
266
|
+
return out;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// src/resources/documents.ts
|
|
270
|
+
var id = (n) => encodeURIComponent(String(n));
|
|
271
|
+
var withKey = (o = {}) => ({ ...o, idempotencyKey: o.idempotencyKey ?? idempotencyKey() });
|
|
272
|
+
var Documents = class {
|
|
273
|
+
constructor(http) {
|
|
274
|
+
this.http = http;
|
|
275
|
+
}
|
|
276
|
+
http;
|
|
277
|
+
/** Emite `FT`, `FR`, `TV` ou `PF` (`POST /api/v1/documents`). Permissão `invoices.issue`. */
|
|
278
|
+
async issue(body, options) {
|
|
279
|
+
return (await this.http.request({ method: "POST", path: "/api/v1/documents", body }, withKey(options))).data;
|
|
280
|
+
}
|
|
281
|
+
/** Uma página de documentos, do mais recente para o mais antigo. Permissão `invoices.view`. */
|
|
282
|
+
async list(params = {}, options) {
|
|
283
|
+
return (await this.http.request({ method: "GET", path: "/api/v1/documents", query: params }, options)).data;
|
|
284
|
+
}
|
|
285
|
+
/** Todos os documentos que correspondem aos filtros, página a página. */
|
|
286
|
+
listAll(params = {}, options) {
|
|
287
|
+
return paginate((p) => this.list(p, options), params);
|
|
288
|
+
}
|
|
289
|
+
/** Um documento, com linhas, totais, valor em dívida e estado na AGT. */
|
|
290
|
+
async get(documentId, options) {
|
|
291
|
+
return (await this.http.request({ method: "GET", path: `/api/v1/documents/${id(documentId)}` }, options)).data;
|
|
292
|
+
}
|
|
293
|
+
/** O PDF do documento (bytes). Conta como mais de um pedido no limite da chave: guarde-o em vez de o pedir de cada vez. */
|
|
294
|
+
async pdf(documentId, params = {}, options) {
|
|
295
|
+
return (await this.http.request({ method: "GET", path: `/api/v1/documents/${id(documentId)}/pdf`, query: params, as: "bytes", accept: "application/pdf" }, options)).data;
|
|
296
|
+
}
|
|
297
|
+
async export(documentId, format = "json", options) {
|
|
298
|
+
const xml = format === "xml";
|
|
299
|
+
return (await this.http.request(
|
|
300
|
+
{ method: "GET", path: `/api/v1/documents/${id(documentId)}/export`, query: { format }, as: xml ? "text" : "json", accept: xml ? "application/xml" : "application/json" },
|
|
301
|
+
options
|
|
302
|
+
)).data;
|
|
303
|
+
}
|
|
304
|
+
/** Paga o documento, no todo (sem `amount`) ou em parte, e emite o recibo (`RC`). Permissão `invoices.payments`. */
|
|
305
|
+
async pay(documentId, body, options) {
|
|
306
|
+
return (await this.http.request({ method: "POST", path: `/api/v1/documents/${id(documentId)}/payments`, body }, withKey(options))).data;
|
|
307
|
+
}
|
|
308
|
+
/** Liquida várias faturas de um mesmo cliente num recibo global (`RG`). */
|
|
309
|
+
async payGlobal(body, options) {
|
|
310
|
+
return (await this.http.request({ method: "POST", path: "/api/v1/documents/payments/global", body }, withKey(options))).data;
|
|
311
|
+
}
|
|
312
|
+
/** Anula o documento (numa fatura emitida, só com `basis`). Repetido, dá o mesmo resultado. Permissão `invoices.cancel`. */
|
|
313
|
+
async cancel(documentId, body, options) {
|
|
314
|
+
await this.http.request({ method: "POST", path: `/api/v1/documents/${id(documentId)}/cancel`, body }, options);
|
|
315
|
+
}
|
|
316
|
+
/** Retifica: emite uma nota de crédito (`NC`) que espelha o original. */
|
|
317
|
+
async rectify(documentId, body, options) {
|
|
318
|
+
return (await this.http.request({ method: "POST", path: `/api/v1/documents/${id(documentId)}/rectify`, body }, withKey(options))).data;
|
|
319
|
+
}
|
|
320
|
+
/** Nota de crédito parcial (ou total, sem `lines`). */
|
|
321
|
+
async creditNote(documentId, body, options) {
|
|
322
|
+
return (await this.http.request({ method: "POST", path: `/api/v1/documents/${id(documentId)}/credit-notes`, body }, withKey(options))).data;
|
|
323
|
+
}
|
|
324
|
+
/** Quanto de cada linha já foi creditado e quanto ainda se pode creditar. */
|
|
325
|
+
async credits(documentId, options) {
|
|
326
|
+
return (await this.http.request({ method: "GET", path: `/api/v1/documents/${id(documentId)}/credits` }, options)).data;
|
|
327
|
+
}
|
|
328
|
+
/** O histórico do documento (auditoria e envios). */
|
|
329
|
+
async history(documentId, options) {
|
|
330
|
+
return (await this.http.request({ method: "GET", path: `/api/v1/documents/${id(documentId)}/history` }, options)).data;
|
|
331
|
+
}
|
|
332
|
+
/** Muda a data de vencimento (AAAA-MM-DD, até 365 dias depois da emissão). */
|
|
333
|
+
async setDueDate(documentId, dueDate, options) {
|
|
334
|
+
await this.http.request({ method: "PUT", path: `/api/v1/documents/${id(documentId)}/due-date`, body: { dueDate } }, options);
|
|
335
|
+
}
|
|
336
|
+
/** Envia o documento por e-mail. Com uma chave de API, só ao e-mail do cliente que consta do documento. Permissão `invoices.send`. */
|
|
337
|
+
async send(documentId, body = {}, options) {
|
|
338
|
+
return (await this.http.request({ method: "POST", path: `/api/v1/documents/${id(documentId)}/send`, body }, options)).data;
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
// src/resources/others.ts
|
|
343
|
+
var seg = (v) => encodeURIComponent(String(v));
|
|
344
|
+
var Clients = class {
|
|
345
|
+
constructor(http) {
|
|
346
|
+
this.http = http;
|
|
347
|
+
}
|
|
348
|
+
http;
|
|
349
|
+
/** Regista um cliente e devolve o seu `id`. Permissão `clients.manage`. */
|
|
350
|
+
async create(body, options = {}) {
|
|
351
|
+
const o = { ...options, idempotencyKey: options.idempotencyKey ?? idempotencyKey() };
|
|
352
|
+
return (await this.http.request({ method: "POST", path: "/api/v1/clients", body }, o)).data;
|
|
353
|
+
}
|
|
354
|
+
/** Substitui os dados do cliente: envie o corpo completo (com `taxId`). */
|
|
355
|
+
async update(clientId, body, options) {
|
|
356
|
+
await this.http.request({ method: "PUT", path: `/api/v1/clients/${seg(clientId)}`, body }, options);
|
|
357
|
+
}
|
|
358
|
+
async get(clientId, options) {
|
|
359
|
+
return (await this.http.request({ method: "GET", path: `/api/v1/clients/${seg(clientId)}` }, options)).data;
|
|
360
|
+
}
|
|
361
|
+
async list(params = {}, options) {
|
|
362
|
+
return (await this.http.request({ method: "GET", path: "/api/v1/clients", query: params }, options)).data;
|
|
363
|
+
}
|
|
364
|
+
listAll(params = {}, options) {
|
|
365
|
+
return paginate((p) => this.list(p, options), params);
|
|
366
|
+
}
|
|
367
|
+
/** Ativa ou desativa o cliente. Permissão `clients.delete`. */
|
|
368
|
+
async setActive(clientId, active, options) {
|
|
369
|
+
await this.http.request({ method: "PUT", path: `/api/v1/clients/${seg(clientId)}/active`, body: { active } }, options);
|
|
370
|
+
}
|
|
371
|
+
/** A conta corrente do cliente (faturas, notas de crédito e recibos dia a dia, com o saldo). Permissões `clients.view` e `invoices.view`. */
|
|
372
|
+
async statement(clientId, period = {}, options) {
|
|
373
|
+
return (await this.http.request({ method: "GET", path: `/api/v1/clients/${seg(clientId)}/statement`, query: period }, options)).data;
|
|
374
|
+
}
|
|
375
|
+
/** O extrato para imprimir (PDF, bytes). Pede também a permissão `reports.export`. */
|
|
376
|
+
async statementPdf(clientId, period = {}, options) {
|
|
377
|
+
return (await this.http.request(
|
|
378
|
+
{ method: "GET", path: `/api/v1/clients/${seg(clientId)}/statement`, query: { ...period, format: "pdf" }, as: "bytes", accept: "application/pdf" },
|
|
379
|
+
options
|
|
380
|
+
)).data;
|
|
381
|
+
}
|
|
382
|
+
/** O extrato em CSV (texto). Pede também a permissão `reports.export`. */
|
|
383
|
+
async statementCsv(clientId, period = {}, options) {
|
|
384
|
+
return (await this.http.request(
|
|
385
|
+
{ method: "GET", path: `/api/v1/clients/${seg(clientId)}/statement`, query: { ...period, format: "csv" }, as: "text", accept: "text/csv" },
|
|
386
|
+
options
|
|
387
|
+
)).data;
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
var Products = class {
|
|
391
|
+
constructor(http) {
|
|
392
|
+
this.http = http;
|
|
393
|
+
}
|
|
394
|
+
http;
|
|
395
|
+
/** Cria o produto se o código não existir; senão atualiza-o. Permissão `products.manage`. */
|
|
396
|
+
async upsert(code, body, options) {
|
|
397
|
+
return (await this.http.request({ method: "PUT", path: `/api/v1/catalog/products/${seg(code)}`, body }, options)).data;
|
|
398
|
+
}
|
|
399
|
+
/** Um produto, com o stock atual. */
|
|
400
|
+
async get(code, options) {
|
|
401
|
+
return (await this.http.request({ method: "GET", path: `/api/v1/catalog/products/${seg(code)}` }, options)).data;
|
|
402
|
+
}
|
|
403
|
+
async list(params = {}, options) {
|
|
404
|
+
return (await this.http.request({ method: "GET", path: "/api/v1/catalog/products", query: params }, options)).data;
|
|
405
|
+
}
|
|
406
|
+
listAll(params = {}, options) {
|
|
407
|
+
return paginate((p) => this.list(p, options), params);
|
|
408
|
+
}
|
|
409
|
+
/** Entrada, saída ou acerto de stock. Permissão `stock.adjust`. */
|
|
410
|
+
async moveStock(code, body, options = {}) {
|
|
411
|
+
const o = { ...options, idempotencyKey: options.idempotencyKey ?? idempotencyKey() };
|
|
412
|
+
return (await this.http.request({ method: "POST", path: `/api/v1/products/${seg(code)}/movements`, body }, o)).data;
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
var Catalog = class {
|
|
416
|
+
constructor(http) {
|
|
417
|
+
this.http = http;
|
|
418
|
+
}
|
|
419
|
+
http;
|
|
420
|
+
/** Os impostos da empresa: o `id` é o `taxId` dos produtos; uma linha só aceita impostos daqui. */
|
|
421
|
+
async taxes(params = {}, options) {
|
|
422
|
+
return (await this.http.request({ method: "GET", path: "/api/v1/catalog/taxes", query: params }, options)).data;
|
|
423
|
+
}
|
|
424
|
+
/** Os motivos de isenção `M00`…`M94` aceites pela AGT. */
|
|
425
|
+
async exemptionReasons(options) {
|
|
426
|
+
return (await this.http.request({ method: "GET", path: "/api/v1/catalog/exemption-reasons" }, options)).data;
|
|
427
|
+
}
|
|
428
|
+
async categories(options) {
|
|
429
|
+
return (await this.http.request({ method: "GET", path: "/api/v1/catalog/categories" }, options)).data;
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
var Saft = class {
|
|
433
|
+
constructor(http) {
|
|
434
|
+
this.http = http;
|
|
435
|
+
}
|
|
436
|
+
http;
|
|
437
|
+
/** Pede a exportação de um período (o fim não pode ser no futuro). Gera-se em segundo plano: veja `get` ou `waitUntilReady`. */
|
|
438
|
+
async request(period, options) {
|
|
439
|
+
return (await this.http.request({ method: "POST", path: "/api/v1/saft/exports", body: period }, options)).data;
|
|
440
|
+
}
|
|
441
|
+
async list(params = {}, options) {
|
|
442
|
+
return (await this.http.request({ method: "GET", path: "/api/v1/saft/exports", query: params }, options)).data;
|
|
443
|
+
}
|
|
444
|
+
async get(exportId, options) {
|
|
445
|
+
return (await this.http.request({ method: "GET", path: `/api/v1/saft/exports/${seg(exportId)}` }, options)).data;
|
|
446
|
+
}
|
|
447
|
+
/** O XML de uma exportação `READY` (`409` antes disso). Conta como vários pedidos no limite da chave. */
|
|
448
|
+
async file(exportId, options) {
|
|
449
|
+
return (await this.http.request({ method: "GET", path: `/api/v1/saft/exports/${seg(exportId)}/file`, as: "text", accept: "application/xml" }, options)).data;
|
|
450
|
+
}
|
|
451
|
+
/** Espera até a exportação ficar `READY` (ou falha com `FAILED`). */
|
|
452
|
+
async waitUntilReady(exportId, { intervalMs = 3e3, timeoutMs = 3e5 } = {}, options) {
|
|
453
|
+
const until = Date.now() + timeoutMs;
|
|
454
|
+
for (; ; ) {
|
|
455
|
+
const e = await this.get(exportId, options);
|
|
456
|
+
if (e.status === "READY") return e;
|
|
457
|
+
if (e.status === "FAILED") throw new BrisaError(`A exporta\xE7\xE3o SAF-T ${exportId} falhou: ${e.error ?? "sem detalhe"}`);
|
|
458
|
+
if (Date.now() + intervalMs > until) throw new BrisaError(`A exporta\xE7\xE3o SAF-T ${exportId} n\xE3o ficou pronta em ${timeoutMs} ms (estado ${e.status}).`);
|
|
459
|
+
await new Promise((r) => setTimeout(r, intervalMs));
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
// src/webhooks.ts
|
|
465
|
+
var encoder = new TextEncoder();
|
|
466
|
+
var hmacImpl;
|
|
467
|
+
async function hmacSha256Hex(secret, message) {
|
|
468
|
+
if (!hmacImpl) {
|
|
469
|
+
const subtle = globalThis.crypto?.subtle;
|
|
470
|
+
if (subtle) {
|
|
471
|
+
hmacImpl = async (s, m) => {
|
|
472
|
+
const key = await subtle.importKey("raw", encoder.encode(s), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
473
|
+
return toHex(new Uint8Array(await subtle.sign("HMAC", key, encoder.encode(m))));
|
|
474
|
+
};
|
|
475
|
+
} else {
|
|
476
|
+
const name = "node:crypto";
|
|
477
|
+
const nodeCrypto = await import(
|
|
478
|
+
/* @vite-ignore */
|
|
479
|
+
/* webpackIgnore: true */
|
|
480
|
+
name
|
|
481
|
+
);
|
|
482
|
+
hmacImpl = async (s, m) => nodeCrypto.createHmac("sha256", s).update(m).digest("hex");
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return hmacImpl(secret, message);
|
|
486
|
+
}
|
|
487
|
+
function toHex(bytes) {
|
|
488
|
+
let s = "";
|
|
489
|
+
for (const b of bytes) s += b.toString(16).padStart(2, "0");
|
|
490
|
+
return s;
|
|
491
|
+
}
|
|
492
|
+
function timingSafeEqual(a, b) {
|
|
493
|
+
if (a.length !== b.length) return false;
|
|
494
|
+
let diff = 0;
|
|
495
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
496
|
+
return diff === 0;
|
|
497
|
+
}
|
|
498
|
+
function parseSignatureHeader(header) {
|
|
499
|
+
let timestamp = Number.NaN;
|
|
500
|
+
const signatures = [];
|
|
501
|
+
for (const part of header.split(",")) {
|
|
502
|
+
const i = part.indexOf("=");
|
|
503
|
+
if (i < 0) continue;
|
|
504
|
+
const k = part.slice(0, i).trim();
|
|
505
|
+
const v = part.slice(i + 1).trim();
|
|
506
|
+
if (k === "t") timestamp = Number(v);
|
|
507
|
+
else if (k === "v1" && /^[0-9a-f]+$/i.test(v)) signatures.push(v.toLowerCase());
|
|
508
|
+
}
|
|
509
|
+
return { timestamp, signatures };
|
|
510
|
+
}
|
|
511
|
+
function text(payload) {
|
|
512
|
+
if (typeof payload === "string") return payload;
|
|
513
|
+
return new TextDecoder().decode(payload instanceof ArrayBuffer ? new Uint8Array(payload) : payload);
|
|
514
|
+
}
|
|
515
|
+
async function verifyWebhook(payload, signatureHeader, secret, options = {}) {
|
|
516
|
+
if (!signatureHeader) throw new BrisaWebhookSignatureError("Falta o cabe\xE7alho Brisa-Signature.");
|
|
517
|
+
const { timestamp, signatures } = parseSignatureHeader(signatureHeader);
|
|
518
|
+
if (!Number.isFinite(timestamp) || signatures.length === 0) throw new BrisaWebhookSignatureError("Cabe\xE7alho Brisa-Signature mal formado.");
|
|
519
|
+
const tolerance = options.toleranceSeconds ?? 300;
|
|
520
|
+
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
521
|
+
if (tolerance > 0 && Math.abs(now - timestamp) > tolerance)
|
|
522
|
+
throw new BrisaWebhookSignatureError(`A assinatura tem ${Math.abs(now - timestamp)} s de diferen\xE7a do rel\xF3gio (m\xE1ximo ${tolerance} s).`);
|
|
523
|
+
const body = text(payload);
|
|
524
|
+
for (const s of Array.isArray(secret) ? secret : [secret]) {
|
|
525
|
+
const expected = await hmacSha256Hex(s, `${timestamp}.${body}`);
|
|
526
|
+
if (signatures.some((v) => timingSafeEqual(v, expected))) {
|
|
527
|
+
try {
|
|
528
|
+
return JSON.parse(body);
|
|
529
|
+
} catch (e) {
|
|
530
|
+
throw new BrisaWebhookSignatureError("A assinatura \xE9 v\xE1lida mas o corpo n\xE3o \xE9 JSON.", { cause: e });
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
throw new BrisaWebhookSignatureError("A assinatura n\xE3o coincide com o segredo do webhook.");
|
|
535
|
+
}
|
|
536
|
+
async function signWebhookPayload(payload, secret, timestamp = Math.floor(Date.now() / 1e3)) {
|
|
537
|
+
return `t=${timestamp},v1=${await hmacSha256Hex(secret, `${timestamp}.${payload}`)}`;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// src/client.ts
|
|
541
|
+
var Brisa = class {
|
|
542
|
+
documents;
|
|
543
|
+
clients;
|
|
544
|
+
products;
|
|
545
|
+
catalog;
|
|
546
|
+
saft;
|
|
547
|
+
/** Verificação de webhooks (também exportada como `verifyWebhook`). */
|
|
548
|
+
static webhooks = { verify: verifyWebhook };
|
|
549
|
+
http;
|
|
550
|
+
constructor(options = {}) {
|
|
551
|
+
this.http = new HttpClient(options);
|
|
552
|
+
this.documents = new Documents(this.http);
|
|
553
|
+
this.clients = new Clients(this.http);
|
|
554
|
+
this.products = new Products(this.http);
|
|
555
|
+
this.catalog = new Catalog(this.http);
|
|
556
|
+
this.saft = new Saft(this.http);
|
|
557
|
+
}
|
|
558
|
+
get baseUrl() {
|
|
559
|
+
return this.http.baseUrl;
|
|
560
|
+
}
|
|
561
|
+
/** Os limites de pedidos indicados na última resposta (`X-RateLimit-*`). */
|
|
562
|
+
get rateLimit() {
|
|
563
|
+
return this.http.lastRateLimit;
|
|
564
|
+
}
|
|
565
|
+
/** Quem é a chave e que permissões tem (`GET /api/v1/me`). */
|
|
566
|
+
async me(options) {
|
|
567
|
+
return (await this.http.request({ method: "GET", path: "/api/v1/me" }, options)).data;
|
|
568
|
+
}
|
|
569
|
+
/** Os dados da empresa da chave (`GET /api/v1/company`). */
|
|
570
|
+
async company(options) {
|
|
571
|
+
return (await this.http.request({ method: "GET", path: "/api/v1/company" }, options)).data;
|
|
572
|
+
}
|
|
573
|
+
/** Os dados bancários da empresa (`GET /api/v1/company/bank`): o que as suas faturas por pagar dizem sobre como pagar. */
|
|
574
|
+
async bank(options) {
|
|
575
|
+
return (await this.http.request({ method: "GET", path: "/api/v1/company/bank" }, options)).data;
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* Substitui os dados bancários da empresa (o IBAN é verificado: um angolano tem 25 caracteres e dígitos de controlo certos; tudo vazio limpa-os).
|
|
579
|
+
* Permissão `settings.manage`. Devolve o que ficou guardado.
|
|
580
|
+
*/
|
|
581
|
+
async setBank(details, options) {
|
|
582
|
+
return (await this.http.request({ method: "PUT", path: "/api/v1/company/bank", body: details }, options)).data;
|
|
583
|
+
}
|
|
584
|
+
/** Um pedido qualquer à API, com autenticação, repetições e erros do SDK; devolve também o estado e os cabeçalhos. */
|
|
585
|
+
request(req, options) {
|
|
586
|
+
return this.http.request(req, options);
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
|
|
590
|
+
exports.Brisa = Brisa;
|
|
591
|
+
exports.BrisaApiError = BrisaApiError;
|
|
592
|
+
exports.BrisaAuthenticationError = BrisaAuthenticationError;
|
|
593
|
+
exports.BrisaConflictError = BrisaConflictError;
|
|
594
|
+
exports.BrisaConnectionError = BrisaConnectionError;
|
|
595
|
+
exports.BrisaError = BrisaError;
|
|
596
|
+
exports.BrisaNotFoundError = BrisaNotFoundError;
|
|
597
|
+
exports.BrisaPermissionError = BrisaPermissionError;
|
|
598
|
+
exports.BrisaPlanError = BrisaPlanError;
|
|
599
|
+
exports.BrisaRateLimitError = BrisaRateLimitError;
|
|
600
|
+
exports.BrisaRuleError = BrisaRuleError;
|
|
601
|
+
exports.BrisaServerError = BrisaServerError;
|
|
602
|
+
exports.BrisaTimeoutError = BrisaTimeoutError;
|
|
603
|
+
exports.BrisaValidationError = BrisaValidationError;
|
|
604
|
+
exports.BrisaWebhookSignatureError = BrisaWebhookSignatureError;
|
|
605
|
+
exports.Catalog = Catalog;
|
|
606
|
+
exports.Clients = Clients;
|
|
607
|
+
exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
|
|
608
|
+
exports.Documents = Documents;
|
|
609
|
+
exports.Products = Products;
|
|
610
|
+
exports.Saft = Saft;
|
|
611
|
+
exports.VERSION = VERSION;
|
|
612
|
+
exports.collect = collect;
|
|
613
|
+
exports.errorFor = errorFor;
|
|
614
|
+
exports.idempotencyKey = idempotencyKey;
|
|
615
|
+
exports.paginate = paginate;
|
|
616
|
+
exports.parseRetryAfter = parseRetryAfter;
|
|
617
|
+
exports.parseSignatureHeader = parseSignatureHeader;
|
|
618
|
+
exports.signWebhookPayload = signWebhookPayload;
|
|
619
|
+
exports.verifyWebhook = verifyWebhook;
|
|
620
|
+
//# sourceMappingURL=index.cjs.map
|
|
621
|
+
//# sourceMappingURL=index.cjs.map
|