@zerosls/clm-sdk 1.1.6 → 1.1.7

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.
@@ -3,6 +3,7 @@ import { RequestOptions } from "../types/common";
3
3
  import { EventEmitter } from "./event-emitter";
4
4
  export declare class ApiClient {
5
5
  private baseUrl;
6
+ private fallbackBaseUrl;
6
7
  private organization;
7
8
  private token;
8
9
  private eventEmitter;
@@ -6,6 +6,7 @@ export class ApiClient {
6
6
  var _a, _b;
7
7
  this.token = null;
8
8
  this.baseUrl = config.baseUrl;
9
+ this.fallbackBaseUrl = config.fallbackBaseUrl || "http://216.250.117.119/ZeroServicesQA/api/v1";
9
10
  this.organization = config.organization;
10
11
  this.token = config.token || null;
11
12
  this.eventEmitter = eventEmitter;
@@ -56,15 +57,14 @@ export class ApiClient {
56
57
  }
57
58
  }
58
59
  async request(method, endpoint, data, params, options = {}) {
59
- const url = buildUrl(this.baseUrl, endpoint, params);
60
+ // Primer intento con baseUrl normal
61
+ const primaryUrl = buildUrl(this.baseUrl, endpoint, params);
60
62
  const base = buildHeaders(this.token, {
61
63
  "X-Organization": this.organization,
62
64
  ...(options.headers || {}),
63
65
  });
64
66
  const headers = new Headers(base);
65
- //const legacyPattern = /(^|\/)legacy(\/|$)/i;
66
- //const isLegacyEndpoint = legacyPattern.test(endpoint);
67
- //if (isLegacyEndpoint) {
67
+ // Obtener token legacy
68
68
  const legacyToken = window.__LEGACY_TOKEN__ ||
69
69
  sessionStorage.getItem("legacy_token") ||
70
70
  null;
@@ -75,7 +75,6 @@ export class ApiClient {
75
75
  }
76
76
  }
77
77
  else if (this.token) {
78
- // ✅ Si no hay legacy token, usar token v1
79
78
  if (this.debug) {
80
79
  console.log("🔐 Using v1 token for:", endpoint);
81
80
  }
@@ -83,14 +82,9 @@ export class ApiClient {
83
82
  else {
84
83
  console.warn("⚠️ No token available for endpoint:", endpoint);
85
84
  }
86
- //} else {
87
- // if (!this.token) {
88
- // headers.delete("Authorization");
89
- // }
90
- //}
91
85
  const useCache = this.cacheEnabled && options.useCache !== false;
92
86
  if (useCache && method === "GET") {
93
- const cacheKey = generateCacheKey(method, url, data);
87
+ const cacheKey = generateCacheKey(method, primaryUrl, data);
94
88
  const cachedData = this.cache.get(cacheKey);
95
89
  if (cachedData) {
96
90
  if (this.debug) {
@@ -100,7 +94,7 @@ export class ApiClient {
100
94
  }
101
95
  }
102
96
  this.eventEmitter.emit("beforeRequest", {
103
- url,
97
+ url: primaryUrl,
104
98
  method,
105
99
  data,
106
100
  });
@@ -112,16 +106,58 @@ export class ApiClient {
112
106
  };
113
107
  if (data && method !== "GET") {
114
108
  fetchOptions.body = JSON.stringify(data);
115
- console.log(`📤 ${method} Body:`, data);
109
+ if (this.debug) {
110
+ console.log(`📤 ${method} Body:`, data);
111
+ }
112
+ }
113
+ if (this.debug) {
114
+ console.log(`🌐 ${method} ${primaryUrl}`);
115
+ }
116
+ // ✅ Primer intento
117
+ const response = await fetch(primaryUrl, fetchOptions);
118
+ // ✅ Si es 404, intentar con fallback URL
119
+ if (response.status === 404) {
120
+ console.warn(`⚠️ 404 en ${primaryUrl}, intentando con fallback...`);
121
+ const fallbackUrl = buildUrl(this.fallbackBaseUrl, endpoint, params);
122
+ if (this.debug) {
123
+ console.log(`🔄 Retry: ${method} ${fallbackUrl}`);
124
+ }
125
+ // ✅ Segundo intento con fallback
126
+ const fallbackResponse = await fetch(fallbackUrl, fetchOptions);
127
+ if (!fallbackResponse.ok) {
128
+ let errorData;
129
+ try {
130
+ errorData = await fallbackResponse.json();
131
+ }
132
+ catch (_a) {
133
+ errorData = { message: fallbackResponse.statusText };
134
+ }
135
+ console.error(`❌ Fallback también falló ${fallbackResponse.status}:`, errorData);
136
+ if (fallbackResponse.status === 401) {
137
+ this.eventEmitter.emit("authError", {
138
+ statusCode: 401,
139
+ message: errorData.message || "Authentication required",
140
+ });
141
+ }
142
+ return errorData;
143
+ }
144
+ // ✅ Fallback exitoso
145
+ const fallbackData = await parseResponse(fallbackResponse);
146
+ console.log(`✅ Fallback exitoso para: ${endpoint}`);
147
+ this.eventEmitter.emit("afterRequest", {
148
+ url: fallbackUrl,
149
+ method,
150
+ response: fallbackData,
151
+ });
152
+ return fallbackData;
116
153
  }
117
- console.log(`🌐 ${method} ${url}`, fetchOptions);
118
- const response = await fetch(url, fetchOptions);
154
+ // Otros errores (no 404)
119
155
  if (!response.ok) {
120
156
  let errorData;
121
157
  try {
122
158
  errorData = await response.json();
123
159
  }
124
- catch (_a) {
160
+ catch (_b) {
125
161
  errorData = { message: response.statusText };
126
162
  }
127
163
  console.error(`❌ ${method} ${response.status}:`, errorData);
@@ -133,9 +169,10 @@ export class ApiClient {
133
169
  }
134
170
  return errorData;
135
171
  }
172
+ // ✅ Respuesta exitosa del primer intento
136
173
  const responseData = await parseResponse(response);
137
174
  if (useCache && method === "GET") {
138
- const cacheKey = generateCacheKey(method, url, data);
175
+ const cacheKey = generateCacheKey(method, primaryUrl, data);
139
176
  const cacheTime = options.cacheTime || undefined;
140
177
  this.cache.set(cacheKey, responseData, cacheTime);
141
178
  if (this.debug) {
@@ -143,7 +180,7 @@ export class ApiClient {
143
180
  }
144
181
  }
145
182
  this.eventEmitter.emit("afterRequest", {
146
- url,
183
+ url: primaryUrl,
147
184
  method,
148
185
  response: responseData,
149
186
  });
@@ -151,7 +188,7 @@ export class ApiClient {
151
188
  }
152
189
  catch (error) {
153
190
  this.eventEmitter.emit("requestError", {
154
- url,
191
+ url: primaryUrl,
155
192
  method,
156
193
  error,
157
194
  });
@@ -1,5 +1,6 @@
1
1
  export interface SdkConfig {
2
2
  baseUrl: string;
3
+ fallbackBaseUrl?: string;
3
4
  organization: string;
4
5
  token?: string | null;
5
6
  cache?: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerosls/clm-sdk",
3
- "version": "1.1.6",
3
+ "version": "1.1.7",
4
4
  "description": "SDK for ZeroCLM API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,3 +1,4 @@
1
+ // core/api-client.ts
1
2
  import { SdkConfig, SdkEventType, SdkEvents } from "../types/sdk";
2
3
  import { PaginatedResponse, RequestOptions } from "../types/common";
3
4
  import { EventEmitter } from "./event-emitter";
@@ -12,6 +13,7 @@ import {
12
13
 
13
14
  export class ApiClient {
14
15
  private baseUrl: string;
16
+ private fallbackBaseUrl: string; // ✅ URL de respaldo
15
17
  private organization: string;
16
18
  private token: string | null = null;
17
19
  private eventEmitter: EventEmitter;
@@ -22,6 +24,7 @@ export class ApiClient {
22
24
 
23
25
  constructor(config: SdkConfig, eventEmitter: EventEmitter) {
24
26
  this.baseUrl = config.baseUrl;
27
+ this.fallbackBaseUrl = config.fallbackBaseUrl || "http://216.250.117.119/ZeroServicesQA/api/v1";
25
28
  this.organization = config.organization;
26
29
  this.token = config.token || null;
27
30
  this.eventEmitter = eventEmitter;
@@ -129,8 +132,9 @@ export class ApiClient {
129
132
  params?: Record<string, any>,
130
133
  options: RequestOptions = {}
131
134
  ): Promise<T> {
132
- const url = buildUrl(this.baseUrl, endpoint, params);
133
-
135
+ // Primer intento con baseUrl normal
136
+ const primaryUrl = buildUrl(this.baseUrl, endpoint, params);
137
+
134
138
  const base: HeadersInit = buildHeaders(this.token, {
135
139
  "X-Organization": this.organization,
136
140
  ...(options.headers || {}),
@@ -138,10 +142,7 @@ export class ApiClient {
138
142
 
139
143
  const headers = new Headers(base);
140
144
 
141
- //const legacyPattern = /(^|\/)legacy(\/|$)/i;
142
- //const isLegacyEndpoint = legacyPattern.test(endpoint);
143
-
144
- //if (isLegacyEndpoint) {
145
+ // Obtener token legacy
145
146
  const legacyToken =
146
147
  (window as any).__LEGACY_TOKEN__ ||
147
148
  sessionStorage.getItem("legacy_token") ||
@@ -149,12 +150,10 @@ export class ApiClient {
149
150
 
150
151
  if (legacyToken) {
151
152
  headers.set("Authorization", `Bearer ${legacyToken}`);
152
-
153
153
  if (this.debug) {
154
154
  console.log("🔐 Using legacy token for:", endpoint);
155
155
  }
156
156
  } else if (this.token) {
157
- // ✅ Si no hay legacy token, usar token v1
158
157
  if (this.debug) {
159
158
  console.log("🔐 Using v1 token for:", endpoint);
160
159
  }
@@ -162,15 +161,9 @@ export class ApiClient {
162
161
  console.warn("⚠️ No token available for endpoint:", endpoint);
163
162
  }
164
163
 
165
- //} else {
166
- // if (!this.token) {
167
- // headers.delete("Authorization");
168
- // }
169
- //}
170
-
171
164
  const useCache = this.cacheEnabled && options.useCache !== false;
172
165
  if (useCache && method === "GET") {
173
- const cacheKey = generateCacheKey(method, url, data);
166
+ const cacheKey = generateCacheKey(method, primaryUrl, data);
174
167
  const cachedData = this.cache.get<T>(cacheKey);
175
168
  if (cachedData) {
176
169
  if (this.debug) {
@@ -181,7 +174,7 @@ export class ApiClient {
181
174
  }
182
175
 
183
176
  this.eventEmitter.emit("beforeRequest", {
184
- url,
177
+ url: primaryUrl,
185
178
  method,
186
179
  data,
187
180
  });
@@ -195,12 +188,66 @@ export class ApiClient {
195
188
 
196
189
  if (data && method !== "GET") {
197
190
  fetchOptions.body = JSON.stringify(data);
198
- console.log(`📤 ${method} Body:`, data);
191
+ if (this.debug) {
192
+ console.log(`📤 ${method} Body:`, data);
193
+ }
194
+ }
195
+
196
+ if (this.debug) {
197
+ console.log(`🌐 ${method} ${primaryUrl}`);
199
198
  }
200
199
 
201
- console.log(`🌐 ${method} ${url}`, fetchOptions);
202
- const response = await fetch(url, fetchOptions);
200
+ // Primer intento
201
+ const response = await fetch(primaryUrl, fetchOptions);
202
+
203
+ // ✅ Si es 404, intentar con fallback URL
204
+ if (response.status === 404) {
205
+ console.warn(`⚠️ 404 en ${primaryUrl}, intentando con fallback...`);
206
+
207
+ const fallbackUrl = buildUrl(this.fallbackBaseUrl, endpoint, params);
208
+
209
+ if (this.debug) {
210
+ console.log(`🔄 Retry: ${method} ${fallbackUrl}`);
211
+ }
212
+
213
+ // ✅ Segundo intento con fallback
214
+ const fallbackResponse = await fetch(fallbackUrl, fetchOptions);
215
+
216
+ if (!fallbackResponse.ok) {
217
+ let errorData;
218
+ try {
219
+ errorData = await fallbackResponse.json();
220
+ } catch {
221
+ errorData = { message: fallbackResponse.statusText };
222
+ }
223
+
224
+ console.error(`❌ Fallback también falló ${fallbackResponse.status}:`, errorData);
225
+
226
+ if (fallbackResponse.status === 401) {
227
+ this.eventEmitter.emit("authError", {
228
+ statusCode: 401,
229
+ message: errorData.message || "Authentication required",
230
+ });
231
+ }
232
+
233
+ return errorData as T;
234
+ }
235
+
236
+ // ✅ Fallback exitoso
237
+ const fallbackData = await parseResponse<T>(fallbackResponse);
238
+
239
+ console.log(`✅ Fallback exitoso para: ${endpoint}`);
240
+
241
+ this.eventEmitter.emit("afterRequest", {
242
+ url: fallbackUrl,
243
+ method,
244
+ response: fallbackData,
245
+ });
246
+
247
+ return fallbackData;
248
+ }
203
249
 
250
+ // ✅ Otros errores (no 404)
204
251
  if (!response.ok) {
205
252
  let errorData;
206
253
  try {
@@ -221,10 +268,11 @@ export class ApiClient {
221
268
  return errorData as T;
222
269
  }
223
270
 
271
+ // ✅ Respuesta exitosa del primer intento
224
272
  const responseData = await parseResponse<T>(response);
225
273
 
226
274
  if (useCache && method === "GET") {
227
- const cacheKey = generateCacheKey(method, url, data);
275
+ const cacheKey = generateCacheKey(method, primaryUrl, data);
228
276
  const cacheTime = options.cacheTime || undefined;
229
277
  this.cache.set(cacheKey, responseData, cacheTime);
230
278
 
@@ -234,7 +282,7 @@ export class ApiClient {
234
282
  }
235
283
 
236
284
  this.eventEmitter.emit("afterRequest", {
237
- url,
285
+ url: primaryUrl,
238
286
  method,
239
287
  response: responseData,
240
288
  });
@@ -242,7 +290,7 @@ export class ApiClient {
242
290
  return responseData;
243
291
  } catch (error) {
244
292
  this.eventEmitter.emit("requestError", {
245
- url,
293
+ url: primaryUrl,
246
294
  method,
247
295
  error,
248
296
  });
@@ -256,4 +304,4 @@ export class ApiClient {
256
304
  });
257
305
  }
258
306
  }
259
- }
307
+ }
package/src/types/sdk.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export interface SdkConfig {
2
2
  baseUrl: string;
3
+ fallbackBaseUrl?: string;
3
4
  organization: string;
4
5
  token?: string | null;
5
6
  cache?: {