@anzar-auth/client 1.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,970 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ Anzar: () => Anzar
34
+ });
35
+ module.exports = __toCommonJS(src_exports);
36
+ var import_axios6 = __toESM(require("axios"), 1);
37
+
38
+ // src/adapters/memory_storage.ts
39
+ var MemoryStorage = class {
40
+ acessToken = null;
41
+ refreshToken = null;
42
+ getToken() {
43
+ return this.acessToken;
44
+ }
45
+ getRefreshToken() {
46
+ return this.refreshToken;
47
+ }
48
+ onTokenRefresh(tokens) {
49
+ this.acessToken = tokens.access;
50
+ this.refreshToken = tokens.refresh;
51
+ }
52
+ onSessionExpired() {
53
+ this.acessToken = null;
54
+ this.refreshToken = null;
55
+ }
56
+ onLogout() {
57
+ this.acessToken = null;
58
+ this.refreshToken = null;
59
+ }
60
+ };
61
+
62
+ // src/api/auth.ts
63
+ var import_axios = __toESM(require("axios"), 1);
64
+ var AuthModule = class {
65
+ constructor(authApi, userApi, strategy, options) {
66
+ this.authApi = authApi;
67
+ this.userApi = userApi;
68
+ this.strategy = strategy;
69
+ this.options = options;
70
+ }
71
+ async login(body) {
72
+ const response = await this.authApi.login(body);
73
+ const auth_response = response.data;
74
+ if (auth_response.tokens) {
75
+ this.options?.storage.onTokenRefresh?.(auth_response.tokens);
76
+ }
77
+ return {
78
+ user: auth_response.user,
79
+ verification: auth_response.verification
80
+ };
81
+ }
82
+ async register(body) {
83
+ const response = await this.authApi.register(body);
84
+ const auth_response = response.data;
85
+ if (auth_response.tokens) {
86
+ this.options?.storage.onTokenRefresh?.(auth_response.tokens);
87
+ }
88
+ return {
89
+ user: auth_response.user,
90
+ verification: auth_response.verification
91
+ };
92
+ }
93
+ async logout() {
94
+ const refreshToken = this.options?.storage.getRefreshToken();
95
+ await this.authApi.logout({ refresh_token: refreshToken ?? "" });
96
+ this.options?.storage.onLogout?.();
97
+ }
98
+ resetPassword(body) {
99
+ this.authApi.requestPasswordReset(body);
100
+ }
101
+ async isAuthenticated() {
102
+ try {
103
+ const response = await this.userApi.findUser();
104
+ return !!response.data.username;
105
+ } catch (error) {
106
+ if (import_axios.default.isAxiosError(error) && error.response?.status === 401) {
107
+ return false;
108
+ }
109
+ throw false;
110
+ }
111
+ }
112
+ async session() {
113
+ if (this.strategy !== "Session" /* Session */) {
114
+ throw new Error("session() is only available with Session auth strategy");
115
+ }
116
+ const response = await this.authApi.getSession();
117
+ return response.data;
118
+ }
119
+ };
120
+
121
+ // src/api/interceptor.ts
122
+ var JwtInterceptor = class {
123
+ isRefreshing = false;
124
+ waitingQueue = [];
125
+ drainQueue(token) {
126
+ this.waitingQueue.forEach(({ resolve }) => resolve(token));
127
+ this.waitingQueue = [];
128
+ }
129
+ rejectQueue(error) {
130
+ this.waitingQueue.forEach(({ reject }) => reject(error));
131
+ this.waitingQueue = [];
132
+ }
133
+ apply(axiosInstance, options) {
134
+ const REFRESH_URI = "/auth/refresh-token";
135
+ axiosInstance.interceptors.request.use(
136
+ (config) => {
137
+ const accessToken = options?.storage.getToken();
138
+ if (!config.url?.includes(REFRESH_URI) && accessToken) {
139
+ config.headers.Authorization = `Bearer ${accessToken}`;
140
+ }
141
+ return config;
142
+ },
143
+ (error) => {
144
+ return Promise.reject(error);
145
+ }
146
+ );
147
+ axiosInstance.interceptors.response.use(
148
+ (response) => response,
149
+ async (error) => {
150
+ const originalRequest = error.config;
151
+ if (error.response?.status !== 401 || originalRequest._retry || originalRequest.url?.includes(REFRESH_URI)) {
152
+ return Promise.reject(error);
153
+ }
154
+ if (this.isRefreshing) {
155
+ return new Promise((resolve, reject) => {
156
+ this.waitingQueue.push({ resolve, reject });
157
+ }).then((newToken) => {
158
+ originalRequest.headers.Authorization = `Bearer ${newToken}`;
159
+ return axiosInstance(originalRequest);
160
+ });
161
+ }
162
+ originalRequest._retry = true;
163
+ this.isRefreshing = true;
164
+ try {
165
+ const refreshToken = options?.storage.getRefreshToken();
166
+ if (!refreshToken) return Promise.reject(error);
167
+ const response = await axiosInstance.post(REFRESH_URI, {
168
+ refresh_token: refreshToken
169
+ });
170
+ const auth_response = response.data;
171
+ if (auth_response.tokens) {
172
+ options?.storage.onTokenRefresh?.(auth_response.tokens);
173
+ }
174
+ this.drainQueue(auth_response.tokens?.access);
175
+ originalRequest.headers.Authorization = `Bearer ${auth_response.tokens?.access}`;
176
+ return axiosInstance(originalRequest);
177
+ } catch (e) {
178
+ this.rejectQueue(e);
179
+ options?.storage.onSessionExpired?.();
180
+ return Promise.reject(e);
181
+ } finally {
182
+ this.isRefreshing = false;
183
+ }
184
+ }
185
+ );
186
+ }
187
+ };
188
+
189
+ // src/generated/api/auth-api.ts
190
+ var import_axios3 = __toESM(require("axios"), 1);
191
+
192
+ // src/generated/base.ts
193
+ var import_axios2 = __toESM(require("axios"), 1);
194
+ var BASE_PATH = "http://localhost".replace(/\/+$/, "");
195
+ var BaseAPI = class {
196
+ constructor(configuration, basePath = BASE_PATH, axios3 = import_axios2.default) {
197
+ this.basePath = basePath;
198
+ this.axios = axios3;
199
+ if (configuration) {
200
+ this.configuration = configuration;
201
+ this.basePath = configuration.basePath ?? basePath;
202
+ }
203
+ }
204
+ configuration;
205
+ };
206
+ var RequiredError = class extends Error {
207
+ constructor(field, msg) {
208
+ super(msg);
209
+ this.field = field;
210
+ this.name = "RequiredError";
211
+ }
212
+ };
213
+ var operationServerMap = {};
214
+
215
+ // src/generated/common.ts
216
+ var DUMMY_BASE_URL = "https://example.com";
217
+ var assertParamExists = function(functionName, paramName, paramValue) {
218
+ if (paramValue === null || paramValue === void 0) {
219
+ throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`);
220
+ }
221
+ };
222
+ var setBearerAuthToObject = async function(object, configuration) {
223
+ if (configuration && configuration.accessToken) {
224
+ const accessToken = typeof configuration.accessToken === "function" ? await configuration.accessToken() : await configuration.accessToken;
225
+ object["Authorization"] = "Bearer " + accessToken;
226
+ }
227
+ };
228
+ function setFlattenedQueryParams(urlSearchParams, parameter, key = "") {
229
+ if (parameter == null) return;
230
+ if (typeof parameter === "object") {
231
+ if (Array.isArray(parameter) || parameter instanceof Set) {
232
+ parameter.forEach((item) => setFlattenedQueryParams(urlSearchParams, item, key));
233
+ } else {
234
+ Object.keys(parameter).forEach(
235
+ (currentKey) => setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== "" ? "." : ""}${currentKey}`)
236
+ );
237
+ }
238
+ } else {
239
+ if (urlSearchParams.has(key)) {
240
+ urlSearchParams.append(key, parameter);
241
+ } else {
242
+ urlSearchParams.set(key, parameter);
243
+ }
244
+ }
245
+ }
246
+ var setSearchParams = function(url, ...objects) {
247
+ const searchParams = new URLSearchParams(url.search);
248
+ setFlattenedQueryParams(searchParams, objects);
249
+ url.search = searchParams.toString();
250
+ };
251
+ var replaceWithSerializableTypeIfNeeded = function(key, value) {
252
+ if (value instanceof Set) {
253
+ return Array.from(value);
254
+ } else {
255
+ return value;
256
+ }
257
+ };
258
+ var serializeDataIfNeeded = function(value, requestOptions, configuration) {
259
+ const nonString = typeof value !== "string";
260
+ const needsSerialization = nonString && configuration && configuration.isJsonMime ? configuration.isJsonMime(requestOptions.headers["Content-Type"]) : nonString;
261
+ return needsSerialization ? JSON.stringify(value !== void 0 ? value : {}, replaceWithSerializableTypeIfNeeded) : value || "";
262
+ };
263
+ var toPathString = function(url) {
264
+ return url.pathname + url.search + url.hash;
265
+ };
266
+ var createRequestFunction = function(axiosArgs, globalAxios5, BASE_PATH2, configuration) {
267
+ return (axios3 = globalAxios5, basePath = BASE_PATH2) => {
268
+ const axiosRequestArgs = { ...axiosArgs.options, url: (axios3.defaults.baseURL ? "" : configuration?.basePath ?? basePath) + axiosArgs.url };
269
+ return axios3.request(axiosRequestArgs);
270
+ };
271
+ };
272
+
273
+ // src/generated/api/auth-api.ts
274
+ var AuthApiAxiosParamCreator = function(configuration) {
275
+ return {
276
+ /**
277
+ * Returns the currently authenticated user\'s session data. Requires a valid Bearer token.
278
+ * @summary Get current session
279
+ * @param {*} [options] Override http request option.
280
+ * @throws {RequiredError}
281
+ */
282
+ getSession: async (options = {}) => {
283
+ const localVarPath = `/auth/session`;
284
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
285
+ let baseOptions;
286
+ if (configuration) {
287
+ baseOptions = configuration.baseOptions;
288
+ }
289
+ const localVarRequestOptions = { method: "GET", ...baseOptions, ...options };
290
+ const localVarHeaderParameter = {};
291
+ const localVarQueryParameter = {};
292
+ await setBearerAuthToObject(localVarHeaderParameter, configuration);
293
+ localVarHeaderParameter["Accept"] = "application/json";
294
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
295
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
296
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
297
+ return {
298
+ url: toPathString(localVarUrlObj),
299
+ options: localVarRequestOptions
300
+ };
301
+ },
302
+ /**
303
+ * Authenticates a user with email and password. Returns an access token and refresh token on success.
304
+ * @summary User login
305
+ * @param {LoginRequest} loginRequest User login credentials
306
+ * @param {*} [options] Override http request option.
307
+ * @throws {RequiredError}
308
+ */
309
+ login: async (loginRequest, options = {}) => {
310
+ assertParamExists("login", "loginRequest", loginRequest);
311
+ const localVarPath = `/auth/login`;
312
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
313
+ let baseOptions;
314
+ if (configuration) {
315
+ baseOptions = configuration.baseOptions;
316
+ }
317
+ const localVarRequestOptions = { method: "POST", ...baseOptions, ...options };
318
+ const localVarHeaderParameter = {};
319
+ const localVarQueryParameter = {};
320
+ localVarHeaderParameter["Content-Type"] = "application/json";
321
+ localVarHeaderParameter["Accept"] = "application/json";
322
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
323
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
324
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
325
+ localVarRequestOptions.data = serializeDataIfNeeded(loginRequest, localVarRequestOptions, configuration);
326
+ return {
327
+ url: toPathString(localVarUrlObj),
328
+ options: localVarRequestOptions
329
+ };
330
+ },
331
+ /**
332
+ * Invalidates the current session and refresh token. The client should discard stored tokens.
333
+ * @summary Logout
334
+ * @param {RefreshTokenRequest} refreshTokenRequest
335
+ * @param {*} [options] Override http request option.
336
+ * @throws {RequiredError}
337
+ */
338
+ logout: async (refreshTokenRequest, options = {}) => {
339
+ assertParamExists("logout", "refreshTokenRequest", refreshTokenRequest);
340
+ const localVarPath = `/auth/logout`;
341
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
342
+ let baseOptions;
343
+ if (configuration) {
344
+ baseOptions = configuration.baseOptions;
345
+ }
346
+ const localVarRequestOptions = { method: "POST", ...baseOptions, ...options };
347
+ const localVarHeaderParameter = {};
348
+ const localVarQueryParameter = {};
349
+ await setBearerAuthToObject(localVarHeaderParameter, configuration);
350
+ localVarHeaderParameter["Content-Type"] = "application/json";
351
+ localVarHeaderParameter["Accept"] = "application/json";
352
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
353
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
354
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
355
+ localVarRequestOptions.data = serializeDataIfNeeded(refreshTokenRequest, localVarRequestOptions, configuration);
356
+ return {
357
+ url: toPathString(localVarUrlObj),
358
+ options: localVarRequestOptions
359
+ };
360
+ },
361
+ /**
362
+ * Issues a new access token using a valid refresh token. Rotate refresh tokens on each call.
363
+ * @summary Refresh access token
364
+ * @param {RefreshTokenRequest} refreshTokenRequest
365
+ * @param {*} [options] Override http request option.
366
+ * @throws {RequiredError}
367
+ */
368
+ refreshToken: async (refreshTokenRequest, options = {}) => {
369
+ assertParamExists("refreshToken", "refreshTokenRequest", refreshTokenRequest);
370
+ const localVarPath = `/auth/refresh-token`;
371
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
372
+ let baseOptions;
373
+ if (configuration) {
374
+ baseOptions = configuration.baseOptions;
375
+ }
376
+ const localVarRequestOptions = { method: "POST", ...baseOptions, ...options };
377
+ const localVarHeaderParameter = {};
378
+ const localVarQueryParameter = {};
379
+ await setBearerAuthToObject(localVarHeaderParameter, configuration);
380
+ localVarHeaderParameter["Content-Type"] = "application/json";
381
+ localVarHeaderParameter["Accept"] = "application/json";
382
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
383
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
384
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
385
+ localVarRequestOptions.data = serializeDataIfNeeded(refreshTokenRequest, localVarRequestOptions, configuration);
386
+ return {
387
+ url: toPathString(localVarUrlObj),
388
+ options: localVarRequestOptions
389
+ };
390
+ },
391
+ /**
392
+ * Creates a new user account. Sends a verification email upon successful registration.
393
+ * @summary Register a new user
394
+ * @param {RegisterRequest} registerRequest User register credentials
395
+ * @param {*} [options] Override http request option.
396
+ * @throws {RequiredError}
397
+ */
398
+ register: async (registerRequest, options = {}) => {
399
+ assertParamExists("register", "registerRequest", registerRequest);
400
+ const localVarPath = `/auth/register`;
401
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
402
+ let baseOptions;
403
+ if (configuration) {
404
+ baseOptions = configuration.baseOptions;
405
+ }
406
+ const localVarRequestOptions = { method: "POST", ...baseOptions, ...options };
407
+ const localVarHeaderParameter = {};
408
+ const localVarQueryParameter = {};
409
+ localVarHeaderParameter["Content-Type"] = "application/json";
410
+ localVarHeaderParameter["Accept"] = "application/json";
411
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
412
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
413
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
414
+ localVarRequestOptions.data = serializeDataIfNeeded(registerRequest, localVarRequestOptions, configuration);
415
+ return {
416
+ url: toPathString(localVarUrlObj),
417
+ options: localVarRequestOptions
418
+ };
419
+ },
420
+ /**
421
+ * Validates the reset token from the email link and renders the password reset form.
422
+ * @summary Render password reset form
423
+ * @param {TokenQuery} token Password reset token
424
+ * @param {*} [options] Override http request option.
425
+ * @throws {RequiredError}
426
+ */
427
+ renderResetForm: async (token, options = {}) => {
428
+ assertParamExists("renderResetForm", "token", token);
429
+ const localVarPath = `/auth/password/reset`;
430
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
431
+ let baseOptions;
432
+ if (configuration) {
433
+ baseOptions = configuration.baseOptions;
434
+ }
435
+ const localVarRequestOptions = { method: "GET", ...baseOptions, ...options };
436
+ const localVarHeaderParameter = {};
437
+ const localVarQueryParameter = {};
438
+ if (token !== void 0) {
439
+ for (const [key, value] of Object.entries(token)) {
440
+ localVarQueryParameter[key] = value;
441
+ }
442
+ }
443
+ localVarHeaderParameter["Accept"] = "text/html,application/json";
444
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
445
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
446
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
447
+ return {
448
+ url: toPathString(localVarUrlObj),
449
+ options: localVarRequestOptions
450
+ };
451
+ },
452
+ /**
453
+ * Sends a password reset link to the provided email address if an account exists.
454
+ * @summary Request a password reset
455
+ * @param {EmailRequest} emailRequest Email address to send the reset link to
456
+ * @param {*} [options] Override http request option.
457
+ * @throws {RequiredError}
458
+ */
459
+ requestPasswordReset: async (emailRequest, options = {}) => {
460
+ assertParamExists("requestPasswordReset", "emailRequest", emailRequest);
461
+ const localVarPath = `/auth/password/forgot`;
462
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
463
+ let baseOptions;
464
+ if (configuration) {
465
+ baseOptions = configuration.baseOptions;
466
+ }
467
+ const localVarRequestOptions = { method: "POST", ...baseOptions, ...options };
468
+ const localVarHeaderParameter = {};
469
+ const localVarQueryParameter = {};
470
+ localVarHeaderParameter["Content-Type"] = "application/json";
471
+ localVarHeaderParameter["Accept"] = "application/json";
472
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
473
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
474
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
475
+ localVarRequestOptions.data = serializeDataIfNeeded(emailRequest, localVarRequestOptions, configuration);
476
+ return {
477
+ url: toPathString(localVarUrlObj),
478
+ options: localVarRequestOptions
479
+ };
480
+ },
481
+ /**
482
+ * Submits a new password using a valid reset token. Invalidates the token after use.
483
+ * @summary Submit new password
484
+ * @param {ResetPasswordRequest} resetPasswordRequest Reset token and the new password
485
+ * @param {*} [options] Override http request option.
486
+ * @throws {RequiredError}
487
+ */
488
+ submitNewPassword: async (resetPasswordRequest, options = {}) => {
489
+ assertParamExists("submitNewPassword", "resetPasswordRequest", resetPasswordRequest);
490
+ const localVarPath = `/auth/password/reset`;
491
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
492
+ let baseOptions;
493
+ if (configuration) {
494
+ baseOptions = configuration.baseOptions;
495
+ }
496
+ const localVarRequestOptions = { method: "POST", ...baseOptions, ...options };
497
+ const localVarHeaderParameter = {};
498
+ const localVarQueryParameter = {};
499
+ localVarHeaderParameter["Content-Type"] = "application/json";
500
+ localVarHeaderParameter["Accept"] = "application/json";
501
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
502
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
503
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
504
+ localVarRequestOptions.data = serializeDataIfNeeded(resetPasswordRequest, localVarRequestOptions, configuration);
505
+ return {
506
+ url: toPathString(localVarUrlObj),
507
+ options: localVarRequestOptions
508
+ };
509
+ }
510
+ };
511
+ };
512
+ var AuthApiFp = function(configuration) {
513
+ const localVarAxiosParamCreator = AuthApiAxiosParamCreator(configuration);
514
+ return {
515
+ /**
516
+ * Returns the currently authenticated user\'s session data. Requires a valid Bearer token.
517
+ * @summary Get current session
518
+ * @param {*} [options] Override http request option.
519
+ * @throws {RequiredError}
520
+ */
521
+ async getSession(options) {
522
+ const localVarAxiosArgs = await localVarAxiosParamCreator.getSession(options);
523
+ const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
524
+ const localVarOperationServerBasePath = operationServerMap["AuthApi.getSession"]?.[localVarOperationServerIndex]?.url;
525
+ return (axios3, basePath) => createRequestFunction(localVarAxiosArgs, import_axios3.default, BASE_PATH, configuration)(axios3, localVarOperationServerBasePath || basePath);
526
+ },
527
+ /**
528
+ * Authenticates a user with email and password. Returns an access token and refresh token on success.
529
+ * @summary User login
530
+ * @param {LoginRequest} loginRequest User login credentials
531
+ * @param {*} [options] Override http request option.
532
+ * @throws {RequiredError}
533
+ */
534
+ async login(loginRequest, options) {
535
+ const localVarAxiosArgs = await localVarAxiosParamCreator.login(loginRequest, options);
536
+ const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
537
+ const localVarOperationServerBasePath = operationServerMap["AuthApi.login"]?.[localVarOperationServerIndex]?.url;
538
+ return (axios3, basePath) => createRequestFunction(localVarAxiosArgs, import_axios3.default, BASE_PATH, configuration)(axios3, localVarOperationServerBasePath || basePath);
539
+ },
540
+ /**
541
+ * Invalidates the current session and refresh token. The client should discard stored tokens.
542
+ * @summary Logout
543
+ * @param {RefreshTokenRequest} refreshTokenRequest
544
+ * @param {*} [options] Override http request option.
545
+ * @throws {RequiredError}
546
+ */
547
+ async logout(refreshTokenRequest, options) {
548
+ const localVarAxiosArgs = await localVarAxiosParamCreator.logout(refreshTokenRequest, options);
549
+ const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
550
+ const localVarOperationServerBasePath = operationServerMap["AuthApi.logout"]?.[localVarOperationServerIndex]?.url;
551
+ return (axios3, basePath) => createRequestFunction(localVarAxiosArgs, import_axios3.default, BASE_PATH, configuration)(axios3, localVarOperationServerBasePath || basePath);
552
+ },
553
+ /**
554
+ * Issues a new access token using a valid refresh token. Rotate refresh tokens on each call.
555
+ * @summary Refresh access token
556
+ * @param {RefreshTokenRequest} refreshTokenRequest
557
+ * @param {*} [options] Override http request option.
558
+ * @throws {RequiredError}
559
+ */
560
+ async refreshToken(refreshTokenRequest, options) {
561
+ const localVarAxiosArgs = await localVarAxiosParamCreator.refreshToken(refreshTokenRequest, options);
562
+ const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
563
+ const localVarOperationServerBasePath = operationServerMap["AuthApi.refreshToken"]?.[localVarOperationServerIndex]?.url;
564
+ return (axios3, basePath) => createRequestFunction(localVarAxiosArgs, import_axios3.default, BASE_PATH, configuration)(axios3, localVarOperationServerBasePath || basePath);
565
+ },
566
+ /**
567
+ * Creates a new user account. Sends a verification email upon successful registration.
568
+ * @summary Register a new user
569
+ * @param {RegisterRequest} registerRequest User register credentials
570
+ * @param {*} [options] Override http request option.
571
+ * @throws {RequiredError}
572
+ */
573
+ async register(registerRequest, options) {
574
+ const localVarAxiosArgs = await localVarAxiosParamCreator.register(registerRequest, options);
575
+ const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
576
+ const localVarOperationServerBasePath = operationServerMap["AuthApi.register"]?.[localVarOperationServerIndex]?.url;
577
+ return (axios3, basePath) => createRequestFunction(localVarAxiosArgs, import_axios3.default, BASE_PATH, configuration)(axios3, localVarOperationServerBasePath || basePath);
578
+ },
579
+ /**
580
+ * Validates the reset token from the email link and renders the password reset form.
581
+ * @summary Render password reset form
582
+ * @param {TokenQuery} token Password reset token
583
+ * @param {*} [options] Override http request option.
584
+ * @throws {RequiredError}
585
+ */
586
+ async renderResetForm(token, options) {
587
+ const localVarAxiosArgs = await localVarAxiosParamCreator.renderResetForm(token, options);
588
+ const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
589
+ const localVarOperationServerBasePath = operationServerMap["AuthApi.renderResetForm"]?.[localVarOperationServerIndex]?.url;
590
+ return (axios3, basePath) => createRequestFunction(localVarAxiosArgs, import_axios3.default, BASE_PATH, configuration)(axios3, localVarOperationServerBasePath || basePath);
591
+ },
592
+ /**
593
+ * Sends a password reset link to the provided email address if an account exists.
594
+ * @summary Request a password reset
595
+ * @param {EmailRequest} emailRequest Email address to send the reset link to
596
+ * @param {*} [options] Override http request option.
597
+ * @throws {RequiredError}
598
+ */
599
+ async requestPasswordReset(emailRequest, options) {
600
+ const localVarAxiosArgs = await localVarAxiosParamCreator.requestPasswordReset(emailRequest, options);
601
+ const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
602
+ const localVarOperationServerBasePath = operationServerMap["AuthApi.requestPasswordReset"]?.[localVarOperationServerIndex]?.url;
603
+ return (axios3, basePath) => createRequestFunction(localVarAxiosArgs, import_axios3.default, BASE_PATH, configuration)(axios3, localVarOperationServerBasePath || basePath);
604
+ },
605
+ /**
606
+ * Submits a new password using a valid reset token. Invalidates the token after use.
607
+ * @summary Submit new password
608
+ * @param {ResetPasswordRequest} resetPasswordRequest Reset token and the new password
609
+ * @param {*} [options] Override http request option.
610
+ * @throws {RequiredError}
611
+ */
612
+ async submitNewPassword(resetPasswordRequest, options) {
613
+ const localVarAxiosArgs = await localVarAxiosParamCreator.submitNewPassword(resetPasswordRequest, options);
614
+ const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
615
+ const localVarOperationServerBasePath = operationServerMap["AuthApi.submitNewPassword"]?.[localVarOperationServerIndex]?.url;
616
+ return (axios3, basePath) => createRequestFunction(localVarAxiosArgs, import_axios3.default, BASE_PATH, configuration)(axios3, localVarOperationServerBasePath || basePath);
617
+ }
618
+ };
619
+ };
620
+ var AuthApi = class extends BaseAPI {
621
+ /**
622
+ * Returns the currently authenticated user\'s session data. Requires a valid Bearer token.
623
+ * @summary Get current session
624
+ * @param {*} [options] Override http request option.
625
+ * @throws {RequiredError}
626
+ */
627
+ getSession(options) {
628
+ return AuthApiFp(this.configuration).getSession(options).then((request) => request(this.axios, this.basePath));
629
+ }
630
+ /**
631
+ * Authenticates a user with email and password. Returns an access token and refresh token on success.
632
+ * @summary User login
633
+ * @param {LoginRequest} loginRequest User login credentials
634
+ * @param {*} [options] Override http request option.
635
+ * @throws {RequiredError}
636
+ */
637
+ login(loginRequest, options) {
638
+ return AuthApiFp(this.configuration).login(loginRequest, options).then((request) => request(this.axios, this.basePath));
639
+ }
640
+ /**
641
+ * Invalidates the current session and refresh token. The client should discard stored tokens.
642
+ * @summary Logout
643
+ * @param {RefreshTokenRequest} refreshTokenRequest
644
+ * @param {*} [options] Override http request option.
645
+ * @throws {RequiredError}
646
+ */
647
+ logout(refreshTokenRequest, options) {
648
+ return AuthApiFp(this.configuration).logout(refreshTokenRequest, options).then((request) => request(this.axios, this.basePath));
649
+ }
650
+ /**
651
+ * Issues a new access token using a valid refresh token. Rotate refresh tokens on each call.
652
+ * @summary Refresh access token
653
+ * @param {RefreshTokenRequest} refreshTokenRequest
654
+ * @param {*} [options] Override http request option.
655
+ * @throws {RequiredError}
656
+ */
657
+ refreshToken(refreshTokenRequest, options) {
658
+ return AuthApiFp(this.configuration).refreshToken(refreshTokenRequest, options).then((request) => request(this.axios, this.basePath));
659
+ }
660
+ /**
661
+ * Creates a new user account. Sends a verification email upon successful registration.
662
+ * @summary Register a new user
663
+ * @param {RegisterRequest} registerRequest User register credentials
664
+ * @param {*} [options] Override http request option.
665
+ * @throws {RequiredError}
666
+ */
667
+ register(registerRequest, options) {
668
+ return AuthApiFp(this.configuration).register(registerRequest, options).then((request) => request(this.axios, this.basePath));
669
+ }
670
+ /**
671
+ * Validates the reset token from the email link and renders the password reset form.
672
+ * @summary Render password reset form
673
+ * @param {TokenQuery} token Password reset token
674
+ * @param {*} [options] Override http request option.
675
+ * @throws {RequiredError}
676
+ */
677
+ renderResetForm(token, options) {
678
+ return AuthApiFp(this.configuration).renderResetForm(token, options).then((request) => request(this.axios, this.basePath));
679
+ }
680
+ /**
681
+ * Sends a password reset link to the provided email address if an account exists.
682
+ * @summary Request a password reset
683
+ * @param {EmailRequest} emailRequest Email address to send the reset link to
684
+ * @param {*} [options] Override http request option.
685
+ * @throws {RequiredError}
686
+ */
687
+ requestPasswordReset(emailRequest, options) {
688
+ return AuthApiFp(this.configuration).requestPasswordReset(emailRequest, options).then((request) => request(this.axios, this.basePath));
689
+ }
690
+ /**
691
+ * Submits a new password using a valid reset token. Invalidates the token after use.
692
+ * @summary Submit new password
693
+ * @param {ResetPasswordRequest} resetPasswordRequest Reset token and the new password
694
+ * @param {*} [options] Override http request option.
695
+ * @throws {RequiredError}
696
+ */
697
+ submitNewPassword(resetPasswordRequest, options) {
698
+ return AuthApiFp(this.configuration).submitNewPassword(resetPasswordRequest, options).then((request) => request(this.axios, this.basePath));
699
+ }
700
+ };
701
+
702
+ // src/generated/api/email-api.ts
703
+ var import_axios4 = __toESM(require("axios"), 1);
704
+ var EmailApiAxiosParamCreator = function(configuration) {
705
+ return {
706
+ /**
707
+ * Validates the email token and update the user account.
708
+ * @summary Verify user email
709
+ * @param {TokenQuery} token Email Verification Token
710
+ * @param {*} [options] Override http request option.
711
+ * @throws {RequiredError}
712
+ */
713
+ verifyEmail: async (token, options = {}) => {
714
+ assertParamExists("verifyEmail", "token", token);
715
+ const localVarPath = `/email`;
716
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
717
+ let baseOptions;
718
+ if (configuration) {
719
+ baseOptions = configuration.baseOptions;
720
+ }
721
+ const localVarRequestOptions = { method: "GET", ...baseOptions, ...options };
722
+ const localVarHeaderParameter = {};
723
+ const localVarQueryParameter = {};
724
+ if (token !== void 0) {
725
+ for (const [key, value] of Object.entries(token)) {
726
+ localVarQueryParameter[key] = value;
727
+ }
728
+ }
729
+ localVarHeaderParameter["Accept"] = "application/json";
730
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
731
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
732
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
733
+ return {
734
+ url: toPathString(localVarUrlObj),
735
+ options: localVarRequestOptions
736
+ };
737
+ }
738
+ };
739
+ };
740
+ var EmailApiFp = function(configuration) {
741
+ const localVarAxiosParamCreator = EmailApiAxiosParamCreator(configuration);
742
+ return {
743
+ /**
744
+ * Validates the email token and update the user account.
745
+ * @summary Verify user email
746
+ * @param {TokenQuery} token Email Verification Token
747
+ * @param {*} [options] Override http request option.
748
+ * @throws {RequiredError}
749
+ */
750
+ async verifyEmail(token, options) {
751
+ const localVarAxiosArgs = await localVarAxiosParamCreator.verifyEmail(token, options);
752
+ const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
753
+ const localVarOperationServerBasePath = operationServerMap["EmailApi.verifyEmail"]?.[localVarOperationServerIndex]?.url;
754
+ return (axios3, basePath) => createRequestFunction(localVarAxiosArgs, import_axios4.default, BASE_PATH, configuration)(axios3, localVarOperationServerBasePath || basePath);
755
+ }
756
+ };
757
+ };
758
+ var EmailApi = class extends BaseAPI {
759
+ /**
760
+ * Validates the email token and update the user account.
761
+ * @summary Verify user email
762
+ * @param {TokenQuery} token Email Verification Token
763
+ * @param {*} [options] Override http request option.
764
+ * @throws {RequiredError}
765
+ */
766
+ verifyEmail(token, options) {
767
+ return EmailApiFp(this.configuration).verifyEmail(token, options).then((request) => request(this.axios, this.basePath));
768
+ }
769
+ };
770
+
771
+ // src/generated/api/users-api.ts
772
+ var import_axios5 = __toESM(require("axios"), 1);
773
+ var UsersApiAxiosParamCreator = function(configuration) {
774
+ return {
775
+ /**
776
+ * Returns the currently authenticated user\'s data. Requires a valid Bearer token.
777
+ * @summary Get current User
778
+ * @param {*} [options] Override http request option.
779
+ * @throws {RequiredError}
780
+ */
781
+ findUser: async (options = {}) => {
782
+ const localVarPath = `/user`;
783
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
784
+ let baseOptions;
785
+ if (configuration) {
786
+ baseOptions = configuration.baseOptions;
787
+ }
788
+ const localVarRequestOptions = { method: "GET", ...baseOptions, ...options };
789
+ const localVarHeaderParameter = {};
790
+ const localVarQueryParameter = {};
791
+ await setBearerAuthToObject(localVarHeaderParameter, configuration);
792
+ localVarHeaderParameter["Accept"] = "application/json";
793
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
794
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
795
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
796
+ return {
797
+ url: toPathString(localVarUrlObj),
798
+ options: localVarRequestOptions
799
+ };
800
+ }
801
+ };
802
+ };
803
+ var UsersApiFp = function(configuration) {
804
+ const localVarAxiosParamCreator = UsersApiAxiosParamCreator(configuration);
805
+ return {
806
+ /**
807
+ * Returns the currently authenticated user\'s data. Requires a valid Bearer token.
808
+ * @summary Get current User
809
+ * @param {*} [options] Override http request option.
810
+ * @throws {RequiredError}
811
+ */
812
+ async findUser(options) {
813
+ const localVarAxiosArgs = await localVarAxiosParamCreator.findUser(options);
814
+ const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
815
+ const localVarOperationServerBasePath = operationServerMap["UsersApi.findUser"]?.[localVarOperationServerIndex]?.url;
816
+ return (axios3, basePath) => createRequestFunction(localVarAxiosArgs, import_axios5.default, BASE_PATH, configuration)(axios3, localVarOperationServerBasePath || basePath);
817
+ }
818
+ };
819
+ };
820
+ var UsersApi = class extends BaseAPI {
821
+ /**
822
+ * Returns the currently authenticated user\'s data. Requires a valid Bearer token.
823
+ * @summary Get current User
824
+ * @param {*} [options] Override http request option.
825
+ * @throws {RequiredError}
826
+ */
827
+ findUser(options) {
828
+ return UsersApiFp(this.configuration).findUser(options).then((request) => request(this.axios, this.basePath));
829
+ }
830
+ };
831
+
832
+ // src/generated/configuration.ts
833
+ var Configuration = class {
834
+ /**
835
+ * parameter for apiKey security
836
+ * @param name security name
837
+ */
838
+ apiKey;
839
+ /**
840
+ * parameter for basic security
841
+ */
842
+ username;
843
+ /**
844
+ * parameter for basic security
845
+ */
846
+ password;
847
+ /**
848
+ * parameter for oauth2 security
849
+ * @param name security name
850
+ * @param scopes oauth2 scope
851
+ */
852
+ accessToken;
853
+ /**
854
+ * parameter for aws4 signature security
855
+ * @param {Object} AWS4Signature - AWS4 Signature security
856
+ * @param {string} options.region - aws region
857
+ * @param {string} options.service - name of the service.
858
+ * @param {string} credentials.accessKeyId - aws access key id
859
+ * @param {string} credentials.secretAccessKey - aws access key
860
+ * @param {string} credentials.sessionToken - aws session token
861
+ * @memberof Configuration
862
+ */
863
+ awsv4;
864
+ /**
865
+ * override base path
866
+ */
867
+ basePath;
868
+ /**
869
+ * override server index
870
+ */
871
+ serverIndex;
872
+ /**
873
+ * base options for axios calls
874
+ */
875
+ baseOptions;
876
+ /**
877
+ * The FormData constructor that will be used to create multipart form data
878
+ * requests. You can inject this here so that execution environments that
879
+ * do not support the FormData class can still run the generated client.
880
+ *
881
+ * @type {new () => FormData}
882
+ */
883
+ formDataCtor;
884
+ constructor(param = {}) {
885
+ this.apiKey = param.apiKey;
886
+ this.username = param.username;
887
+ this.password = param.password;
888
+ this.accessToken = param.accessToken;
889
+ this.awsv4 = param.awsv4;
890
+ this.basePath = param.basePath;
891
+ this.serverIndex = param.serverIndex;
892
+ this.baseOptions = {
893
+ ...param.baseOptions,
894
+ headers: {
895
+ ...param.baseOptions?.headers
896
+ }
897
+ };
898
+ this.formDataCtor = param.formDataCtor;
899
+ }
900
+ /**
901
+ * Check if the given MIME is a JSON MIME.
902
+ * JSON MIME examples:
903
+ * application/json
904
+ * application/json; charset=UTF8
905
+ * APPLICATION/JSON
906
+ * application/vnd.company+json
907
+ * @param mime - MIME (Multipurpose Internet Mail Extensions)
908
+ * @return True if the given MIME is JSON, false otherwise.
909
+ */
910
+ isJsonMime(mime) {
911
+ const jsonMime = new RegExp("^(application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(;.*)?$", "i");
912
+ return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === "application/json-patch+json");
913
+ }
914
+ };
915
+
916
+ // src/index.ts
917
+ var DEFAULT_OPTIONS = {
918
+ storage: new MemoryStorage()
919
+ };
920
+ var Anzar = class {
921
+ Auth;
922
+ User;
923
+ Email;
924
+ constructor(anzarConfig, options = DEFAULT_OPTIONS) {
925
+ const basePath = anzarConfig.api_url;
926
+ const axiosInstance = this.createAxiosInstance(basePath);
927
+ const configuration = new Configuration({ basePath });
928
+ if (anzarConfig.auth?.strategy === "Jwt" /* Jwt */) {
929
+ new JwtInterceptor().apply(axiosInstance, options);
930
+ }
931
+ const apis = this.createApis(configuration, basePath, axiosInstance);
932
+ this.Auth = new AuthModule(
933
+ apis.auth,
934
+ apis.user,
935
+ anzarConfig.auth?.strategy ?? "Session" /* Session */,
936
+ options
937
+ );
938
+ this.User = apis.user;
939
+ this.Email = apis.email;
940
+ const originalFetch = window.fetch;
941
+ window.fetch = async (url, _options = {}) => {
942
+ const accessToken = options.storage.getToken();
943
+ if (!accessToken) return originalFetch(url, _options);
944
+ return originalFetch(url, {
945
+ ..._options,
946
+ headers: {
947
+ ..._options.headers,
948
+ Authorization: `Bearer ${accessToken}`
949
+ }
950
+ });
951
+ };
952
+ }
953
+ createAxiosInstance(baseURL) {
954
+ return import_axios6.default.create({
955
+ baseURL,
956
+ withCredentials: true,
957
+ headers: {
958
+ "Content-Type": "application/json",
959
+ Accept: "application/json"
960
+ }
961
+ });
962
+ }
963
+ createApis(configuration, basePath, axiosInstance) {
964
+ return {
965
+ auth: new AuthApi(configuration, basePath, axiosInstance),
966
+ user: new UsersApi(configuration, basePath, axiosInstance),
967
+ email: new EmailApi(configuration, basePath, axiosInstance)
968
+ };
969
+ }
970
+ };