@pakento/cms-sdk 4.3.1 → 4.3.3

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.mjs CHANGED
@@ -1,15 +1,14 @@
1
- // src/services/api.ts
1
+ // src/api/core/apiClient.ts
2
2
  import axios, { AxiosError } from "axios";
3
+ import { z } from "zod";
3
4
 
4
- // src/services/cache.ts
5
+ // src/api/core/cache.ts
5
6
  import { Redis } from "@upstash/redis";
6
7
  import { createHash } from "crypto";
7
8
  var CacheService = class {
8
- isCacheEnvelope(value) {
9
- return typeof value === "object" && value !== null && "__pakento_cache_version" in value && "data" in value;
10
- }
11
- constructor(defaultTTL, apiKey) {
12
- this.defaultTTL = defaultTTL;
9
+ // 24 hours
10
+ constructor(apiKey) {
11
+ this.defaultTTL = 86400;
13
12
  this.apiKeyHash = createHash("sha256").update(apiKey).digest("hex").substring(0, 8);
14
13
  if (process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN) {
15
14
  this.redis = new Redis({
@@ -19,269 +18,51 @@ var CacheService = class {
19
18
  }
20
19
  }
21
20
  generateParamsHash(params) {
22
- const canonicalize = (value) => {
23
- if (value === void 0) return void 0;
24
- if (value === null) return null;
25
- if (Array.isArray(value)) {
26
- return value.map((v) => canonicalize(v));
27
- }
28
- if (typeof value === "object") {
29
- const obj = value;
30
- const result = {};
31
- Object.keys(obj).sort().forEach((key) => {
32
- const canon = canonicalize(obj[key]);
33
- if (canon !== void 0) {
34
- result[key] = canon;
35
- }
36
- });
37
- return result;
38
- }
39
- return value;
40
- };
41
- const canonicalParams = canonicalize(params);
42
- const paramsString = JSON.stringify(canonicalParams);
21
+ const paramsString = JSON.stringify(params, Object.keys(params).sort());
43
22
  return createHash("sha256").update(paramsString).digest("hex").substring(0, 16);
44
23
  }
45
24
  buildCacheKey(functionName, params = {}) {
46
25
  const paramsHash = this.generateParamsHash(params);
47
26
  return `pakento:${this.apiKeyHash}:${functionName}:${paramsHash}`;
48
27
  }
49
- safeJsonParse(data) {
50
- try {
51
- if (typeof data === "object" && data !== null) {
52
- return data;
53
- }
54
- if (typeof data === "string") {
55
- return JSON.parse(data);
56
- }
57
- return data;
58
- } catch (error) {
59
- console.warn("[PakentoSDK] Error en safeJsonParse:", error);
60
- console.warn("[PakentoSDK] Datos que causaron error:", {
61
- type: typeof data,
62
- isArray: Array.isArray(data),
63
- data
64
- });
65
- return null;
66
- }
67
- }
68
- serializeForCache(value) {
69
- try {
70
- const cacheData = {
71
- __pakento_cache_version: "2.0",
72
- __pakento_timestamp: Date.now(),
73
- data: value
74
- };
75
- return JSON.stringify(cacheData);
76
- } catch (error) {
77
- console.warn("[PakentoSDK] Error en serializeForCache:", error);
78
- return JSON.stringify(value);
79
- }
80
- }
81
- async getCachedOrFetch(key, fetcher, ttl, skipCache = false) {
82
- if (!this.redis || skipCache) {
28
+ async cacheWrap(key, fetcher) {
29
+ if (!this.redis) {
83
30
  return fetcher();
84
31
  }
32
+ let cached = null;
85
33
  try {
86
- const cached = await this.redis.get(key);
87
- if (cached !== null && cached !== void 0) {
88
- try {
89
- const parsed = this.safeJsonParse(cached);
90
- if (parsed !== null) {
91
- if (this.isCacheEnvelope(parsed)) {
92
- console.log("[PakentoSDK] Cache encontrado y devuelto");
93
- return parsed.data;
94
- } else {
95
- console.log("[PakentoSDK] Cache encontrado y devuelto");
96
- return parsed;
97
- }
98
- } else {
99
- console.warn(`[PakentoSDK] \u26A0\uFE0F Error parseando cache para: ${key}`);
100
- console.warn(`[PakentoSDK] Datos raw del cache:`, {
101
- type: typeof cached,
102
- value: cached
103
- });
104
- this.clearCorruptedCache(key).catch(
105
- (err) => console.warn(
106
- `[PakentoSDK] Error limpiando cache corrupto: ${err}`
107
- )
108
- );
109
- }
110
- } catch (parseError) {
111
- console.warn(
112
- `[PakentoSDK] \u26A0\uFE0F Excepci\xF3n parseando cache para: ${key}:`,
113
- parseError
114
- );
115
- this.clearCorruptedCache(key).catch(
116
- (err) => console.warn(`[PakentoSDK] Error limpiando cache corrupto: ${err}`)
117
- );
118
- }
34
+ cached = await this.redis.get(key);
35
+ if (typeof cached === "object" && cached !== null) {
36
+ console.log("[Cache] \u2705 Reading from cache:", key);
37
+ return cached;
38
+ }
39
+ if (cached) {
40
+ console.log("[Cache] \u2705 Reading from cache:", key);
41
+ return JSON.parse(cached);
119
42
  }
120
43
  } catch (err) {
121
- console.warn("[PakentoSDK] Error leyendo cache Redis", err);
44
+ console.warn("[Cache] \u274C Error reading from cache:", err);
45
+ console.log(`[Cache] \u274C Key: ${key}, type: ${typeof cached}`);
122
46
  }
123
47
  const result = await fetcher();
124
48
  try {
125
- const serializedData = this.serializeForCache(result);
126
- await this.redis.set(key, serializedData, {
127
- ex: ttl ?? this.defaultTTL
49
+ console.log("[Cache] \u2705 Writing to cache:", key);
50
+ await this.redis.set(key, JSON.stringify(result), {
51
+ ex: this.defaultTTL
128
52
  });
129
- console.log(
130
- "[PakentoSDK] Cache no encontrado, se guarda y se devuelve uno nuevo"
131
- );
132
53
  } catch (err) {
133
- console.warn("[PakentoSDK] Error escribiendo cache Redis", err);
134
- console.warn("[PakentoSDK] Detalles del error:", {
135
- error: err,
136
- key,
137
- resultType: typeof result,
138
- resultSize: JSON.stringify(result).length
139
- });
54
+ console.warn("[Cache] \u274C Error writing to cache:", err);
140
55
  }
141
56
  return result;
142
57
  }
143
- async hasCache(functionName, params = {}) {
144
- if (!this.redis) {
145
- console.warn("[PakentoSDK] Redis no configurado");
146
- return false;
147
- }
148
- try {
149
- const key = this.buildCacheKey(functionName, params);
150
- const cached = await this.redis.get(key);
151
- if (cached === null || cached === void 0) {
152
- return false;
153
- }
154
- const parsed = this.safeJsonParse(cached);
155
- return parsed !== null;
156
- } catch (err) {
157
- console.warn("[PakentoSDK] Error verificando cache", err);
158
- return false;
159
- }
160
- }
161
- /**
162
- * Limpia un cache específico si está corrupto
163
- */
164
- async clearCorruptedCache(key) {
165
- if (!this.redis) {
166
- return false;
167
- }
168
- try {
169
- await this.redis.del(key);
170
- return true;
171
- } catch (err) {
172
- console.warn("[PakentoSDK] Error limpiando cache corrupto", err);
173
- return false;
174
- }
175
- }
176
- getCacheKey(functionName, params = {}) {
177
- return this.buildCacheKey(functionName, params);
178
- }
179
- async clearCache(functionName, params = {}) {
180
- if (!this.redis) {
181
- console.warn("[PakentoSDK] Redis no configurado");
182
- return false;
183
- }
184
- try {
185
- const key = this.buildCacheKey(functionName, params);
186
- await this.redis.del(key);
187
- return true;
188
- } catch (err) {
189
- console.warn("[PakentoSDK] Error limpiando cache", err);
190
- return false;
191
- }
192
- }
193
- async clearAllCache() {
194
- if (!this.redis) {
195
- console.warn("[PakentoSDK] Redis no configurado");
196
- return false;
197
- }
198
- try {
199
- const pattern = `pakento:${this.apiKeyHash}:*`;
200
- const keys = await this.redis.keys(pattern);
201
- if (keys.length > 0) {
202
- await this.redis.del(...keys);
203
- }
204
- return true;
205
- } catch (err) {
206
- console.warn("[PakentoSDK] Error limpiando todo el cache", err);
207
- return false;
208
- }
209
- }
210
- async getCacheInfo(functionName, params = {}) {
211
- if (!this.redis) {
212
- console.warn("[PakentoSDK] Redis no configurado");
213
- return {
214
- exists: false,
215
- key: this.buildCacheKey(functionName, params)
216
- };
217
- }
218
- try {
219
- const key = this.buildCacheKey(functionName, params);
220
- const exists = await this.redis.exists(key);
221
- const ttl = exists ? await this.redis.ttl(key) : void 0;
222
- return {
223
- exists: exists === 1,
224
- key,
225
- ttl: ttl === -1 ? void 0 : ttl
226
- };
227
- } catch (err) {
228
- console.warn("[PakentoSDK] Error obteniendo info del cache", err);
229
- return {
230
- exists: false,
231
- key: this.buildCacheKey(functionName, params)
232
- };
233
- }
234
- }
235
58
  };
236
59
 
237
- // src/services/api.ts
238
- import { z } from "zod";
239
-
240
- // src/utils/itemParser.ts
241
- function parseRawItemToItem(rawItem) {
242
- const firstPrice = rawItem.item_prices.docs[0];
243
- const images = rawItem.images.map((img) => ({
244
- url: img.url,
245
- thumbnail_url: img.thumbnailURL
246
- }));
247
- const coverImageUrl = rawItem.coverImage?.url || rawItem.images[0]?.url || "";
248
- const coverImageThumbnailUrl = rawItem.coverImage?.thumbnailURL || rawItem.images[0]?.thumbnailURL || "";
249
- return {
250
- id: rawItem.id,
251
- name: rawItem.name,
252
- featured: rawItem.featured,
253
- url_safe_name: rawItem.url_safe_name,
254
- currency_prefix: "$",
255
- // Default currency prefix, could be made configurable
256
- description: rawItem.description,
257
- old_price: firstPrice?.old_price || 0,
258
- item_category_name: rawItem.item_category?.name || "",
259
- item_category_id: parseInt(rawItem.item_category?.id || "0"),
260
- price_text: firstPrice?.price_text || "",
261
- price_notes: firstPrice?.price_notes || "",
262
- // Not available in raw response
263
- price: firstPrice?.amount || 0,
264
- brand_id: parseInt(rawItem.brand?.id || "0"),
265
- brand_name: rawItem.brand?.name || "",
266
- cover_image_url: coverImageUrl,
267
- cover_image_thumbnail_url: coverImageThumbnailUrl,
268
- images
269
- };
270
- }
271
- function parseRawItemsToItems(rawItems) {
272
- return rawItems.map(parseRawItemToItem);
273
- }
274
-
275
- // src/services/api.ts
276
- var PakentoCMSAPI = class {
277
- constructor(config) {
278
- this.defaultTTL = 86400;
60
+ // src/api/core/apiClient.ts
61
+ var ApiClient = class {
62
+ constructor() {
279
63
  this.baseURL = process.env.PAKENTO_CMS_BASE_URL || "";
280
64
  this.apiKey = process.env.PAKENTO_API_KEY || "";
281
- if (config?.cacheTTL && typeof config.cacheTTL === "number") {
282
- this.defaultTTL = config.cacheTTL;
283
- }
284
- this.cache = new CacheService(this.defaultTTL, this.apiKey);
65
+ this.cache = new CacheService(this.apiKey);
285
66
  this.client = axios.create({
286
67
  baseURL: this.baseURL,
287
68
  headers: {
@@ -290,17 +71,14 @@ var PakentoCMSAPI = class {
290
71
  }
291
72
  });
292
73
  this.client.interceptors.request.use(
293
- (config2) => {
294
- const fullUrl = `${config2.baseURL}${config2.url}`;
295
- console.log(`\u{1F310} API Call: ${config2.method?.toUpperCase()} ${fullUrl}`);
296
- return config2;
74
+ (config) => {
75
+ const fullUrl = `${config.baseURL}${config.url}`;
76
+ console.log(`\u{1F310} API Call: ${config.method?.toUpperCase()} ${fullUrl}`);
77
+ return config;
297
78
  },
298
- (error) => {
299
- return Promise.reject(error);
300
- }
79
+ (error) => Promise.reject(error)
301
80
  );
302
81
  }
303
- // Centralized error handler
304
82
  handleApiError(error, context) {
305
83
  if (error instanceof AxiosError) {
306
84
  const status = error.response?.status;
@@ -316,7 +94,6 @@ var PakentoCMSAPI = class {
316
94
  }
317
95
  return "Error desconocido";
318
96
  }
319
- // Generic GraphQL fetcher
320
97
  async fetchGraphQL(query, variables, extractData) {
321
98
  try {
322
99
  const response = await this.client.post("/api/graphql", {
@@ -334,32 +111,71 @@ var PakentoCMSAPI = class {
334
111
  return { data: null, error: true, errorMessage };
335
112
  }
336
113
  }
114
+ };
115
+
116
+ // src/api/items/parsers.ts
117
+ function parseRawItemToItem(rawItem) {
118
+ const firstPrice = rawItem.item_prices.docs[0];
119
+ const images = rawItem.images.map((img) => ({
120
+ url: img.url,
121
+ thumbnail_url: img.thumbnailURL
122
+ }));
123
+ const coverImageUrl = rawItem.coverImage?.url || rawItem.images[0]?.url || "";
124
+ const coverImageThumbnailUrl = rawItem.coverImage?.thumbnailURL || rawItem.images[0]?.thumbnailURL || "";
125
+ return {
126
+ id: rawItem.id,
127
+ name: rawItem.name,
128
+ featured: rawItem.featured,
129
+ url_safe_name: rawItem.url_safe_name,
130
+ currency_prefix: "$",
131
+ // Default currency prefix, could be made configurable
132
+ description: rawItem.description,
133
+ old_price: firstPrice?.old_price || 0,
134
+ item_category_name: rawItem.item_category?.name || "",
135
+ item_category_id: parseInt(rawItem.item_category?.id || "0"),
136
+ price_text: firstPrice?.price_text || "",
137
+ price_notes: firstPrice?.price_notes || "",
138
+ price: firstPrice?.amount || 0,
139
+ brand_id: parseInt(rawItem.brand?.id || "0"),
140
+ brand_name: rawItem.brand?.name || "",
141
+ cover_image_url: coverImageUrl,
142
+ cover_image_thumbnail_url: coverImageThumbnailUrl,
143
+ images
144
+ };
145
+ }
146
+ function parseRawItemsToItems(rawItems) {
147
+ return rawItems.map(parseRawItemToItem);
148
+ }
149
+
150
+ // src/api/items/validators.ts
151
+ import { z as z2 } from "zod";
152
+ var itemsParamsSchema = z2.object({
153
+ where: z2.object({
154
+ item_category_id: z2.object({ equals: z2.string().optional() }).optional(),
155
+ item_super_category_id: z2.object({ equals: z2.string().optional() }).optional(),
156
+ brand_id: z2.object({ equals: z2.string().optional() }).optional(),
157
+ id: z2.object({ equals: z2.string().optional() }).optional()
158
+ }).optional(),
159
+ onlyOffers: z2.boolean().optional(),
160
+ limit: z2.coerce.number().optional(),
161
+ page: z2.coerce.number().optional(),
162
+ search: z2.string().optional(),
163
+ sort: z2.string().optional(),
164
+ minPrice: z2.coerce.number().optional(),
165
+ maxPrice: z2.coerce.number().optional()
166
+ });
167
+
168
+ // src/api/items/api.ts
169
+ var ItemsApi = class extends ApiClient {
337
170
  async getItems(params = {}) {
338
- const itemsSchema = z.object({
339
- where: z.object({
340
- item_category_id: z.object({ equals: z.string().optional() }).optional(),
341
- item_super_category_id: z.object({ equals: z.string().optional() }).optional(),
342
- brand_id: z.object({ equals: z.string().optional() }).optional(),
343
- id: z.object({ equals: z.string().optional() }).optional()
344
- }).optional(),
345
- onlyOffers: z.boolean().optional(),
346
- limit: z.coerce.number().optional(),
347
- page: z.coerce.number().optional(),
348
- search: z.string().optional(),
349
- sort: z.string().optional(),
350
- minPrice: z.coerce.number().optional(),
351
- maxPrice: z.coerce.number().optional(),
352
- skipCache: z.boolean().optional(),
353
- cacheTTL: z.number().optional()
354
- });
355
- const validatedParams = itemsSchema.safeParse(params);
171
+ const validatedParams = itemsParamsSchema.safeParse(params);
356
172
  if (!validatedParams.success) {
357
173
  const errorMessage = this.handleApiError(
358
174
  validatedParams.error,
359
175
  "getItems validation"
360
176
  );
361
177
  return {
362
- data: null,
178
+ data: [],
363
179
  totalDocs: 0,
364
180
  totalPages: 0,
365
181
  prevPage: null,
@@ -368,28 +184,19 @@ var PakentoCMSAPI = class {
368
184
  errorMessage
369
185
  };
370
186
  }
371
- const { skipCache = false, cacheTTL, ...rest } = validatedParams.data;
372
- const cacheKey = this.cache.buildCacheKey("GetEcommerceItems", rest);
373
- const finalData = await this.cache.getCachedOrFetch(
187
+ const cacheKey = this.cache.buildCacheKey(
188
+ "GetEcommerceItems",
189
+ validatedParams.data
190
+ );
191
+ return this.cache.cacheWrap(
374
192
  cacheKey,
375
- () => this.fetchItemsFromAPI(rest),
376
- cacheTTL,
377
- skipCache
193
+ () => this.fetchItemsFromAPI(validatedParams.data)
378
194
  );
379
- return {
380
- data: finalData.data,
381
- totalDocs: finalData.totalDocs,
382
- totalPages: finalData.totalPages,
383
- prevPage: finalData.prevPage,
384
- nextPage: finalData.nextPage,
385
- error: false,
386
- errorMessage: null
387
- };
388
195
  }
389
- async fetchItemsFromAPI(params = {}) {
196
+ async fetchItemsFromAPI(params) {
390
197
  if (!this.baseURL || !this.apiKey) {
391
198
  return {
392
- data: null,
199
+ data: [],
393
200
  totalDocs: 0,
394
201
  totalPages: 0,
395
202
  prevPage: null,
@@ -485,7 +292,7 @@ var PakentoCMSAPI = class {
485
292
  );
486
293
  if (error) {
487
294
  return {
488
- data: null,
295
+ data: [],
489
296
  totalDocs: 0,
490
297
  totalPages: 0,
491
298
  prevPage: null,
@@ -504,25 +311,57 @@ var PakentoCMSAPI = class {
504
311
  errorMessage: null
505
312
  };
506
313
  }
314
+ };
315
+ var itemsApi = new ItemsApi();
316
+
317
+ // src/api/categories/validators.ts
318
+ import { z as z3 } from "zod";
319
+ var categoriesParamsSchema = z3.object({
320
+ where: z3.object({
321
+ item_super_category_id: z3.object({ equals: z3.string().optional() }).optional(),
322
+ brand_id: z3.object({ equals: z3.string().optional() }).optional()
323
+ }).optional(),
324
+ limit: z3.coerce.number().optional(),
325
+ page: z3.coerce.number().optional(),
326
+ sort: z3.string().optional()
327
+ });
328
+
329
+ // src/api/categories/parsers.ts
330
+ function parseRawCategoryToCategory(rawCategory) {
331
+ return {
332
+ id: rawCategory.id,
333
+ name: rawCategory.name,
334
+ image_url: rawCategory.image_url
335
+ };
336
+ }
337
+ function parseRawCategoriesToCategories(rawCategories) {
338
+ return rawCategories.map(parseRawCategoryToCategory);
339
+ }
340
+
341
+ // src/api/categories/api.ts
342
+ var CategoriesApi = class extends ApiClient {
507
343
  async getCategories(params = {}) {
508
- const {
509
- skipCache = false,
510
- cacheTTL,
511
- ...rest
512
- } = params;
513
- const cacheKey = this.cache.buildCacheKey("GetEcommerceCategories", rest);
514
- return this.cache.getCachedOrFetch(
344
+ const validatedParams = categoriesParamsSchema.safeParse(params);
345
+ if (!validatedParams.success) {
346
+ const errorMessage = this.handleApiError(
347
+ validatedParams.error,
348
+ "getCategories validation"
349
+ );
350
+ return { data: [], error: true, errorMessage };
351
+ }
352
+ const cacheKey = this.cache.buildCacheKey(
353
+ "GetEcommerceCategories",
354
+ validatedParams.data
355
+ );
356
+ return this.cache.cacheWrap(
515
357
  cacheKey,
516
- () => this.fetchCategoriesFromAPI(rest),
517
- cacheTTL,
518
- skipCache
358
+ () => this.fetchCategoriesFromAPI(validatedParams.data)
519
359
  );
520
360
  }
521
- async fetchCategoriesFromAPI(params = {}) {
361
+ async fetchCategoriesFromAPI(params) {
522
362
  if (!this.baseURL || !this.apiKey) {
523
363
  return {
524
- data: null,
525
- categories: [],
364
+ data: [],
526
365
  error: true,
527
366
  errorMessage: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes."
528
367
  };
@@ -554,45 +393,77 @@ var PakentoCMSAPI = class {
554
393
  (responseData) => responseData.GetEcommerceCategories
555
394
  );
556
395
  if (error) {
557
- return {
558
- data: null,
559
- categories: [],
560
- error: true,
561
- errorMessage
562
- };
396
+ return { data: [], error: true, errorMessage };
563
397
  }
564
398
  return {
565
- data: data.docs,
566
- categories: data.docs,
399
+ data: parseRawCategoriesToCategories(data.docs),
567
400
  error: false,
568
401
  errorMessage: null
569
402
  };
570
403
  }
404
+ };
405
+ var categoriesApi = new CategoriesApi();
406
+
407
+ // src/api/brands/validators.ts
408
+ import { z as z4 } from "zod";
409
+ var brandsParamsSchema = z4.object({
410
+ limit: z4.coerce.number().optional(),
411
+ page: z4.coerce.number().optional(),
412
+ sort: z4.string().optional()
413
+ });
414
+
415
+ // src/api/brands/parsers.ts
416
+ function parseRawBrandToBrand(rawBrand) {
417
+ return {
418
+ id: rawBrand.id,
419
+ name: rawBrand.name,
420
+ description: rawBrand.description,
421
+ items_count: rawBrand.items_count,
422
+ image_url: rawBrand.image_url,
423
+ image_thumbnail_url: rawBrand.image_thumbnail_url,
424
+ image_alt: rawBrand.image_alt
425
+ };
426
+ }
427
+ function parseRawBrandsToBrands(rawBrands) {
428
+ return rawBrands.map(parseRawBrandToBrand);
429
+ }
430
+
431
+ // src/api/brands/api.ts
432
+ var BrandsApi = class extends ApiClient {
571
433
  async getBrands(params = {}) {
572
- const { skipCache = false, cacheTTL, ...rest } = params;
573
- const cacheKey = this.cache.buildCacheKey("GetEcommerceBrands", rest);
574
- return this.cache.getCachedOrFetch(
434
+ const validatedParams = brandsParamsSchema.safeParse(params);
435
+ if (!validatedParams.success) {
436
+ const errorMessage = this.handleApiError(
437
+ validatedParams.error,
438
+ "getBrands validation"
439
+ );
440
+ return {
441
+ data: [],
442
+ totalDocs: 0,
443
+ totalPages: 0,
444
+ prevPage: null,
445
+ nextPage: null,
446
+ error: true,
447
+ errorMessage
448
+ };
449
+ }
450
+ const cacheKey = this.cache.buildCacheKey(
451
+ "GetEcommerceBrands",
452
+ validatedParams.data
453
+ );
454
+ return this.cache.cacheWrap(
575
455
  cacheKey,
576
- () => this.fetchBrandsFromAPI(rest),
577
- cacheTTL,
578
- skipCache
456
+ () => this.fetchBrandsFromAPI(validatedParams.data)
579
457
  );
580
458
  }
581
- async fetchBrandsFromAPI(params = {}) {
459
+ async fetchBrandsFromAPI(params) {
582
460
  if (!this.baseURL || !this.apiKey) {
583
461
  return {
584
- data: null,
585
- brands: [],
586
- hasNextPage: false,
587
- hasPrevPage: false,
588
- limit: 0,
589
- nextPage: 0,
590
- offset: 0,
591
- page: 0,
592
- pagingCounter: 0,
593
- prevPage: 0,
462
+ data: [],
594
463
  totalDocs: 0,
595
464
  totalPages: 0,
465
+ prevPage: null,
466
+ nextPage: null,
596
467
  error: true,
597
468
  errorMessage: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes."
598
469
  };
@@ -608,6 +479,10 @@ var PakentoCMSAPI = class {
608
479
  page: $page
609
480
  sort: $sort
610
481
  ) {
482
+ totalDocs
483
+ totalPages
484
+ prevPage
485
+ nextPage
611
486
  docs {
612
487
  id
613
488
  name
@@ -617,16 +492,6 @@ var PakentoCMSAPI = class {
617
492
  image_thumbnail_url
618
493
  image_alt
619
494
  }
620
- hasNextPage
621
- hasPrevPage
622
- limit
623
- nextPage
624
- offset
625
- page
626
- pagingCounter
627
- prevPage
628
- totalDocs
629
- totalPages
630
495
  }
631
496
  }
632
497
  `;
@@ -637,54 +502,79 @@ var PakentoCMSAPI = class {
637
502
  );
638
503
  if (error) {
639
504
  return {
640
- data: null,
641
- brands: [],
642
- hasNextPage: false,
643
- hasPrevPage: false,
644
- limit: 0,
645
- nextPage: 0,
646
- offset: 0,
647
- page: 0,
648
- pagingCounter: 0,
649
- prevPage: 0,
505
+ data: [],
650
506
  totalDocs: 0,
651
507
  totalPages: 0,
508
+ prevPage: null,
509
+ nextPage: null,
652
510
  error: true,
653
511
  errorMessage
654
512
  };
655
513
  }
656
514
  return {
657
- data,
658
- brands: data.docs,
659
- hasNextPage: data.hasNextPage,
660
- hasPrevPage: data.hasPrevPage,
661
- limit: data.limit,
662
- nextPage: data.nextPage,
663
- offset: data.offset,
664
- page: data.page,
665
- pagingCounter: data.pagingCounter,
666
- prevPage: data.prevPage,
515
+ data: parseRawBrandsToBrands(data.docs),
667
516
  totalDocs: data.totalDocs,
668
517
  totalPages: data.totalPages,
518
+ prevPage: data.prevPage,
519
+ nextPage: data.nextPage,
669
520
  error: false,
670
521
  errorMessage: null
671
522
  };
672
523
  }
524
+ };
525
+ var brandsApi = new BrandsApi();
526
+
527
+ // src/api/entity/parsers.ts
528
+ function parseRawEntityToEntity(rawEntity) {
529
+ return {
530
+ id: rawEntity.id,
531
+ tin: rawEntity.tin,
532
+ name: rawEntity.name,
533
+ web: rawEntity.web,
534
+ address: rawEntity.address,
535
+ country: rawEntity.country,
536
+ city: rawEntity.city,
537
+ currency_id: rawEntity.currency_id,
538
+ currency_name: rawEntity.currency_name,
539
+ currency_prefix: rawEntity.currency_prefix,
540
+ currency_suffix: rawEntity.currency_suffix,
541
+ logo_url: rawEntity.logo_url,
542
+ logo_alt: rawEntity.logo_alt,
543
+ logo_thumbnail_url: rawEntity.logo_thumbnail_url,
544
+ logo_sizes_thumbnail_filename: rawEntity.logo_sizes_thumbnail_filename,
545
+ logo_filename: rawEntity.logo_filename,
546
+ logo_width: rawEntity.logo_width,
547
+ logo_height: rawEntity.logo_height,
548
+ logo_2_url: rawEntity.logo_2_url,
549
+ logo_2_alt: rawEntity.logo_2_alt,
550
+ logo_2_thumbnail_url: rawEntity.logo_2_thumbnail_url,
551
+ logo_2_sizes_thumbnail_filename: rawEntity.logo_2_sizes_thumbnail_filename,
552
+ logo_2_filename: rawEntity.logo_2_filename,
553
+ logo_2_width: rawEntity.logo_2_width,
554
+ logo_2_height: rawEntity.logo_2_height,
555
+ featured_image_url: rawEntity.featured_image_url,
556
+ featured_image_alt: rawEntity.featured_image_alt,
557
+ featured_image_thumbnail_url: rawEntity.featured_image_thumbnail_url,
558
+ featured_image_sizes_thumbnail_filename: rawEntity.featured_image_sizes_thumbnail_filename,
559
+ featured_image_filename: rawEntity.featured_image_filename,
560
+ featured_image_width: rawEntity.featured_image_width,
561
+ featured_image_height: rawEntity.featured_image_height
562
+ };
563
+ }
564
+
565
+ // src/api/entity/api.ts
566
+ var EntityApi = class extends ApiClient {
673
567
  async getEntity(params = {}) {
674
- const { skipCache = false, cacheTTL, ...rest } = params;
675
- const cacheKey = this.cache.buildCacheKey("GetEntity", rest);
676
- return this.cache.getCachedOrFetch(
568
+ const cacheKey = this.cache.buildCacheKey("GetEntity", params);
569
+ return this.cache.cacheWrap(
677
570
  cacheKey,
678
- () => this.fetchEntityFromAPI(rest),
679
- cacheTTL,
680
- skipCache
571
+ () => this.fetchEntityFromAPI(params)
681
572
  );
682
573
  }
683
- async fetchEntityFromAPI(params = {}) {
574
+ async fetchEntityFromAPI(params) {
684
575
  if (!this.baseURL || !this.apiKey) {
685
576
  return {
686
577
  data: null,
687
- entity: null,
688
578
  error: true,
689
579
  errorMessage: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes."
690
580
  };
@@ -730,23 +620,38 @@ var PakentoCMSAPI = class {
730
620
  const { data, error, errorMessage } = await this.fetchGraphQL(
731
621
  query,
732
622
  params,
733
- (responseData) => responseData.GetEntity
623
+ (responseData) => responseData
734
624
  );
735
625
  if (error) {
736
- return {
737
- data: null,
738
- entity: null,
739
- error: true,
740
- errorMessage
741
- };
626
+ return { data: null, error: true, errorMessage };
742
627
  }
743
628
  return {
744
- data,
745
- entity: data,
629
+ data: parseRawEntityToEntity(data.GetEntity),
746
630
  error: false,
747
631
  errorMessage: null
748
632
  };
749
633
  }
634
+ };
635
+ var entityApi = new EntityApi();
636
+
637
+ // src/api/orders/validators.ts
638
+ import { z as z5 } from "zod";
639
+ var orderSchema = z5.object({
640
+ name: z5.string().min(1),
641
+ email: z5.string().email(),
642
+ phone: z5.string().optional(),
643
+ notes: z5.string().optional(),
644
+ tin: z5.string().optional(),
645
+ items: z5.array(
646
+ z5.object({ id: z5.number().positive(), quantity: z5.number().positive() })
647
+ ).min(1),
648
+ delivery_address: z5.string().optional(),
649
+ delivery_instructions: z5.string().optional(),
650
+ payment_method: z5.enum(["cash", "transfer"]).optional()
651
+ });
652
+
653
+ // src/api/orders/api.ts
654
+ var OrdersApi = class extends ApiClient {
750
655
  async createEcommerceOrder(params) {
751
656
  if (!this.baseURL || !this.apiKey) {
752
657
  return {
@@ -755,22 +660,6 @@ var PakentoCMSAPI = class {
755
660
  errorMessage: "SDK no configurado"
756
661
  };
757
662
  }
758
- const orderSchema = z.object({
759
- name: z.string().min(1),
760
- email: z.string().email(),
761
- phone: z.string().optional(),
762
- notes: z.string().optional(),
763
- tin: z.string().optional(),
764
- items: z.array(
765
- z.object({
766
- id: z.number().positive(),
767
- quantity: z.number().positive()
768
- })
769
- ).min(1),
770
- delivery_address: z.string().optional(),
771
- delivery_instructions: z.string().optional(),
772
- payment_method: z.enum(["cash", "transfer"]).optional()
773
- });
774
663
  const validated = orderSchema.safeParse(params);
775
664
  if (!validated.success) {
776
665
  const errorMessage = this.handleApiError(
@@ -800,6 +689,62 @@ var PakentoCMSAPI = class {
800
689
  return { message: errorMessage, error: true, errorMessage };
801
690
  }
802
691
  }
692
+ };
693
+ var ordersApi = new OrdersApi();
694
+
695
+ // src/api/contact/validators.ts
696
+ import { z as z6 } from "zod";
697
+ var contactUsSchema = z6.object({
698
+ name: z6.string().min(1),
699
+ email: z6.string().email(),
700
+ phone: z6.string().optional(),
701
+ subject: z6.string().optional(),
702
+ notes: z6.string().min(1)
703
+ });
704
+
705
+ // src/api/contact/api.ts
706
+ var ContactApi = class extends ApiClient {
707
+ async sendContactUsEmail(params) {
708
+ if (!this.baseURL || !this.apiKey) {
709
+ return {
710
+ message: "SDK no configurado",
711
+ error: true,
712
+ errorMessage: "SDK no configurado"
713
+ };
714
+ }
715
+ const validated = contactUsSchema.safeParse(params);
716
+ if (!validated.success) {
717
+ const errorMessage = this.handleApiError(
718
+ validated.error,
719
+ "sendContactUsEmail validation"
720
+ );
721
+ return { message: errorMessage, error: true, errorMessage };
722
+ }
723
+ try {
724
+ const response = await this.client.post(
725
+ "/api/entities/send-contact-us-email",
726
+ validated.data
727
+ );
728
+ if (response.status === 200) {
729
+ return {
730
+ message: response.data.message || "Mensaje enviado exitosamente",
731
+ error: false,
732
+ errorMessage: null
733
+ };
734
+ } else {
735
+ const errorMessage = response.data.message || "Error al enviar el mensaje";
736
+ return { message: errorMessage, error: true, errorMessage };
737
+ }
738
+ } catch (error) {
739
+ const errorMessage = this.handleApiError(error, "sendContactUsEmail");
740
+ return { message: errorMessage, error: true, errorMessage };
741
+ }
742
+ }
743
+ };
744
+ var contactApi = new ContactApi();
745
+
746
+ // src/api/custom/api.ts
747
+ var CustomApi = class extends ApiClient {
803
748
  async executeCustomQuery(params) {
804
749
  if (!this.baseURL || !this.apiKey) {
805
750
  return {
@@ -834,116 +779,20 @@ var PakentoCMSAPI = class {
834
779
  errorMessage: null
835
780
  };
836
781
  } catch (error) {
837
- let errorMessage = "Error desconocido";
838
- if (error instanceof AxiosError) {
839
- const status = error.response?.status;
840
- if (status === 401) {
841
- errorMessage = "API Key inv\xE1lida o expirada";
842
- } else if (status === 404) {
843
- errorMessage = "Endpoint GraphQL no encontrado";
844
- } else if (status === 400) {
845
- errorMessage = "Query GraphQL inv\xE1lido o malformado";
846
- } else if (status && status >= 500) {
847
- errorMessage = "Error del servidor CMS";
848
- } else {
849
- errorMessage = `Error de conexi\xF3n: ${error.message}`;
850
- }
851
- } else if (error instanceof Error) {
852
- errorMessage = error.message;
853
- }
854
- return {
855
- data: null,
856
- error: true,
857
- errorMessage
858
- };
859
- }
860
- }
861
- async sendContactUsEmail(params) {
862
- if (!this.baseURL || !this.apiKey) {
863
- return {
864
- message: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes.",
865
- error: true,
866
- errorMessage: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes."
867
- };
868
- }
869
- const contactUsSchema = z.object({
870
- name: z.string().min(1),
871
- email: z.email(),
872
- phone: z.string().optional(),
873
- subject: z.string().optional(),
874
- message: z.string().min(1)
875
- });
876
- const validated = contactUsSchema.safeParse(params);
877
- if (!validated.success) {
878
- const errorMessage = this.handleApiError(
879
- validated.error,
880
- "sendContactUsEmail validation"
881
- );
882
- return { message: errorMessage, error: true, errorMessage };
883
- }
884
- try {
885
- const response = await this.client.post(
886
- "/api/entities/send-contact-us-email",
887
- validated.data
888
- );
889
- if (response.status === 200) {
890
- return {
891
- message: response.data.message || "Mensaje enviado exitosamente",
892
- error: false,
893
- errorMessage: null
894
- };
895
- } else {
896
- const errorMessage = response.data.message || "Error al enviar el mensaje";
897
- return { message: errorMessage, error: true, errorMessage };
898
- }
899
- } catch (error) {
900
- const errorMessage = this.handleApiError(error, "sendContactUsEmail");
901
- return { message: errorMessage, error: true, errorMessage };
782
+ const errorMessage = this.handleApiError(error, "Custom GraphQL");
783
+ return { data: null, error: true, errorMessage };
902
784
  }
903
785
  }
904
- /**
905
- * Verifica si existe cache para una función y parámetros específicos
906
- */
907
- async hasCache(functionName, params = {}) {
908
- return this.cache.hasCache(functionName, params);
909
- }
910
- /**
911
- * Obtiene la key de cache para una función y parámetros específicos
912
- */
913
- getCacheKey(functionName, params = {}) {
914
- return this.cache.getCacheKey(functionName, params);
915
- }
916
- /**
917
- * Limpia el cache para una función y parámetros específicos
918
- */
919
- async clearCache(functionName, params = {}) {
920
- return this.cache.clearCache(functionName, params);
921
- }
922
- /**
923
- * Limpia todo el cache relacionado con este API Key
924
- */
925
- async clearAllCache() {
926
- return this.cache.clearAllCache();
927
- }
928
- /**
929
- * Obtiene información del cache (útil para debugging)
930
- */
931
- async getCacheInfo(functionName, params = {}) {
932
- return this.cache.getCacheInfo(functionName, params);
933
- }
934
- /**
935
- * Limpia un cache específico que pueda estar corrupto
936
- */
937
- async clearCorruptedCache(functionName, params = {}) {
938
- const key = this.cache.getCacheKey(functionName, params);
939
- return this.cache.clearCorruptedCache(key);
940
- }
941
786
  };
942
- var pakentoCMSAPI = new PakentoCMSAPI();
787
+ var customApi = new CustomApi();
943
788
  export {
944
- CacheService,
945
- pakentoCMSAPI,
946
- parseRawItemToItem,
947
- parseRawItemsToItems
789
+ ApiClient,
790
+ brandsApi,
791
+ categoriesApi,
792
+ contactApi,
793
+ customApi,
794
+ entityApi,
795
+ itemsApi,
796
+ ordersApi
948
797
  };
949
798
  //# sourceMappingURL=index.mjs.map