@pakento/cms-sdk 4.3.0 → 4.3.2

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,25 +111,64 @@ 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,
@@ -360,7 +176,6 @@ var PakentoCMSAPI = class {
360
176
  );
361
177
  return {
362
178
  data: null,
363
- items: [],
364
179
  totalDocs: 0,
365
180
  totalPages: 0,
366
181
  prevPage: null,
@@ -369,20 +184,19 @@ var PakentoCMSAPI = class {
369
184
  errorMessage
370
185
  };
371
186
  }
372
- const { skipCache = false, cacheTTL, ...rest } = validatedParams.data;
373
- const cacheKey = this.cache.buildCacheKey("GetEcommerceItems", rest);
374
- return this.cache.getCachedOrFetch(
187
+ const cacheKey = this.cache.buildCacheKey(
188
+ "GetEcommerceItems",
189
+ validatedParams.data
190
+ );
191
+ return this.cache.cacheWrap(
375
192
  cacheKey,
376
- () => this.fetchItemsFromAPI(rest),
377
- cacheTTL,
378
- skipCache
193
+ () => this.fetchItemsFromAPI(validatedParams.data)
379
194
  );
380
195
  }
381
- async fetchItemsFromAPI(params = {}) {
196
+ async fetchItemsFromAPI(params) {
382
197
  if (!this.baseURL || !this.apiKey) {
383
198
  return {
384
199
  data: null,
385
- items: [],
386
200
  totalDocs: 0,
387
201
  totalPages: 0,
388
202
  prevPage: null,
@@ -479,7 +293,6 @@ var PakentoCMSAPI = class {
479
293
  if (error) {
480
294
  return {
481
295
  data: null,
482
- items: [],
483
296
  totalDocs: 0,
484
297
  totalPages: 0,
485
298
  prevPage: null,
@@ -489,8 +302,7 @@ var PakentoCMSAPI = class {
489
302
  };
490
303
  }
491
304
  return {
492
- data,
493
- items: parseRawItemsToItems(data.docs),
305
+ data: parseRawItemsToItems(data.docs),
494
306
  totalDocs: data.totalDocs,
495
307
  totalPages: data.totalPages,
496
308
  prevPage: data.prevPage,
@@ -499,21 +311,42 @@ var PakentoCMSAPI = class {
499
311
  errorMessage: null
500
312
  };
501
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/api.ts
330
+ var CategoriesApi = class extends ApiClient {
502
331
  async getCategories(params = {}) {
503
- const {
504
- skipCache = false,
505
- cacheTTL,
506
- ...rest
507
- } = params;
508
- const cacheKey = this.cache.buildCacheKey("GetEcommerceCategories", rest);
509
- return this.cache.getCachedOrFetch(
332
+ const validatedParams = categoriesParamsSchema.safeParse(params);
333
+ if (!validatedParams.success) {
334
+ const errorMessage = this.handleApiError(
335
+ validatedParams.error,
336
+ "getCategories validation"
337
+ );
338
+ return { data: null, categories: [], error: true, errorMessage };
339
+ }
340
+ const cacheKey = this.cache.buildCacheKey(
341
+ "GetEcommerceCategories",
342
+ validatedParams.data
343
+ );
344
+ return this.cache.cacheWrap(
510
345
  cacheKey,
511
- () => this.fetchCategoriesFromAPI(rest),
512
- cacheTTL,
513
- skipCache
346
+ () => this.fetchCategoriesFromAPI(validatedParams.data)
514
347
  );
515
348
  }
516
- async fetchCategoriesFromAPI(params = {}) {
349
+ async fetchCategoriesFromAPI(params) {
517
350
  if (!this.baseURL || !this.apiKey) {
518
351
  return {
519
352
  data: null,
@@ -549,12 +382,7 @@ var PakentoCMSAPI = class {
549
382
  (responseData) => responseData.GetEcommerceCategories
550
383
  );
551
384
  if (error) {
552
- return {
553
- data: null,
554
- categories: [],
555
- error: true,
556
- errorMessage
557
- };
385
+ return { data: null, categories: [], error: true, errorMessage };
558
386
  }
559
387
  return {
560
388
  data: data.docs,
@@ -563,17 +391,53 @@ var PakentoCMSAPI = class {
563
391
  errorMessage: null
564
392
  };
565
393
  }
394
+ };
395
+ var categoriesApi = new CategoriesApi();
396
+
397
+ // src/api/brands/validators.ts
398
+ import { z as z4 } from "zod";
399
+ var brandsParamsSchema = z4.object({
400
+ limit: z4.coerce.number().optional(),
401
+ page: z4.coerce.number().optional(),
402
+ sort: z4.string().optional()
403
+ });
404
+
405
+ // src/api/brands/api.ts
406
+ var BrandsApi = class extends ApiClient {
566
407
  async getBrands(params = {}) {
567
- const { skipCache = false, cacheTTL, ...rest } = params;
568
- const cacheKey = this.cache.buildCacheKey("GetEcommerceBrands", rest);
569
- return this.cache.getCachedOrFetch(
408
+ const validatedParams = brandsParamsSchema.safeParse(params);
409
+ if (!validatedParams.success) {
410
+ const errorMessage = this.handleApiError(
411
+ validatedParams.error,
412
+ "getBrands validation"
413
+ );
414
+ return {
415
+ data: null,
416
+ brands: [],
417
+ hasNextPage: false,
418
+ hasPrevPage: false,
419
+ limit: 0,
420
+ nextPage: 0,
421
+ offset: 0,
422
+ page: 0,
423
+ pagingCounter: 0,
424
+ prevPage: 0,
425
+ totalDocs: 0,
426
+ totalPages: 0,
427
+ error: true,
428
+ errorMessage
429
+ };
430
+ }
431
+ const cacheKey = this.cache.buildCacheKey(
432
+ "GetEcommerceBrands",
433
+ validatedParams.data
434
+ );
435
+ return this.cache.cacheWrap(
570
436
  cacheKey,
571
- () => this.fetchBrandsFromAPI(rest),
572
- cacheTTL,
573
- skipCache
437
+ () => this.fetchBrandsFromAPI(validatedParams.data)
574
438
  );
575
439
  }
576
- async fetchBrandsFromAPI(params = {}) {
440
+ async fetchBrandsFromAPI(params) {
577
441
  if (!this.baseURL || !this.apiKey) {
578
442
  return {
579
443
  data: null,
@@ -665,17 +529,19 @@ var PakentoCMSAPI = class {
665
529
  errorMessage: null
666
530
  };
667
531
  }
532
+ };
533
+ var brandsApi = new BrandsApi();
534
+
535
+ // src/api/entity/api.ts
536
+ var EntityApi = class extends ApiClient {
668
537
  async getEntity(params = {}) {
669
- const { skipCache = false, cacheTTL, ...rest } = params;
670
- const cacheKey = this.cache.buildCacheKey("GetEntity", rest);
671
- return this.cache.getCachedOrFetch(
538
+ const cacheKey = this.cache.buildCacheKey("GetEntity", params);
539
+ return this.cache.cacheWrap(
672
540
  cacheKey,
673
- () => this.fetchEntityFromAPI(rest),
674
- cacheTTL,
675
- skipCache
541
+ () => this.fetchEntityFromAPI(params)
676
542
  );
677
543
  }
678
- async fetchEntityFromAPI(params = {}) {
544
+ async fetchEntityFromAPI(params) {
679
545
  if (!this.baseURL || !this.apiKey) {
680
546
  return {
681
547
  data: null,
@@ -725,23 +591,39 @@ var PakentoCMSAPI = class {
725
591
  const { data, error, errorMessage } = await this.fetchGraphQL(
726
592
  query,
727
593
  params,
728
- (responseData) => responseData.GetEntity
594
+ (responseData) => responseData
729
595
  );
730
596
  if (error) {
731
- return {
732
- data: null,
733
- entity: null,
734
- error: true,
735
- errorMessage
736
- };
597
+ return { data: null, entity: null, error: true, errorMessage };
737
598
  }
738
599
  return {
739
- data,
740
- entity: data,
600
+ data: data.GetEntity,
601
+ entity: data.GetEntity,
741
602
  error: false,
742
603
  errorMessage: null
743
604
  };
744
605
  }
606
+ };
607
+ var entityApi = new EntityApi();
608
+
609
+ // src/api/orders/validators.ts
610
+ import { z as z5 } from "zod";
611
+ var orderSchema = z5.object({
612
+ name: z5.string().min(1),
613
+ email: z5.string().email(),
614
+ phone: z5.string().optional(),
615
+ notes: z5.string().optional(),
616
+ tin: z5.string().optional(),
617
+ items: z5.array(
618
+ z5.object({ id: z5.number().positive(), quantity: z5.number().positive() })
619
+ ).min(1),
620
+ delivery_address: z5.string().optional(),
621
+ delivery_instructions: z5.string().optional(),
622
+ payment_method: z5.enum(["cash", "transfer"]).optional()
623
+ });
624
+
625
+ // src/api/orders/api.ts
626
+ var OrdersApi = class extends ApiClient {
745
627
  async createEcommerceOrder(params) {
746
628
  if (!this.baseURL || !this.apiKey) {
747
629
  return {
@@ -750,22 +632,6 @@ var PakentoCMSAPI = class {
750
632
  errorMessage: "SDK no configurado"
751
633
  };
752
634
  }
753
- const orderSchema = z.object({
754
- name: z.string().min(1),
755
- email: z.string().email(),
756
- phone: z.string().optional(),
757
- notes: z.string().optional(),
758
- tin: z.string().optional(),
759
- items: z.array(
760
- z.object({
761
- id: z.number().positive(),
762
- quantity: z.number().positive()
763
- })
764
- ).min(1),
765
- delivery_address: z.string().optional(),
766
- delivery_instructions: z.string().optional(),
767
- payment_method: z.enum(["cash", "transfer"]).optional()
768
- });
769
635
  const validated = orderSchema.safeParse(params);
770
636
  if (!validated.success) {
771
637
  const errorMessage = this.handleApiError(
@@ -795,6 +661,62 @@ var PakentoCMSAPI = class {
795
661
  return { message: errorMessage, error: true, errorMessage };
796
662
  }
797
663
  }
664
+ };
665
+ var ordersApi = new OrdersApi();
666
+
667
+ // src/api/contact/validators.ts
668
+ import { z as z6 } from "zod";
669
+ var contactUsSchema = z6.object({
670
+ name: z6.string().min(1),
671
+ email: z6.string().email(),
672
+ phone: z6.string().optional(),
673
+ subject: z6.string().optional(),
674
+ notes: z6.string().min(1)
675
+ });
676
+
677
+ // src/api/contact/api.ts
678
+ var ContactApi = class extends ApiClient {
679
+ async sendContactUsEmail(params) {
680
+ if (!this.baseURL || !this.apiKey) {
681
+ return {
682
+ message: "SDK no configurado",
683
+ error: true,
684
+ errorMessage: "SDK no configurado"
685
+ };
686
+ }
687
+ const validated = contactUsSchema.safeParse(params);
688
+ if (!validated.success) {
689
+ const errorMessage = this.handleApiError(
690
+ validated.error,
691
+ "sendContactUsEmail validation"
692
+ );
693
+ return { message: errorMessage, error: true, errorMessage };
694
+ }
695
+ try {
696
+ const response = await this.client.post(
697
+ "/api/entities/send-contact-us-email",
698
+ validated.data
699
+ );
700
+ if (response.status === 200) {
701
+ return {
702
+ message: response.data.message || "Mensaje enviado exitosamente",
703
+ error: false,
704
+ errorMessage: null
705
+ };
706
+ } else {
707
+ const errorMessage = response.data.message || "Error al enviar el mensaje";
708
+ return { message: errorMessage, error: true, errorMessage };
709
+ }
710
+ } catch (error) {
711
+ const errorMessage = this.handleApiError(error, "sendContactUsEmail");
712
+ return { message: errorMessage, error: true, errorMessage };
713
+ }
714
+ }
715
+ };
716
+ var contactApi = new ContactApi();
717
+
718
+ // src/api/custom/api.ts
719
+ var CustomApi = class extends ApiClient {
798
720
  async executeCustomQuery(params) {
799
721
  if (!this.baseURL || !this.apiKey) {
800
722
  return {
@@ -829,116 +751,20 @@ var PakentoCMSAPI = class {
829
751
  errorMessage: null
830
752
  };
831
753
  } catch (error) {
832
- let errorMessage = "Error desconocido";
833
- if (error instanceof AxiosError) {
834
- const status = error.response?.status;
835
- if (status === 401) {
836
- errorMessage = "API Key inv\xE1lida o expirada";
837
- } else if (status === 404) {
838
- errorMessage = "Endpoint GraphQL no encontrado";
839
- } else if (status === 400) {
840
- errorMessage = "Query GraphQL inv\xE1lido o malformado";
841
- } else if (status && status >= 500) {
842
- errorMessage = "Error del servidor CMS";
843
- } else {
844
- errorMessage = `Error de conexi\xF3n: ${error.message}`;
845
- }
846
- } else if (error instanceof Error) {
847
- errorMessage = error.message;
848
- }
849
- return {
850
- data: null,
851
- error: true,
852
- errorMessage
853
- };
854
- }
855
- }
856
- async sendContactUsEmail(params) {
857
- if (!this.baseURL || !this.apiKey) {
858
- return {
859
- message: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes.",
860
- error: true,
861
- errorMessage: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes."
862
- };
863
- }
864
- const contactUsSchema = z.object({
865
- name: z.string().min(1),
866
- email: z.email(),
867
- phone: z.string().optional(),
868
- subject: z.string().optional(),
869
- message: z.string().min(1)
870
- });
871
- const validated = contactUsSchema.safeParse(params);
872
- if (!validated.success) {
873
- const errorMessage = this.handleApiError(
874
- validated.error,
875
- "sendContactUsEmail validation"
876
- );
877
- return { message: errorMessage, error: true, errorMessage };
878
- }
879
- try {
880
- const response = await this.client.post(
881
- "/api/entities/send-contact-us-email",
882
- validated.data
883
- );
884
- if (response.status === 200) {
885
- return {
886
- message: response.data.message || "Mensaje enviado exitosamente",
887
- error: false,
888
- errorMessage: null
889
- };
890
- } else {
891
- const errorMessage = response.data.message || "Error al enviar el mensaje";
892
- return { message: errorMessage, error: true, errorMessage };
893
- }
894
- } catch (error) {
895
- const errorMessage = this.handleApiError(error, "sendContactUsEmail");
896
- return { message: errorMessage, error: true, errorMessage };
754
+ const errorMessage = this.handleApiError(error, "Custom GraphQL");
755
+ return { data: null, error: true, errorMessage };
897
756
  }
898
757
  }
899
- /**
900
- * Verifica si existe cache para una función y parámetros específicos
901
- */
902
- async hasCache(functionName, params = {}) {
903
- return this.cache.hasCache(functionName, params);
904
- }
905
- /**
906
- * Obtiene la key de cache para una función y parámetros específicos
907
- */
908
- getCacheKey(functionName, params = {}) {
909
- return this.cache.getCacheKey(functionName, params);
910
- }
911
- /**
912
- * Limpia el cache para una función y parámetros específicos
913
- */
914
- async clearCache(functionName, params = {}) {
915
- return this.cache.clearCache(functionName, params);
916
- }
917
- /**
918
- * Limpia todo el cache relacionado con este API Key
919
- */
920
- async clearAllCache() {
921
- return this.cache.clearAllCache();
922
- }
923
- /**
924
- * Obtiene información del cache (útil para debugging)
925
- */
926
- async getCacheInfo(functionName, params = {}) {
927
- return this.cache.getCacheInfo(functionName, params);
928
- }
929
- /**
930
- * Limpia un cache específico que pueda estar corrupto
931
- */
932
- async clearCorruptedCache(functionName, params = {}) {
933
- const key = this.cache.getCacheKey(functionName, params);
934
- return this.cache.clearCorruptedCache(key);
935
- }
936
758
  };
937
- var pakentoCMSAPI = new PakentoCMSAPI();
759
+ var customApi = new CustomApi();
938
760
  export {
939
- CacheService,
940
- pakentoCMSAPI,
941
- parseRawItemToItem,
942
- parseRawItemsToItems
761
+ ApiClient,
762
+ brandsApi,
763
+ categoriesApi,
764
+ contactApi,
765
+ customApi,
766
+ entityApi,
767
+ itemsApi,
768
+ ordersApi
943
769
  };
944
770
  //# sourceMappingURL=index.mjs.map