@jay-framework/wix-stores-v1 0.24.7 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,7 +36,13 @@ oauthStrategy:
36
36
  clientId: 'your-oauth-client-id'
37
37
  ```
38
38
 
39
- ### 2. Use Server Actions
39
+ ### 2. Store configuration (optional)
40
+
41
+ Run `jay-stack setup wix-stores-v1` to create `config/.wix-stores-v1.yaml`. Use **`locale`** for product-card price formatting (BCP 47), and **`productOrder`** for manual sort order on the default shop grid (product URL slugs only).
42
+
43
+ Full reference: `agent-kit/designer/store-configuration.md` (materialized under your project after `jay-stack agent-kit`).
44
+
45
+ ### 3. Use Server Actions
40
46
 
41
47
  ```typescript
42
48
  import { searchProducts, getProductBySlug, getCollections } from '@jay-framework/wix-stores-v1';
@@ -58,7 +64,7 @@ const product = await getProductBySlug({ slug: 'peat-s-beast-px-finish-54-1' });
58
64
  const collections = await getCollections();
59
65
  ```
60
66
 
61
- ### 3. Use Client Context
67
+ ### 4. Use Client Context
62
68
 
63
69
  ```typescript
64
70
  import { useContext } from '@jay-framework/runtime';
@@ -0,0 +1,57 @@
1
+ # Wix Stores V1 — store configuration
2
+
3
+ Optional project config for **Catalog V1** stores (`@jay-framework/wix-stores-v1`). For Catalog V3, use `config/.wix-stores.yaml` with `@jay-framework/wix-stores` instead.
4
+
5
+ ## File location
6
+
7
+ `config/.wix-stores-v1.yaml` — created by `jay-stack setup wix-stores-v1` when missing.
8
+
9
+ ## Example
10
+
11
+ ```yaml
12
+ # BCP 47 — Wix dashboard → Settings → Language & region (regional settings).
13
+ # Omit to keep API formatted prices on product cards.
14
+ locale: 'he-IL'
15
+
16
+ # Product URL slugs (V1 `product.slug`), top-of-grid order on the default shop listing.
17
+ productOrder:
18
+ - 'i-m-a-product'
19
+ - 'blue-widget'
20
+ - 'sale-item'
21
+ ```
22
+
23
+ ## Fields
24
+
25
+ | Field | Type | Values | Behavior |
26
+ | ----- | ---- | ------ | -------- |
27
+ | **`locale`** | string (optional) | BCP 47 tag, e.g. `he-IL`, `ja-JP`, `en-US` | Reformats **product card** prices in `searchProducts` / `getProductBySlug` via `Intl.NumberFormat`. **Product page (PDP) prices still use API formatted strings** until wired in a follow-up. |
28
+ | **`productOrder`** | string[] (optional) | Each entry = one product **`slug`** from the V1 API | Applies only when `searchProducts` uses **`sortBy: relevance`**, **no text query**, and **no filters** (no collection, price, etc.). Unknown slugs are ignored. Remaining products follow, sorted by **`numericId` ascending**. **Does not** reorder collection/category pages. |
29
+
30
+ ## How to get slugs for `productOrder`
31
+
32
+ 1. Product URL path on the Wix site.
33
+ 2. `jay-stack action wixStoresV1/searchProducts` or `getProductBySlug` — read `slug` on each product.
34
+ 3. Match sequence to manual collection order in the Wix editor (same slugs, same order).
35
+
36
+ ## Anti-patterns
37
+
38
+ - Using product **name**, **SKU**, or numeric id instead of **slug**.
39
+ - Expecting `productOrder` on a **filtered** or **collection** listing.
40
+ - Setting `productOrder` on a **large** catalog without understanding cost (see below).
41
+
42
+ ## Performance
43
+
44
+ When `productOrder` is non-empty and the default listing uses manual order, `searchProducts` may **paginate the entire catalog** before returning one page. Setup warns when the catalog exceeds **200** products and `productOrder` is set. Consider caching or trimming `productOrder` for very large stores.
45
+
46
+ ## Validation
47
+
48
+ - **Setup** — invalid `locale`, empty slugs, duplicate/unusual/unknown slugs (when the API is reachable).
49
+ - **`jay-stack validate`** — same rules when `config/.wix-stores-v1.yaml` exists or a page imports `wix-stores-v1`.
50
+
51
+ ## V3 comparison
52
+
53
+ | Feature | V3 (`wix-stores`) | V1 (this package) |
54
+ | ------- | ----------------- | ----------------- |
55
+ | Locale on cards | `config/.wix-stores.yaml` | `locale` here |
56
+ | Locale on PDP | Yes | Not yet |
57
+ | Manual grid order | Different API story | `productOrder` slugs only |
@@ -0,0 +1,79 @@
1
+ import { createJayService } from "@jay-framework/fullstack-component";
2
+ import { registerService } from "@jay-framework/stack-server-runtime";
3
+ import { wixFetch } from "@jay-framework/wix-server-client";
4
+ import * as fs from "fs";
5
+ import * as path from "path";
6
+ import * as yaml from "js-yaml";
7
+ const WIX_STORES_V1_SERVICE_MARKER = createJayService("Wix Store V1 Service");
8
+ function provideWixStoresV1Service(wixClient, config) {
9
+ const service = {
10
+ wixClient,
11
+ locale: config?.locale ?? null,
12
+ productOrder: config?.productOrder ?? []
13
+ };
14
+ registerService(WIX_STORES_V1_SERVICE_MARKER, service);
15
+ return service;
16
+ }
17
+ function normalizeProduct(product) {
18
+ const p = { ...product };
19
+ const raw = product;
20
+ if (raw.id && !p._id) {
21
+ p._id = raw.id;
22
+ }
23
+ return p;
24
+ }
25
+ function stableSort(request) {
26
+ const sort = [...request?.sort ?? []];
27
+ if (request?.paging && !sort.some((s) => s.fieldName === "numericId")) {
28
+ sort.push({ fieldName: "numericId", order: "ASC" });
29
+ }
30
+ return sort;
31
+ }
32
+ async function queryProducts(client, request) {
33
+ const query = {};
34
+ if (request?.filter) query.filter = JSON.stringify(request.filter);
35
+ const sort = stableSort(request);
36
+ if (sort.length) {
37
+ const v1Sort = sort.map((s) => ({
38
+ [s.fieldName]: (s.order || "ASC").toLowerCase()
39
+ }));
40
+ query.sort = JSON.stringify(v1Sort);
41
+ }
42
+ if (request?.paging) query.paging = request.paging;
43
+ const result = await wixFetch(client, "/stores/v1/products/query", {
44
+ method: "POST",
45
+ body: {
46
+ query,
47
+ includeVariants: request?.includeVariants ?? true,
48
+ // Merchant-specific data (cost, profit, ...) requires WIX_STORES.MODIFY_PRODUCTS: a storefront
49
+ // (visitor or read-only) client gets 403. Only request it explicitly.
50
+ includeMerchantSpecificData: request?.includeMerchantSpecificData ?? false
51
+ }
52
+ });
53
+ if (result.products) {
54
+ result.products = result.products.map(
55
+ (p) => normalizeProduct(p)
56
+ );
57
+ }
58
+ return result;
59
+ }
60
+ const WIX_STORES_V1_CONFIG_FILE_NAME = ".wix-stores-v1.yaml";
61
+ function loadWixStoresV1Config(projectRoot) {
62
+ const configPath = path.join(
63
+ projectRoot ?? process.cwd(),
64
+ "config",
65
+ WIX_STORES_V1_CONFIG_FILE_NAME
66
+ );
67
+ const raw = fs.existsSync(configPath) ? yaml.load(fs.readFileSync(configPath, "utf8")) : null;
68
+ return {
69
+ locale: typeof raw?.locale === "string" ? raw.locale : null,
70
+ productOrder: Array.isArray(raw?.productOrder) ? raw.productOrder.filter((slug) => typeof slug === "string") : []
71
+ };
72
+ }
73
+ export {
74
+ WIX_STORES_V1_SERVICE_MARKER as W,
75
+ WIX_STORES_V1_CONFIG_FILE_NAME as a,
76
+ loadWixStoresV1Config as l,
77
+ provideWixStoresV1Service as p,
78
+ queryProducts as q
79
+ };
@@ -16,6 +16,30 @@ var Selected = /* @__PURE__ */ ((Selected2) => {
16
16
  Selected2[Selected2["notSelected"] = 1] = "notSelected";
17
17
  return Selected2;
18
18
  })(Selected || {});
19
+ function selectMedia(gallery, mediaId) {
20
+ const oldSelectedIndex = gallery.availableMedia.findIndex(
21
+ (_) => _.selected === Selected.selected
22
+ );
23
+ const newSelectedIndex = Math.max(
24
+ 0,
25
+ gallery.availableMedia.findIndex((_) => _.mediaId === mediaId)
26
+ );
27
+ const newSelectedMedia = gallery.availableMedia[newSelectedIndex];
28
+ if (!newSelectedMedia || oldSelectedIndex === newSelectedIndex) return gallery;
29
+ return patch(gallery, [
30
+ { op: REPLACE, path: ["selectedMedia"], value: newSelectedMedia.media },
31
+ {
32
+ op: REPLACE,
33
+ path: ["availableMedia", oldSelectedIndex, "selected"],
34
+ value: Selected.notSelected
35
+ },
36
+ {
37
+ op: REPLACE,
38
+ path: ["availableMedia", newSelectedIndex, "selected"],
39
+ value: Selected.selected
40
+ }
41
+ ]);
42
+ }
19
43
  function normalizeProduct(product) {
20
44
  const p = { ...product };
21
45
  const raw = product;
@@ -24,11 +48,19 @@ function normalizeProduct(product) {
24
48
  }
25
49
  return p;
26
50
  }
51
+ function stableSort(request) {
52
+ const sort = [...request?.sort ?? []];
53
+ if (request?.paging && !sort.some((s) => s.fieldName === "numericId")) {
54
+ sort.push({ fieldName: "numericId", order: "ASC" });
55
+ }
56
+ return sort;
57
+ }
27
58
  async function queryProducts(client, request) {
28
59
  const query = {};
29
60
  if (request?.filter) query.filter = JSON.stringify(request.filter);
30
- if (request?.sort) {
31
- const v1Sort = request.sort.map((s) => ({
61
+ const sort = stableSort(request);
62
+ if (sort.length) {
63
+ const v1Sort = sort.map((s) => ({
32
64
  [s.fieldName]: (s.order || "ASC").toLowerCase()
33
65
  }));
34
66
  query.sort = JSON.stringify(v1Sort);
@@ -39,7 +71,9 @@ async function queryProducts(client, request) {
39
71
  body: {
40
72
  query,
41
73
  includeVariants: request?.includeVariants ?? true,
42
- includeMerchantSpecificData: request?.includeMerchantSpecificData ?? true
74
+ // Merchant-specific data (cost, profit, ...) requires WIX_STORES.MODIFY_PRODUCTS: a storefront
75
+ // (visitor or read-only) client gets 403. Only request it explicitly.
76
+ includeMerchantSpecificData: request?.includeMerchantSpecificData ?? false
43
77
  }
44
78
  });
45
79
  if (result.products) {
@@ -134,6 +168,9 @@ var ChoiceType = /* @__PURE__ */ ((ChoiceType2) => {
134
168
  function stripWixMediaResize(url) {
135
169
  return url.replace(/\/v1\/(?:fit|fill|crop)\/[^/]+\/file\.\w+$/, "");
136
170
  }
171
+ function formatPrice(amount, currency, locale, formatted) {
172
+ return formatted || "";
173
+ }
137
174
  function mapAvailabilityStatus(status) {
138
175
  switch (status) {
139
176
  case "OUT_OF_STOCK":
@@ -194,13 +231,24 @@ function mapQuickOption(option, variants) {
194
231
  };
195
232
  }
196
233
  const DEFAULT_PRODUCT_PAGE_PATH = "/products";
197
- function mapProductToCard(product, productPagePath = DEFAULT_PRODUCT_PAGE_PATH) {
234
+ function mapProductToCard(product, productPagePath = DEFAULT_PRODUCT_PAGE_PATH, locale) {
198
235
  const mainMedia = product.media?.mainMedia;
199
236
  const slug = product.slug || "";
200
237
  product.price?.discountedPrice ?? product.price?.price ?? 0;
201
238
  product.price?.price ?? 0;
202
- const formattedActualPrice = product.price?.formatted?.discountedPrice || "";
203
- const formattedCompareAtPrice = product.price?.formatted?.price || "";
239
+ const currency = product.price?.currency;
240
+ const formattedActualPrice = formatPrice(
241
+ product.price?.discountedPrice ?? product.price?.price,
242
+ currency,
243
+ locale,
244
+ product.price?.formatted?.discountedPrice
245
+ );
246
+ const formattedCompareAtPrice = formatPrice(
247
+ product.price?.price,
248
+ currency,
249
+ locale,
250
+ product.price?.formatted?.price
251
+ );
204
252
  const hasDiscount = hasProductDiscount(product);
205
253
  return {
206
254
  _id: product._id || "",
@@ -259,7 +307,7 @@ function provideWixStoresV1Context() {
259
307
  const wixClient = wixClientContext.client;
260
308
  const cartContext = useGlobalContext(WIX_CART_CONTEXT);
261
309
  const storesContext = registerReactiveGlobalContext(WIX_STORES_V1_CONTEXT, () => {
262
- async function addToCart(productId, quantity = 1, variantId) {
310
+ async function addToCart(productId, quantity = 1, variantId, options) {
263
311
  console.log(`[WixStoresV1] Adding to cart: ${productId} x ${quantity}`);
264
312
  let finalVariantId = variantId;
265
313
  let productSlug;
@@ -275,7 +323,9 @@ function provideWixStoresV1Context() {
275
323
  }
276
324
  return cartContext.addToCart(productId, quantity, {
277
325
  variantId: finalVariantId,
278
- productSlug
326
+ productSlug,
327
+ // Chosen options by option name (catalogReference.options.options).
328
+ ...options && Object.keys(options).length ? { modifiers: options } : {}
279
329
  });
280
330
  }
281
331
  async function loadMoreCollectionProducts(collectionId, page, pageSize) {
@@ -322,26 +372,32 @@ function provideWixStoresV1Context() {
322
372
  console.log("[wix-stores-v1] Client stores context initialized (delegating cart to wix-cart)");
323
373
  return storesContext;
324
374
  }
375
+ function choiceIdForOption(option) {
376
+ return option.textChoiceSelection || option.choices.find((c) => c.isSelected)?.choiceId;
377
+ }
378
+ function selectedChoices(options) {
379
+ const result = {};
380
+ for (const option of options) {
381
+ const choiceId = choiceIdForOption(option);
382
+ if (choiceId) result[option._id] = choiceId;
383
+ }
384
+ return result;
385
+ }
386
+ function allOptionsHaveSelection(options) {
387
+ for (const option of options) {
388
+ if (!choiceIdForOption(option)) {
389
+ return false;
390
+ }
391
+ }
392
+ return true;
393
+ }
325
394
  function ProductPageInteractive(props, refs, viewStateSignals, fastCarryForward, storesContext) {
326
395
  const [quantity, setQuantity] = createSignal(viewStateSignals.quantity[0]().quantity);
327
396
  const { productId, variants } = fastCarryForward;
328
397
  const { actionsEnabled: [actionsEnabled, setActionsEnabled], options: [options, setOptions], mediaGallery: [mediaGallery, setMediaGallery], pricePerUnit: [pricePerUnit, setPricePerUnit] } = viewStateSignals;
329
398
  const [isAddingToCart, setIsAddingToCart] = createSignal(false);
330
399
  const [selectedMediaId, setSelectedMediaId] = createSignal(null);
331
- const selectedOptionsRecord = createMemo(() => {
332
- const result = {};
333
- for (const option of options()) {
334
- if (option.textChoiceSelection) {
335
- result[option._id] = option.textChoiceSelection;
336
- } else {
337
- const selectedChoice = option.choices.find((c) => c.isSelected);
338
- if (selectedChoice) {
339
- result[option._id] = selectedChoice.choiceId;
340
- }
341
- }
342
- }
343
- return result;
344
- });
400
+ const selectedOptionsRecord = createMemo(() => selectedChoices(options()));
345
401
  function findVariant(variants2, selectedOptions) {
346
402
  const found = variants2.find((variant) => Object.entries(selectedOptions).every(([optionName, choiceValue]) => variant.choices[optionName] === choiceValue));
347
403
  return found || variants2[0];
@@ -351,28 +407,8 @@ function ProductPageInteractive(props, refs, viewStateSignals, fastCarryForward,
351
407
  const price = createMemo(() => selectedVariant()?.price || "");
352
408
  const strikethroughPrice = createMemo(() => selectedVariant()?.strikethroughPrice || "");
353
409
  const stockStatus = createMemo(() => selectedVariant()?.inventoryStatus || StockStatus.OUT_OF_STOCK);
354
- const computedActionsEnabled = createMemo(() => stockStatus() === StockStatus.IN_STOCK);
355
- const interactiveMedia = createMemo((prev) => {
356
- prev = prev || mediaGallery();
357
- const oldSelectedIndex = prev.availableMedia.findIndex((_) => _.selected === Selected.selected);
358
- const newSelectedIndex = Math.max(0, prev.availableMedia.findIndex((_) => _.mediaId === selectedMediaId()));
359
- if (oldSelectedIndex === newSelectedIndex)
360
- return prev;
361
- const newSelectedMedia = prev.availableMedia[newSelectedIndex];
362
- return patch(prev, [
363
- { op: REPLACE, path: ["selectedMedia"], value: newSelectedMedia.media },
364
- {
365
- op: REPLACE,
366
- path: ["availableMedia", oldSelectedIndex, "selected"],
367
- value: Selected.notSelected
368
- },
369
- {
370
- op: REPLACE,
371
- path: ["availableMedia", newSelectedIndex, "selected"],
372
- value: Selected.selected
373
- }
374
- ]);
375
- });
410
+ const computedActionsEnabled = createMemo(() => stockStatus() === StockStatus.IN_STOCK && allOptionsHaveSelection(options()));
411
+ const interactiveMedia = createMemo((prev) => selectMedia(prev || mediaGallery(), selectedMediaId()));
376
412
  refs.quantity.decrementButton.onclick(() => {
377
413
  setQuantity((prev) => Math.max(1, prev - 1));
378
414
  });
@@ -424,14 +460,14 @@ function ProductPageInteractive(props, refs, viewStateSignals, fastCarryForward,
424
460
  ]));
425
461
  });
426
462
  refs.addToCartButton.onclick(async () => {
427
- if (stockStatus() === StockStatus.OUT_OF_STOCK) {
428
- console.warn("[ProductPage V1] Product is out of stock");
463
+ if (!computedActionsEnabled()) {
464
+ console.warn("[ProductPage V1] Product is not available for purchase");
429
465
  return;
430
466
  }
431
467
  setIsAddingToCart(true);
432
468
  try {
433
469
  const variantId = selectedVariant()?._id;
434
- await storesContext.addToCart(productId, quantity(), variantId);
470
+ await storesContext.addToCart(productId, quantity(), variantId, selectedOptionsRecord());
435
471
  console.log("[ProductPage V1] Added to cart:", quantity(), "items");
436
472
  } catch (error) {
437
473
  console.error("[ProductPage V1] Failed to add to cart:", error);
package/dist/index.d.ts CHANGED
@@ -8,11 +8,25 @@ import { HTMLElementCollectionProxy, HTMLElementProxy } from '@jay-framework/run
8
8
  import { Getter } from '@jay-framework/reactive';
9
9
  import * as _jay_framework_component from '@jay-framework/component';
10
10
 
11
- interface WixStoresV1Service {
11
+ interface WixStoresV1Config {
12
+ /**
13
+ * Locale product card prices are formatted with (BCP 47, e.g. "he-IL" — a Wix site's regional setting).
14
+ * Not set = the API's formatted price.
15
+ */
16
+ locale: string | null;
17
+ /**
18
+ * Product slugs listed first, in this order, by the default (relevance, unfiltered) product search — e.g. a
19
+ * Wix collection's manual order, which no public V1 query returns. Other products follow by numericId.
20
+ * Empty = the API's order.
21
+ */
22
+ productOrder: string[];
23
+ }
24
+
25
+ interface WixStoresV1Service extends WixStoresV1Config {
12
26
  wixClient: WixClient;
13
27
  }
14
28
  declare const WIX_STORES_V1_SERVICE_MARKER: _jay_framework_fullstack_component.ServiceMarker<WixStoresV1Service>;
15
- declare function provideWixStoresV1Service(wixClient: WixClient): WixStoresV1Service;
29
+ declare function provideWixStoresV1Service(wixClient: WixClient, config?: Partial<WixStoresV1Config>): WixStoresV1Service;
16
30
 
17
31
  declare enum OptionRenderType$1 {
18
32
  TEXT_CHOICES,
@@ -216,7 +230,7 @@ interface WixStoresV1Context {
216
230
  cartIndicator: ReactiveCartIndicator;
217
231
  refreshCartIndicator(): Promise<void>;
218
232
  getEstimatedCart(): Promise<CartState>;
219
- addToCart(productId: string, quantity?: number, variantId?: string): Promise<CartOperationResult>;
233
+ addToCart(productId: string, quantity?: number, variantId?: string, options?: Record<string, string>): Promise<CartOperationResult>;
220
234
  removeLineItems(lineItemIds: string[]): Promise<CartOperationResult>;
221
235
  updateLineItemQuantity(lineItemId: string, quantity: number): Promise<CartOperationResult>;
222
236
  clearCart(): Promise<void>;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { WIX_CART_CONTEXT, WIX_CART_SERVICE, cartIndicator, cartPage, provideWixCartContext, provideWixCartService } from "@jay-framework/wix-cart";
2
- import { W as WIX_STORES_V1_SERVICE_MARKER, q as queryProducts, p as provideWixStoresV1Service } from "./query-products-CXhRabj0.js";
2
+ import { W as WIX_STORES_V1_SERVICE_MARKER, q as queryProducts, p as provideWixStoresV1Service, l as loadWixStoresV1Config } from "./config-loader-WTVH_LdA.js";
3
3
  import { createJayContext } from "@jay-framework/runtime";
4
4
  import "@jay-framework/component";
5
5
  import { wixFetch, WIX_CLIENT_SERVICE } from "@jay-framework/wix-server-client";
@@ -74,6 +74,15 @@ var ChoiceType$1 = /* @__PURE__ */ ((ChoiceType2) => {
74
74
  function stripWixMediaResize(url) {
75
75
  return url.replace(/\/v1\/(?:fit|fill|crop)\/[^/]+\/file\.\w+$/, "");
76
76
  }
77
+ function formatPrice(amount, currency, locale, formatted) {
78
+ if (locale && currency && typeof amount === "number" && Number.isFinite(amount)) {
79
+ try {
80
+ return new Intl.NumberFormat(locale, { style: "currency", currency }).format(amount);
81
+ } catch {
82
+ }
83
+ }
84
+ return formatted || "";
85
+ }
77
86
  function mapAvailabilityStatus(status) {
78
87
  switch (status) {
79
88
  case "OUT_OF_STOCK":
@@ -134,13 +143,24 @@ function mapQuickOption(option, variants) {
134
143
  };
135
144
  }
136
145
  const DEFAULT_PRODUCT_PAGE_PATH = "/products";
137
- function mapProductToCard(product, productPagePath = DEFAULT_PRODUCT_PAGE_PATH) {
146
+ function mapProductToCard(product, productPagePath = DEFAULT_PRODUCT_PAGE_PATH, locale) {
138
147
  const mainMedia = product.media?.mainMedia;
139
148
  const slug = product.slug || "";
140
149
  product.price?.discountedPrice ?? product.price?.price ?? 0;
141
150
  product.price?.price ?? 0;
142
- const formattedActualPrice = product.price?.formatted?.discountedPrice || "";
143
- const formattedCompareAtPrice = product.price?.formatted?.price || "";
151
+ const currency = product.price?.currency;
152
+ const formattedActualPrice = formatPrice(
153
+ product.price?.discountedPrice ?? product.price?.price,
154
+ currency,
155
+ locale,
156
+ product.price?.formatted?.discountedPrice
157
+ );
158
+ const formattedCompareAtPrice = formatPrice(
159
+ product.price?.price,
160
+ currency,
161
+ locale,
162
+ product.price?.formatted?.price
163
+ );
144
164
  const hasDiscount = hasProductDiscount(product);
145
165
  return {
146
166
  _id: product._id || "",
@@ -194,6 +214,18 @@ function mapCollectionToViewState(collection) {
194
214
  };
195
215
  }
196
216
  const WIX_STORES_V1_CONTEXT = createJayContext("wix:stores-v1");
217
+ function usesProductOrder(productOrder, sortBy, filter) {
218
+ return productOrder.length > 0 && sortBy === "relevance" && Object.keys(filter).length === 0;
219
+ }
220
+ function pageInProductOrder(products, productOrder, page, pageSize) {
221
+ const rank = new Map(productOrder.map((slug, i) => [slug, i]));
222
+ const at = (product) => rank.get(product.slug || "") ?? rank.size;
223
+ const ordered = [...products].sort((a, b) => at(a) - at(b));
224
+ return {
225
+ products: ordered.slice((page - 1) * pageSize, page * pageSize),
226
+ totalResults: ordered.length
227
+ };
228
+ }
197
229
  function getNiceBoundaries(minPrice, maxPrice) {
198
230
  const multipliers = [1, 2, 5];
199
231
  const boundaries = [];
@@ -263,6 +295,19 @@ function buildPriceFilter(baseFilter, minPrice, maxPrice) {
263
295
  if (Object.keys(baseFilter).length === 0) return priceFilter;
264
296
  return { $and: [baseFilter, priceFilter] };
265
297
  }
298
+ async function queryInProductOrder(wixStores, page, pageSize) {
299
+ const all = [];
300
+ for (let offset = 0; ; offset += 100) {
301
+ const result = await queryProducts(wixStores.wixClient, {
302
+ sort: [{ fieldName: "numericId", order: "ASC" }],
303
+ paging: { limit: 100, offset }
304
+ });
305
+ const products = result.products || [];
306
+ all.push(...products);
307
+ if (products.length < 100) break;
308
+ }
309
+ return pageInProductOrder(all, wixStores.productOrder, page, pageSize);
310
+ }
266
311
  const searchProducts = makeJayQuery("wixStoresV1.searchProducts").withServices(WIX_STORES_V1_SERVICE_MARKER).withHandler(
267
312
  async (input, wixStores) => {
268
313
  const { query, filters = {}, sortBy = "relevance", page = 1, pageSize = 12 } = input;
@@ -288,7 +333,7 @@ const searchProducts = makeJayQuery("wixStoresV1.searchProducts").withServices(W
288
333
  break;
289
334
  }
290
335
  const [result, minPriceResult, maxPriceResult] = await Promise.all([
291
- queryProducts(wixStores.wixClient, {
336
+ usesProductOrder(wixStores.productOrder, sortBy, fullFilter) ? queryInProductOrder(wixStores, page, pageSize) : queryProducts(wixStores.wixClient, {
292
337
  filter: fullFilter,
293
338
  sort: sort.length > 0 ? sort : void 0,
294
339
  paging: { limit: pageSize, offset: (page - 1) * pageSize }
@@ -312,7 +357,9 @@ const searchProducts = makeJayQuery("wixStoresV1.searchProducts").withServices(W
312
357
  const ranges = generatePriceBuckets(minBound, maxBound, currencySymbol);
313
358
  const totalCount = result.totalResults ?? products.length;
314
359
  const totalPages = Math.ceil(totalCount / pageSize);
315
- const mappedProducts = products.map((p) => mapProductToCard(p));
360
+ const mappedProducts = products.map(
361
+ (p) => mapProductToCard(p, void 0, wixStores.locale)
362
+ );
316
363
  return {
317
364
  products: mappedProducts,
318
365
  totalCount,
@@ -346,7 +393,7 @@ const getProductBySlug = makeJayQuery("wixStoresV1.getProductBySlug").withServic
346
393
  }
347
394
  const product = result.products?.[0];
348
395
  if (!product) return null;
349
- return mapProductToCard(product);
396
+ return mapProductToCard(product, void 0, wixStores.locale);
350
397
  } catch (error) {
351
398
  console.error("[wixStoresV1.getProductBySlug] Failed to get product:", error);
352
399
  return null;
@@ -399,6 +446,25 @@ var MediaType$1 = /* @__PURE__ */ ((MediaType2) => {
399
446
  MediaType2[MediaType2["VIDEO"] = 1] = "VIDEO";
400
447
  return MediaType2;
401
448
  })(MediaType$1 || {});
449
+ function mapChoice(optionType, choice) {
450
+ const name = choice.description || choice.value || "";
451
+ return {
452
+ choiceId: name,
453
+ name,
454
+ colorCode: optionType === "color" ? choice.value || "" : ""
455
+ };
456
+ }
457
+ function choiceIdForOption(option) {
458
+ return option.textChoiceSelection || option.choices.find((c) => c.isSelected)?.choiceId;
459
+ }
460
+ function allOptionsHaveSelection(options) {
461
+ for (const option of options) {
462
+ if (!choiceIdForOption(option)) {
463
+ return false;
464
+ }
465
+ }
466
+ return true;
467
+ }
402
468
  function mapProductType(productType) {
403
469
  return productType === "digital" ? ProductType.DIGITAL : ProductType.PHYSICAL;
404
470
  }
@@ -436,11 +502,9 @@ function mapOptionsToSlowVS(product) {
436
502
  name: option.name || "",
437
503
  optionRenderType: option.optionType === "color" ? OptionRenderType.COLOR_SWATCH_CHOICES : OptionRenderType.TEXT_CHOICES,
438
504
  choices: (option.choices || []).map((choice) => ({
439
- choiceId: choice.value || "",
440
- name: choice.value || "",
505
+ ...mapChoice(option.optionType, choice),
441
506
  choiceType: option.optionType === "color" ? ChoiceType.ONE_COLOR : ChoiceType.CHOICE_TEXT,
442
- inStock: choice.inStock ?? true,
443
- colorCode: ""
507
+ inStock: choice.inStock ?? true
444
508
  }))
445
509
  }));
446
510
  }
@@ -449,7 +513,7 @@ function mapOptionsToFastVS(product) {
449
513
  _id: option.name || "",
450
514
  textChoiceSelection: void 0,
451
515
  choices: (option.choices || []).map((choice) => ({
452
- choiceId: choice.value || "",
516
+ choiceId: mapChoice(option.optionType, choice).choiceId,
453
517
  isSelected: false
454
518
  }))
455
519
  }));
@@ -564,7 +628,7 @@ async function renderFastChanging$2(props, slowCarryForward, wixStores) {
564
628
  const isInStock = slowCarryForward.stockStatus === StockStatus.IN_STOCK;
565
629
  const firstVariant = slowCarryForward.variants[0];
566
630
  return Pipeline.ok({
567
- actionsEnabled: isInStock,
631
+ actionsEnabled: isInStock && allOptionsHaveSelection(slowCarryForward.options),
568
632
  options: slowCarryForward.options,
569
633
  modifiers: [],
570
634
  mediaGallery: slowCarryForward.mediaGallery,
@@ -876,7 +940,7 @@ const categoryPage = collectionPage;
876
940
  const init = makeJayInit().withServer(async () => {
877
941
  console.log("[wix-stores-v1] Initializing Wix Stores V1 service...");
878
942
  const wixClient = getService(WIX_CLIENT_SERVICE);
879
- provideWixStoresV1Service(wixClient);
943
+ provideWixStoresV1Service(wixClient, loadWixStoresV1Config());
880
944
  console.log("[wix-stores-v1] Server initialization complete");
881
945
  return {
882
946
  enableClientCart: true,
package/dist/tools.d.ts CHANGED
@@ -1,16 +1,13 @@
1
+ import { PluginSetupContext, PluginSetupResult } from '@jay-framework/stack-server-runtime';
2
+ import { JayHtmlValidatorFn } from '@jay-framework/compiler-shared';
3
+
1
4
  /**
2
5
  * Setup handler for wix-stores-v1 plugin.
3
- * Validates that the Wix Stores app is installed by querying products.
6
+ * Validates Stores V1 API access, writes config template, and checks config/.wix-stores-v1.yaml.
4
7
  */
5
- interface PluginSetupContext {
6
- configDir: string;
7
- projectRoot: string;
8
- initError?: Error;
9
- }
10
- interface PluginSetupResult {
11
- status: 'configured' | 'needs-config' | 'error';
12
- message?: string;
13
- }
8
+
14
9
  declare function setupWixStoresV1(ctx: PluginSetupContext): Promise<PluginSetupResult>;
15
10
 
16
- export { setupWixStoresV1 };
11
+ declare const validateWixStoresV1ProjectConfig: JayHtmlValidatorFn;
12
+
13
+ export { setupWixStoresV1, validateWixStoresV1ProjectConfig };
package/dist/tools.js CHANGED
@@ -1,6 +1,164 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
1
3
  import { getService } from "@jay-framework/stack-server-runtime";
2
- import { W as WIX_STORES_V1_SERVICE_MARKER, q as queryProducts } from "./query-products-CXhRabj0.js";
4
+ import { q as queryProducts, a as WIX_STORES_V1_CONFIG_FILE_NAME, l as loadWixStoresV1Config, W as WIX_STORES_V1_SERVICE_MARKER } from "./config-loader-WTVH_LdA.js";
3
5
  import "@jay-framework/wix-server-client";
6
+ import { walkElements } from "@jay-framework/compiler-shared";
7
+ import * as fs$1 from "node:fs";
8
+ import * as path$1 from "node:path";
9
+ async function fetchCatalogProductSlugs(wixClient) {
10
+ const slugs = /* @__PURE__ */ new Set();
11
+ let offset = 0;
12
+ const limit = 100;
13
+ let totalCount = 0;
14
+ while (true) {
15
+ const response = await queryProducts(wixClient, { paging: { limit, offset } });
16
+ const products = response.products ?? [];
17
+ for (const product of products) {
18
+ if (product.slug) {
19
+ slugs.add(product.slug);
20
+ }
21
+ }
22
+ totalCount = response.metadata?.items ?? Math.max(totalCount, offset + products.length);
23
+ if (products.length < limit) {
24
+ break;
25
+ }
26
+ offset += limit;
27
+ }
28
+ return { slugs, totalCount };
29
+ }
30
+ const SLUG_SHAPE_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
31
+ const LARGE_CATALOG_PRODUCT_ORDER_THRESHOLD = 200;
32
+ const UNKNOWN_SLUG_WARNING_CAP = 10;
33
+ const LOCALE_CHARACTERS_RE = /^[a-zA-Z0-9-]+$/;
34
+ function validateLocale(locale) {
35
+ if (!locale) {
36
+ return [];
37
+ }
38
+ if (!LOCALE_CHARACTERS_RE.test(locale)) {
39
+ return [
40
+ {
41
+ severity: "error",
42
+ message: `Invalid locale "${locale}" — use a BCP 47 tag with letters, digits, and hyphens only (for example he-IL, en-US).`,
43
+ suggestion: "Copy the regional setting from the Wix dashboard → Settings → Language & region."
44
+ }
45
+ ];
46
+ }
47
+ try {
48
+ new Intl.NumberFormat(locale, { style: "currency", currency: "USD" });
49
+ return [];
50
+ } catch {
51
+ return [
52
+ {
53
+ severity: "error",
54
+ message: `Invalid locale "${locale}" — use a BCP 47 tag (for example he-IL, en-US).`,
55
+ suggestion: "Copy the regional setting from the Wix dashboard → Settings → Language & region."
56
+ }
57
+ ];
58
+ }
59
+ }
60
+ function validateProductOrderSlugs(productOrder, options) {
61
+ const issues = [];
62
+ const seen = /* @__PURE__ */ new Set();
63
+ const duplicates = [];
64
+ const badShape = [];
65
+ const unknown = [];
66
+ for (const slug of productOrder) {
67
+ if (slug.length === 0) {
68
+ issues.push({
69
+ severity: "error",
70
+ message: "productOrder contains an empty slug entry — remove it or set a product URL slug."
71
+ });
72
+ continue;
73
+ }
74
+ if (seen.has(slug)) {
75
+ duplicates.push(slug);
76
+ } else {
77
+ seen.add(slug);
78
+ }
79
+ if (!SLUG_SHAPE_RE.test(slug)) {
80
+ badShape.push(slug);
81
+ }
82
+ if (options?.catalogSlugs && !options.catalogSlugs.has(slug)) {
83
+ unknown.push(slug);
84
+ }
85
+ }
86
+ if (duplicates.length > 0) {
87
+ issues.push({
88
+ severity: "warning",
89
+ message: `Duplicate productOrder slugs: ${formatSlugList(duplicates)}`
90
+ });
91
+ }
92
+ if (badShape.length > 0) {
93
+ issues.push({
94
+ severity: "warning",
95
+ message: `productOrder slugs with unusual shape (expected lowercase letters, digits, hyphens): ${formatSlugList(badShape)}`
96
+ });
97
+ }
98
+ if (unknown.length > 0) {
99
+ const listed = unknown.slice(0, UNKNOWN_SLUG_WARNING_CAP);
100
+ const suffix = unknown.length > UNKNOWN_SLUG_WARNING_CAP ? ` (and ${unknown.length - UNKNOWN_SLUG_WARNING_CAP} more)` : "";
101
+ issues.push({
102
+ severity: "warning",
103
+ message: `productOrder slugs not found in the catalog: ${formatSlugList(listed)}${suffix}`,
104
+ suggestion: "Use each product slug field from the V1 API, not the product name or SKU."
105
+ });
106
+ }
107
+ if (productOrder.length > 0 && options?.productCount !== void 0 && options.productCount > LARGE_CATALOG_PRODUCT_ORDER_THRESHOLD) {
108
+ issues.push({
109
+ severity: "warning",
110
+ message: `productOrder is set but the catalog has ${options.productCount} products — the default shop listing fetches the full catalog when manual order applies.`,
111
+ suggestion: "See agent-kit/designer/store-configuration.md (performance) or trim productOrder for large stores."
112
+ });
113
+ }
114
+ return issues;
115
+ }
116
+ function validateWixStoresV1ConfigValue(config, options) {
117
+ return [
118
+ ...validateLocale(config.locale),
119
+ ...validateProductOrderSlugs(config.productOrder, options)
120
+ ];
121
+ }
122
+ function validateWixStoresV1Config(projectRoot, options) {
123
+ const configPath = path.join(projectRoot, "config", WIX_STORES_V1_CONFIG_FILE_NAME);
124
+ if (!fs.existsSync(configPath)) {
125
+ return [];
126
+ }
127
+ const config = loadWixStoresV1Config(projectRoot);
128
+ return validateWixStoresV1ConfigValue(config, options);
129
+ }
130
+ function formatSlugList(slugs) {
131
+ return slugs.map((slug) => `"${slug}"`).join(", ");
132
+ }
133
+ const CONFIG_TEMPLATE = `# Wix Stores V1 configuration (config/.wix-stores-v1.yaml)
134
+ #
135
+ # BCP 47 — copy from the Wix site dashboard → Settings → Language & region (regional settings).
136
+ # Omit or leave unset to keep the Catalog V1 API formatted price strings on product cards.
137
+ # locale: 'he-IL'
138
+ #
139
+ # Product URL slugs (product.slug from the V1 API), in the order they should appear on the
140
+ # default shop listing (relevance sort, no filters). NOT product names, SKUs, or collection IDs.
141
+ # productOrder:
142
+ # - 'i-m-a-product'
143
+ # - 'blue-widget'
144
+ #
145
+ # Full reference: agent-kit/designer/store-configuration.md (materialized after jay-stack agent-kit)
146
+
147
+ `;
148
+ function formatConfigIssues(issues) {
149
+ if (issues.length === 0) {
150
+ return "";
151
+ }
152
+ const lines = issues.map((issue) => {
153
+ const label = issue.severity === "error" ? "Error" : "Warning";
154
+ const hint = issue.suggestion ? ` ${issue.suggestion}` : "";
155
+ return ` - ${label}: ${issue.message}${hint}`;
156
+ });
157
+ return `
158
+
159
+ Config (${WIX_STORES_V1_CONFIG_FILE_NAME}):
160
+ ${lines.join("\n")}`;
161
+ }
4
162
  async function setupWixStoresV1(ctx) {
5
163
  if (ctx.initError) {
6
164
  return {
@@ -17,21 +175,101 @@ async function setupWixStoresV1(ctx) {
17
175
  message: "WixStoresV1Service not available. Run setup for wix-server-client first."
18
176
  };
19
177
  }
178
+ const configPath = path.join(ctx.configDir, WIX_STORES_V1_CONFIG_FILE_NAME);
179
+ const configCreated = [];
180
+ if (!fs.existsSync(configPath)) {
181
+ if (!fs.existsSync(ctx.configDir)) {
182
+ fs.mkdirSync(ctx.configDir, { recursive: true });
183
+ }
184
+ fs.writeFileSync(configPath, CONFIG_TEMPLATE, "utf-8");
185
+ configCreated.push(`config/${WIX_STORES_V1_CONFIG_FILE_NAME}`);
186
+ }
20
187
  try {
21
188
  await queryProducts(service.wixClient, { paging: { limit: 1 } });
22
189
  } catch (e) {
23
- const msg = e.message || "";
190
+ const msg = e instanceof Error ? e.message : String(e);
24
191
  const hint = msg.includes("404") || msg.includes("not found") ? "Wix Stores may not be installed on this site" : msg.includes("403") || msg.includes("permission") ? "API key may lack Wix Stores permissions" : "This package requires the Stores Catalog V1 API — if using Catalog V3, use @jay-framework/wix-stores instead";
25
192
  return {
26
193
  status: "error",
27
194
  message: `Wix Stores V1 API check failed: ${hint}. (${msg})`
28
195
  };
29
196
  }
197
+ const config = loadWixStoresV1Config(ctx.projectRoot);
198
+ let catalogSlugs;
199
+ let productCount;
200
+ if (config.productOrder.length > 0) {
201
+ try {
202
+ const catalog = await fetchCatalogProductSlugs(service.wixClient);
203
+ catalogSlugs = catalog.slugs;
204
+ productCount = catalog.totalCount;
205
+ } catch {
206
+ }
207
+ }
208
+ const configIssues = validateWixStoresV1ConfigValue(config, {
209
+ catalogSlugs,
210
+ productCount
211
+ });
212
+ const hasConfigErrors = configIssues.some((issue) => issue.severity === "error");
213
+ let message = "Wix Stores V1 connected";
214
+ message += formatConfigIssues(configIssues);
30
215
  return {
31
- status: "configured",
32
- message: "Wix Stores V1 connected"
216
+ status: hasConfigErrors ? "needs-config" : "configured",
217
+ message,
218
+ ...configCreated.length > 0 ? { configCreated } : {}
33
219
  };
34
220
  }
221
+ const WIX_STORES_V1_PLUGIN_RE = /wix-stores-v1/;
222
+ const validatedProjects = /* @__PURE__ */ new Set();
223
+ function pageUsesWixStoresV1(ctx) {
224
+ let usesV1 = false;
225
+ walkElements(ctx.body, ctx, (element) => {
226
+ if (usesV1) {
227
+ return;
228
+ }
229
+ const tagName = element.rawTagName?.toLowerCase();
230
+ if (tagName !== "script") {
231
+ return;
232
+ }
233
+ if (element.getAttribute("type") !== "application/jay-headless") {
234
+ return;
235
+ }
236
+ const pluginAttr = element.getAttribute("plugin") ?? "";
237
+ if (WIX_STORES_V1_PLUGIN_RE.test(pluginAttr)) {
238
+ usesV1 = true;
239
+ }
240
+ });
241
+ return usesV1;
242
+ }
243
+ function toFindings(issues) {
244
+ return issues.map((issue) => ({
245
+ severity: issue.severity,
246
+ message: issue.message,
247
+ ...issue.suggestion ? { suggestion: issue.suggestion } : {}
248
+ }));
249
+ }
250
+ const validateWixStoresV1ProjectConfig = (ctx) => {
251
+ if (validatedProjects.has(ctx.projectRoot)) {
252
+ return [];
253
+ }
254
+ const configPath = path$1.join(ctx.projectRoot, "config", WIX_STORES_V1_CONFIG_FILE_NAME);
255
+ const configExists = fs$1.existsSync(configPath);
256
+ const usesV1 = pageUsesWixStoresV1(ctx);
257
+ if (!configExists && !usesV1) {
258
+ return [];
259
+ }
260
+ validatedProjects.add(ctx.projectRoot);
261
+ if (!configExists) {
262
+ return [
263
+ {
264
+ severity: "warning",
265
+ message: "This page uses @jay-framework/wix-stores-v1 but config/.wix-stores-v1.yaml is missing.",
266
+ suggestion: "Run jay-stack setup wix-stores-v1 to create the config template."
267
+ }
268
+ ];
269
+ }
270
+ return toFindings(validateWixStoresV1Config(ctx.projectRoot));
271
+ };
35
272
  export {
36
- setupWixStoresV1
273
+ setupWixStoresV1,
274
+ validateWixStoresV1ProjectConfig
37
275
  };
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@jay-framework/wix-stores-v1",
3
- "version": "0.24.7",
3
+ "version": "0.25.1",
4
4
  "type": "module",
5
5
  "description": "Wix Stores Catalog V1 API client for Jay Framework",
6
6
  "license": "Apache-2.0",
7
7
  "main": "dist/index.js",
8
8
  "files": [
9
9
  "dist",
10
- "plugin.yaml"
10
+ "plugin.yaml",
11
+ "agent-kit"
11
12
  ],
12
13
  "exports": {
13
14
  ".": "./dist/index.js",
@@ -33,34 +34,38 @@
33
34
  "build:check-types": "tsc",
34
35
  "clean": "rimraf dist",
35
36
  "confirm": "npm run clean && npm run build && npm run test",
36
- "test": ":"
37
+ "test": "vitest run"
37
38
  },
38
39
  "dependencies": {
39
- "@jay-framework/component": "^0.24.7",
40
- "@jay-framework/fullstack-component": "^0.24.7",
41
- "@jay-framework/reactive": "^0.24.7",
42
- "@jay-framework/runtime": "^0.24.7",
43
- "@jay-framework/secure": "^0.24.7",
44
- "@jay-framework/stack-client-runtime": "^0.24.7",
45
- "@jay-framework/stack-server-runtime": "^0.24.7",
46
- "@jay-framework/wix-cart": "^0.24.7",
47
- "@jay-framework/wix-server-client": "^0.24.7",
48
- "@jay-framework/wix-utils": "^0.24.7",
49
- "@wix/sdk": "^1.21.5"
40
+ "@jay-framework/component": "^0.25.1",
41
+ "@jay-framework/fullstack-component": "^0.25.1",
42
+ "@jay-framework/reactive": "^0.25.1",
43
+ "@jay-framework/runtime": "^0.25.1",
44
+ "@jay-framework/secure": "^0.25.1",
45
+ "@jay-framework/stack-client-runtime": "^0.25.1",
46
+ "@jay-framework/stack-server-runtime": "^0.25.1",
47
+ "@jay-framework/wix-cart": "^0.25.1",
48
+ "@jay-framework/wix-server-client": "^0.25.1",
49
+ "@jay-framework/wix-utils": "^0.25.1",
50
+ "@wix/sdk": "^1.21.5",
51
+ "js-yaml": "^4.1.0"
50
52
  },
51
53
  "devDependencies": {
52
54
  "@babel/core": "^7.23.7",
53
55
  "@babel/preset-env": "^7.23.8",
54
56
  "@babel/preset-typescript": "^7.23.3",
55
- "@jay-framework/compiler-jay-stack": "^0.24.7",
56
- "@jay-framework/jay-cli": "^0.24.7",
57
- "@jay-framework/vite-plugin": "^0.24.7",
57
+ "@jay-framework/compiler-jay-stack": "^0.25.1",
58
+ "@jay-framework/compiler-shared": "^0.25.1",
59
+ "@jay-framework/jay-cli": "^0.25.1",
60
+ "@jay-framework/jay-stack-cli": "^0.25.1",
61
+ "@jay-framework/vite-plugin": "^0.25.1",
58
62
  "nodemon": "^3.0.3",
59
63
  "rimraf": "^5.0.5",
60
64
  "tslib": "^2.6.2",
61
65
  "tsup": "^8.5.1",
62
66
  "typescript": "^5.3.3",
63
67
  "vite": "^5.0.11",
64
- "vite-plugin-inspect": "^0.8.1"
68
+ "vite-plugin-inspect": "^0.8.1",
69
+ "vitest": "^1.2.0"
65
70
  }
66
71
  }
package/plugin.yaml CHANGED
@@ -43,4 +43,9 @@ contexts:
43
43
 
44
44
  setup: setupWixStoresV1
45
45
 
46
+ validators:
47
+ - name: wix-stores-v1-config
48
+ handler: validateWixStoresV1ProjectConfig
49
+ description: Checks config/.wix-stores-v1.yaml when the project uses wix-stores-v1
50
+
46
51
  # Plugin initialization uses makeJayInit pattern in lib/init.ts
@@ -1,47 +0,0 @@
1
- import { createJayService } from "@jay-framework/fullstack-component";
2
- import { registerService } from "@jay-framework/stack-server-runtime";
3
- import { wixFetch } from "@jay-framework/wix-server-client";
4
- const WIX_STORES_V1_SERVICE_MARKER = createJayService("Wix Store V1 Service");
5
- function provideWixStoresV1Service(wixClient) {
6
- const service = { wixClient };
7
- registerService(WIX_STORES_V1_SERVICE_MARKER, service);
8
- return service;
9
- }
10
- function normalizeProduct(product) {
11
- const p = { ...product };
12
- const raw = product;
13
- if (raw.id && !p._id) {
14
- p._id = raw.id;
15
- }
16
- return p;
17
- }
18
- async function queryProducts(client, request) {
19
- const query = {};
20
- if (request?.filter) query.filter = JSON.stringify(request.filter);
21
- if (request?.sort) {
22
- const v1Sort = request.sort.map((s) => ({
23
- [s.fieldName]: (s.order || "ASC").toLowerCase()
24
- }));
25
- query.sort = JSON.stringify(v1Sort);
26
- }
27
- if (request?.paging) query.paging = request.paging;
28
- const result = await wixFetch(client, "/stores/v1/products/query", {
29
- method: "POST",
30
- body: {
31
- query,
32
- includeVariants: request?.includeVariants ?? true,
33
- includeMerchantSpecificData: request?.includeMerchantSpecificData ?? true
34
- }
35
- });
36
- if (result.products) {
37
- result.products = result.products.map(
38
- (p) => normalizeProduct(p)
39
- );
40
- }
41
- return result;
42
- }
43
- export {
44
- WIX_STORES_V1_SERVICE_MARKER as W,
45
- provideWixStoresV1Service as p,
46
- queryProducts as q
47
- };