@authenty/authapi-types 1.0.9 → 1.0.11

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.
@@ -0,0 +1,425 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AuthApi = void 0;
7
+ const package_json_1 = __importDefault(require("../package.json"));
8
+ const tools_1 = require("./tools");
9
+ /**
10
+ * Namespace principal da API de autenticação
11
+ * Acesso aos tipos: AuthApi.objects.User, AuthApi.responses.auth.login.post, etc.
12
+ */
13
+ var AuthApi;
14
+ (function (AuthApi) {
15
+ /**
16
+ * Objetos de domínio da aplicação
17
+ */
18
+ let objects;
19
+ (function (objects) {
20
+ let BundleType;
21
+ (function (BundleType) {
22
+ BundleType[BundleType["BUNDLE"] = 0] = "BUNDLE";
23
+ BundleType[BundleType["SYMBOLIC_PRODUCT"] = 1] = "SYMBOLIC_PRODUCT";
24
+ BundleType[BundleType["SYMBOLIC_COURSE"] = 2] = "SYMBOLIC_COURSE";
25
+ BundleType[BundleType["SYMBOLIC_CONSULTANCY"] = 3] = "SYMBOLIC_CONSULTANCY";
26
+ })(BundleType = objects.BundleType || (objects.BundleType = {}));
27
+ let PaymentSystem;
28
+ (function (PaymentSystem) {
29
+ let PG_PurchaseLicenseStatus;
30
+ (function (PG_PurchaseLicenseStatus) {
31
+ // Pagamentos ou Assinaturas
32
+ PG_PurchaseLicenseStatus[PG_PurchaseLicenseStatus["UNKNOWN"] = 0] = "UNKNOWN";
33
+ PG_PurchaseLicenseStatus[PG_PurchaseLicenseStatus["OPEN"] = 3] = "OPEN";
34
+ // Pagamentos
35
+ PG_PurchaseLicenseStatus[PG_PurchaseLicenseStatus["EXPIRED"] = 1] = "EXPIRED";
36
+ PG_PurchaseLicenseStatus[PG_PurchaseLicenseStatus["PAID"] = 5] = "PAID";
37
+ // Assinaturas
38
+ PG_PurchaseLicenseStatus[PG_PurchaseLicenseStatus["ACTIVE"] = 6] = "ACTIVE";
39
+ PG_PurchaseLicenseStatus[PG_PurchaseLicenseStatus["RECYCLING"] = 4] = "RECYCLING";
40
+ PG_PurchaseLicenseStatus[PG_PurchaseLicenseStatus["CANCELED"] = 2] = "CANCELED";
41
+ })(PG_PurchaseLicenseStatus = PaymentSystem.PG_PurchaseLicenseStatus || (PaymentSystem.PG_PurchaseLicenseStatus = {}));
42
+ PaymentSystem.PG_PurchaseLicenseStatus_GroupActive = [
43
+ PG_PurchaseLicenseStatus.PAID,
44
+ PG_PurchaseLicenseStatus.ACTIVE,
45
+ PG_PurchaseLicenseStatus.RECYCLING,
46
+ ];
47
+ let PG_PurchasePaymentStatus;
48
+ (function (PG_PurchasePaymentStatus) {
49
+ PG_PurchasePaymentStatus[PG_PurchasePaymentStatus["UNKNOWN"] = 0] = "UNKNOWN";
50
+ PG_PurchasePaymentStatus[PG_PurchasePaymentStatus["ACTIVE"] = 1] = "ACTIVE";
51
+ PG_PurchasePaymentStatus[PG_PurchasePaymentStatus["CANCELED"] = 2] = "CANCELED";
52
+ PG_PurchasePaymentStatus[PG_PurchasePaymentStatus["REFUNDED"] = 3] = "REFUNDED";
53
+ PG_PurchasePaymentStatus[PG_PurchasePaymentStatus["REMOVED"] = 4] = "REMOVED";
54
+ PG_PurchasePaymentStatus[PG_PurchasePaymentStatus["PENDING"] = 5] = "PENDING";
55
+ })(PG_PurchasePaymentStatus = PaymentSystem.PG_PurchasePaymentStatus || (PaymentSystem.PG_PurchasePaymentStatus = {}));
56
+ let PG_PurchaseType;
57
+ (function (PG_PurchaseType) {
58
+ PG_PurchaseType[PG_PurchaseType["SESSION"] = 0] = "SESSION";
59
+ PG_PurchaseType[PG_PurchaseType["STANDARD"] = 1] = "STANDARD";
60
+ PG_PurchaseType[PG_PurchaseType["RECURRENT"] = 2] = "RECURRENT";
61
+ })(PG_PurchaseType = PaymentSystem.PG_PurchaseType || (PaymentSystem.PG_PurchaseType = {}));
62
+ let PG_RecurrenceType;
63
+ (function (PG_RecurrenceType) {
64
+ PG_RecurrenceType[PG_RecurrenceType["NONE"] = 0] = "NONE";
65
+ PG_RecurrenceType[PG_RecurrenceType["DAILY"] = 1] = "DAILY";
66
+ PG_RecurrenceType[PG_RecurrenceType["WEEKLY"] = 2] = "WEEKLY";
67
+ PG_RecurrenceType[PG_RecurrenceType["MONTHLY"] = 3] = "MONTHLY";
68
+ PG_RecurrenceType[PG_RecurrenceType["YEARLY"] = 4] = "YEARLY";
69
+ })(PG_RecurrenceType = PaymentSystem.PG_RecurrenceType || (PaymentSystem.PG_RecurrenceType = {}));
70
+ })(PaymentSystem = objects.PaymentSystem || (objects.PaymentSystem = {}));
71
+ })(objects = AuthApi.objects || (AuthApi.objects = {}));
72
+ let auxiliarTypes;
73
+ (function (auxiliarTypes) {
74
+ let Privilege;
75
+ (function (Privilege) {
76
+ Privilege[Privilege["NONE"] = 0] = "NONE";
77
+ Privilege[Privilege["READ"] = 1] = "READ";
78
+ Privilege[Privilege["WRITE"] = 2] = "WRITE";
79
+ })(Privilege = auxiliarTypes.Privilege || (auxiliarTypes.Privilege = {}));
80
+ })(auxiliarTypes = AuthApi.auxiliarTypes || (AuthApi.auxiliarTypes = {}));
81
+ /**
82
+ * Client para comunicação com a API de autenticação
83
+ */
84
+ class Client {
85
+ constructor(config) {
86
+ this.bearer = '';
87
+ this.pin1 = '';
88
+ this.retryAttempts = 0;
89
+ this.retryDelay = 500;
90
+ this.isHealth = true;
91
+ // ==================== MÉTODOS DE AUTENTICAÇÃO ====================
92
+ this.auth = {
93
+ /**
94
+ * Faz login na API
95
+ */
96
+ login: async (email, password) => {
97
+ return this.request('POST', 'auth/login', { email, password });
98
+ },
99
+ /**
100
+ * Faz logout da API
101
+ */
102
+ logout: async () => {
103
+ const result = await this.request('GET', 'auth/logout', {});
104
+ this.setToken('');
105
+ this.setPin1('');
106
+ return result;
107
+ },
108
+ /**
109
+ * Verifica a sessão atual
110
+ */
111
+ checkSession: async () => {
112
+ if (!this.bearer) {
113
+ return {
114
+ conex: true,
115
+ reqStat: 401,
116
+ success: false,
117
+ data: {},
118
+ msg: 'Token not found'
119
+ };
120
+ }
121
+ return this.request('GET', 'auth', {}, { retryAttempts: 2, retryDelay: 1000 });
122
+ }
123
+ };
124
+ this.user = {
125
+ list: async () => {
126
+ return await this.request('GET', 'users', {});
127
+ },
128
+ get: async (userId, includePurchases = true) => {
129
+ return await this.request('GET', `user/${userId}?includePurchases=${includePurchases}`, {});
130
+ },
131
+ update: async (userId, userData) => {
132
+ return await this.request('PUT', `user/${userId}`, userData);
133
+ },
134
+ updateConfig: async (obj) => {
135
+ return await this.request('PUT', `user/${obj.id}/config`, obj);
136
+ },
137
+ updateAdmin: async (userId, isAdmin) => {
138
+ return await this.request('PUT', `user/${userId}/admin`, { isAdmin });
139
+ },
140
+ license: async (userId) => {
141
+ return await this.request('GET', `user/${userId}/license`, {});
142
+ }
143
+ };
144
+ this.purchase = {
145
+ new: async (paymentMethodId, userId) => {
146
+ return await this.request('POST', `user/${userId}/purchase/new/${paymentMethodId}`, {});
147
+ },
148
+ sync: async (purchaseId, userId, async = false) => {
149
+ return await this.request('POST', `user/${userId}/purchase/${purchaseId}/sync`, { async });
150
+ },
151
+ update: async (userId, purchase) => {
152
+ return await this.request('PUT', `user/${userId}/purchase/${purchase.id}`, purchase);
153
+ },
154
+ cancel: async (purchaseId, userId) => {
155
+ return await this.request('PUT', `user/${userId}/purchase/${purchaseId}/cancel`, {});
156
+ },
157
+ delete: async (purchaseId, userId) => {
158
+ return await this.request('DELETE', `user/${userId}/purchase/${purchaseId}`, {});
159
+ },
160
+ list: async (page = 1, pageSize, userId) => {
161
+ return await this.request('POST', `admin/purchases/search`, { page, pageSize, userId });
162
+ },
163
+ getFromGateway: async (purchaseId, userId, async = false) => {
164
+ return await this.request('GET', `user/${userId}/purchase/${purchaseId}/getFromGateway`, {});
165
+ },
166
+ };
167
+ this.products = {
168
+ list: async () => {
169
+ return await this.request('GET', 'products', {});
170
+ },
171
+ get: async (productId) => {
172
+ return await this.request('GET', `product/${productId}`, { mode: 'admin' });
173
+ },
174
+ update: async (productId, productData) => {
175
+ return await this.request('PUT', `product/${productId}`, productData);
176
+ }
177
+ };
178
+ this.paymentMethods = {
179
+ create: async (id, paymentMethodData) => {
180
+ return await this.request('POST', `bundle/${id}/payment-method`, paymentMethodData);
181
+ },
182
+ update: async (id, paymentMethodId, paymentMethodData) => {
183
+ return await this.request('PUT', `bundle/${id}/payment-method/${paymentMethodId}`, paymentMethodData);
184
+ },
185
+ delete: async (id, paymentMethodId) => {
186
+ return await this.request('DELETE', `bundle/${id}/payment-method/${paymentMethodId}`, {});
187
+ }
188
+ };
189
+ this.aux = {
190
+ countries: async () => {
191
+ return await this.request('GET', 'aux/countries', {});
192
+ },
193
+ states: async (countryId) => {
194
+ return await this.request('GET', `aux/country/${countryId}/states`, {});
195
+ },
196
+ cities: async (countryId, stateId) => {
197
+ return await this.request('GET', `aux/country/${countryId}/state/${stateId}/cities`, {});
198
+ }
199
+ };
200
+ this.admin = {
201
+ logs: {
202
+ /**
203
+ * @param filters
204
+ * @returns
205
+ */
206
+ list: async (filters = {}) => {
207
+ const defaultFilters = {
208
+ page: 1,
209
+ itemsPerPage: 50,
210
+ search: '',
211
+ ...filters
212
+ };
213
+ return await this.request('POST', 'logs', defaultFilters);
214
+ },
215
+ status: async () => {
216
+ return await this.request('GET', 'logs/status', {});
217
+ }
218
+ },
219
+ cronJobs: {
220
+ status: async () => {
221
+ return await this.request('GET', 'admin/cronjobs/status', {});
222
+ },
223
+ run: async (name) => {
224
+ return await this.request('POST', `admin/cronjobs/run/${name}`, {});
225
+ }
226
+ }
227
+ };
228
+ this.report = {
229
+ new: async (id, data) => {
230
+ return await this.request('POST', 'report', {
231
+ id,
232
+ data: (0, tools_1.safeStringify)(data),
233
+ appVersion: package_json_1.default.version
234
+ });
235
+ }
236
+ };
237
+ this.baseURL = config.baseURL;
238
+ this.tokenStorage = config.tokenStorage;
239
+ this.onTokenUpdate = config.onTokenUpdate;
240
+ this.onPin1Update = config.onPin1Update;
241
+ this.retryAttempts = config.retryAttempts ?? 0;
242
+ this.retryDelay = config.retryDelay ?? 500;
243
+ // Carrega tokens do storage se disponível
244
+ if (this.tokenStorage) {
245
+ this.bearer = this.tokenStorage.getToken() ?? '';
246
+ this.pin1 = this.tokenStorage.getPin1() ?? '';
247
+ }
248
+ }
249
+ /**
250
+ * Define o token de autenticação
251
+ */
252
+ setToken(token) {
253
+ this.bearer = token;
254
+ if (this.tokenStorage) {
255
+ this.tokenStorage.setToken(token);
256
+ }
257
+ if (this.onTokenUpdate) {
258
+ this.onTokenUpdate(token);
259
+ }
260
+ }
261
+ /**
262
+ * Define o PIN1
263
+ */
264
+ setPin1(pin1) {
265
+ this.pin1 = pin1;
266
+ if (this.tokenStorage) {
267
+ this.tokenStorage.setPin1(pin1);
268
+ }
269
+ if (this.onPin1Update) {
270
+ this.onPin1Update(pin1);
271
+ }
272
+ }
273
+ /**
274
+ * Obtém o token atual
275
+ */
276
+ getToken() {
277
+ return this.bearer;
278
+ }
279
+ /**
280
+ * Obtém o PIN1 atual
281
+ */
282
+ getPin1() {
283
+ return this.pin1;
284
+ }
285
+ /**
286
+ * Verifica se o servidor está saudável
287
+ */
288
+ async isHealthy() {
289
+ if (!this.isHealth) {
290
+ try {
291
+ const r = await this.request('GET', '', {});
292
+ if (r.success) {
293
+ this.isHealth = true;
294
+ return true;
295
+ }
296
+ }
297
+ catch { }
298
+ return false;
299
+ }
300
+ return true;
301
+ }
302
+ /**
303
+ * Requisição base para a API
304
+ */
305
+ async request(method, endpoint, params = {}, options) {
306
+ const result = {
307
+ conex: true,
308
+ reqStat: 0,
309
+ success: false,
310
+ data: {},
311
+ msg: ''
312
+ };
313
+ const headers = {};
314
+ if (this.bearer)
315
+ headers['authorization'] = `Bearer ${this.bearer}`;
316
+ if (this.pin1)
317
+ headers['pin1'] = this.pin1;
318
+ const maxAttempts = 1 + (options?.retryAttempts ?? this.retryAttempts);
319
+ const retryDelay = options?.retryDelay ?? this.retryDelay;
320
+ let attempts = 0;
321
+ let response = null;
322
+ while (attempts < maxAttempts) {
323
+ attempts++;
324
+ try {
325
+ const url = `${this.baseURL}/${endpoint}${method === 'GET' || method === 'DELETE' ? this.buildQueryString(params) : ''}`;
326
+ const fetchOptions = {
327
+ method,
328
+ headers: {
329
+ 'Content-Type': 'application/json',
330
+ ...headers
331
+ },
332
+ credentials: 'include'
333
+ };
334
+ if (method === 'POST' || method === 'PUT') {
335
+ fetchOptions.body = JSON.stringify(params);
336
+ }
337
+ response = await fetch(url, fetchOptions);
338
+ // Atualiza tokens se presentes nos headers
339
+ const newToken = response.headers.get('authorization');
340
+ if (newToken) {
341
+ this.setToken(newToken.replace('Bearer ', ''));
342
+ }
343
+ const newPin1 = response.headers.get('pin1');
344
+ if (newPin1) {
345
+ this.setPin1(newPin1);
346
+ }
347
+ // Se receber 503, marca como unhealthy e tenta novamente
348
+ if (response.status === 503) {
349
+ this.isHealth = false;
350
+ if (attempts >= maxAttempts)
351
+ break;
352
+ await new Promise(res => setTimeout(res, retryDelay));
353
+ continue;
354
+ }
355
+ this.isHealth = true;
356
+ result.reqStat = response.status;
357
+ result.success = response.status >= 200 && response.status < 300;
358
+ try {
359
+ const jsonData = await response.json();
360
+ result.data = jsonData;
361
+ result.msg = jsonData.msg ?? '';
362
+ }
363
+ catch {
364
+ result.msg = `stat_${response.status}`;
365
+ }
366
+ break;
367
+ }
368
+ catch (e) {
369
+ this.isHealth = false;
370
+ if (attempts >= maxAttempts) {
371
+ result.conex = false;
372
+ result.msg = `connectionError_${e.code ?? 'unknown'}`;
373
+ }
374
+ else {
375
+ await new Promise(res => setTimeout(res, retryDelay));
376
+ }
377
+ }
378
+ }
379
+ if (!result.conex) {
380
+ result.msg = result.msg || 'generic connection error';
381
+ }
382
+ return result;
383
+ }
384
+ /**
385
+ * Constrói query string a partir de um objeto
386
+ */
387
+ buildQueryString(params) {
388
+ if (!params || Object.keys(params).length === 0)
389
+ return '';
390
+ const queryParams = new URLSearchParams();
391
+ Object.keys(params).forEach(key => {
392
+ const value = params[key];
393
+ if (value !== undefined && value !== null) {
394
+ if (Array.isArray(value)) {
395
+ queryParams.append(key, JSON.stringify(value));
396
+ }
397
+ else if (typeof value === 'object') {
398
+ queryParams.append(key, JSON.stringify(value));
399
+ }
400
+ else {
401
+ queryParams.append(key, String(value));
402
+ }
403
+ }
404
+ });
405
+ return `?${queryParams.toString()}`;
406
+ }
407
+ async checkHealth() {
408
+ if (!this.isHealth) {
409
+ try {
410
+ const r = await this.request('GET', '', {});
411
+ if (r.success) {
412
+ this.isHealth = true;
413
+ return true;
414
+ }
415
+ }
416
+ catch { }
417
+ return false;
418
+ }
419
+ return true;
420
+ }
421
+ }
422
+ AuthApi.Client = Client;
423
+ })(AuthApi || (exports.AuthApi = AuthApi = {}));
424
+ // Exporta o namespace como default também
425
+ exports.default = AuthApi;
@@ -0,0 +1 @@
1
+ export declare function safeStringify(obj: any): string;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.safeStringify = safeStringify;
4
+ function safeStringify(obj) {
5
+ const seen = new WeakSet();
6
+ return JSON.stringify(obj, (key, val) => {
7
+ if (val != null && typeof val === "object") {
8
+ if (seen.has(val)) {
9
+ return '[Circular]';
10
+ }
11
+ seen.add(val);
12
+ }
13
+ return val;
14
+ });
15
+ }
16
+ ;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authenty/authapi-types",
3
- "version": "1.0.9",
3
+ "version": "1.0.11",
4
4
  "description": "Shared types for Authenty API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",