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