@decocms/apps-vtex 7.2.0

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.
Files changed (109) hide show
  1. package/package.json +67 -0
  2. package/src/README.md +6 -0
  3. package/src/__tests__/client-segment-cookie.test.ts +255 -0
  4. package/src/__tests__/client-set-cookie-forward.test.ts +257 -0
  5. package/src/actions/address.ts +250 -0
  6. package/src/actions/analytics/sendEvent.ts +86 -0
  7. package/src/actions/auth.ts +333 -0
  8. package/src/actions/checkout.ts +522 -0
  9. package/src/actions/index.ts +11 -0
  10. package/src/actions/masterData.ts +168 -0
  11. package/src/actions/misc.ts +188 -0
  12. package/src/actions/newsletter.ts +105 -0
  13. package/src/actions/orders.ts +34 -0
  14. package/src/actions/profile.ts +201 -0
  15. package/src/actions/session.ts +85 -0
  16. package/src/actions/trigger.ts +43 -0
  17. package/src/actions/wishlist.ts +114 -0
  18. package/src/client.ts +667 -0
  19. package/src/commerceLoaders.ts +261 -0
  20. package/src/hooks/__tests__/createUseCart.test.ts +184 -0
  21. package/src/hooks/__tests__/createUseUser.test.ts +48 -0
  22. package/src/hooks/__tests__/createUseWishlist.test.ts +87 -0
  23. package/src/hooks/createUseCart.ts +360 -0
  24. package/src/hooks/createUseUser.ts +153 -0
  25. package/src/hooks/createUseWishlist.ts +242 -0
  26. package/src/hooks/index.ts +19 -0
  27. package/src/hooks/useAutocomplete.ts +83 -0
  28. package/src/hooks/useCart.ts +243 -0
  29. package/src/hooks/useUser.ts +78 -0
  30. package/src/hooks/useWishlist.ts +119 -0
  31. package/src/index.ts +17 -0
  32. package/src/invoke.ts +181 -0
  33. package/src/loaders/ProductDetailsPage.ts +1 -0
  34. package/src/loaders/ProductList.ts +1 -0
  35. package/src/loaders/ProductListingPage.ts +1 -0
  36. package/src/loaders/address.ts +115 -0
  37. package/src/loaders/autocomplete.ts +58 -0
  38. package/src/loaders/brands.ts +44 -0
  39. package/src/loaders/cart.ts +52 -0
  40. package/src/loaders/catalog.ts +163 -0
  41. package/src/loaders/collections.ts +55 -0
  42. package/src/loaders/index.ts +19 -0
  43. package/src/loaders/intelligentSearch/__tests__/productListingPage.test.ts +20 -0
  44. package/src/loaders/intelligentSearch/productDetailsPage.ts +95 -0
  45. package/src/loaders/intelligentSearch/productList.ts +154 -0
  46. package/src/loaders/intelligentSearch/productListingPage.ts +506 -0
  47. package/src/loaders/intelligentSearch/suggestions.ts +46 -0
  48. package/src/loaders/legacy/productDetailsPage.ts +1 -0
  49. package/src/loaders/legacy/productList.ts +1 -0
  50. package/src/loaders/legacy/relatedProductsLoader.ts +81 -0
  51. package/src/loaders/legacy.ts +635 -0
  52. package/src/loaders/logistics.ts +111 -0
  53. package/src/loaders/minicart.ts +78 -0
  54. package/src/loaders/navbar.ts +26 -0
  55. package/src/loaders/orders.ts +92 -0
  56. package/src/loaders/pageType.ts +68 -0
  57. package/src/loaders/payment.ts +97 -0
  58. package/src/loaders/productListFull.ts +159 -0
  59. package/src/loaders/profile.ts +138 -0
  60. package/src/loaders/promotion.ts +30 -0
  61. package/src/loaders/search.ts +124 -0
  62. package/src/loaders/session.ts +83 -0
  63. package/src/loaders/user.ts +87 -0
  64. package/src/loaders/wishlist.ts +89 -0
  65. package/src/loaders/wishlistProducts.ts +69 -0
  66. package/src/loaders/workflow/products.ts +64 -0
  67. package/src/loaders/workflow.ts +316 -0
  68. package/src/logo.png +0 -0
  69. package/src/middleware.ts +240 -0
  70. package/src/mod.ts +152 -0
  71. package/src/registry.ts +9 -0
  72. package/src/types.ts +248 -0
  73. package/src/utils/__tests__/cookieSanitizer.test.ts +162 -0
  74. package/src/utils/__tests__/fetch.test.ts +80 -0
  75. package/src/utils/__tests__/fetchCache.test.ts +112 -0
  76. package/src/utils/__tests__/instrumentedFetch.test.ts +158 -0
  77. package/src/utils/__tests__/intelligentSearch.test.ts +88 -0
  78. package/src/utils/__tests__/minicart.test.ts +184 -0
  79. package/src/utils/__tests__/operationRouter.test.ts +227 -0
  80. package/src/utils/__tests__/resourceRange.test.ts +32 -0
  81. package/src/utils/__tests__/sitemap.test.ts +185 -0
  82. package/src/utils/__tests__/slugify.test.ts +31 -0
  83. package/src/utils/__tests__/transform.test.ts +698 -0
  84. package/src/utils/accountLoaders.ts +203 -0
  85. package/src/utils/authHelpers.ts +85 -0
  86. package/src/utils/batch.ts +18 -0
  87. package/src/utils/cookieSanitizer.ts +173 -0
  88. package/src/utils/cookies.ts +167 -0
  89. package/src/utils/enrichment.ts +560 -0
  90. package/src/utils/fetch.ts +107 -0
  91. package/src/utils/fetchCache.ts +222 -0
  92. package/src/utils/index.ts +19 -0
  93. package/src/utils/instrumentedFetch.ts +78 -0
  94. package/src/utils/intelligentSearch.ts +96 -0
  95. package/src/utils/legacy.ts +139 -0
  96. package/src/utils/minicart.ts +139 -0
  97. package/src/utils/operationRouter.ts +139 -0
  98. package/src/utils/pickAndOmit.ts +25 -0
  99. package/src/utils/proxy.ts +435 -0
  100. package/src/utils/resourceRange.ts +10 -0
  101. package/src/utils/segment.ts +152 -0
  102. package/src/utils/similars.ts +37 -0
  103. package/src/utils/sitemap.ts +282 -0
  104. package/src/utils/slugCache.ts +28 -0
  105. package/src/utils/slugify.ts +13 -0
  106. package/src/utils/transform.ts +1509 -0
  107. package/src/utils/types.ts +1884 -0
  108. package/src/utils/vtexId.ts +138 -0
  109. package/tsconfig.json +7 -0
@@ -0,0 +1,1509 @@
1
+ import type {
2
+ AggregateOffer,
3
+ Brand,
4
+ BreadcrumbList,
5
+ DayOfWeek,
6
+ Filter,
7
+ FilterToggleValue,
8
+ ItemAvailability,
9
+ Offer,
10
+ OpeningHoursSpecification,
11
+ PageType,
12
+ Place,
13
+ PostalAddress,
14
+ PriceComponentTypeEnumeration,
15
+ PriceTypeEnumeration,
16
+ Product,
17
+ ProductDetailsPage,
18
+ ProductGroup,
19
+ PropertyValue,
20
+ SiteNavigationElement,
21
+ UnitPriceSpecification,
22
+ } from "@decocms/apps-commerce/types";
23
+ import { DEFAULT_IMAGE } from "@decocms/apps-commerce/utils/constants";
24
+ import { formatRange } from "@decocms/apps-commerce/utils/filters";
25
+ import { pick } from "./pickAndOmit";
26
+ import { slugify } from "./slugify";
27
+ import type {
28
+ Address,
29
+ Brand as BrandVTEX,
30
+ Category,
31
+ FacetValueBoolean,
32
+ FacetValueRange,
33
+ Facet as FacetVTEX,
34
+ LegacyFacet,
35
+ LegacyProduct,
36
+ LegacyProduct as LegacyProductVTEX,
37
+ LegacyItem as LegacySkuVTEX,
38
+ Maybe,
39
+ OrderForm,
40
+ PageType as PageTypeVTEX,
41
+ PickupHolidays,
42
+ PickupPoint,
43
+ ProductInventoryData,
44
+ ProductRating,
45
+ ProductReviewData,
46
+ Product as ProductVTEX,
47
+ SelectedFacet,
48
+ Seller as SellerVTEX,
49
+ Item as SkuVTEX,
50
+ Teasers,
51
+ } from "./types";
52
+
53
+ interface PickupPointVCS {
54
+ name?: string;
55
+ address?: {
56
+ country?: { acronym?: string };
57
+ location?: { latitude?: number; longitude?: number };
58
+ city?: string;
59
+ state?: string;
60
+ postalCode?: string;
61
+ street?: string;
62
+ };
63
+ pickupHolidays?: any[];
64
+ businessHours?: any[];
65
+ isActive?: boolean;
66
+ id?: string;
67
+ [key: string]: unknown;
68
+ }
69
+
70
+ const DEFAULT_CATEGORY_SEPARATOR = ">";
71
+
72
+ export const SCHEMA_LIST_PRICE: PriceTypeEnumeration = "https://schema.org/ListPrice";
73
+ export const SCHEMA_SALE_PRICE: PriceTypeEnumeration = "https://schema.org/SalePrice";
74
+ export const SCHEMA_SRP: PriceTypeEnumeration = "https://schema.org/SRP";
75
+ export const SCHEMA_INSTALLMENT: PriceComponentTypeEnumeration = "https://schema.org/Installment";
76
+ export const SCHEMA_IN_STOCK: ItemAvailability = "https://schema.org/InStock";
77
+ export const SCHEMA_OUT_OF_STOCK: ItemAvailability = "https://schema.org/OutOfStock";
78
+
79
+ const isLegacySku = (sku: LegacySkuVTEX | SkuVTEX): sku is LegacySkuVTEX =>
80
+ typeof (sku as LegacySkuVTEX).variations?.[0] === "string" || !!(sku as LegacySkuVTEX).Videos;
81
+
82
+ const isLegacyProduct = (product: ProductVTEX | LegacyProductVTEX): product is LegacyProductVTEX =>
83
+ product.origin !== "intelligent-search";
84
+
85
+ const getProductGroupURL = (origin: string, { linkText }: { linkText: string }) =>
86
+ new URL(`/${linkText}/p`, origin);
87
+
88
+ const getProductURL = (origin: string, product: { linkText: string }, skuId?: string) => {
89
+ const canonicalUrl = getProductGroupURL(origin, product);
90
+
91
+ if (skuId) {
92
+ canonicalUrl.searchParams.set("skuId", skuId);
93
+ }
94
+
95
+ return canonicalUrl;
96
+ };
97
+
98
+ const nonEmptyArray = <T>(array: T[] | null | undefined) =>
99
+ Array.isArray(array) && array.length > 0 ? array : null;
100
+
101
+ interface ProductOptions {
102
+ baseUrl: string;
103
+ /** Price coded currency, e.g.: USD, BRL */
104
+ priceCurrency: string;
105
+ imagesByKey?: Map<string, string>;
106
+ /** Original attributes to be included in the transformed product */
107
+ includeOriginalAttributes?: string[];
108
+ /** Use lean toProductVariant for hasVariant[] instead of full toProduct at level=1 */
109
+ leanVariants?: boolean;
110
+ /** Property names to keep on lean variant additionalProperty. Defaults to VARIANT_PROPERTY_NAMES. */
111
+ variantPropertyNames?: Set<string>;
112
+ /** When leanVariants is true, still include image[0] on each variant entry. Default true. */
113
+ variantIncludeImage?: boolean;
114
+ /** When leanVariants is true, still include inventoryLevel on each variant offer. Default true. */
115
+ variantIncludeInventory?: boolean;
116
+ }
117
+
118
+ /** Returns first available sku */
119
+ const findFirstAvailable = (items: Array<LegacySkuVTEX | SkuVTEX>) =>
120
+ items?.find((item) =>
121
+ Boolean(item?.sellers?.find((s) => s.commertialOffer?.AvailableQuantity > 0)),
122
+ );
123
+
124
+ export const pickSku = <T extends ProductVTEX | LegacyProductVTEX>(
125
+ product: T,
126
+ maybeSkuId?: string,
127
+ ): T["items"][number] => {
128
+ const skuId = maybeSkuId ?? findFirstAvailable(product.items)?.itemId ?? product.items[0]?.itemId;
129
+ for (const item of product.items) {
130
+ if (item.itemId === skuId) {
131
+ return item;
132
+ }
133
+ }
134
+
135
+ return product.items[0];
136
+ };
137
+
138
+ const toAccessoryOrSparePartFor = <T extends ProductVTEX | LegacyProductVTEX>(
139
+ sku: T["items"][number],
140
+ kitItems: T[],
141
+ options: ProductOptions,
142
+ ) => {
143
+ const productBySkuId = kitItems.reduce((map, product) => {
144
+ product.items.forEach((item) => map.set(item.itemId, product));
145
+
146
+ return map;
147
+ }, new Map<string, T>());
148
+
149
+ return sku.kitItems
150
+ ?.map(({ itemId }) => {
151
+ const product = productBySkuId.get(itemId);
152
+
153
+ /** Sometimes VTEX does not return what I've asked for */
154
+ if (!product) return;
155
+
156
+ const sku = pickSku(product, itemId);
157
+
158
+ return toProduct(product, sku, 0, options);
159
+ })
160
+ .filter((p): p is Product => typeof p !== "undefined");
161
+ };
162
+
163
+ export const forceHttpsOnAssets = (orderForm: OrderForm) => {
164
+ orderForm.items.forEach((item) => {
165
+ if (item.imageUrl) {
166
+ item.imageUrl = item.imageUrl.startsWith("http://")
167
+ ? item.imageUrl.replace("http://", "https://")
168
+ : item.imageUrl;
169
+ }
170
+ });
171
+ return orderForm;
172
+ };
173
+
174
+ export const toProductPage = <T extends ProductVTEX | LegacyProductVTEX>(
175
+ product: T,
176
+ sku: T["items"][number],
177
+ kitItems: T[],
178
+ options: ProductOptions,
179
+ ): Omit<ProductDetailsPage, "seo"> => {
180
+ const partialProduct = toProduct(product, sku, 0, options);
181
+ // This is deprecated. Compose this loader at loaders > product > extension > detailsPage.ts
182
+ const isAccessoryOrSparePartFor = toAccessoryOrSparePartFor(sku, kitItems, options);
183
+
184
+ return {
185
+ "@type": "ProductDetailsPage",
186
+ breadcrumbList: toBreadcrumbList(product, options),
187
+ product: { ...partialProduct, isAccessoryOrSparePartFor },
188
+ };
189
+ };
190
+
191
+ export const inStock = (offer: Offer) => offer.availability === SCHEMA_IN_STOCK;
192
+
193
+ // Smallest Available Spot Price First
194
+ export const bestOfferFirst = (a: Offer, b: Offer) => {
195
+ if (inStock(a) && !inStock(b)) {
196
+ return -1;
197
+ }
198
+
199
+ if (!inStock(a) && inStock(b)) {
200
+ return 1;
201
+ }
202
+
203
+ return a.price - b.price;
204
+ };
205
+
206
+ const getHighPriceIndex = (offers: Offer[]) => {
207
+ let it = offers.length - 1;
208
+ for (; it > 0 && !inStock(offers[it]); it--);
209
+ return it;
210
+ };
211
+
212
+ const splitCategory = (firstCategory: string) => firstCategory.split("/").filter(Boolean);
213
+
214
+ const toAdditionalPropertyCategories = <P extends LegacyProductVTEX | ProductVTEX>(
215
+ product: P,
216
+ ): Product["additionalProperty"] => {
217
+ const categories = new Set<string>();
218
+ const categoryIds = new Set<string>();
219
+
220
+ product.categories.forEach((productCategory, i) => {
221
+ const category = splitCategory(productCategory);
222
+ const categoryId = splitCategory(product.categoriesIds[i]);
223
+
224
+ category.forEach((splitCategoryItem, j) => {
225
+ categories.add(splitCategoryItem);
226
+ categoryIds.add(categoryId[j]);
227
+ });
228
+ });
229
+
230
+ const categoriesArray = Array.from(categories);
231
+ const categoryIdsArray = Array.from(categoryIds);
232
+
233
+ return categoriesArray.map((category, index) =>
234
+ toAdditionalPropertyCategory({
235
+ propertyID: categoryIdsArray[index],
236
+ value: category || "",
237
+ }),
238
+ );
239
+ };
240
+
241
+ export const toAdditionalPropertyCategory = ({
242
+ propertyID,
243
+ value,
244
+ }: {
245
+ propertyID: string;
246
+ value: string;
247
+ }): PropertyValue => ({
248
+ "@type": "PropertyValue" as const,
249
+ name: "category",
250
+ propertyID,
251
+ value,
252
+ });
253
+
254
+ const toAdditionalPropertyClusters = <P extends LegacyProductVTEX | ProductVTEX>(
255
+ product: P,
256
+ ): Product["additionalProperty"] => {
257
+ const mapEntriesToIdName = ([id, name]: [string, unknown]) => ({
258
+ id,
259
+ name: name as string,
260
+ });
261
+
262
+ const allClusters = isLegacyProduct(product)
263
+ ? Object.entries(product.productClusters).map(mapEntriesToIdName)
264
+ : product.productClusters;
265
+
266
+ const highlightsSet = isLegacyProduct(product)
267
+ ? new Set(Object.keys(product.clusterHighlights))
268
+ : new Set(product.clusterHighlights.map(({ id }) => id));
269
+
270
+ return allClusters.map((cluster) =>
271
+ toAdditionalPropertyCluster(
272
+ {
273
+ propertyID: cluster.id,
274
+ value: cluster.name || "",
275
+ },
276
+ highlightsSet,
277
+ ),
278
+ );
279
+ };
280
+
281
+ export const toAdditionalPropertyCluster = (
282
+ { propertyID, value }: { propertyID: string; value: string },
283
+ highlights?: Set<string>,
284
+ ): PropertyValue => ({
285
+ "@type": "PropertyValue",
286
+ name: "cluster",
287
+ value,
288
+ propertyID,
289
+ description: highlights?.has(propertyID) ? "highlight" : undefined,
290
+ });
291
+
292
+ const toAdditionalPropertyReferenceIds = (
293
+ referenceId: Array<{ Key: string; Value: string }>,
294
+ ): Product["additionalProperty"] => {
295
+ return referenceId.map(({ Key, Value }) =>
296
+ toAdditionalPropertyReferenceId({ name: Key, value: Value }),
297
+ );
298
+ };
299
+
300
+ export const toAdditionalPropertyReferenceId = ({
301
+ name,
302
+ value,
303
+ }: {
304
+ name: string;
305
+ value: string;
306
+ }): PropertyValue => ({
307
+ "@type": "PropertyValue",
308
+ name,
309
+ value,
310
+ valueReference: "ReferenceID",
311
+ });
312
+
313
+ const getImageKey = (src = "") => {
314
+ return src;
315
+
316
+ // TODO: figure out how we can improve this
317
+ // const match = new URLPattern({
318
+ // pathname: "/arquivos/ids/:skuId/:imageId",
319
+ // }).exec(src);
320
+
321
+ // if (match == null) {
322
+ // return src;
323
+ // }
324
+
325
+ // return `${match.pathname.groups.imageId}${match.search.input}`;
326
+ };
327
+
328
+ export const aggregateOffers = (
329
+ offers: Offer[],
330
+ priceCurrency?: string,
331
+ ): AggregateOffer | undefined => {
332
+ const sorted = offers.sort(bestOfferFirst);
333
+
334
+ if (sorted.length === 0) return;
335
+
336
+ const highPriceIndex = getHighPriceIndex(sorted);
337
+ const lowPriceIndex = 0;
338
+
339
+ return {
340
+ "@type": "AggregateOffer",
341
+ priceCurrency,
342
+ highPrice: sorted[highPriceIndex]?.price ?? null,
343
+ lowPrice: sorted[lowPriceIndex]?.price ?? null,
344
+ offerCount: sorted.length,
345
+ offers: sorted,
346
+ };
347
+ };
348
+
349
+ export const toProduct = <P extends LegacyProductVTEX | ProductVTEX>(
350
+ product: P,
351
+ sku: P["items"][number],
352
+ level = 0, // prevent inifinte loop while self referencing the product
353
+ options: ProductOptions,
354
+ ): Product => {
355
+ const { baseUrl, priceCurrency } = options;
356
+ const {
357
+ brand,
358
+ brandId,
359
+ brandImageUrl,
360
+ productId,
361
+ productReference,
362
+ description,
363
+ releaseDate,
364
+ items,
365
+ } = product;
366
+ const { name, ean, itemId: skuId, referenceId = [], kitItems, estimatedDateArrival } = sku;
367
+
368
+ const videos = isLegacySku(sku) ? sku.Videos : sku.videos;
369
+ const nonEmptyVideos = nonEmptyArray(videos);
370
+ const imagesByKey =
371
+ options.imagesByKey ??
372
+ items
373
+ .flatMap((i) => i.images)
374
+ .reduce((map, img) => {
375
+ img?.imageUrl && map.set(getImageKey(img.imageUrl), img.imageUrl);
376
+ return map;
377
+ }, new Map<string, string>());
378
+
379
+ const groupAdditionalProperty = isLegacyProduct(product)
380
+ ? legacyToProductGroupAdditionalProperties(product)
381
+ : toProductGroupAdditionalProperties(product);
382
+ const originalAttributesAdditionalProperties = toOriginalAttributesAdditionalProperties(
383
+ options.includeOriginalAttributes,
384
+ product,
385
+ );
386
+ const specificationsAdditionalProperty = isLegacySku(sku)
387
+ ? toAdditionalPropertiesLegacy(sku)
388
+ : toAdditionalProperties(sku);
389
+ const referenceIdAdditionalProperty = toAdditionalPropertyReferenceIds(referenceId);
390
+ const images = nonEmptyArray(sku.images);
391
+ const offers = (sku.sellers ?? []).map(isLegacyProduct(product) ? toOfferLegacy : toOffer);
392
+
393
+ const variantOptions =
394
+ imagesByKey !== options.imagesByKey ? { ...options, imagesByKey } : options;
395
+ const isVariantOf =
396
+ level < 1
397
+ ? ({
398
+ "@type": "ProductGroup",
399
+ productGroupID: productId,
400
+ hasVariant: options.leanVariants
401
+ ? items.map((sku) => toProductVariant(product, sku, variantOptions))
402
+ : items.map((sku) => toProduct(product, sku, 1, variantOptions)),
403
+ url: getProductGroupURL(baseUrl, product).href,
404
+ name: product.productName,
405
+ additionalProperty: [
406
+ ...groupAdditionalProperty,
407
+ ...originalAttributesAdditionalProperties,
408
+ ],
409
+ model: productReference,
410
+ } satisfies ProductGroup)
411
+ : undefined;
412
+
413
+ const finalImages = images?.map(({ imageUrl, imageText, imageLabel }) => {
414
+ const url = imagesByKey.get(getImageKey(imageUrl)) ?? imageUrl;
415
+ const alternateName = imageText || imageLabel || "";
416
+ const name = imageLabel || "";
417
+ const encodingFormat = "image";
418
+
419
+ return {
420
+ "@type": "ImageObject" as const,
421
+ alternateName,
422
+ url,
423
+ name,
424
+ encodingFormat,
425
+ };
426
+ }) ?? [DEFAULT_IMAGE];
427
+
428
+ const finalVideos = nonEmptyVideos?.map((video) => {
429
+ const url = video;
430
+ const alternateName = "Product video";
431
+ const name = "Product video";
432
+ const encodingFormat = "video";
433
+ return {
434
+ "@type": "VideoObject" as const,
435
+ alternateName,
436
+ contentUrl: url,
437
+ name,
438
+ encodingFormat,
439
+ };
440
+ });
441
+
442
+ // From schema.org: A category for the item. Greater signs or slashes can be used to informally indicate a category hierarchy
443
+ const categoriesString = splitCategory(product.categories[0]).join(DEFAULT_CATEGORY_SEPARATOR);
444
+
445
+ const categoryAdditionalProperties = toAdditionalPropertyCategories(product);
446
+ const clusterAdditionalProperties = toAdditionalPropertyClusters(product);
447
+
448
+ const additionalProperty: PropertyValue[] = [...specificationsAdditionalProperty];
449
+ if (categoryAdditionalProperties) {
450
+ additionalProperty.push(...categoryAdditionalProperties);
451
+ }
452
+ if (clusterAdditionalProperties) {
453
+ additionalProperty.push(...clusterAdditionalProperties);
454
+ }
455
+ if (referenceIdAdditionalProperty) {
456
+ additionalProperty.push(...referenceIdAdditionalProperty);
457
+ }
458
+
459
+ estimatedDateArrival &&
460
+ additionalProperty.push({
461
+ "@type": "PropertyValue",
462
+ name: "Estimated Date Arrival",
463
+ value: estimatedDateArrival,
464
+ });
465
+
466
+ if (sku.modalType) {
467
+ additionalProperty.push({
468
+ "@type": "PropertyValue",
469
+ name: "Modal Type",
470
+ value: sku.modalType,
471
+ });
472
+ }
473
+
474
+ return {
475
+ "@type": "Product",
476
+ category: categoriesString,
477
+ productID: skuId,
478
+ url: getProductURL(baseUrl, product, sku.itemId).href,
479
+ name,
480
+ alternateName: sku.complementName,
481
+ description,
482
+ brand: {
483
+ "@type": "Brand",
484
+ "@id": brandId?.toString(),
485
+ name: brand,
486
+ logo: brandImageUrl,
487
+ },
488
+ isAccessoryOrSparePartFor: kitItems?.map(({ itemId }) => ({
489
+ "@type": "Product",
490
+ productID: itemId,
491
+ sku: itemId,
492
+ })),
493
+ inProductGroupWithID: productId,
494
+ sku: skuId,
495
+ gtin: ean,
496
+ releaseDate,
497
+ additionalProperty,
498
+ isVariantOf,
499
+ image: finalImages,
500
+ video: finalVideos,
501
+ offers: aggregateOffers(offers, priceCurrency),
502
+ };
503
+ };
504
+
505
+ /**
506
+ * Determines if an installment has no interest by checking if
507
+ * billingDuration * billingIncrement ≈ total price (within 1 cent tolerance).
508
+ */
509
+ const isNoInterest = (spec: UnitPriceSpecification): boolean => {
510
+ if (spec.billingDuration == null || spec.billingIncrement == null || spec.price == null) {
511
+ return false;
512
+ }
513
+ return Math.abs(spec.billingDuration * spec.billingIncrement - spec.price) < 0.01;
514
+ };
515
+
516
+ /**
517
+ * Build a lean offer for shelf display. Keeps only:
518
+ * - ListPrice, SalePrice, SRP price types
519
+ * - PIX installment (name?.toUpperCase() === "PIX")
520
+ * - Best no-interest installment (highest billingDuration)
521
+ * Drops: inventoryLevel, giftSkuIds, priceValidUntil
522
+ */
523
+ const buildOfferShelf = (offer: Offer): Offer => {
524
+ const leanSpecs: UnitPriceSpecification[] = [];
525
+
526
+ let bestNoInterest: UnitPriceSpecification | null = null;
527
+
528
+ for (const spec of offer.priceSpecification ?? []) {
529
+ // Keep base price types
530
+ if (
531
+ spec.priceType === SCHEMA_LIST_PRICE ||
532
+ spec.priceType === SCHEMA_SALE_PRICE ||
533
+ spec.priceType === SCHEMA_SRP
534
+ ) {
535
+ if (spec.priceComponentType !== SCHEMA_INSTALLMENT) {
536
+ leanSpecs.push(spec);
537
+ continue;
538
+ }
539
+ }
540
+
541
+ // Keep PIX installment
542
+ if (spec.priceComponentType === SCHEMA_INSTALLMENT && spec.name?.toUpperCase() === "PIX") {
543
+ leanSpecs.push(spec);
544
+ continue;
545
+ }
546
+
547
+ // Track best no-interest installment (highest billingDuration)
548
+ if (
549
+ spec.priceComponentType === SCHEMA_INSTALLMENT &&
550
+ isNoInterest(spec) &&
551
+ (bestNoInterest == null ||
552
+ (spec.billingDuration ?? 0) > (bestNoInterest.billingDuration ?? 0))
553
+ ) {
554
+ bestNoInterest = spec;
555
+ }
556
+ }
557
+
558
+ if (bestNoInterest) {
559
+ leanSpecs.push(bestNoInterest);
560
+ }
561
+
562
+ return {
563
+ "@type": "Offer",
564
+ identifier: offer.identifier,
565
+ price: offer.price,
566
+ seller: offer.seller,
567
+ sellerName: offer.sellerName,
568
+ teasers: offer.teasers,
569
+ priceSpecification: leanSpecs,
570
+ availability: offer.availability,
571
+ inventoryLevel: { value: 0 },
572
+ };
573
+ };
574
+
575
+ /** Property names commonly used by ProductCard/Shelf components */
576
+ const SHELF_PROPERTY_NAMES = new Set([
577
+ "category",
578
+ "cluster",
579
+ "Cor",
580
+ "Tamanho",
581
+ "Voltagem",
582
+ "sellerId",
583
+ ]);
584
+
585
+ /**
586
+ * Lean product transform for shelf/card display. Same signature as toProduct().
587
+ *
588
+ * Differences from toProduct():
589
+ * - Images: capped at 2 per SKU (front + back)
590
+ * - Offers: best seller only (in-stock first, then cheapest), stripped installments (keeps ListPrice, SalePrice, SRP, PIX, best no-interest)
591
+ * - isVariantOf: single in-stock variant at level 0
592
+ * - additionalProperty: filtered to known-used property names
593
+ * - Drops: description, video, isAccessoryOrSparePartFor, alternateName, gtin, releaseDate, model
594
+ */
595
+ export const toProductShelf = <P extends LegacyProductVTEX | ProductVTEX>(
596
+ product: P,
597
+ sku: P["items"][number],
598
+ level = 0,
599
+ options: ProductOptions,
600
+ ): Product => {
601
+ const { baseUrl, priceCurrency } = options;
602
+ const { productId, items } = product;
603
+ const { name, itemId: skuId } = sku;
604
+
605
+ // Images: cap at 2
606
+ const rawImages = nonEmptyArray(sku.images);
607
+ const mappedImages = (rawImages ?? []).slice(0, 2).map(({ imageUrl, imageText, imageLabel }) => ({
608
+ "@type": "ImageObject" as const,
609
+ alternateName: imageText || imageLabel || "",
610
+ url: imageUrl,
611
+ name: imageLabel || "",
612
+ encodingFormat: "image",
613
+ }));
614
+ const finalImages = mappedImages.length > 0 ? mappedImages : [DEFAULT_IMAGE];
615
+
616
+ // Offers: best seller (in-stock first, then cheapest), lean.
617
+ // Must consider ALL sellers so marketplace products where sellers[0]
618
+ // is OOS but another seller has stock still show as available.
619
+ const offerConverter = isLegacyProduct(product) ? toOfferLegacy : toOffer;
620
+ const allOffers = (sku.sellers ?? []).map(offerConverter).sort(bestOfferFirst);
621
+ const bestOffer = allOffers[0];
622
+ const leanOffers = bestOffer ? [buildOfferShelf(bestOffer)] : [];
623
+
624
+ // isVariantOf: single in-stock variant at level 0
625
+ const isVariantOf =
626
+ level < 1
627
+ ? (() => {
628
+ const inStockSku = findFirstAvailable(items) ?? items[0];
629
+ const singleVariant = inStockSku ? [toProductShelf(product, inStockSku, 1, options)] : [];
630
+ return {
631
+ "@type": "ProductGroup" as const,
632
+ productGroupID: productId,
633
+ hasVariant: singleVariant,
634
+ url: getProductGroupURL(baseUrl, product).href,
635
+ name: product.productName,
636
+ additionalProperty: [],
637
+ } satisfies ProductGroup;
638
+ })()
639
+ : undefined;
640
+
641
+ // additionalProperty: filter to known-used names
642
+ const specificationsAdditionalProperty = isLegacySku(sku)
643
+ ? toAdditionalPropertiesLegacy(sku)
644
+ : toAdditionalProperties(sku);
645
+ const categoryAdditionalProperties = toAdditionalPropertyCategories(product) ?? [];
646
+ const clusterAdditionalProperties = toAdditionalPropertyClusters(product) ?? [];
647
+
648
+ const additionalProperty = [
649
+ ...specificationsAdditionalProperty,
650
+ ...categoryAdditionalProperties,
651
+ ...clusterAdditionalProperties,
652
+ ].filter((prop) => SHELF_PROPERTY_NAMES.has(prop.name ?? ""));
653
+
654
+ const categoriesString = splitCategory(product.categories[0]).join(DEFAULT_CATEGORY_SEPARATOR);
655
+
656
+ return {
657
+ "@type": "Product",
658
+ category: categoriesString,
659
+ productID: skuId,
660
+ url: getProductURL(baseUrl, product, sku.itemId).href,
661
+ name,
662
+ brand: { "@type": "Brand", name: product.brand },
663
+ inProductGroupWithID: productId,
664
+ sku: skuId,
665
+ image: finalImages,
666
+ offers: aggregateOffers(leanOffers, priceCurrency),
667
+ isVariantOf,
668
+ additionalProperty,
669
+ };
670
+ };
671
+
672
+ /** Property names that differentiate SKU variants (used by variant selectors) */
673
+ const VARIANT_PROPERTY_NAMES = new Set(["Cor", "Voltagem", "Tamanho"]);
674
+
675
+ /**
676
+ * Build a minimal offer for variant display. Keeps only availability and seller.
677
+ * No priceSpecification, no teasers. inventoryLevel is preserved from the real
678
+ * offer unless `includeInventory` is false (variant selectors rely on it to
679
+ * decide stock state per SKU — dropping it hard-zeroes every variant).
680
+ */
681
+ const buildOfferVariant = (offer: Offer, includeInventory: boolean): Offer => ({
682
+ "@type": "Offer",
683
+ identifier: offer.identifier,
684
+ price: offer.price,
685
+ seller: offer.seller,
686
+ availability: offer.availability,
687
+ priceSpecification: [],
688
+ inventoryLevel: includeInventory ? offer.inventoryLevel : { value: 0 },
689
+ });
690
+
691
+ /**
692
+ * Minimal product transform for variant entries inside isVariantOf.hasVariant[].
693
+ *
694
+ * Keeps only what variant selectors need:
695
+ * - url, productID, sku, name, inProductGroupWithID
696
+ * - additionalProperty filtered to variant-differentiating props (Cor, Voltagem, Tamanho)
697
+ * - image[0] (when variantIncludeImage is not false) — selectors render thumbnails
698
+ * - offers with availability + seller + real inventoryLevel (when variantIncludeInventory
699
+ * is not false) — selectors decide stock state per SKU from inventoryLevel.value
700
+ *
701
+ * Drops: description, video, brand, category, gtin, releaseDate,
702
+ * alternateName, isAccessoryOrSparePartFor, isVariantOf
703
+ */
704
+ export const toProductVariant = <P extends LegacyProductVTEX | ProductVTEX>(
705
+ product: P,
706
+ sku: P["items"][number],
707
+ options: ProductOptions,
708
+ ): Product => {
709
+ const { baseUrl, priceCurrency } = options;
710
+ const { productId, items } = product;
711
+ const { name, itemId: skuId } = sku;
712
+ const variantProps = options.variantPropertyNames ?? VARIANT_PROPERTY_NAMES;
713
+ const includeImage = options.variantIncludeImage !== false;
714
+ const includeInventory = options.variantIncludeInventory !== false;
715
+
716
+ // additionalProperty: only variant-differentiating specs
717
+ const specificationsAdditionalProperty = isLegacySku(sku)
718
+ ? toAdditionalPropertiesLegacy(sku)
719
+ : toAdditionalProperties(sku);
720
+ const additionalProperty = specificationsAdditionalProperty.filter((prop) =>
721
+ variantProps.has(prop.name ?? ""),
722
+ );
723
+
724
+ // Offers: best seller, lean (availability + seller; optional inventoryLevel)
725
+ const offerConverter = isLegacyProduct(product) ? toOfferLegacy : toOffer;
726
+ const allOffers = (sku.sellers ?? []).map(offerConverter).sort(bestOfferFirst);
727
+ const bestOffer = allOffers[0];
728
+ const leanOffers = bestOffer ? [buildOfferVariant(bestOffer, includeInventory)] : [];
729
+
730
+ // image[0] only — selectors render a single thumbnail. Reuse the same
731
+ // imagesByKey lookup toProduct uses so URLs stay consistent across variants.
732
+ const imagesByKey =
733
+ options.imagesByKey ??
734
+ items
735
+ .flatMap((i) => i.images)
736
+ .reduce((map, img) => {
737
+ img?.imageUrl && map.set(getImageKey(img.imageUrl), img.imageUrl);
738
+ return map;
739
+ }, new Map<string, string>());
740
+
741
+ const image = includeImage
742
+ ? nonEmptyArray(sku.images)
743
+ ?.slice(0, 1)
744
+ .map(({ imageUrl, imageText, imageLabel }) => ({
745
+ "@type": "ImageObject" as const,
746
+ alternateName: imageText || imageLabel || "",
747
+ url: imagesByKey.get(getImageKey(imageUrl)) ?? imageUrl,
748
+ name: imageLabel || "",
749
+ encodingFormat: "image",
750
+ }))
751
+ : undefined;
752
+
753
+ return {
754
+ "@type": "Product",
755
+ productID: skuId,
756
+ sku: skuId,
757
+ name,
758
+ url: getProductURL(baseUrl, product, sku.itemId).href,
759
+ inProductGroupWithID: productId,
760
+ additionalProperty,
761
+ ...(image ? { image } : {}),
762
+ offers: aggregateOffers(leanOffers, priceCurrency),
763
+ };
764
+ };
765
+
766
+ const toBreadcrumbList = (
767
+ product: ProductVTEX | LegacyProductVTEX,
768
+ { baseUrl }: ProductOptions,
769
+ ): BreadcrumbList => {
770
+ const { categories, productName } = product;
771
+ const names = categories[0]?.split("/").filter(Boolean);
772
+
773
+ const segments = names.map(slugify);
774
+
775
+ return {
776
+ "@type": "BreadcrumbList",
777
+ itemListElement: [
778
+ ...names.map((name, index) => {
779
+ const position = index + 1;
780
+
781
+ return {
782
+ "@type": "ListItem" as const,
783
+ name,
784
+ item: new URL(`/${segments.slice(0, position).join("/")}`, baseUrl).href,
785
+ position,
786
+ };
787
+ }),
788
+ {
789
+ "@type": "ListItem",
790
+ name: productName,
791
+ item: getProductGroupURL(baseUrl, product).href,
792
+ position: categories.length + 1,
793
+ },
794
+ ],
795
+ numberOfItems: categories.length + 1,
796
+ };
797
+ };
798
+
799
+ const legacyToProductGroupAdditionalProperties = (product: LegacyProductVTEX) => {
800
+ const groups = product.allSpecificationsGroups ?? [];
801
+ const allSpecifications = product.allSpecifications ?? [];
802
+
803
+ const specByGroup: Record<string, string> = {};
804
+
805
+ groups.forEach((group) => {
806
+ const groupSpecs = (product as unknown as Record<string, string[]>)[group];
807
+ groupSpecs.forEach((specName) => {
808
+ specByGroup[specName] = group;
809
+ });
810
+ });
811
+
812
+ return allSpecifications.flatMap((name) => {
813
+ const values = (product as unknown as Record<string, string[]>)[name];
814
+ return values.map((value) =>
815
+ toAdditionalPropertySpecification({
816
+ name,
817
+ value,
818
+ propertyID: specByGroup[name],
819
+ }),
820
+ );
821
+ });
822
+ };
823
+
824
+ const toProductGroupAdditionalProperties = ({ specificationGroups = [] }: ProductVTEX) =>
825
+ specificationGroups.flatMap(({ name: groupName, specifications }) =>
826
+ specifications.flatMap(({ name, values }) =>
827
+ values.map(
828
+ (value) =>
829
+ ({
830
+ "@type": "PropertyValue",
831
+ name,
832
+ value,
833
+ propertyID: groupName,
834
+ valueReference: "PROPERTY" as string,
835
+ }) as const,
836
+ ),
837
+ ),
838
+ );
839
+
840
+ const toOriginalAttributesAdditionalProperties = (
841
+ originalAttributes: Maybe<string[]>,
842
+ product: ProductVTEX | LegacyProduct,
843
+ ) => {
844
+ if (!originalAttributes) {
845
+ return [];
846
+ }
847
+
848
+ const attributes = pick(originalAttributes as Array<keyof typeof product>, product) ?? {};
849
+
850
+ return Object.entries(attributes).map(
851
+ ([name, value]) =>
852
+ ({
853
+ "@type": "PropertyValue",
854
+ name,
855
+ value,
856
+ valueReference: "ORIGINAL_PROPERTY" as string,
857
+ }) as const,
858
+ ) as unknown as PropertyValue[];
859
+ };
860
+
861
+ const toAdditionalProperties = (sku: SkuVTEX): PropertyValue[] =>
862
+ sku.variations?.flatMap(({ name, values }) =>
863
+ values.map((value) => toAdditionalPropertySpecification({ name, value })),
864
+ ) ?? [];
865
+
866
+ export const toAdditionalPropertySpecification = ({
867
+ name,
868
+ value,
869
+ propertyID,
870
+ }: {
871
+ name: string;
872
+ value: string;
873
+ propertyID?: string;
874
+ }): PropertyValue => ({
875
+ "@type": "PropertyValue",
876
+ name,
877
+ value,
878
+ propertyID,
879
+ valueReference: "SPECIFICATION",
880
+ });
881
+
882
+ const toAdditionalPropertiesLegacy = (sku: LegacySkuVTEX): PropertyValue[] => {
883
+ const { variations = [], attachments = [] } = sku;
884
+
885
+ const specificationProperties = variations.flatMap((variation) =>
886
+ sku[variation].map((value) => toAdditionalPropertySpecification({ name: variation, value })),
887
+ );
888
+
889
+ const attachmentProperties = attachments.map(
890
+ (attachment) =>
891
+ ({
892
+ "@type": "PropertyValue",
893
+ propertyID: `${attachment.id}`,
894
+ name: attachment.name,
895
+ value: attachment.domainValues,
896
+ required: attachment.required,
897
+ valueReference: "ATTACHMENT",
898
+ }) as const,
899
+ );
900
+
901
+ if (attachmentProperties.length === 0) return specificationProperties;
902
+ specificationProperties.push(...attachmentProperties);
903
+ return specificationProperties;
904
+ };
905
+
906
+ const buildOffer = (
907
+ { commertialOffer: offer, sellerId, sellerName, sellerDefault }: SellerVTEX,
908
+ teasers: Teasers[],
909
+ ): Offer => ({
910
+ "@type": "Offer",
911
+ identifier: sellerDefault ? "default" : undefined,
912
+ price: offer.spotPrice ?? offer.Price,
913
+ seller: sellerId,
914
+ sellerName,
915
+ priceValidUntil: offer.PriceValidUntil,
916
+ inventoryLevel: { value: offer.AvailableQuantity },
917
+ giftSkuIds: offer.GiftSkuIds ?? [],
918
+ teasers,
919
+ priceSpecification: [
920
+ {
921
+ "@type": "UnitPriceSpecification",
922
+ priceType: SCHEMA_LIST_PRICE,
923
+ price: offer.ListPrice,
924
+ },
925
+ {
926
+ "@type": "UnitPriceSpecification",
927
+ priceType: SCHEMA_SALE_PRICE,
928
+ price: offer.Price,
929
+ },
930
+ {
931
+ "@type": "UnitPriceSpecification",
932
+ priceType: SCHEMA_SRP,
933
+ price: offer.PriceWithoutDiscount,
934
+ },
935
+ ...offer.Installments.map(
936
+ (installment): UnitPriceSpecification => ({
937
+ "@type": "UnitPriceSpecification",
938
+ priceType: SCHEMA_SALE_PRICE,
939
+ priceComponentType: SCHEMA_INSTALLMENT,
940
+ name: installment.PaymentSystemName,
941
+ description: installment.Name,
942
+ billingDuration: installment.NumberOfInstallments,
943
+ billingIncrement: installment.Value,
944
+ price: installment.TotalValuePlusInterestRate,
945
+ }),
946
+ ),
947
+ ],
948
+ availability: offer.AvailableQuantity > 0 ? SCHEMA_IN_STOCK : SCHEMA_OUT_OF_STOCK,
949
+ });
950
+
951
+ const toOffer = (seller: SellerVTEX): Offer =>
952
+ buildOffer(seller, seller.commertialOffer.teasers ?? []);
953
+
954
+ const toOfferLegacy = (seller: SellerVTEX): Offer => {
955
+ const otherTeasers =
956
+ seller.commertialOffer.DiscountHighLight?.map((i) => {
957
+ const discount = i as Record<string, string>;
958
+ const [_k__BackingField, discountName] = Object.entries(discount)?.[0] ?? [];
959
+
960
+ const teasers: Teasers = {
961
+ name: discountName,
962
+ conditions: {
963
+ minimumQuantity: 0,
964
+ parameters: [],
965
+ },
966
+ effects: {
967
+ parameters: [],
968
+ },
969
+ };
970
+
971
+ return teasers;
972
+ }) ?? [];
973
+
974
+ const legacyTeasers = (seller.commertialOffer.Teasers ?? []).map((teaser) => ({
975
+ name: teaser["<Name>k__BackingField"],
976
+ generalValues: teaser["<GeneralValues>k__BackingField"],
977
+ conditions: {
978
+ minimumQuantity: teaser["<Conditions>k__BackingField"]["<MinimumQuantity>k__BackingField"],
979
+ parameters: teaser["<Conditions>k__BackingField"]["<Parameters>k__BackingField"].map(
980
+ (parameter) => ({
981
+ name: parameter["<Name>k__BackingField"],
982
+ value: parameter["<Value>k__BackingField"],
983
+ }),
984
+ ),
985
+ },
986
+ effects: {
987
+ parameters: teaser["<Effects>k__BackingField"]["<Parameters>k__BackingField"].map(
988
+ (parameter) => ({
989
+ name: parameter["<Name>k__BackingField"],
990
+ value: parameter["<Value>k__BackingField"],
991
+ }),
992
+ ),
993
+ },
994
+ }));
995
+
996
+ return buildOffer(seller, [...otherTeasers, ...legacyTeasers]);
997
+ };
998
+
999
+ export const legacyFacetToFilter = (
1000
+ name: string,
1001
+ facets: LegacyFacet[],
1002
+ url: URL,
1003
+ map: string,
1004
+ term: string,
1005
+ behavior: "dynamic" | "static",
1006
+ ignoreCaseSelected?: boolean,
1007
+ fullPath = false,
1008
+ ): Filter | null => {
1009
+ const mapSegments = map.split(",").filter((x) => x.length > 0);
1010
+ const pathSegments = term.replace(/^\//, "").split("/").slice(0, mapSegments.length);
1011
+
1012
+ const mapSet = new Set(mapSegments.map((i) => (ignoreCaseSelected ? i.toLowerCase() : i)));
1013
+ const pathSet = new Set(pathSegments.map((i) => (ignoreCaseSelected ? i.toLowerCase() : i)));
1014
+
1015
+ // for productClusterIds, we have to use the full path
1016
+ // example:
1017
+ // category2/123?map=c,productClusterIds -> DO NOT WORK
1018
+ // category1/category2/123?map=c,c,productClusterIds -> WORK
1019
+ const hasProductClusterIds = mapSegments.includes("productClusterIds");
1020
+ const hasToBeFullpath =
1021
+ fullPath || hasProductClusterIds || mapSegments.includes("ft") || mapSegments.includes("b");
1022
+
1023
+ const getLink = (facet: LegacyFacet, selected: boolean) => {
1024
+ const index = pathSegments.findIndex((s) => {
1025
+ if (ignoreCaseSelected) {
1026
+ return s.toLowerCase() === facet.Value.toLowerCase();
1027
+ }
1028
+
1029
+ return s === facet.Value;
1030
+ });
1031
+
1032
+ const map = hasToBeFullpath ? facet.Link.split("map=")[1].split(",") : [facet.Map];
1033
+ const value = hasToBeFullpath ? facet.Link.split("?")[0].slice(1).split("/") : [facet.Value];
1034
+
1035
+ const pathSegmentsFiltered = hasProductClusterIds
1036
+ ? [pathSegments[mapSegments.indexOf("productClusterIds")]]
1037
+ : [];
1038
+ const mapSegmentsFiltered = hasProductClusterIds ? ["productClusterIds"] : [];
1039
+
1040
+ const _mapSegments = hasToBeFullpath ? mapSegmentsFiltered : mapSegments;
1041
+ const _pathSegments = hasToBeFullpath ? pathSegmentsFiltered : pathSegments;
1042
+
1043
+ const newMap = selected
1044
+ ? [...mapSegments.filter((_, i) => i !== index)]
1045
+ : [..._mapSegments, ...map];
1046
+ const newPath = selected
1047
+ ? [...pathSegments.filter((_, i) => i !== index)]
1048
+ : [..._pathSegments, ...value];
1049
+
1050
+ // Insertion-sort like algorithm. Uses the c-continuum theorem
1051
+ const zipped: [string, string][] = [];
1052
+ for (let it = 0; it < newMap.length; it++) {
1053
+ let i = 0;
1054
+ while (i < zipped.length && (zipped[i][0] === "c" || zipped[i][0] === "C")) i++;
1055
+
1056
+ zipped.splice(i, 0, [newMap[it], newPath[it]]);
1057
+ }
1058
+
1059
+ const link = new URL(`/${zipped.map(([, s]) => s).join("/")}`, url);
1060
+ link.searchParams.set("map", zipped.map(([m]) => m).join(","));
1061
+ if (behavior === "static") {
1062
+ link.searchParams.set("fmap", url.searchParams.get("fmap") || mapSegments.join(","));
1063
+ }
1064
+ const currentQuery = url.searchParams.get("q");
1065
+ if (currentQuery) {
1066
+ link.searchParams.set("q", currentQuery);
1067
+ }
1068
+
1069
+ return `${link.pathname}${link.search}`;
1070
+ };
1071
+
1072
+ return {
1073
+ "@type": "FilterToggle",
1074
+ quantity: facets?.length,
1075
+ label: name,
1076
+ key: name,
1077
+ values: facets.map((facet) => {
1078
+ const normalizedFacet = name !== "PriceRanges" ? facet : normalizeFacet(facet);
1079
+
1080
+ const selected =
1081
+ mapSet.has(ignoreCaseSelected ? normalizedFacet.Map.toLowerCase() : normalizedFacet.Map) &&
1082
+ pathSet.has(
1083
+ ignoreCaseSelected ? normalizedFacet.Value.toLowerCase() : normalizedFacet.Value,
1084
+ );
1085
+
1086
+ return {
1087
+ value: normalizedFacet.Value,
1088
+ quantity: normalizedFacet.Quantity,
1089
+ url: getLink(normalizedFacet, selected),
1090
+ label: normalizedFacet.Name,
1091
+ selected,
1092
+ children:
1093
+ facet.Children?.length > 0
1094
+ ? legacyFacetToFilter(
1095
+ normalizedFacet.Name,
1096
+ facet.Children,
1097
+ url,
1098
+ map,
1099
+ term,
1100
+ behavior,
1101
+ ignoreCaseSelected,
1102
+ fullPath,
1103
+ )
1104
+ : undefined,
1105
+ };
1106
+ }),
1107
+ };
1108
+ };
1109
+
1110
+ export const filtersToSearchParams = (
1111
+ selectedFacets: SelectedFacet[],
1112
+ paramsToPersist?: URLSearchParams,
1113
+ ) => {
1114
+ const searchParams = new URLSearchParams(paramsToPersist);
1115
+
1116
+ for (const { key, value } of selectedFacets) {
1117
+ searchParams.append(`filter.${key}`, value);
1118
+ }
1119
+
1120
+ return searchParams;
1121
+ };
1122
+
1123
+ const fromLegacyMap: Record<string, string> = {
1124
+ priceFrom: "price",
1125
+ productClusterSearchableIds: "productClusterIds",
1126
+ };
1127
+
1128
+ export const legacyFacetsNormalize = (map: string, path: string) => {
1129
+ // Replace legacy price path param to IS price facet format
1130
+ // exemple: de-34,90-a-56,90 turns to 34.90:56.90
1131
+ // may this regex have to be adjusted for international stores
1132
+ const value = path.replace(
1133
+ /de-(?<from>\d+[,]?[\d]+)-a-(?<to>\d+[,]?[\d]+)/,
1134
+ (_match, from, to) => {
1135
+ return `${from.replace(",", ".")}:${to.replace(",", ".")}`;
1136
+ },
1137
+ );
1138
+
1139
+ const key = fromLegacyMap[map] || map;
1140
+
1141
+ return { key, value };
1142
+ };
1143
+
1144
+ /**
1145
+ * Transform ?map urls into selected facets. This happens when a store is migrating
1146
+ * to Deco and also migrating from VTEX Legacy to VTEX Intelligent Search.
1147
+ */
1148
+ export const legacyFacetsFromURL = (url: URL) => {
1149
+ const mapSegments = url.searchParams.get("map")?.split(",") ?? [];
1150
+ const pathSegments = url.pathname.split("/").slice(1); // Remove first slash
1151
+ const length = Math.min(mapSegments.length, pathSegments.length);
1152
+
1153
+ const selectedFacets: SelectedFacet[] = [];
1154
+ for (let it = 0; it < length; it++) {
1155
+ const facet = legacyFacetsNormalize(mapSegments[it], pathSegments[it]);
1156
+
1157
+ selectedFacets.push(facet);
1158
+ }
1159
+
1160
+ return selectedFacets;
1161
+ };
1162
+
1163
+ export const filtersFromURL = (url: URL) => {
1164
+ const selectedFacets: SelectedFacet[] = legacyFacetsFromURL(url);
1165
+
1166
+ url.searchParams.forEach((value, name) => {
1167
+ const [filter, key] = name.split(".");
1168
+
1169
+ if (filter === "filter" && typeof key === "string") {
1170
+ selectedFacets.push({ key, value });
1171
+ }
1172
+ });
1173
+
1174
+ return selectedFacets;
1175
+ };
1176
+
1177
+ export const mergeFacets = (f1: SelectedFacet[], f2: SelectedFacet[]): SelectedFacet[] => {
1178
+ const facetKey = (facet: SelectedFacet) => `key:${facet.key}-value:${facet.value}`;
1179
+ const merged = new Map<string, SelectedFacet>();
1180
+
1181
+ for (const f of f1) {
1182
+ merged.set(facetKey(f), f);
1183
+ }
1184
+ for (const f of f2) {
1185
+ merged.set(facetKey(f), f);
1186
+ }
1187
+
1188
+ return [...merged.values()];
1189
+ };
1190
+
1191
+ const isValueRange = (facet: FacetValueRange | FacetValueBoolean): facet is FacetValueRange =>
1192
+ // deno-lint-ignore no-explicit-any
1193
+ Boolean((facet as any).range);
1194
+
1195
+ const facetToToggle =
1196
+ (selectedFacets: SelectedFacet[], key: string, paramsToPersist?: URLSearchParams) =>
1197
+ (item: FacetValueRange | FacetValueBoolean): FilterToggleValue => {
1198
+ const { quantity, selected } = item;
1199
+ const isRange = isValueRange(item);
1200
+
1201
+ const value = isRange ? formatRange(item.range.from, item.range.to) : item.value;
1202
+ const label = isRange ? value : item.name;
1203
+ const facet = { key, value };
1204
+
1205
+ const filters = selected
1206
+ ? selectedFacets.filter((f) => f.key !== key || f.value !== value)
1207
+ : [...selectedFacets, facet];
1208
+
1209
+ return {
1210
+ value,
1211
+ quantity,
1212
+ selected,
1213
+ url: `?${filtersToSearchParams(filters, paramsToPersist)}`,
1214
+ label,
1215
+ };
1216
+ };
1217
+
1218
+ export const toFilter =
1219
+ (selectedFacets: SelectedFacet[], paramsToPersist?: URLSearchParams) =>
1220
+ ({ key, name, quantity, values }: FacetVTEX): Filter => ({
1221
+ "@type": "FilterToggle",
1222
+ key,
1223
+ label: name,
1224
+ quantity: quantity,
1225
+ values: values.map(facetToToggle(selectedFacets, key, paramsToPersist)),
1226
+ });
1227
+
1228
+ function nodeToNavbar(node: Category): SiteNavigationElement {
1229
+ const url = new URL(node.url, "https://example.com");
1230
+
1231
+ return {
1232
+ "@type": "SiteNavigationElement",
1233
+ url: `${url.pathname}${url.search}`,
1234
+ name: node.name,
1235
+ children: node.children.map(nodeToNavbar),
1236
+ };
1237
+ }
1238
+
1239
+ export const categoryTreeToNavbar = (tree: Category[]): SiteNavigationElement[] =>
1240
+ tree.map(nodeToNavbar);
1241
+
1242
+ export const toBrand = (
1243
+ { id, name, imageUrl, metaTagDescription }: BrandVTEX,
1244
+ baseUrl: string,
1245
+ ): Brand => ({
1246
+ "@type": "Brand",
1247
+ "@id": `${id}`,
1248
+ name,
1249
+ logo: imageUrl?.startsWith("http") ? imageUrl : `${baseUrl}${imageUrl}`,
1250
+ description: metaTagDescription,
1251
+ });
1252
+
1253
+ export const normalizeFacet = (facet: LegacyFacet) => {
1254
+ return {
1255
+ ...facet,
1256
+ Map: "priceFrom",
1257
+ Value: facet.Slug!,
1258
+ };
1259
+ };
1260
+
1261
+ export const toReview = (
1262
+ products: Product[],
1263
+ ratings: ProductRating[],
1264
+ reviews: ProductReviewData[],
1265
+ ): Product[] => {
1266
+ return products.map((p, index) => {
1267
+ const ratingsCount = ratings[index].totalCount || 0;
1268
+ const productReviews = reviews[index].data || [];
1269
+
1270
+ return {
1271
+ ...p,
1272
+ aggregateRating: {
1273
+ "@type": "AggregateRating",
1274
+ reviewCount: ratingsCount,
1275
+ ratingCount: ratingsCount,
1276
+ ratingValue: ratings[index]?.average || 0,
1277
+ },
1278
+ review: productReviews.map((_, reviewIndex) => ({
1279
+ "@type": "Review",
1280
+ id: productReviews[reviewIndex]?.id?.toString(),
1281
+ author: [
1282
+ {
1283
+ "@type": "Author",
1284
+ name: productReviews[reviewIndex]?.reviewerName,
1285
+ verifiedBuyer: productReviews[reviewIndex]?.verifiedPurchaser,
1286
+ },
1287
+ ],
1288
+ itemReviewed: productReviews[reviewIndex]?.productId,
1289
+ datePublished: productReviews[reviewIndex]?.reviewDateTime,
1290
+ reviewHeadline: productReviews[reviewIndex]?.title,
1291
+ reviewBody: productReviews[reviewIndex]?.text,
1292
+ reviewRating: {
1293
+ "@type": "AggregateRating",
1294
+ ratingValue: productReviews[reviewIndex]?.rating || 0,
1295
+ },
1296
+ })),
1297
+ };
1298
+ });
1299
+ };
1300
+
1301
+ export const toInventories = (
1302
+ products: Product[],
1303
+ inventoriesData: ProductInventoryData[],
1304
+ ): Product[] => {
1305
+ return products.map((p, index) => {
1306
+ const balance = inventoriesData[index].balance || [];
1307
+
1308
+ const additionalProperty = Array.from(p.additionalProperty || []);
1309
+
1310
+ const inventories: PropertyValue[] = balance.map((b) => ({
1311
+ "@type": "PropertyValue",
1312
+ valueReference: "INVENTORY",
1313
+ propertyID: b.warehouseId,
1314
+ name: b.warehouseName,
1315
+ value: b.totalQuantity?.toString(),
1316
+ }));
1317
+
1318
+ return {
1319
+ ...p,
1320
+ additionalProperty: [...additionalProperty, ...inventories],
1321
+ };
1322
+ });
1323
+ };
1324
+
1325
+ type ProductMap = Record<string, Product>;
1326
+
1327
+ export const sortProducts = (
1328
+ products: Product[],
1329
+ orderOfIdsOrSkus: string[],
1330
+ prop: "sku" | "inProductGroupWithID",
1331
+ ) => {
1332
+ const productMap: ProductMap = {};
1333
+
1334
+ products.forEach((product) => {
1335
+ productMap[product[prop] || product.sku] = product;
1336
+ });
1337
+
1338
+ return orderOfIdsOrSkus.map((id) => productMap[id]);
1339
+ };
1340
+
1341
+ export const parsePageType = (p: PageTypeVTEX): PageType => {
1342
+ const type = p.pageType;
1343
+
1344
+ // Search or Busca vazia
1345
+ if (type === "FullText") {
1346
+ return "Search";
1347
+ }
1348
+
1349
+ // A page that vtex doesn't recognize
1350
+ if (type === "NotFound") {
1351
+ return "Unknown";
1352
+ }
1353
+
1354
+ return type;
1355
+ };
1356
+
1357
+ function dayOfWeekIndexToString(day?: number): DayOfWeek | undefined {
1358
+ switch (day) {
1359
+ case 0:
1360
+ return "Sunday";
1361
+ case 1:
1362
+ return "Monday";
1363
+ case 2:
1364
+ return "Tuesday";
1365
+ case 3:
1366
+ return "Wednesday";
1367
+ case 4:
1368
+ return "Thursday";
1369
+ case 5:
1370
+ return "Friday";
1371
+ case 6:
1372
+ return "Saturday";
1373
+ default:
1374
+ return undefined;
1375
+ }
1376
+ }
1377
+
1378
+ interface Hours {
1379
+ dayOfWeek?: number;
1380
+ openingTime?: string;
1381
+ closingTime?: string;
1382
+ }
1383
+
1384
+ function toHoursSpecification(hours: Hours): OpeningHoursSpecification {
1385
+ return {
1386
+ "@type": "OpeningHoursSpecification",
1387
+ opens: hours.openingTime,
1388
+ closes: hours.closingTime,
1389
+ dayOfWeek: dayOfWeekIndexToString(hours.dayOfWeek),
1390
+ };
1391
+ }
1392
+
1393
+ function toSpecialHoursSpecification(holiday: PickupHolidays): OpeningHoursSpecification {
1394
+ const dateHoliday = new Date(holiday.date ?? "");
1395
+ // VTEX provide date in ISO format, at 00h on the day
1396
+ const validThrough = dateHoliday.setDate(dateHoliday.getDate() + 1).toString();
1397
+
1398
+ return {
1399
+ "@type": "OpeningHoursSpecification",
1400
+ opens: holiday.hourBegin,
1401
+ closes: holiday.hourEnd,
1402
+ validFrom: holiday.date,
1403
+ validThrough,
1404
+ };
1405
+ }
1406
+
1407
+ function isPickupPointVCS(
1408
+ pickupPoint: PickupPoint | PickupPointVCS,
1409
+ ): pickupPoint is PickupPointVCS {
1410
+ return "name" in pickupPoint;
1411
+ }
1412
+
1413
+ interface ToPlaceOptions {
1414
+ isActive?: boolean;
1415
+ }
1416
+
1417
+ export function toPlace(
1418
+ pickupPoint: (PickupPoint & { distance?: number }) | PickupPointVCS,
1419
+ options?: ToPlaceOptions,
1420
+ ): Place {
1421
+ const {
1422
+ name,
1423
+ country,
1424
+ latitude,
1425
+ longitude,
1426
+ openingHoursSpecification,
1427
+ specialOpeningHoursSpecification,
1428
+ isActive,
1429
+ } = isPickupPointVCS(pickupPoint)
1430
+ ? {
1431
+ name: pickupPoint.name,
1432
+ country: pickupPoint.address?.country?.acronym,
1433
+ latitude: pickupPoint.address?.location?.latitude,
1434
+ longitude: pickupPoint.address?.location?.longitude,
1435
+ specialOpeningHoursSpecification: pickupPoint.pickupHolidays?.map(
1436
+ toSpecialHoursSpecification,
1437
+ ),
1438
+ openingHoursSpecification: pickupPoint.businessHours?.map(toHoursSpecification),
1439
+ isActive: pickupPoint.isActive,
1440
+ }
1441
+ : {
1442
+ name: pickupPoint.friendlyName,
1443
+ country: pickupPoint.address?.country,
1444
+ latitude: pickupPoint.address?.geoCoordinates?.[0],
1445
+ longitude: pickupPoint.address?.geoCoordinates?.[1],
1446
+ specialOpeningHoursSpecification: pickupPoint.pickupHolidays?.map(
1447
+ toSpecialHoursSpecification,
1448
+ ),
1449
+ openingHoursSpecification: pickupPoint.businessHours?.map(
1450
+ ({ ClosingTime, DayOfWeek, OpeningTime }) =>
1451
+ toHoursSpecification({
1452
+ closingTime: ClosingTime,
1453
+ dayOfWeek: DayOfWeek,
1454
+ openingTime: OpeningTime,
1455
+ }),
1456
+ ),
1457
+ isActive: options?.isActive,
1458
+ };
1459
+
1460
+ return {
1461
+ "@id": pickupPoint.id,
1462
+ "@type": "Place",
1463
+ address: {
1464
+ "@type": "PostalAddress",
1465
+ addressCountry: country,
1466
+ addressLocality: pickupPoint.address?.city,
1467
+ addressRegion: pickupPoint.address?.state,
1468
+ postalCode: pickupPoint.address?.postalCode,
1469
+ streetAddress: pickupPoint.address?.street,
1470
+ },
1471
+ latitude,
1472
+ longitude,
1473
+ name,
1474
+ specialOpeningHoursSpecification,
1475
+ openingHoursSpecification,
1476
+ additionalProperty: [
1477
+ {
1478
+ "@type": "PropertyValue",
1479
+ name: "distance",
1480
+ value: `${pickupPoint.distance}`,
1481
+ },
1482
+ {
1483
+ "@type": "PropertyValue",
1484
+ name: "isActive",
1485
+ value: typeof isActive === "boolean" ? `${isActive}` : undefined,
1486
+ },
1487
+ ],
1488
+ };
1489
+ }
1490
+
1491
+ export const toPostalAddress = (address: Address): PostalAddress => {
1492
+ return {
1493
+ "@type": "PostalAddress",
1494
+ "@id": address.addressId,
1495
+ addressCountry: address.country,
1496
+ addressLocality: address.city,
1497
+ addressRegion: address.state,
1498
+ areaServed: address.neighborhood || undefined,
1499
+ postalCode: address.postalCode,
1500
+ streetAddress: address.street,
1501
+ identifier: address.number || undefined,
1502
+ name: address.addressName || undefined,
1503
+ alternateName: address.receiverName || undefined,
1504
+ description: address.complement || undefined,
1505
+ disambiguatingDescription: address.reference || undefined,
1506
+ latitude: address.geoCoordinates?.[0] || undefined,
1507
+ longitude: address.geoCoordinates?.[1] || undefined,
1508
+ };
1509
+ };