@thelllabs/winehaus-sdk 0.0.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/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # Winehaus SDK
2
+ ## Installation
3
+
4
+ Install the package with npm
5
+ ```
6
+ npm i @thelllabs/winehaus-sdk --save
7
+ ```
8
+
9
+ Use the package in the project
10
+
11
+ ```js
12
+ import 'dotenv/config'
13
+ import { WinehausSDK } from '@thelllabs/winehaus-sdk'
14
+
15
+ async function main() {
16
+ const sdk = new WinehausSDK({
17
+ baseURL: 'http://localhost:3000',
18
+ autoRefresh: true
19
+ });
20
+ await sdk.authenticate({ email: 'example@example.com', password: 'P@ssw0rd' })
21
+ }
22
+
23
+ main().then(() => {
24
+ console.log('script running with success')
25
+ })
26
+ ```
27
+
28
+
29
+
30
+ ## Generate Api from Swagger
31
+
32
+ `SWAGGER_JSON_PATH=http://localhost:3000/docs-json npm run gen:api`
@@ -0,0 +1,293 @@
1
+ "use strict";
2
+ /* eslint-disable */
3
+ /* tslint:disable */
4
+ // @ts-nocheck
5
+ /*
6
+ * ---------------------------------------------------------------
7
+ * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
8
+ * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
9
+ * ---------------------------------------------------------------
10
+ */
11
+ var __extends = (this && this.__extends) || (function () {
12
+ var extendStatics = function (d, b) {
13
+ extendStatics = Object.setPrototypeOf ||
14
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
16
+ return extendStatics(d, b);
17
+ };
18
+ return function (d, b) {
19
+ if (typeof b !== "function" && b !== null)
20
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
21
+ extendStatics(d, b);
22
+ function __() { this.constructor = d; }
23
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24
+ };
25
+ })();
26
+ var __assign = (this && this.__assign) || function () {
27
+ __assign = Object.assign || function(t) {
28
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
29
+ s = arguments[i];
30
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
31
+ t[p] = s[p];
32
+ }
33
+ return t;
34
+ };
35
+ return __assign.apply(this, arguments);
36
+ };
37
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
38
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
39
+ return new (P || (P = Promise))(function (resolve, reject) {
40
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
41
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
42
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
43
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
44
+ });
45
+ };
46
+ var __generator = (this && this.__generator) || function (thisArg, body) {
47
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
48
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
49
+ function verb(n) { return function (v) { return step([n, v]); }; }
50
+ function step(op) {
51
+ if (f) throw new TypeError("Generator is already executing.");
52
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
53
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
54
+ if (y = 0, t) op = [op[0] & 2, t.value];
55
+ switch (op[0]) {
56
+ case 0: case 1: t = op; break;
57
+ case 4: _.label++; return { value: op[1], done: false };
58
+ case 5: _.label++; y = op[1]; op = [0]; continue;
59
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
60
+ default:
61
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
62
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
63
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
64
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
65
+ if (t[2]) _.ops.pop();
66
+ _.trys.pop(); continue;
67
+ }
68
+ op = body.call(thisArg, _);
69
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
70
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
71
+ }
72
+ };
73
+ var __rest = (this && this.__rest) || function (s, e) {
74
+ var t = {};
75
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
76
+ t[p] = s[p];
77
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
78
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
79
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
80
+ t[p[i]] = s[p[i]];
81
+ }
82
+ return t;
83
+ };
84
+ var __importDefault = (this && this.__importDefault) || function (mod) {
85
+ return (mod && mod.__esModule) ? mod : { "default": mod };
86
+ };
87
+ Object.defineProperty(exports, "__esModule", { value: true });
88
+ exports.Api = exports.HttpClient = exports.ContentType = exports.TenantUserEntityDtoStatusEnum = exports.TenantUserEntityDtoRolesEnum = exports.CreateTenantUserDtoRolesEnum = void 0;
89
+ var CreateTenantUserDtoRolesEnum;
90
+ (function (CreateTenantUserDtoRolesEnum) {
91
+ CreateTenantUserDtoRolesEnum["Operator"] = "operator";
92
+ CreateTenantUserDtoRolesEnum["Admin"] = "admin";
93
+ CreateTenantUserDtoRolesEnum["Owner"] = "owner";
94
+ })(CreateTenantUserDtoRolesEnum = exports.CreateTenantUserDtoRolesEnum || (exports.CreateTenantUserDtoRolesEnum = {}));
95
+ var TenantUserEntityDtoRolesEnum;
96
+ (function (TenantUserEntityDtoRolesEnum) {
97
+ TenantUserEntityDtoRolesEnum["Operator"] = "operator";
98
+ TenantUserEntityDtoRolesEnum["Admin"] = "admin";
99
+ TenantUserEntityDtoRolesEnum["Owner"] = "owner";
100
+ })(TenantUserEntityDtoRolesEnum = exports.TenantUserEntityDtoRolesEnum || (exports.TenantUserEntityDtoRolesEnum = {}));
101
+ /** @example "enabled" */
102
+ var TenantUserEntityDtoStatusEnum;
103
+ (function (TenantUserEntityDtoStatusEnum) {
104
+ TenantUserEntityDtoStatusEnum["Enabled"] = "enabled";
105
+ TenantUserEntityDtoStatusEnum["Blocked"] = "blocked";
106
+ })(TenantUserEntityDtoStatusEnum = exports.TenantUserEntityDtoStatusEnum || (exports.TenantUserEntityDtoStatusEnum = {}));
107
+ var axios_1 = __importDefault(require("axios"));
108
+ var ContentType;
109
+ (function (ContentType) {
110
+ ContentType["Json"] = "application/json";
111
+ ContentType["JsonApi"] = "application/vnd.api+json";
112
+ ContentType["FormData"] = "multipart/form-data";
113
+ ContentType["UrlEncoded"] = "application/x-www-form-urlencoded";
114
+ ContentType["Text"] = "text/plain";
115
+ })(ContentType = exports.ContentType || (exports.ContentType = {}));
116
+ var HttpClient = /** @class */ (function () {
117
+ function HttpClient(_a) {
118
+ if (_a === void 0) { _a = {}; }
119
+ var _this = this;
120
+ var securityWorker = _a.securityWorker, secure = _a.secure, format = _a.format, axiosConfig = __rest(_a, ["securityWorker", "secure", "format"]);
121
+ this.securityData = null;
122
+ this.setSecurityData = function (data) {
123
+ _this.securityData = data;
124
+ };
125
+ this.request = function (_a) { return __awaiter(_this, void 0, void 0, function () {
126
+ var secureParams, _b, requestParams, responseFormat;
127
+ var secure = _a.secure, path = _a.path, type = _a.type, query = _a.query, format = _a.format, body = _a.body, params = __rest(_a, ["secure", "path", "type", "query", "format", "body"]);
128
+ return __generator(this, function (_c) {
129
+ switch (_c.label) {
130
+ case 0:
131
+ _b = (typeof secure === "boolean" ? secure : this.secure) &&
132
+ this.securityWorker;
133
+ if (!_b) return [3 /*break*/, 2];
134
+ return [4 /*yield*/, this.securityWorker(this.securityData)];
135
+ case 1:
136
+ _b = (_c.sent());
137
+ _c.label = 2;
138
+ case 2:
139
+ secureParams = (_b) ||
140
+ {};
141
+ requestParams = this.mergeRequestParams(params, secureParams);
142
+ responseFormat = format || this.format || undefined;
143
+ if (type === ContentType.FormData &&
144
+ body &&
145
+ body !== null &&
146
+ typeof body === "object") {
147
+ body = this.createFormData(body);
148
+ }
149
+ if (type === ContentType.Text &&
150
+ body &&
151
+ body !== null &&
152
+ typeof body !== "string") {
153
+ body = JSON.stringify(body);
154
+ }
155
+ return [2 /*return*/, this.instance.request(__assign(__assign({}, requestParams), { headers: __assign(__assign({}, (requestParams.headers || {})), (type ? { "Content-Type": type } : {})), params: query, responseType: responseFormat, data: body, url: path }))];
156
+ }
157
+ });
158
+ }); };
159
+ this.instance = axios_1.default.create(__assign(__assign({}, axiosConfig), { baseURL: axiosConfig.baseURL || "http://localhost:3000" }));
160
+ this.secure = secure;
161
+ this.format = format;
162
+ this.securityWorker = securityWorker;
163
+ }
164
+ HttpClient.prototype.mergeRequestParams = function (params1, params2) {
165
+ var method = params1.method || (params2 && params2.method);
166
+ return __assign(__assign(__assign(__assign({}, this.instance.defaults), params1), (params2 || {})), { headers: __assign(__assign(__assign({}, ((method &&
167
+ this.instance.defaults.headers[method.toLowerCase()]) ||
168
+ {})), (params1.headers || {})), ((params2 && params2.headers) || {})) });
169
+ };
170
+ HttpClient.prototype.stringifyFormItem = function (formItem) {
171
+ if (typeof formItem === "object" && formItem !== null) {
172
+ return JSON.stringify(formItem);
173
+ }
174
+ else {
175
+ return "".concat(formItem);
176
+ }
177
+ };
178
+ HttpClient.prototype.createFormData = function (input) {
179
+ var _this = this;
180
+ if (input instanceof FormData) {
181
+ return input;
182
+ }
183
+ return Object.keys(input || {}).reduce(function (formData, key) {
184
+ var property = input[key];
185
+ var propertyContent = property instanceof Array ? property : [property];
186
+ for (var _i = 0, propertyContent_1 = propertyContent; _i < propertyContent_1.length; _i++) {
187
+ var formItem = propertyContent_1[_i];
188
+ var isFileType = formItem instanceof Blob || formItem instanceof File;
189
+ formData.append(key, isFileType ? formItem : _this.stringifyFormItem(formItem));
190
+ }
191
+ return formData;
192
+ }, new FormData());
193
+ };
194
+ return HttpClient;
195
+ }());
196
+ exports.HttpClient = HttpClient;
197
+ /**
198
+ * @title winehaus-api
199
+ * @version 0.0.1
200
+ * @baseUrl http://localhost:3000
201
+ * @contact
202
+ */
203
+ var Api = /** @class */ (function (_super) {
204
+ __extends(Api, _super);
205
+ function Api() {
206
+ var _this = _super !== null && _super.apply(this, arguments) || this;
207
+ /**
208
+ * No description
209
+ *
210
+ * @tags App
211
+ * @name Index
212
+ * @request GET:/
213
+ * @response `200` `void`
214
+ */
215
+ _this.index = function (params) {
216
+ if (params === void 0) { params = {}; }
217
+ return _this.request(__assign({ path: "/", method: "GET" }, params));
218
+ };
219
+ _this.auth = {
220
+ /**
221
+ * No description
222
+ *
223
+ * @tags Authentication
224
+ * @name Logout
225
+ * @request POST:/auth/logout
226
+ * @secure
227
+ * @response `204` `void`
228
+ */
229
+ logout: function (params) {
230
+ if (params === void 0) { params = {}; }
231
+ return _this.request(__assign({ path: "/auth/logout", method: "POST", secure: true }, params));
232
+ },
233
+ /**
234
+ * No description
235
+ *
236
+ * @tags Authentication
237
+ * @name RequestPasswordReset
238
+ * @request POST:/auth/request-password-reset
239
+ * @secure
240
+ * @response `204` `void`
241
+ */
242
+ requestPasswordReset: function (data, params) {
243
+ if (params === void 0) { params = {}; }
244
+ return _this.request(__assign({ path: "/auth/request-password-reset", method: "POST", body: data, secure: true, type: ContentType.Json }, params));
245
+ },
246
+ /**
247
+ * No description
248
+ *
249
+ * @tags Authentication
250
+ * @name ResetPassword
251
+ * @request PATCH:/auth/reset-password
252
+ * @secure
253
+ * @response `200` `SigninResponseDto`
254
+ */
255
+ resetPassword: function (data, params) {
256
+ if (params === void 0) { params = {}; }
257
+ return _this.request(__assign({ path: "/auth/reset-password", method: "PATCH", body: data, secure: true, type: ContentType.Json, format: "json" }, params));
258
+ },
259
+ /**
260
+ * No description
261
+ *
262
+ * @tags Authentication
263
+ * @name SignIn
264
+ * @request POST:/auth/signin
265
+ * @secure
266
+ * @response `200` `SigninResponseDto`
267
+ */
268
+ signIn: function (data, params) {
269
+ if (params === void 0) { params = {}; }
270
+ return _this.request(__assign({ path: "/auth/signin", method: "POST", body: data, secure: true, type: ContentType.Json, format: "json" }, params));
271
+ },
272
+ };
273
+ _this.admin = {
274
+ /**
275
+ * @description Gives some user access to the tenant. If there's no account attached to this users, it creates a new one
276
+ *
277
+ * @tags Admin Users
278
+ * @name CreateTenantUser
279
+ * @request POST:/admin/tenants/{tenantId}/users
280
+ * @secure
281
+ * @response `201` `TenantUserEntityDto`
282
+ * @response `403` `HttpExceptionDto` Need user with one of these roles: owner, admin
283
+ */
284
+ createTenantUser: function (tenantId, data, params) {
285
+ if (params === void 0) { params = {}; }
286
+ return _this.request(__assign({ path: "/admin/tenants/".concat(tenantId, "/users"), method: "POST", body: data, secure: true, type: ContentType.Json, format: "json" }, params));
287
+ },
288
+ };
289
+ return _this;
290
+ }
291
+ return Api;
292
+ }(HttpClient));
293
+ exports.Api = Api;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.WinehausSDK = void 0;
18
+ var sdk_1 = require("./sdk");
19
+ Object.defineProperty(exports, "WinehausSDK", { enumerable: true, get: function () { return sdk_1.WinehausSDK; } });
20
+ __exportStar(require("./api/api"), exports);
21
+ __exportStar(require("./interfaces"), exports);
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,329 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || function (mod) {
30
+ if (mod && mod.__esModule) return mod;
31
+ var result = {};
32
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
33
+ __setModuleDefault(result, mod);
34
+ return result;
35
+ };
36
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
37
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
38
+ return new (P || (P = Promise))(function (resolve, reject) {
39
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
40
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
41
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
42
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
43
+ });
44
+ };
45
+ var __generator = (this && this.__generator) || function (thisArg, body) {
46
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
47
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
48
+ function verb(n) { return function (v) { return step([n, v]); }; }
49
+ function step(op) {
50
+ if (f) throw new TypeError("Generator is already executing.");
51
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
52
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
53
+ if (y = 0, t) op = [op[0] & 2, t.value];
54
+ switch (op[0]) {
55
+ case 0: case 1: t = op; break;
56
+ case 4: _.label++; return { value: op[1], done: false };
57
+ case 5: _.label++; y = op[1]; op = [0]; continue;
58
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
59
+ default:
60
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
61
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
62
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
63
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
64
+ if (t[2]) _.ops.pop();
65
+ _.trys.pop(); continue;
66
+ }
67
+ op = body.call(thisArg, _);
68
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
69
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
70
+ }
71
+ };
72
+ var __importDefault = (this && this.__importDefault) || function (mod) {
73
+ return (mod && mod.__esModule) ? mod : { "default": mod };
74
+ };
75
+ Object.defineProperty(exports, "__esModule", { value: true });
76
+ exports.WinehausSDK = void 0;
77
+ var jwt_decode_1 = __importDefault(require("jwt-decode"));
78
+ var api_1 = require("./api/api");
79
+ var mitt_1 = __importDefault(require("mitt"));
80
+ var datefns = __importStar(require("date-fns"));
81
+ var WinehausSDK = /** @class */ (function () {
82
+ function WinehausSDK(options) {
83
+ this.authToken = '';
84
+ this.refreshToken = '';
85
+ this.defaultOptions = {
86
+ autoRefresh: false,
87
+ tokenExpireOffset: 5000,
88
+ };
89
+ this.options = __assign(__assign({}, this.defaultOptions), (options || {}));
90
+ this.emitter = (0, mitt_1.default)();
91
+ this.api = new api_1.Api({
92
+ baseURL: options.baseURL,
93
+ securityWorker: function (securityData) {
94
+ if (!(securityData === null || securityData === void 0 ? void 0 : securityData.bearer)) {
95
+ return {};
96
+ }
97
+ return {
98
+ headers: {
99
+ Authorization: "Bearer ".concat(securityData === null || securityData === void 0 ? void 0 : securityData.bearer),
100
+ },
101
+ };
102
+ },
103
+ secure: true,
104
+ });
105
+ this.hookInterceptors();
106
+ }
107
+ WinehausSDK.prototype.enableAutoRefresh = function (force) {
108
+ var _this = this;
109
+ if (this.options.autoRefresh && !force)
110
+ return;
111
+ this.options.autoRefresh = true;
112
+ if (!this.autoRefreshTimer) {
113
+ this.autoRefreshTimer = setInterval(function () {
114
+ return _this.triggerRefreshToken().catch(function (error) { var _a; return console.error(((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) || error); });
115
+ }, 500);
116
+ }
117
+ };
118
+ WinehausSDK.prototype.disableAutoRefresh = function () {
119
+ if (!this.options.autoRefresh)
120
+ return;
121
+ this.options.autoRefresh = false;
122
+ if (this.autoRefreshTimer) {
123
+ clearInterval(this.autoRefreshTimer);
124
+ this.autoRefreshTimer = undefined;
125
+ }
126
+ };
127
+ WinehausSDK.prototype.hookTimer = function () {
128
+ if (!this.options.autoRefresh)
129
+ return;
130
+ if (!this.autoRefreshTimer) {
131
+ this.enableAutoRefresh();
132
+ }
133
+ };
134
+ WinehausSDK.prototype.hookInterceptors = function () {
135
+ var _this = this;
136
+ var refreshTokenUsed = new Set();
137
+ this.api.instance.interceptors.request.use(function (config) {
138
+ if (_this.isTokenExpired()) {
139
+ _this.clearTokens();
140
+ }
141
+ return config;
142
+ });
143
+ this.api.instance.interceptors.response.use(function (response) {
144
+ return response;
145
+ }, function (error) { return __awaiter(_this, void 0, void 0, function () {
146
+ var error_1;
147
+ var _a, _b;
148
+ return __generator(this, function (_c) {
149
+ switch (_c.label) {
150
+ case 0:
151
+ if (!(((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status) === 401 &&
152
+ this.authToken &&
153
+ this.refreshToken &&
154
+ !refreshTokenUsed.has(this.refreshToken))) return [3 /*break*/, 4];
155
+ refreshTokenUsed.add(this.refreshToken);
156
+ _c.label = 1;
157
+ case 1:
158
+ _c.trys.push([1, 3, , 4]);
159
+ return [4 /*yield*/, this.refreshTokens()];
160
+ case 2:
161
+ _c.sent();
162
+ return [3 /*break*/, 4];
163
+ case 3:
164
+ error_1 = _c.sent();
165
+ console.error('Refresh token failed', ((_b = error_1 === null || error_1 === void 0 ? void 0 : error_1.response) === null || _b === void 0 ? void 0 : _b.data) || error_1);
166
+ this.clearTokens();
167
+ return [3 /*break*/, 4];
168
+ case 4: return [2 /*return*/, Promise.reject(error)];
169
+ }
170
+ });
171
+ }); });
172
+ };
173
+ WinehausSDK.prototype.clearTokens = function () {
174
+ this.authToken = '';
175
+ this.authTokenDecoded = undefined;
176
+ this.refreshToken = '';
177
+ this.refreshTokenDecoded = undefined;
178
+ this.emitter.emit('authChanged', { authToken: '', refreshToken: '' });
179
+ };
180
+ WinehausSDK.prototype.authenticate = function (credential, opts) {
181
+ return __awaiter(this, void 0, void 0, function () {
182
+ return __generator(this, function (_a) {
183
+ switch (_a.label) {
184
+ case 0:
185
+ if (!(opts === null || opts === void 0 ? void 0 : opts.avoidEvents))
186
+ this.emitter.emit('connecting');
187
+ return [4 /*yield*/, this.authenticateAsUser(credential)];
188
+ case 1:
189
+ _a.sent();
190
+ this.credential = credential;
191
+ if (!(opts === null || opts === void 0 ? void 0 : opts.avoidEvents))
192
+ this.emitter.emit('connected');
193
+ this.hookTimer();
194
+ return [2 /*return*/];
195
+ }
196
+ });
197
+ });
198
+ };
199
+ WinehausSDK.prototype.reAuthenticate = function () {
200
+ return __awaiter(this, void 0, void 0, function () {
201
+ return __generator(this, function (_a) {
202
+ switch (_a.label) {
203
+ case 0:
204
+ if (!this.credential)
205
+ throw new Error('No credential found');
206
+ return [4 /*yield*/, this.authenticate(this.credential)];
207
+ case 1:
208
+ _a.sent();
209
+ return [2 /*return*/];
210
+ }
211
+ });
212
+ });
213
+ };
214
+ WinehausSDK.prototype.isAuthenticated = function () {
215
+ return this.authToken.length > 0;
216
+ };
217
+ WinehausSDK.prototype.setAuthToken = function (token) {
218
+ if (!token || (token === null || token === void 0 ? void 0 : token.length) === 0)
219
+ throw new Error('Invalid token');
220
+ if (this.authToken === token)
221
+ return;
222
+ var decoded = (0, jwt_decode_1.default)(token);
223
+ if (!decoded.exp)
224
+ throw new Error('Invalid decoded token');
225
+ this.authTokenDecoded = decoded;
226
+ this.authToken = token;
227
+ this.api.setSecurityData({ bearer: token });
228
+ };
229
+ WinehausSDK.prototype.triggerRefreshToken = function () {
230
+ var _a;
231
+ return __awaiter(this, void 0, void 0, function () {
232
+ return __generator(this, function (_b) {
233
+ switch (_b.label) {
234
+ case 0:
235
+ if (!this.authToken || !this.refreshToken) {
236
+ return [2 /*return*/, this.clearTokens()];
237
+ }
238
+ if (!((_a = this.authTokenDecoded) === null || _a === void 0 ? void 0 : _a.exp)) {
239
+ return [2 /*return*/];
240
+ }
241
+ if (!this.isTokenExpired()) return [3 /*break*/, 2];
242
+ return [4 /*yield*/, this.refreshTokens()];
243
+ case 1:
244
+ _b.sent();
245
+ _b.label = 2;
246
+ case 2: return [2 /*return*/];
247
+ }
248
+ });
249
+ });
250
+ };
251
+ WinehausSDK.prototype.isTokenExpired = function () {
252
+ var _a, _b, _c, _d;
253
+ var offset = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.tokenExpireOffset) || 0;
254
+ if (offset < 0)
255
+ return true;
256
+ if (!((_b = this.authTokenDecoded) === null || _b === void 0 ? void 0 : _b.exp) || !((_c = this.refreshTokenDecoded) === null || _c === void 0 ? void 0 : _c.exp)) {
257
+ return true;
258
+ }
259
+ var nextExpiration = Math.min(this.authTokenDecoded.exp, (_d = this.refreshTokenDecoded) === null || _d === void 0 ? void 0 : _d.exp) * 1000;
260
+ return datefns.isPast(datefns.subSeconds(nextExpiration, offset));
261
+ };
262
+ WinehausSDK.prototype.getAuthToken = function () {
263
+ return this.authToken.toString();
264
+ };
265
+ WinehausSDK.prototype.setRefreshToken = function (refreshToken) {
266
+ if (this.refreshToken === refreshToken)
267
+ return;
268
+ var refreshTokenDecoded = (0, jwt_decode_1.default)(refreshToken);
269
+ if (!refreshTokenDecoded.exp)
270
+ throw new Error('Invalid decoded token');
271
+ // if(this.refreshTokenDecoded && this.refreshTokenDecoded != refreshToken) {
272
+ // this.emitter.emit('refreshTokenChanged', this.refreshTokenDecoded, refreshTokenDecoded);
273
+ // }
274
+ this.refreshTokenDecoded = refreshTokenDecoded;
275
+ this.refreshToken = refreshToken;
276
+ };
277
+ WinehausSDK.prototype.getRefreshToken = function () {
278
+ return this.refreshToken.toString();
279
+ };
280
+ WinehausSDK.prototype.refreshTokens = function () {
281
+ return __awaiter(this, void 0, void 0, function () {
282
+ return __generator(this, function (_a) {
283
+ switch (_a.label) {
284
+ case 0:
285
+ // ToDo: Refresh token is not implemented under this version. For a while, lets just re-auth
286
+ this.clearTokens();
287
+ return [4 /*yield*/, this.reAuthenticate()];
288
+ case 1:
289
+ _a.sent();
290
+ return [2 /*return*/];
291
+ }
292
+ });
293
+ });
294
+ };
295
+ WinehausSDK.prototype.authenticateAsUser = function (credential) {
296
+ return __awaiter(this, void 0, void 0, function () {
297
+ var data;
298
+ return __generator(this, function (_a) {
299
+ switch (_a.label) {
300
+ case 0: return [4 /*yield*/, this.api.auth.signIn(credential)];
301
+ case 1:
302
+ data = (_a.sent()).data;
303
+ if (!data.token) {
304
+ throw new Error('Authentication failed. Please check your credentials.');
305
+ }
306
+ // For a while, our api doesn't accept refresh tokens, we will implement it in next versions
307
+ this.setTokens({ token: data.token, refreshToken: '' });
308
+ return [2 /*return*/];
309
+ }
310
+ });
311
+ });
312
+ };
313
+ WinehausSDK.prototype.setTokens = function (data) {
314
+ this.setAuthToken(data.token);
315
+ this.setRefreshToken(data.refreshToken);
316
+ this.emitter.emit('authChanged', { authToken: data.token, refreshToken: data.refreshToken });
317
+ };
318
+ WinehausSDK.prototype.getAuthTokenDecoded = function () {
319
+ return this.authTokenDecoded;
320
+ };
321
+ WinehausSDK.prototype.getRefreshTokenDecoded = function () {
322
+ return this.refreshTokenDecoded;
323
+ };
324
+ WinehausSDK.decodeToken = function (token) {
325
+ return (0, jwt_decode_1.default)(token, {});
326
+ };
327
+ return WinehausSDK;
328
+ }());
329
+ exports.WinehausSDK = WinehausSDK;