@go-avro/avro-js 0.0.1 → 0.0.2-beta.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 CHANGED
@@ -14,4 +14,5 @@ This SDK provides:
14
14
  ## Installation
15
15
 
16
16
  ```bash
17
- npm install avro-client
17
+ npm i @go-avro/avro-js
18
+ ```
@@ -1,9 +1,13 @@
1
- import { TokenStorage, Tokens } from '@/types/auth';
1
+ import { TokenStorage, Tokens } from '../types/auth';
2
2
  export declare class AuthManager {
3
- private fetchNewTokens;
4
3
  private storages;
5
- constructor(fetchNewTokens: () => Promise<Tokens>, storageOrStorages: TokenStorage | TokenStorage[]);
6
- accessToken(): Promise<string>;
7
- refreshTokens(): Promise<Tokens>;
4
+ private baseUrl;
5
+ constructor({ baseUrl, storage, }: {
6
+ baseUrl: string;
7
+ storage: TokenStorage | TokenStorage[];
8
+ });
9
+ fetchNewTokens(): Promise<Tokens>;
10
+ accessToken(): Promise<string | undefined>;
11
+ refreshTokens(): Promise<Tokens | null>;
8
12
  clearToken(): Promise<void>;
9
13
  }
@@ -1,10 +1,42 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AuthManager = void 0;
4
- class AuthManager {
5
- constructor(fetchNewTokens, storageOrStorages) {
6
- this.fetchNewTokens = fetchNewTokens;
7
- this.storages = Array.isArray(storageOrStorages) ? storageOrStorages : [storageOrStorages];
1
+ export class AuthManager {
2
+ constructor({ baseUrl, storage, }) {
3
+ this.storages = Array.isArray(storage) ? storage : [storage];
4
+ if (this.storages.length === 0) {
5
+ throw new Error('At least one token storage must be provided');
6
+ }
7
+ this.storages.forEach(storage => {
8
+ if (!storage || typeof storage.get !== 'function' || typeof storage.set !== 'function' || typeof storage.clear !== 'function') {
9
+ throw new Error('Invalid token storage provided');
10
+ }
11
+ });
12
+ this.baseUrl = baseUrl;
13
+ }
14
+ async fetchNewTokens() {
15
+ const refreshToken = await new Promise((resolve, reject) => {
16
+ this.storages.map(async (storage) => {
17
+ const tokens = await storage.get();
18
+ if (tokens) {
19
+ resolve(tokens.refresh_token);
20
+ }
21
+ });
22
+ reject(new Error('No valid refresh token found'));
23
+ });
24
+ if (!refreshToken) {
25
+ throw new Error('No refresh token available');
26
+ }
27
+ const response = await fetch(`${this.baseUrl}/refresh`, {
28
+ method: 'POST',
29
+ headers: {
30
+ 'Content-Type': 'application/json',
31
+ 'Accept': 'application/json',
32
+ 'Authorization': `Bearer ${refreshToken}`,
33
+ },
34
+ });
35
+ if (!response.ok) {
36
+ throw new Error('Failed to refresh tokens');
37
+ }
38
+ const tokens = await response.json();
39
+ return tokens;
8
40
  }
9
41
  async accessToken() {
10
42
  if (!this.storages.length) {
@@ -13,18 +45,23 @@ class AuthManager {
13
45
  for (const storage of this.storages) {
14
46
  const token = await storage.get();
15
47
  if (token)
16
- return token;
48
+ return token.access_token;
17
49
  }
18
- const newToken = await this.fetchNewTokens();
19
- return newToken.accessToken;
50
+ const newToken = await this.refreshTokens();
51
+ return newToken?.access_token;
20
52
  }
21
53
  async refreshTokens() {
22
- const newToken = await this.fetchNewTokens();
23
- await Promise.all(this.storages.map(s => s.set(newToken)));
24
- return newToken;
54
+ try {
55
+ const newToken = await this.fetchNewTokens();
56
+ await Promise.all(this.storages.map(s => s.set(newToken)));
57
+ return newToken;
58
+ }
59
+ catch (error) {
60
+ console.error('Failed to refresh tokens:', error);
61
+ return null;
62
+ }
25
63
  }
26
64
  async clearToken() {
27
65
  await Promise.all(this.storages.map(s => s.clear()));
28
66
  }
29
67
  }
30
- exports.AuthManager = AuthManager;
@@ -1,14 +1,13 @@
1
- import { Tokens, TokenStorage } from '@/types/auth';
1
+ import { Tokens, TokenStorage } from '../types/auth';
2
2
  export declare class MemoryStorage implements TokenStorage {
3
3
  private tokens;
4
- get(): Promise<string | null>;
4
+ get(): Promise<Tokens | null>;
5
5
  set(tokens: Tokens): Promise<void>;
6
6
  clear(): Promise<void>;
7
7
  }
8
8
  export declare class LocalStorage implements TokenStorage {
9
9
  private key;
10
- constructor(key: string);
11
- get(): Promise<string | null>;
10
+ get(): Promise<Tokens | null>;
12
11
  set(tokens: Tokens): Promise<void>;
13
12
  clear(): Promise<void>;
14
13
  }
@@ -1,13 +1,9 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LocalStorage = exports.MemoryStorage = void 0;
4
- class MemoryStorage {
1
+ export class MemoryStorage {
5
2
  constructor() {
6
- // @ts-ignore: no-unused-vars
7
3
  this.tokens = null;
8
4
  }
9
5
  async get() {
10
- return this.tokens ? this.tokens.accessToken : null;
6
+ return this.tokens ? this.tokens : null;
11
7
  }
12
8
  async set(tokens) {
13
9
  this.tokens = tokens;
@@ -16,14 +12,13 @@ class MemoryStorage {
16
12
  this.tokens = null;
17
13
  }
18
14
  }
19
- exports.MemoryStorage = MemoryStorage;
20
- class LocalStorage {
21
- constructor(key) {
22
- this.key = key;
15
+ export class LocalStorage {
16
+ constructor() {
17
+ this.key = 'auth_tokens';
23
18
  }
24
19
  async get() {
25
20
  const item = localStorage.getItem(this.key);
26
- return item ? JSON.parse(item).accessToken : null;
21
+ return item ? JSON.parse(item) : null;
27
22
  }
28
23
  async set(tokens) {
29
24
  localStorage.setItem(this.key, JSON.stringify(tokens));
@@ -32,4 +27,3 @@ class LocalStorage {
32
27
  localStorage.removeItem(this.key);
33
28
  }
34
29
  }
35
- exports.LocalStorage = LocalStorage;
@@ -1,19 +1,19 @@
1
- import { AuthManager } from '@/auth/AuthManager';
2
- import { CancelToken, RetryStrategy } from '@/types/client';
3
- export interface QueryClientConfig {
1
+ import { AuthManager } from '../auth/AuthManager';
2
+ import { CancelToken, RetryStrategy } from '../types/client';
3
+ export interface AvroQueryClientConfig {
4
4
  baseUrl: string;
5
5
  authManager: AuthManager;
6
6
  maxRetries?: number;
7
7
  retryStrategy?: RetryStrategy;
8
8
  timeout?: number;
9
9
  }
10
- export declare class QueryClient {
10
+ export declare class AvroQueryClient {
11
11
  private config;
12
- constructor(config: QueryClientConfig);
12
+ constructor(config: AvroQueryClientConfig);
13
13
  getDelay(strategy: RetryStrategy, attempt: number): number;
14
14
  private _xhr;
15
- get<T>(path: string, cancelToken?: CancelToken): Promise<T>;
16
- post<T>(path: string, data: any, cancelToken?: CancelToken): Promise<T>;
17
- put<T>(path: string, data: any, cancelToken?: CancelToken): Promise<T>;
18
- delete<T>(path: string, cancelToken?: CancelToken): Promise<T>;
15
+ get<T>(path: string, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<T>;
16
+ post<T>(path: string, data: any, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<T>;
17
+ put<T>(path: string, data: any, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<T>;
18
+ delete<T>(path: string, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<T>;
19
19
  }
@@ -1,8 +1,5 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QueryClient = void 0;
4
- const error_1 = require("@/types/error");
5
- class QueryClient {
1
+ import { StandardError } from '../types/error';
2
+ export class AvroQueryClient {
6
3
  constructor(config) {
7
4
  this.config = {
8
5
  baseUrl: config.baseUrl,
@@ -24,10 +21,10 @@ class QueryClient {
24
21
  }
25
22
  throw new Error(`Invalid retry strategy: ${strategy}`);
26
23
  }
27
- _xhr(method, path, body, cancelToken, retryCount = 0) {
24
+ _xhr(method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0) {
28
25
  const checkCancelled = () => {
29
26
  if (cancelToken?.isCancelled()) {
30
- return new error_1.StandardError(0, 'Request cancelled');
27
+ return new StandardError(0, 'Request cancelled');
31
28
  }
32
29
  return null;
33
30
  };
@@ -39,8 +36,12 @@ class QueryClient {
39
36
  const xhr = new XMLHttpRequest();
40
37
  const url = this.config.baseUrl + path;
41
38
  xhr.open(method, url, true);
42
- xhr.setRequestHeader('Content-Type', 'application/json');
43
- xhr.setRequestHeader('Authorization', `Bearer ${token}`);
39
+ if (token) {
40
+ xhr.setRequestHeader('Authorization', `Bearer ${token}`);
41
+ }
42
+ Object.entries(headers).forEach(([key, value]) => {
43
+ xhr.setRequestHeader(key, value);
44
+ });
44
45
  xhr.onload = () => {
45
46
  const cancelErr = checkCancelled();
46
47
  if (cancelErr)
@@ -49,10 +50,10 @@ class QueryClient {
49
50
  this.config.authManager
50
51
  .refreshTokens()
51
52
  .then(() => {
52
- this._xhr(method, path, body, cancelToken, retryCount + 1).then(resolve, reject);
53
+ this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
53
54
  })
54
55
  .catch(() => {
55
- reject(new error_1.StandardError(401, 'Unauthorized (refresh failed)'));
56
+ reject(new StandardError(401, 'Unauthorized (refresh failed)'));
56
57
  });
57
58
  return;
58
59
  }
@@ -68,7 +69,7 @@ class QueryClient {
68
69
  if (retryCount < this.config.maxRetries) {
69
70
  const delay = this.getDelay(this.config.retryStrategy, retryCount);
70
71
  setTimeout(() => {
71
- this._xhr(method, path, body, cancelToken, retryCount + 1).then(resolve, reject);
72
+ this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
72
73
  }, delay);
73
74
  }
74
75
  else {
@@ -80,7 +81,7 @@ class QueryClient {
80
81
  catch {
81
82
  console.warn('Failed to parse error response:', xhr.responseText);
82
83
  }
83
- reject(new error_1.StandardError(xhr.status, msg));
84
+ reject(new StandardError(xhr.status, msg));
84
85
  }
85
86
  }
86
87
  };
@@ -88,32 +89,31 @@ class QueryClient {
88
89
  if (retryCount < this.config.maxRetries) {
89
90
  const delay = this.getDelay(this.config.retryStrategy, retryCount);
90
91
  setTimeout(() => {
91
- this._xhr(method, path, body, cancelToken, retryCount + 1).then(resolve, reject);
92
+ this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
92
93
  }, delay);
93
94
  }
94
95
  else {
95
- reject(new error_1.StandardError(0, 'Network Error'));
96
+ reject(new StandardError(0, 'Network Error'));
96
97
  }
97
98
  };
98
99
  if (this.config.timeout) {
99
100
  xhr.timeout = this.config.timeout;
100
- xhr.ontimeout = () => reject(new error_1.StandardError(0, 'Request timed out'));
101
+ xhr.ontimeout = () => reject(new StandardError(0, 'Request timed out'));
101
102
  }
102
- xhr.send(body ? JSON.stringify(body) : null);
103
+ xhr.send(body);
103
104
  });
104
105
  });
105
106
  }
106
- get(path, cancelToken) {
107
- return this._xhr('GET', path, null, cancelToken);
107
+ get(path, cancelToken, headers = {}) {
108
+ return this._xhr('GET', path, null, cancelToken, headers, true);
108
109
  }
109
- post(path, data, cancelToken) {
110
- return this._xhr('POST', path, data, cancelToken);
110
+ post(path, data, cancelToken, headers = {}) {
111
+ return this._xhr('POST', path, data, cancelToken, headers, false);
111
112
  }
112
- put(path, data, cancelToken) {
113
- return this._xhr('PUT', path, data, cancelToken);
113
+ put(path, data, cancelToken, headers = {}) {
114
+ return this._xhr('PUT', path, data, cancelToken, headers, true);
114
115
  }
115
- delete(path, cancelToken) {
116
- return this._xhr('DELETE', path, null, cancelToken);
116
+ delete(path, cancelToken, headers = {}) {
117
+ return this._xhr('DELETE', path, null, cancelToken, headers, false);
117
118
  }
118
119
  }
119
- exports.QueryClient = QueryClient;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { QueryClientConfig, QueryClient } from './client/QueryClient';
1
+ export { AvroQueryClientConfig, AvroQueryClient } from './client/QueryClient';
2
2
  export { AuthManager } from './auth/AuthManager';
3
- export { MemoryStorage } from './auth/storage';
4
- export * from '@/types/api';
5
- export * from '@/types/error';
6
- export * from '@/types/client';
3
+ export { MemoryStorage, LocalStorage } from './auth/storage';
4
+ export * from './types/api';
5
+ export * from './types/error';
6
+ export * from './types/client';
package/dist/index.js CHANGED
@@ -1,26 +1,6 @@
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.MemoryStorage = exports.AuthManager = exports.QueryClient = void 0;
18
- var QueryClient_1 = require("./client/QueryClient");
19
- Object.defineProperty(exports, "QueryClient", { enumerable: true, get: function () { return QueryClient_1.QueryClient; } });
20
- var AuthManager_1 = require("./auth/AuthManager");
21
- Object.defineProperty(exports, "AuthManager", { enumerable: true, get: function () { return AuthManager_1.AuthManager; } });
22
- var storage_1 = require("./auth/storage");
23
- Object.defineProperty(exports, "MemoryStorage", { enumerable: true, get: function () { return storage_1.MemoryStorage; } });
24
- __exportStar(require("@/types/api"), exports);
25
- __exportStar(require("@/types/error"), exports);
26
- __exportStar(require("@/types/client"), exports);
1
+ export { AvroQueryClient } from './client/QueryClient';
2
+ export { AuthManager } from './auth/AuthManager';
3
+ export { MemoryStorage, LocalStorage } from './auth/storage';
4
+ export * from './types/api';
5
+ export * from './types/error';
6
+ export * from './types/client';
package/dist/types/api.js CHANGED
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
@@ -1,9 +1,9 @@
1
1
  export interface Tokens {
2
- accessToken: string;
3
- refreshToken: string;
2
+ access_token: string;
3
+ refresh_token: string;
4
4
  }
5
5
  export interface TokenStorage {
6
- get(): Promise<string | null>;
6
+ get(): Promise<Tokens | null>;
7
7
  set(tokens: Tokens): Promise<void>;
8
8
  clear(): Promise<void>;
9
9
  }
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
@@ -1,11 +1,7 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StandardError = void 0;
4
- class StandardError extends Error {
1
+ export class StandardError extends Error {
5
2
  constructor(status, message) {
6
3
  super(message);
7
4
  this.status = status;
8
5
  Object.setPrototypeOf(this, StandardError.prototype);
9
6
  }
10
7
  }
11
- exports.StandardError = StandardError;
package/package.json CHANGED
@@ -1,14 +1,22 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "0.0.1",
3
+ "version": "0.0.2-beta.1",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "scripts": {
8
- "build": "tsc",
8
+ "build": "tsc && tsc-alias",
9
9
  "lint": "eslint src",
10
10
  "test": "jest",
11
- "prepublishOnly": "npm run build"
11
+ "prepublishOnly": "npm run lint && npm run build"
12
+ },
13
+ "type": "module",
14
+ "module": "./dist/index.js",
15
+ "exports": {
16
+ ".": {
17
+ "import": "./dist/index.js",
18
+ "types": "./dist/index.d.ts"
19
+ }
12
20
  },
13
21
  "repository": {
14
22
  "type": "git",
@@ -33,6 +41,7 @@
33
41
  "eslint-plugin-react": "^7.37.5",
34
42
  "jest": "^29.0.0",
35
43
  "ts-jest": "^29.0.0",
44
+ "tsc-alias": "^1.8.16",
36
45
  "typescript": "^5.8.3",
37
46
  "typescript-eslint": "^8.38.0"
38
47
  },