@shopware/composables 1.12.0 → 1.12.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
@@ -5,7 +5,7 @@
5
5
  [![](https://img.shields.io/github/issues/shopware/frontends/composables?label=package%20issues&logo=github)](https://github.com/shopware/frontends/issues?q=is%3Aopen+is%3Aissue+label%3Acomposables)
6
6
  [![](https://img.shields.io/github/license/shopware/frontends?color=blue)](#)
7
7
 
8
- Set of Vue.js composition functions that can be used in any Vue.js project. They provide state management, UI logic and data fetching and are the base for all guides in our [building section](https://frontends.shopware.com/getting-started/page-elements/navigation.html).
8
+ Set of Vue.js composition functions that can be used in any Vue.js project. They provide state management, UI logic and data fetching and are the base for all guides in our [building section](https://developer.shopware.com/frontends/guides/page-elements/navigation.html).
9
9
 
10
10
  ## Features
11
11
 
@@ -88,7 +88,7 @@ Now you can use any composable function in your setup function:
88
88
 
89
89
  const { login } = useUser();
90
90
  const { refreshSessionContext, sessionContext } = useSessionContext();
91
- refreshSessionContext();
91
+ await refreshSessionContext();
92
92
  </script>
93
93
  <template>
94
94
  <pre>{{ sessionContext }}</pre>
@@ -156,7 +156,7 @@ All composable functions are fully typed with TypeScript and they are registed g
156
156
 
157
157
  ## Links
158
158
 
159
- - [📘 Documentation](https://frontends.shopware.com)
159
+ - [📘 Documentation](https://developer.shopware.com/frontends)
160
160
 
161
161
  - [👥 Community Discord](https://discord.com/channels/1308047705309708348/1405501315160739951) (`#composable-frontend`)
162
162
 
@@ -166,20 +166,24 @@ All composable functions are fully typed with TypeScript and they are registed g
166
166
 
167
167
  Full changelog for stable version is available [here](https://github.com/shopware/frontends/blob/main/packages/composables/CHANGELOG.md)
168
168
 
169
- ### Latest changes: 1.12.0
169
+ ### Latest changes: 1.12.1
170
170
 
171
- ### Minor Changes
171
+ ### Patch Changes
172
172
 
173
- - [#2486](https://github.com/shopware/frontends/pull/2486) [`5678fb0`](https://github.com/shopware/frontends/commit/5678fb008cbd86eaddd061e004de89e6f45bb7ec) Thanks [@mkucmus](https://github.com/mkucmus)! - `useSessionContext`: expose `currentLocaleCode` — the active language's locale code (e.g. `"en-GB"`), read directly from the context's `languageInfo`. The current locale can now be derived from the session context alone, without loading the full language list via `useInternationalization().getAvailableLanguages()` just to map the current `languageId` to a locale.
173
+ - [#2568](https://github.com/shopware/frontends/pull/2568) [`6315350`](https://github.com/shopware/frontends/commit/6315350add0464abef153343897d42f5808f2003) Thanks [@patzick](https://github.com/patzick)! - Add cacheable GET support for category details and product reviews while preserving the existing POST behavior when `cacheableReads` is disabled.
174
174
 
175
- - [#2473](https://github.com/shopware/frontends/pull/2473) [`22611e5`](https://github.com/shopware/frontends/commit/22611e542b8f42a4f34dce5186f628f9a17f457b) Thanks [@mkucmus](https://github.com/mkucmus)! - Add an opt-in `cacheableReads` flag that routes anonymous Store API reads through their cacheable GET variants instead of POST. Criteria is compressed into the `_criteria` query param via `encodeForQuery` from `@shopware/api-client/helpers`, which lets CDNs / reverse proxies / the browser cache the responses.
175
+ - `useCategorySearch.search` now calls `GET /category/{navigationId}` and sends the complete encoded Criteria in the `_criteria` query parameter when cacheable reads are enabled.
176
+ - `useProductReviews.loadProductReviews` now calls `GET /product/{productId}/reviews` and sends its encoded Criteria in `_criteria` when cacheable reads are enabled.
177
+ - The CMS product description reviews element follows the same flag and endpoint behavior when it needs to fetch reviews directly.
176
178
 
177
- Disabled by default — fully backwards compatible. Enable it in `nuxt.config` (`shopware: { cacheableReads: true }`) or via `createShopwareContext(app, { cacheableReads: true })` for non-Nuxt setups. It is surfaced on the Shopware context and read by the affected composables; public composable signatures are unchanged.
179
+ - [#2596](https://github.com/shopware/frontends/pull/2596) [`6572aa8`](https://github.com/shopware/frontends/commit/6572aa84431e1f4a34d6cf04e549037692d638a6) Thanks [@patzick](https://github.com/patzick)! - Reduce Rolldown/Vite build noise: scope Nuxt global components, keep the three.js async chunk warning intentional, avoid shipping full carbon icon JSON via UnoCSS runtime, and bump @vueuse to 14.4.0.
178
180
 
179
- Affected composables: `useNavigation`, `useNavigationSearch`, `useCountries`, `useUser` (country + salutation lookups), `useSalutations`, `useInternationalization`, `useProductConfigurator`, `useProductSearch`, and `useCategorySearch.advancedSearch`.
181
+ - [#2514](https://github.com/shopware/frontends/pull/2514) [`744833b`](https://github.com/shopware/frontends/commit/744833b9d7d2f8ea1f5dfe65be3fa554dbe4a09f) Thanks [@mdanilowicz](https://github.com/mdanilowicz)! - Allow passing custom criteria to `useCountries`.
180
182
 
181
- `useListing` (product-listing), single-category `useCategorySearch.search`, and `useLandingSearch` remain POST for now: the generated Store API schema does not type `_criteria` on those GET routes (a Shopware OpenAPI gap). The backend does honor `_criteria` on product-listing GET at runtime, so that one can be migrated later once the types are augmented.
183
+ - [#2552](https://github.com/shopware/frontends/pull/2552) [`e03c91b`](https://github.com/shopware/frontends/commit/e03c91be172374894d90b7a0111855b76719fee1) Thanks [@patzick](https://github.com/patzick)! - Suppress Rolldown diagnostic warnings for invalid third-party pure annotations and plugin timings in the Nuxt layer build config.
182
184
 
183
- ### Patch Changes
185
+ - [#2591](https://github.com/shopware/frontends/pull/2591) [`38379a5`](https://github.com/shopware/frontends/commit/38379a5d52ab09008774533ef417ebe2cde3f7fd) Thanks [@patzick](https://github.com/patzick)! - Propagate session context refresh failures so login, registration, logout, and context setters cannot complete after an unverifiable context switch.
184
186
 
185
- - [#2462](https://github.com/shopware/frontends/pull/2462) [`8be060d`](https://github.com/shopware/frontends/commit/8be060de825ca799f98a8f045a5e7fea61f5d1a2) Thanks [@mkucmus](https://github.com/mkucmus)! - `useProductAssociations`: add optional `includeSeoUrls` option. When `true`, the cross-selling request sends `sw-include-seo-urls: true` so returned products include the `seoUrls` association. Defaults to `false` to avoid extra backend overhead.
187
+ - Updated dependencies [[`b767721`](https://github.com/shopware/frontends/commit/b767721847bf3391f9067eca7a045089fb22fce0), [`f16c5a0`](https://github.com/shopware/frontends/commit/f16c5a0785d6187b73c3edcf37feab7c90bd7988), [`978b02c`](https://github.com/shopware/frontends/commit/978b02c969ca4b16f5fc1d7a953ec4cce3d98173), [`33facb1`](https://github.com/shopware/frontends/commit/33facb178792c8cb26b47ab984ac48c08ab4b72b), [`9137475`](https://github.com/shopware/frontends/commit/91374753cedb2034385f642e6af11314f2971caa), [`474d3fe`](https://github.com/shopware/frontends/commit/474d3fed346816135b0c7c797990b215a8b691c0)]:
188
+ - @shopware/api-client@1.5.1
189
+ - @shopware/helpers@1.7.2
package/dist/index.d.mts CHANGED
@@ -572,7 +572,7 @@ type UseBreadcrumbsReturn = {
572
572
  };
573
573
  /**
574
574
  * Composable for breadcrumbs management.
575
- * Read the [guide](https://frontends.shopware.com/getting-started/page-elements/breadcrumbs.html#building-breadcrumbs-for-cms-pages).
575
+ * Read the [guide](https://developer.shopware.com/frontends/guides/page-elements/breadcrumbs.html#building-breadcrumbs-for-cms-pages).
576
576
  *
577
577
  * @public
578
578
  * @category CMS (Shopping Experiences)
@@ -671,13 +671,14 @@ type UseCartReturn = {
671
671
  /**
672
672
  * Cart management logic.
673
673
  *
674
- * Used as [Shared](https://frontends.shopware.com/framework/composables/shared-composables.html) Composable `useCart`
674
+ * Used as [Shared](https://developer.shopware.com/frontends/concepts/composables/shared-composables.html) Composable `useCart`
675
675
  *
676
676
  * @category Cart & Checkout
677
677
  */
678
678
  declare function useCartFunction(): UseCartReturn;
679
679
  declare const useCart: typeof useCartFunction;
680
680
 
681
+ type LineItemOptions = Schemas["PropertyGroupOption"][];
681
682
  type UseCartItemReturn = {
682
683
  /**
683
684
  * Calculated price {number} for the current item
@@ -698,7 +699,7 @@ type UseCartItemReturn = {
698
699
  /**
699
700
  * Options (of variation) for the current item
700
701
  */
701
- itemOptions: ComputedRef<Schemas["LineItem"]["payload"]["options"]>;
702
+ itemOptions: ComputedRef<LineItemOptions>;
702
703
  /**
703
704
  * Type of the current item: "product" or "promotion"
704
705
  */
@@ -941,7 +942,7 @@ type UseCountriesReturn = {
941
942
  * @public
942
943
  * @category Context & Language
943
944
  */
944
- declare function useCountries(): UseCountriesReturn;
945
+ declare function useCountries(criteria?: Schemas["Criteria"]): UseCountriesReturn;
945
946
 
946
947
  type UseCustomerOrdersReturn = {
947
948
  /**
@@ -1949,6 +1950,10 @@ type UseSessionContextReturn = {
1949
1950
  sessionContext: ComputedRef<Schemas["SalesChannelContext"] | undefined>;
1950
1951
  /**
1951
1952
  * Fetches the session context and assigns the result to the `sessionContext` property
1953
+ *
1954
+ * Throws when the context cannot be loaded. Callers that depend on a verified
1955
+ * context switch, such as logout or checkout flows, should block progression
1956
+ * when this fails.
1952
1957
  */
1953
1958
  refreshSessionContext(): Promise<void>;
1954
1959
  /**
package/dist/index.d.ts CHANGED
@@ -572,7 +572,7 @@ type UseBreadcrumbsReturn = {
572
572
  };
573
573
  /**
574
574
  * Composable for breadcrumbs management.
575
- * Read the [guide](https://frontends.shopware.com/getting-started/page-elements/breadcrumbs.html#building-breadcrumbs-for-cms-pages).
575
+ * Read the [guide](https://developer.shopware.com/frontends/guides/page-elements/breadcrumbs.html#building-breadcrumbs-for-cms-pages).
576
576
  *
577
577
  * @public
578
578
  * @category CMS (Shopping Experiences)
@@ -671,13 +671,14 @@ type UseCartReturn = {
671
671
  /**
672
672
  * Cart management logic.
673
673
  *
674
- * Used as [Shared](https://frontends.shopware.com/framework/composables/shared-composables.html) Composable `useCart`
674
+ * Used as [Shared](https://developer.shopware.com/frontends/concepts/composables/shared-composables.html) Composable `useCart`
675
675
  *
676
676
  * @category Cart & Checkout
677
677
  */
678
678
  declare function useCartFunction(): UseCartReturn;
679
679
  declare const useCart: typeof useCartFunction;
680
680
 
681
+ type LineItemOptions = Schemas["PropertyGroupOption"][];
681
682
  type UseCartItemReturn = {
682
683
  /**
683
684
  * Calculated price {number} for the current item
@@ -698,7 +699,7 @@ type UseCartItemReturn = {
698
699
  /**
699
700
  * Options (of variation) for the current item
700
701
  */
701
- itemOptions: ComputedRef<Schemas["LineItem"]["payload"]["options"]>;
702
+ itemOptions: ComputedRef<LineItemOptions>;
702
703
  /**
703
704
  * Type of the current item: "product" or "promotion"
704
705
  */
@@ -941,7 +942,7 @@ type UseCountriesReturn = {
941
942
  * @public
942
943
  * @category Context & Language
943
944
  */
944
- declare function useCountries(): UseCountriesReturn;
945
+ declare function useCountries(criteria?: Schemas["Criteria"]): UseCountriesReturn;
945
946
 
946
947
  type UseCustomerOrdersReturn = {
947
948
  /**
@@ -1949,6 +1950,10 @@ type UseSessionContextReturn = {
1949
1950
  sessionContext: ComputedRef<Schemas["SalesChannelContext"] | undefined>;
1950
1951
  /**
1951
1952
  * Fetches the session context and assigns the result to the `sessionContext` property
1953
+ *
1954
+ * Throws when the context cannot be loaded. Callers that depend on a verified
1955
+ * context switch, such as logout or checkout flows, should block progression
1956
+ * when this fails.
1952
1957
  */
1953
1958
  refreshSessionContext(): Promise<void>;
1954
1959
  /**
package/dist/index.mjs CHANGED
@@ -357,7 +357,7 @@ function useCartFunction() {
357
357
  });
358
358
  const count = computed(() => {
359
359
  return cartItems.value.reduce(
360
- (accumulator, lineItem) => lineItem.good === true ? lineItem.quantity + accumulator : accumulator,
360
+ (accumulator, lineItem) => lineItem.good === true ? (lineItem.quantity ?? 0) + accumulator : accumulator,
361
361
  0
362
362
  );
363
363
  });
@@ -378,7 +378,7 @@ function useCartFunction() {
378
378
  return cartPrice || 0;
379
379
  });
380
380
  const isVirtualCart = computed(() => {
381
- return cartItems.value.length > 0 && cartItems.value.filter((element) => element.type !== "promotion").every((item) => item.states.includes("is-download"));
381
+ return cartItems.value.length > 0 && cartItems.value.filter((element) => element.type !== "promotion").every((item) => item.states?.includes("is-download") ?? false);
382
382
  });
383
383
  const setCartErrors = (cart2) => {
384
384
  if (Object.keys(cart2.errors || {}).length) {
@@ -430,11 +430,12 @@ function useCartItem(cartItem) {
430
430
  () => cartItem.value?.price?.listPrice?.price && cartItem.value?.price?.unitPrice
431
431
  );
432
432
  const itemTotalPrice = computed(() => cartItem.value.price?.totalPrice);
433
- const itemOptions = computed(
434
- () => cartItem.value.type === "product" && cartItem.value.payload?.options || []
435
- );
433
+ const itemOptions = computed(() => {
434
+ const payload = cartItem.value.payload;
435
+ return cartItem.value.type === "product" ? payload?.options ?? [] : [];
436
+ });
436
437
  const itemStock = computed(
437
- () => cartItem.value.deliveryInformation.stock
438
+ () => cartItem.value.deliveryInformation?.stock
438
439
  );
439
440
  const isDigital = computed(
440
441
  () => !!cartItem.value.states?.includes("is-download")
@@ -527,21 +528,29 @@ function useCategorySearch() {
527
528
  const { apiClient, cacheableReads } = useShopwareContext();
528
529
  async function search(categoryId, options) {
529
530
  const associations = options?.withCmsAssociations ? cmsAssociations : {};
530
- const result = await apiClient.invoke(
531
- "readCategory post /category/{navigationId}",
532
- {
533
- pathParams: {
534
- navigationId: categoryId
535
- },
536
- headers: {
537
- "sw-include-seo-urls": true
538
- },
539
- body: {
540
- associations,
541
- ...options?.query
542
- }
531
+ const criteria = {
532
+ associations,
533
+ ...options?.query
534
+ };
535
+ const result = cacheableReads ? await apiClient.invoke("readCategoryGet get /category/{navigationId}", {
536
+ pathParams: {
537
+ navigationId: categoryId
538
+ },
539
+ headers: {
540
+ "sw-include-seo-urls": true
541
+ },
542
+ query: {
543
+ _criteria: encodeForQuery(criteria)
543
544
  }
544
- );
545
+ }) : await apiClient.invoke("readCategory post /category/{navigationId}", {
546
+ pathParams: {
547
+ navigationId: categoryId
548
+ },
549
+ headers: {
550
+ "sw-include-seo-urls": true
551
+ },
552
+ body: criteria
553
+ });
545
554
  return result.data;
546
555
  }
547
556
  async function advancedSearch(options) {
@@ -702,20 +711,21 @@ function useContext(injectionName, params) {
702
711
  return _context;
703
712
  }
704
713
 
705
- function useCountries() {
714
+ function useCountries(criteria) {
706
715
  const { apiClient, cacheableReads } = useShopwareContext();
707
716
  const _sharedCountries = inject("swCountries", ref());
708
717
  provide("swCountries", _sharedCountries);
718
+ const searchCriteria = ref(criteria ?? {});
709
719
  async function fetchCountries() {
710
- const criteria = {
720
+ const queryCriteria = defu(searchCriteria.value, {
711
721
  associations: {
712
722
  states: {}
713
723
  }
714
- };
724
+ });
715
725
  const result = cacheableReads ? await apiClient.invoke("readCountryGet get /country", {
716
- query: { _criteria: encodeForQuery(criteria) }
726
+ query: { _criteria: encodeForQuery(queryCriteria) }
717
727
  }) : await apiClient.invoke("readCountry post /country", {
718
- body: criteria
728
+ body: queryCriteria
719
729
  });
720
730
  _sharedCountries.value = result.data.elements;
721
731
  return result.data;
@@ -1935,10 +1945,16 @@ function useProductPrice(product) {
1935
1945
  }
1936
1946
 
1937
1947
  function useProductReviews(product) {
1938
- const { apiClient } = useShopwareContext();
1948
+ const { apiClient, cacheableReads } = useShopwareContext();
1939
1949
  const productReviews = ref([]);
1940
1950
  const loadProductReviews = async (parameters = {}) => {
1941
- const fetchedReviews = await apiClient.invoke(
1951
+ const fetchedReviews = cacheableReads ? await apiClient.invoke(
1952
+ "readProductReviewsGet get /product/{productId}/reviews",
1953
+ {
1954
+ pathParams: { productId: product.value.id },
1955
+ query: { _criteria: encodeForQuery(parameters) }
1956
+ }
1957
+ ) : await apiClient.invoke(
1942
1958
  "readProductReviews post /product/{productId}/reviews",
1943
1959
  {
1944
1960
  pathParams: { productId: product.value.id },
@@ -2092,6 +2108,7 @@ function useSessionContext(newContext) {
2092
2108
  _sessionContext.value = data;
2093
2109
  } catch (e) {
2094
2110
  console.error("[UseSessionContext][refreshSessionContext]", e);
2111
+ throw e;
2095
2112
  }
2096
2113
  };
2097
2114
  const selectedShippingMethod = computed(
@@ -2171,7 +2188,7 @@ function useSessionContext(newContext) {
2171
2188
  shippingAddressId: address.id
2172
2189
  }
2173
2190
  });
2174
- refreshSessionContext();
2191
+ await refreshSessionContext();
2175
2192
  };
2176
2193
  const activeBillingAddress = computed(
2177
2194
  () => sessionContext.value?.customer?.activeBillingAddress || null
@@ -2187,7 +2204,7 @@ function useSessionContext(newContext) {
2187
2204
  billingAddressId: address.id
2188
2205
  }
2189
2206
  });
2190
- refreshSessionContext();
2207
+ await refreshSessionContext();
2191
2208
  };
2192
2209
  const setContext = (context) => {
2193
2210
  _sessionContext.value = context;
package/nuxt.config.ts CHANGED
@@ -8,6 +8,16 @@ export default defineNuxtConfig({
8
8
  build: {
9
9
  transpile: ["@shopware/composables"],
10
10
  },
11
+ vite: {
12
+ build: {
13
+ rolldownOptions: {
14
+ checks: {
15
+ invalidAnnotation: false,
16
+ pluginTimings: false,
17
+ },
18
+ },
19
+ },
20
+ },
11
21
  telemetry: {
12
22
  enabled: false,
13
23
  },
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@shopware/composables",
3
- "version": "1.12.0",
3
+ "version": "1.12.1",
4
4
  "description": "Shopware Frontends composables for Vue",
5
5
  "author": "Shopware",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/shopware/frontends.git"
9
9
  },
10
- "homepage": "https://frontends.shopware.com/packages/composables.html",
10
+ "homepage": "https://developer.shopware.com/frontends/packages/composables.html",
11
11
  "keywords": [
12
12
  "shopware",
13
13
  "vue",
@@ -52,22 +52,22 @@
52
52
  "app.config.ts"
53
53
  ],
54
54
  "dependencies": {
55
- "@vueuse/core": "14.3.0",
55
+ "@vueuse/core": "14.4.0",
56
56
  "defu": "6.1.7",
57
57
  "scule": "1.3.0",
58
- "@shopware/helpers": "1.7.1",
59
- "@shopware/api-client": "1.5.0"
58
+ "@shopware/helpers": "1.7.2",
59
+ "@shopware/api-client": "1.5.1"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@nuxt/kit": "4.4.8",
63
63
  "@typescript/native-preview": "7.0.0-dev.20260205.1",
64
- "@vitest/coverage-v8": "4.1.9",
64
+ "@vitest/coverage-v8": "4.1.10",
65
65
  "@vue/test-utils": "2.4.11",
66
66
  "happy-dom": "20.10.6",
67
67
  "typescript": "5.9.3",
68
68
  "unbuild": "3.6.1",
69
- "vitest": "4.1.9",
70
- "vue": "3.5.38",
69
+ "vitest": "4.1.10",
70
+ "vue": "3.5.39",
71
71
  "tsconfig": "0.0.0"
72
72
  },
73
73
  "scripts": {
@@ -44,7 +44,7 @@ export type UseBreadcrumbsReturn = {
44
44
 
45
45
  /**
46
46
  * Composable for breadcrumbs management.
47
- * Read the [guide](https://frontends.shopware.com/getting-started/page-elements/breadcrumbs.html#building-breadcrumbs-for-cms-pages).
47
+ * Read the [guide](https://developer.shopware.com/frontends/guides/page-elements/breadcrumbs.html#building-breadcrumbs-for-cms-pages).
48
48
  *
49
49
  * @public
50
50
  * @category CMS (Shopping Experiences)
@@ -280,6 +280,23 @@ describe("useCart", () => {
280
280
  expect(vm.isVirtualCart).toBe(true);
281
281
  });
282
282
 
283
+ it("handles cart items with optional quantity and states", async () => {
284
+ injections.apiClient.invoke.mockResolvedValue({
285
+ data: {
286
+ lineItems: [
287
+ {
288
+ type: "product",
289
+ good: true,
290
+ },
291
+ ],
292
+ },
293
+ });
294
+ await vm.refreshCart();
295
+
296
+ expect(vm.count).toBe(0);
297
+ expect(vm.isVirtualCart).toBe(false);
298
+ });
299
+
283
300
  it("consumeCartErrors returns null when no errors", async () => {
284
301
  await vm.refreshCart();
285
302
  expect(vm.consumeCartErrors()).toEqual(null);
@@ -100,7 +100,7 @@ export type UseCartReturn = {
100
100
  /**
101
101
  * Cart management logic.
102
102
  *
103
- * Used as [Shared](https://frontends.shopware.com/framework/composables/shared-composables.html) Composable `useCart`
103
+ * Used as [Shared](https://developer.shopware.com/frontends/concepts/composables/shared-composables.html) Composable `useCart`
104
104
  *
105
105
  * @category Cart & Checkout
106
106
  */
@@ -244,7 +244,9 @@ export function useCartFunction(): UseCartReturn {
244
244
  const count = computed(() => {
245
245
  return cartItems.value.reduce(
246
246
  (accumulator: number, lineItem: Schemas["LineItem"]) =>
247
- lineItem.good === true ? lineItem.quantity + accumulator : accumulator,
247
+ lineItem.good === true
248
+ ? (lineItem.quantity ?? 0) + accumulator
249
+ : accumulator,
248
250
  0,
249
251
  );
250
252
  });
@@ -276,7 +278,7 @@ export function useCartFunction(): UseCartReturn {
276
278
  cartItems.value.length > 0 &&
277
279
  cartItems.value
278
280
  .filter((element) => element.type !== "promotion")
279
- .every((item) => item.states.includes("is-download"))
281
+ .every((item) => item.states?.includes("is-download") ?? false)
280
282
  );
281
283
  });
282
284
 
@@ -88,6 +88,19 @@ describe("useCartItem", () => {
88
88
  expect(vm.itemOptions).toStrictEqual([]);
89
89
  });
90
90
 
91
+ it("should show default empty options and stock for non-product items", async () => {
92
+ const { vm } = useSetup(() =>
93
+ useCartItem(
94
+ ref({
95
+ type: "promotion",
96
+ } as Schemas["LineItem"]),
97
+ ),
98
+ );
99
+
100
+ expect(vm.itemOptions).toStrictEqual([]);
101
+ expect(vm.itemStock).toBeUndefined();
102
+ });
103
+
91
104
  it("should remove item from the cart", async () => {
92
105
  const { vm } = useSetup(() =>
93
106
  useCartItem(ref(lineItem) as unknown as Ref<Schemas["LineItem"]>),
@@ -5,6 +5,11 @@ import type { ComputedRef, Ref } from "vue";
5
5
  import { useCart } from "#imports";
6
6
  import type { Schemas } from "#shopware";
7
7
 
8
+ type LineItemOptions = Schemas["PropertyGroupOption"][];
9
+ type LineItemPayloadWithOptions = {
10
+ options?: LineItemOptions;
11
+ };
12
+
8
13
  export type UseCartItemReturn = {
9
14
  /**
10
15
  * Calculated price {number} for the current item
@@ -25,7 +30,7 @@ export type UseCartItemReturn = {
25
30
  /**
26
31
  * Options (of variation) for the current item
27
32
  */
28
- itemOptions: ComputedRef<Schemas["LineItem"]["payload"]["options"]>;
33
+ itemOptions: ComputedRef<LineItemOptions>;
29
34
  /**
30
35
  * Type of the current item: "product" or "promotion"
31
36
  */
@@ -99,14 +104,16 @@ export function useCartItem(
99
104
 
100
105
  const itemTotalPrice = computed(() => cartItem.value.price?.totalPrice);
101
106
 
102
- const itemOptions = computed(
103
- () =>
104
- (cartItem.value.type === "product" && cartItem.value.payload?.options) ||
105
- [],
106
- );
107
+ const itemOptions = computed(() => {
108
+ const payload = cartItem.value.payload as
109
+ | LineItemPayloadWithOptions
110
+ | undefined;
111
+
112
+ return cartItem.value.type === "product" ? (payload?.options ?? []) : [];
113
+ });
107
114
 
108
115
  const itemStock = computed<number | undefined>(
109
- () => cartItem.value.deliveryInformation.stock,
116
+ () => cartItem.value.deliveryInformation?.stock,
110
117
  );
111
118
 
112
119
  const isDigital = computed(
@@ -14,7 +14,7 @@ describe("useCategorySearch", () => {
14
14
  vm.search("categoryId");
15
15
 
16
16
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
17
- expect.stringContaining("readCategory"),
17
+ expect.stringContaining("readCategory post"),
18
18
  expect.objectContaining({
19
19
  pathParams: {
20
20
  navigationId: "categoryId",
@@ -36,7 +36,7 @@ describe("useCategorySearch", () => {
36
36
  });
37
37
 
38
38
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
39
- expect.stringContaining("readCategory"),
39
+ expect.stringContaining("readCategory post"),
40
40
  expect.objectContaining({
41
41
  pathParams: {
42
42
  navigationId: "categoryId",
@@ -51,6 +51,79 @@ describe("useCategorySearch", () => {
51
51
  );
52
52
  });
53
53
 
54
+ it("search uses the cacheable GET variant when cacheableReads is enabled", () => {
55
+ const { vm, injections } = useSetup(useCategorySearch, {
56
+ shopware: { cacheableReads: true },
57
+ });
58
+ injections.apiClient.invoke.mockResolvedValue({
59
+ data: {},
60
+ });
61
+
62
+ vm.search("categoryId", {
63
+ query: {
64
+ filter: [{ type: "equals", field: "active", value: true }],
65
+ limit: 1,
66
+ sort: [{ field: "name", order: "ASC" }],
67
+ },
68
+ withCmsAssociations: true,
69
+ });
70
+
71
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
72
+ expect.stringContaining("readCategoryGet get"),
73
+ expect.objectContaining({
74
+ pathParams: {
75
+ navigationId: "categoryId",
76
+ },
77
+ headers: {
78
+ "sw-include-seo-urls": true,
79
+ },
80
+ query: {
81
+ _criteria: encodeForQuery({
82
+ associations: cmsAssociations,
83
+ filter: [{ type: "equals", field: "active", value: true }],
84
+ limit: 1,
85
+ sort: [{ field: "name", order: "ASC" }],
86
+ }),
87
+ },
88
+ }),
89
+ );
90
+ });
91
+
92
+ it("search encodes Criteria body keys into cacheable GET _criteria", () => {
93
+ const { vm, injections } = useSetup(useCategorySearch, {
94
+ shopware: { cacheableReads: true },
95
+ });
96
+ injections.apiClient.invoke.mockResolvedValue({
97
+ data: {},
98
+ });
99
+
100
+ vm.search("categoryId", {
101
+ query: {
102
+ aggregations: [{ type: "count", field: "id", name: "count-id" }],
103
+ fields: ["name"],
104
+ grouping: ["translated.name"],
105
+ ids: ["categoryId"],
106
+ "post-filter": [{ type: "equals", field: "active", value: true }],
107
+ },
108
+ });
109
+
110
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
111
+ expect.stringContaining("readCategoryGet get"),
112
+ expect.objectContaining({
113
+ query: {
114
+ _criteria: encodeForQuery({
115
+ associations: {},
116
+ aggregations: [{ type: "count", field: "id", name: "count-id" }],
117
+ fields: ["name"],
118
+ grouping: ["translated.name"],
119
+ ids: ["categoryId"],
120
+ "post-filter": [{ type: "equals", field: "active", value: true }],
121
+ }),
122
+ },
123
+ }),
124
+ );
125
+ });
126
+
54
127
  it("advanced search method", () => {
55
128
  const { vm, injections } = useSetup(useCategorySearch);
56
129
  injections.apiClient.invoke.mockResolvedValue({
@@ -1,10 +1,14 @@
1
1
  import { encodeForQuery } from "@shopware/api-client/helpers";
2
2
 
3
3
  import { useShopwareContext } from "#imports";
4
- import type { Schemas } from "#shopware";
4
+ import type { Schemas, operations } from "#shopware";
5
5
 
6
6
  import { cmsAssociations } from "../cms/cmsAssociations";
7
7
 
8
+ type ReadCategoryGetQuery = NonNullable<
9
+ operations["readCategoryGet get /category/{navigationId}"]["query"]
10
+ > & { _criteria?: string };
11
+
8
12
  export type UseCategorySearchReturn = {
9
13
  /**
10
14
  * Search for category by ID
@@ -43,21 +47,31 @@ export function useCategorySearch(): UseCategorySearchReturn {
43
47
  },
44
48
  ) {
45
49
  const associations = options?.withCmsAssociations ? cmsAssociations : {};
46
- const result = await apiClient.invoke(
47
- "readCategory post /category/{navigationId}",
48
- {
49
- pathParams: {
50
- navigationId: categoryId,
51
- },
52
- headers: {
53
- "sw-include-seo-urls": true,
54
- },
55
- body: {
56
- associations,
57
- ...options?.query,
58
- },
59
- },
60
- );
50
+ const criteria = {
51
+ associations,
52
+ ...options?.query,
53
+ };
54
+ const result = cacheableReads
55
+ ? await apiClient.invoke("readCategoryGet get /category/{navigationId}", {
56
+ pathParams: {
57
+ navigationId: categoryId,
58
+ },
59
+ headers: {
60
+ "sw-include-seo-urls": true,
61
+ },
62
+ query: {
63
+ _criteria: encodeForQuery(criteria),
64
+ } as ReadCategoryGetQuery,
65
+ })
66
+ : await apiClient.invoke("readCategory post /category/{navigationId}", {
67
+ pathParams: {
68
+ navigationId: categoryId,
69
+ },
70
+ headers: {
71
+ "sw-include-seo-urls": true,
72
+ },
73
+ body: criteria,
74
+ });
61
75
  return result.data;
62
76
  }
63
77
 
@@ -2,13 +2,15 @@ import { encodeForQuery } from "@shopware/api-client/helpers";
2
2
  import { describe, expect, it, vi } from "vitest";
3
3
  import { ref } from "vue";
4
4
 
5
+ import type { Schemas } from "#shopware";
6
+
5
7
  import { useSetup } from "../_test";
6
8
  import CountryMock from "../mocks/Country";
7
9
  import { useCountries } from "./useCountries";
8
10
 
9
11
  describe("useCountries", () => {
10
12
  it("useCountries flow", async () => {
11
- const { vm, injections } = await useSetup(useCountries, {
13
+ const { vm, injections } = await useSetup(() => useCountries(), {
12
14
  apiClient: {
13
15
  invoke: vi.fn().mockResolvedValue({
14
16
  data: CountryMock,
@@ -30,7 +32,7 @@ describe("useCountries", () => {
30
32
  });
31
33
 
32
34
  it("useCountries flow - no states", async () => {
33
- const { vm } = await useSetup(useCountries, {
35
+ const { vm } = await useSetup(() => useCountries(), {
34
36
  apiClient: {
35
37
  invoke: vi.fn().mockResolvedValue({
36
38
  data: {
@@ -51,7 +53,7 @@ describe("useCountries", () => {
51
53
  });
52
54
 
53
55
  it("useCountries flow - empty", async () => {
54
- const { vm } = await useSetup(useCountries, {
56
+ const { vm } = await useSetup(() => useCountries(), {
55
57
  apiClient: {
56
58
  invoke: vi.fn().mockResolvedValue({
57
59
  data: {
@@ -66,7 +68,7 @@ describe("useCountries", () => {
66
68
  });
67
69
 
68
70
  it("useCountries flow - getCountriesOptions", async () => {
69
- const { vm } = await useSetup(useCountries, {
71
+ const { vm } = await useSetup(() => useCountries(), {
70
72
  apiClient: {
71
73
  invoke: vi.fn().mockResolvedValue({
72
74
  data: CountryMock,
@@ -93,7 +95,7 @@ describe("useCountries", () => {
93
95
  });
94
96
 
95
97
  it("useCountries flow - getCountriesOptions - empty array", async () => {
96
- const { vm } = await useSetup(useCountries, {
98
+ const { vm } = await useSetup(() => useCountries(), {
97
99
  apiClient: {
98
100
  invoke: vi.fn().mockResolvedValue({
99
101
  data: {
@@ -107,7 +109,7 @@ describe("useCountries", () => {
107
109
  });
108
110
 
109
111
  it("uses the cacheable GET variant when cacheableReads is enabled", async () => {
110
- const { vm, injections } = await useSetup(useCountries, {
112
+ const { vm, injections } = await useSetup(() => useCountries(), {
111
113
  shopware: { cacheableReads: true },
112
114
  apiClient: {
113
115
  invoke: vi.fn().mockResolvedValue({ data: CountryMock }),
@@ -123,9 +125,78 @@ describe("useCountries", () => {
123
125
  );
124
126
  });
125
127
 
128
+ it("uses criteria passed to useCountries", async () => {
129
+ const criteria: Schemas["Criteria"] = { limit: 1 };
130
+ const { vm, injections } = await useSetup(() => useCountries(criteria), {
131
+ apiClient: {
132
+ invoke: vi.fn().mockResolvedValue({ data: CountryMock }),
133
+ },
134
+ swCountries: ref([]),
135
+ } as Parameters<typeof useSetup>[1]);
136
+
137
+ await vm.fetchCountries();
138
+
139
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
140
+ expect.stringContaining("readCountry post"),
141
+ expect.objectContaining({
142
+ body: {
143
+ associations: { states: {} },
144
+ limit: 1,
145
+ },
146
+ }),
147
+ );
148
+ });
149
+
150
+ it("uses criteria passed to useCountries for cacheable fetchCountries", async () => {
151
+ const criteria: Schemas["Criteria"] = { limit: 1 };
152
+ const { vm, injections } = await useSetup(() => useCountries(criteria), {
153
+ shopware: { cacheableReads: true },
154
+ apiClient: {
155
+ invoke: vi.fn().mockResolvedValue({ data: CountryMock }),
156
+ },
157
+ swCountries: ref([]),
158
+ } as Parameters<typeof useSetup>[1]);
159
+
160
+ await vm.fetchCountries();
161
+
162
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
163
+ expect.stringContaining("readCountryGet get"),
164
+ expect.objectContaining({
165
+ query: {
166
+ _criteria: encodeForQuery({
167
+ associations: { states: {} },
168
+ limit: 1,
169
+ }),
170
+ },
171
+ }),
172
+ );
173
+ });
174
+
175
+ it("uses criteria passed to useCountries on mountedCallback", async () => {
176
+ const criteria: Schemas["Criteria"] = { limit: 1 };
177
+ const { vm, injections } = await useSetup(() => useCountries(criteria), {
178
+ apiClient: {
179
+ invoke: vi.fn().mockResolvedValue({ data: CountryMock }),
180
+ },
181
+ swCountries: ref(),
182
+ } as Parameters<typeof useSetup>[1]);
183
+
184
+ await vm.mountedCallback();
185
+
186
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
187
+ expect.stringContaining("readCountry post"),
188
+ expect.objectContaining({
189
+ body: {
190
+ associations: { states: {} },
191
+ limit: 1,
192
+ },
193
+ }),
194
+ );
195
+ });
196
+
126
197
  it("should not fetch when swCountries already populated", async () => {
127
198
  const preloadedCountries = ref(CountryMock.elements);
128
- const { vm, injections } = await useSetup(useCountries, {
199
+ const { vm, injections } = await useSetup(() => useCountries(), {
129
200
  apiClient: { invoke: vi.fn() },
130
201
  swCountries: preloadedCountries,
131
202
  } as Parameters<typeof useSetup>[1]);
@@ -1,4 +1,5 @@
1
1
  import { encodeForQuery } from "@shopware/api-client/helpers";
2
+ import { defu } from "defu";
2
3
  import { computed, inject, onMounted, provide, ref } from "vue";
3
4
  import type { ComputedRef } from "vue";
4
5
 
@@ -25,24 +26,27 @@ export type UseCountriesReturn = {
25
26
  * @public
26
27
  * @category Context & Language
27
28
  */
28
- export function useCountries(): UseCountriesReturn {
29
+ export function useCountries(
30
+ criteria?: Schemas["Criteria"],
31
+ ): UseCountriesReturn {
29
32
  const { apiClient, cacheableReads } = useShopwareContext();
30
33
 
31
34
  const _sharedCountries = inject("swCountries", ref());
32
35
  provide("swCountries", _sharedCountries);
36
+ const searchCriteria = ref(criteria ?? {});
33
37
 
34
38
  async function fetchCountries() {
35
- const criteria = {
39
+ const queryCriteria = defu(searchCriteria.value, {
36
40
  associations: {
37
41
  states: {},
38
42
  },
39
- };
43
+ } as Schemas["Criteria"]);
40
44
  const result = cacheableReads
41
45
  ? await apiClient.invoke("readCountryGet get /country", {
42
- query: { _criteria: encodeForQuery(criteria) },
46
+ query: { _criteria: encodeForQuery(queryCriteria) },
43
47
  })
44
48
  : await apiClient.invoke("readCountry post /country", {
45
- body: criteria,
49
+ body: queryCriteria,
46
50
  });
47
51
  _sharedCountries.value = result.data.elements;
48
52
  return result.data;
@@ -1,3 +1,4 @@
1
+ import { encodeForQuery } from "@shopware/api-client/helpers";
1
2
  import { describe, expect, it } from "vitest";
2
3
  import { ref } from "vue";
3
4
 
@@ -15,8 +16,46 @@ describe("useProductReviews", () => {
15
16
  });
16
17
  await vm.loadProductReviews();
17
18
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
18
- expect.stringContaining("readProductReviews"),
19
- expect.objectContaining({}),
19
+ expect.stringContaining("readProductReviews post"),
20
+ expect.objectContaining({
21
+ body: {},
22
+ pathParams: {
23
+ productId: ProductMock.id,
24
+ },
25
+ }),
26
+ );
27
+ expect(vm.productReviews).toEqual([{ id: "1", content: "Great!" }]);
28
+ });
29
+
30
+ it("load product reviews uses GET when cacheableReads is enabled", async () => {
31
+ const { vm, injections } = useSetup(
32
+ () => useProductReviews(ref(ProductMock)),
33
+ {
34
+ shopware: { cacheableReads: true },
35
+ },
36
+ );
37
+ injections.apiClient.invoke.mockResolvedValue({
38
+ data: { elements: [{ id: "1", content: "Great!" }] },
39
+ });
40
+
41
+ await vm.loadProductReviews({
42
+ limit: 5,
43
+ sort: [{ field: "createdAt", order: "DESC" }],
44
+ });
45
+
46
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
47
+ expect.stringContaining("readProductReviewsGet get"),
48
+ expect.objectContaining({
49
+ pathParams: {
50
+ productId: ProductMock.id,
51
+ },
52
+ query: {
53
+ _criteria: encodeForQuery({
54
+ limit: 5,
55
+ sort: [{ field: "createdAt", order: "DESC" }],
56
+ }),
57
+ },
58
+ }),
20
59
  );
21
60
  expect(vm.productReviews).toEqual([{ id: "1", content: "Great!" }]);
22
61
  });
@@ -1,3 +1,4 @@
1
+ import { encodeForQuery } from "@shopware/api-client/helpers";
1
2
  import { computed, ref } from "vue";
2
3
  import type { ComputedRef, Ref } from "vue";
3
4
 
@@ -39,7 +40,7 @@ export type UseProductReviewsReturn = {
39
40
  export function useProductReviews(
40
41
  product: Ref<Schemas["Product"]>,
41
42
  ): UseProductReviewsReturn {
42
- const { apiClient } = useShopwareContext();
43
+ const { apiClient, cacheableReads } = useShopwareContext();
43
44
 
44
45
  const productReviews: Ref<Schemas["ProductReview"][]> = ref([]);
45
46
 
@@ -48,13 +49,21 @@ export function useProductReviews(
48
49
  ): Promise<
49
50
  operations["readProductReviews post /product/{productId}/reviews"]["response"]
50
51
  > => {
51
- const fetchedReviews = await apiClient.invoke(
52
- "readProductReviews post /product/{productId}/reviews",
53
- {
54
- pathParams: { productId: product.value.id },
55
- body: parameters,
56
- },
57
- );
52
+ const fetchedReviews = cacheableReads
53
+ ? await apiClient.invoke(
54
+ "readProductReviewsGet get /product/{productId}/reviews",
55
+ {
56
+ pathParams: { productId: product.value.id },
57
+ query: { _criteria: encodeForQuery(parameters) },
58
+ },
59
+ )
60
+ : await apiClient.invoke(
61
+ "readProductReviews post /product/{productId}/reviews",
62
+ {
63
+ pathParams: { productId: product.value.id },
64
+ body: parameters,
65
+ },
66
+ );
58
67
  productReviews.value = fetchedReviews.data.elements ?? [];
59
68
  return fetchedReviews.data;
60
69
  };
@@ -1,15 +1,18 @@
1
- import { describe, expect, it, vi } from "vitest";
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
2
 
3
3
  import type { Schemas } from "#shopware";
4
4
 
5
5
  import { useSetup } from "../_test";
6
6
  import { useSessionContext } from "./useSessionContext";
7
7
 
8
- const consoleErrorSpy = vi.spyOn(console, "error");
9
- consoleErrorSpy.mockImplementation(() => {});
10
-
11
8
  describe("useSessionContext", () => {
12
9
  const consoleErrorSpy = vi.spyOn(console, "error");
10
+ consoleErrorSpy.mockImplementation(() => {});
11
+
12
+ afterEach(() => {
13
+ vi.clearAllMocks();
14
+ });
15
+
13
16
  it("setLanguage", () => {
14
17
  const { vm, injections } = useSetup(() => useSessionContext());
15
18
  injections.apiClient.invoke.mockResolvedValue({ data: {} });
@@ -57,15 +60,16 @@ describe("useSessionContext", () => {
57
60
  });
58
61
 
59
62
  it("refreshSessionContext - error", async () => {
63
+ const error = new Error("error test");
60
64
  const { vm } = useSetup(() => useSessionContext(), {
61
65
  apiClient: {
62
66
  invoke: vi.fn().mockImplementation(() => {
63
- throw new Error("error test");
67
+ throw error;
64
68
  }),
65
69
  },
66
70
  });
67
71
  consoleErrorSpy.mockImplementation(() => {});
68
- await vm.refreshSessionContext();
72
+ await expect(vm.refreshSessionContext()).rejects.toThrow(error);
69
73
  expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
70
74
  });
71
75
 
@@ -117,6 +121,62 @@ describe("useSessionContext", () => {
117
121
  );
118
122
  });
119
123
 
124
+ it("setActiveShippingAddress waits for refreshed context", async () => {
125
+ const { vm, injections } = useSetup(() => useSessionContext());
126
+ const calls: string[] = [];
127
+ injections.apiClient.invoke.mockImplementation(async (route) => {
128
+ calls.push(route);
129
+ return { data: {} };
130
+ });
131
+
132
+ await vm.setActiveShippingAddress({ id: "shipping-address-id" });
133
+
134
+ expect(calls).toEqual([
135
+ expect.stringContaining("updateContext"),
136
+ expect.stringContaining("readContext"),
137
+ ]);
138
+ });
139
+
140
+ it("setActiveShippingAddress rejects when refreshed context fails", async () => {
141
+ const error = new Error("refresh failed");
142
+ const { vm, injections } = useSetup(() => useSessionContext());
143
+ injections.apiClient.invoke
144
+ .mockResolvedValueOnce({ data: {} })
145
+ .mockRejectedValueOnce(error);
146
+
147
+ await expect(
148
+ vm.setActiveShippingAddress({ id: "shipping-address-id" }),
149
+ ).rejects.toThrow(error);
150
+ });
151
+
152
+ it("setActiveBillingAddress waits for refreshed context", async () => {
153
+ const { vm, injections } = useSetup(() => useSessionContext());
154
+ const calls: string[] = [];
155
+ injections.apiClient.invoke.mockImplementation(async (route) => {
156
+ calls.push(route);
157
+ return { data: {} };
158
+ });
159
+
160
+ await vm.setActiveBillingAddress({ id: "billing-address-id" });
161
+
162
+ expect(calls).toEqual([
163
+ expect.stringContaining("updateContext"),
164
+ expect.stringContaining("readContext"),
165
+ ]);
166
+ });
167
+
168
+ it("setActiveBillingAddress rejects when refreshed context fails", async () => {
169
+ const error = new Error("refresh failed");
170
+ const { vm, injections } = useSetup(() => useSessionContext());
171
+ injections.apiClient.invoke
172
+ .mockResolvedValueOnce({ data: {} })
173
+ .mockRejectedValueOnce(error);
174
+
175
+ await expect(
176
+ vm.setActiveBillingAddress({ id: "billing-address-id" }),
177
+ ).rejects.toThrow(error);
178
+ });
179
+
120
180
  it("setPaymentMethod", async () => {
121
181
  const { vm, injections } = useSetup(() => useSessionContext());
122
182
  injections.apiClient.invoke.mockResolvedValue({ data: {} });
@@ -21,6 +21,10 @@ export type UseSessionContextReturn = {
21
21
  sessionContext: ComputedRef<Schemas["SalesChannelContext"] | undefined>;
22
22
  /**
23
23
  * Fetches the session context and assigns the result to the `sessionContext` property
24
+ *
25
+ * Throws when the context cannot be loaded. Callers that depend on a verified
26
+ * context switch, such as logout or checkout flows, should block progression
27
+ * when this fails.
24
28
  */
25
29
  refreshSessionContext(): Promise<void>;
26
30
  /**
@@ -137,6 +141,7 @@ export function useSessionContext(
137
141
  _sessionContext.value = data;
138
142
  } catch (e) {
139
143
  console.error("[UseSessionContext][refreshSessionContext]", e);
144
+ throw e;
140
145
  }
141
146
  };
142
147
 
@@ -227,7 +232,7 @@ export function useSessionContext(
227
232
  shippingAddressId: address.id,
228
233
  },
229
234
  });
230
- refreshSessionContext();
235
+ await refreshSessionContext();
231
236
  };
232
237
 
233
238
  // TODO: replace the source from defaultBillingAddress by new value once NEXT-28627 is solved
@@ -247,7 +252,7 @@ export function useSessionContext(
247
252
  billingAddressId: address.id,
248
253
  },
249
254
  });
250
- refreshSessionContext();
255
+ await refreshSessionContext();
251
256
  };
252
257
 
253
258
  const setContext = (context: Schemas["SalesChannelContext"]) => {
@@ -56,6 +56,8 @@ const REGISTRATION_DATA: Omit<
56
56
 
57
57
  describe("useUser", () => {
58
58
  afterEach(() => {
59
+ vi.clearAllMocks();
60
+ refreshSessionContextSpy.mockReset();
59
61
  userFromContextRef.value = undefined;
60
62
  });
61
63
 
@@ -151,9 +153,27 @@ describe("useUser", () => {
151
153
  expect(injections.apiClient.invoke).toHaveBeenCalledWith(
152
154
  expect.stringContaining("logoutCustomer"),
153
155
  );
156
+ expect(refreshSessionContextSpy).toHaveBeenCalled();
157
+ expect(refreshCartSpy).toHaveBeenCalled();
154
158
  expect(result).toEqual(logoutResponse.data);
155
159
  });
156
160
 
161
+ it("logout rejects when the session context cannot be verified", async () => {
162
+ const { vm, injections } = useSetup(() => useUser());
163
+ const error = new Error("context refresh failed");
164
+ injections.apiClient.invoke.mockResolvedValue({
165
+ data: { redirectUrl: "/" },
166
+ });
167
+ refreshSessionContextSpy.mockRejectedValue(error);
168
+
169
+ await expect(vm.logout()).rejects.toThrow(error);
170
+
171
+ expect(injections.apiClient.invoke).toHaveBeenCalledWith(
172
+ expect.stringContaining("logoutCustomer"),
173
+ );
174
+ expect(refreshCartSpy).not.toHaveBeenCalled();
175
+ });
176
+
157
177
  it("refreshUser", async () => {
158
178
  const { vm, injections } = useSetup(() => useUser());
159
179
  const customerData = { id: "cust-1", email: "test@test.com" };