@shopbite-de/storefront 2.2.0 → 2.3.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 (61) hide show
  1. package/CLAUDE.md +11 -6
  2. package/app/app.vue +9 -6
  3. package/app/components/Category/Breadcrumb.vue +9 -10
  4. package/app/components/Category/Listing.vue +0 -1
  5. package/app/components/Checkout/Summary.vue +27 -2
  6. package/app/components/Header.vue +2 -2
  7. package/app/components/Menu/BonCard.vue +0 -13
  8. package/app/components/Product/FoodLabels.vue +47 -20
  9. package/app/components/Product/QuickView.vue +1 -1
  10. package/app/components/Sb/Icon.vue +3 -1
  11. package/app/composables/useBusinessHours.ts +35 -14
  12. package/app/composables/useHolidays.ts +31 -11
  13. package/app/composables/useHomeMenuCategories.ts +6 -34
  14. package/app/composables/useLiveShopData.ts +17 -0
  15. package/app/composables/useNavigation.ts +14 -66
  16. package/app/composables/useNavigationSearch.ts +8 -31
  17. package/app/composables/useRestaurantSchema.ts +2 -13
  18. package/app/composables/useSeoUrlRoute.ts +21 -0
  19. package/app/composables/useShopBiteConfig.ts +50 -6
  20. package/app/composables/useTopSellers.ts +2 -43
  21. package/app/error.vue +4 -0
  22. package/app/utils/product.ts +1 -62
  23. package/docs/notes/2026-09-10-issue-275-accessibility.md +2 -2
  24. package/docs/notes/2026-09-12-issue-327-home-hero.md +1 -1
  25. package/docs/notes/2026-09-13-issue-332-home-info-cards.md +1 -3
  26. package/docs/notes/2026-09-21-issue-273-cache-and-demo-video.md +1 -1
  27. package/docs/notes/2026-09-21-issue-363-non-fatal-404.md +1 -1
  28. package/docs/notes/2026-09-23-issue-388-home-sections.md +2 -2
  29. package/docs/notes/2026-10-05-issue-401-restaurant-schema-ordering.md +1 -1
  30. package/modules/theme.ts +1 -1
  31. package/nuxt.config.ts +13 -0
  32. package/package.json +5 -5
  33. package/server/api/_cache/purge.post.ts +6 -3
  34. package/server/api/breadcrumb/[categoryId].get.ts +31 -0
  35. package/server/api/navigation/[type].get.ts +97 -0
  36. package/server/api/payment-methods.get.ts +29 -0
  37. package/server/api/seo-url/index.get.ts +17 -0
  38. package/server/api/seo-url/known.get.ts +33 -0
  39. package/server/api/shopbite/business-hours.get.ts +22 -0
  40. package/server/api/shopbite/config.get.ts +6 -0
  41. package/server/api/shopbite/holidays.get.ts +20 -0
  42. package/server/api/top-sellers.get.ts +59 -0
  43. package/server/utils/backoff.ts +67 -0
  44. package/server/utils/cachePurge.ts +45 -12
  45. package/server/utils/menuRoot.ts +24 -18
  46. package/server/utils/seoPaths.ts +130 -0
  47. package/server/utils/seoUrlCache.ts +98 -0
  48. package/server/utils/shopBiteConfig.ts +30 -0
  49. package/server/utils/storeApi.ts +22 -0
  50. package/test/layer/nuxt.config.ts +1 -1
  51. package/test/nuxt/CheckoutSummary.test.ts +38 -2
  52. package/test/nuxt/ProductFoodLabels.test.ts +70 -0
  53. package/test/nuxt/liveShopData.test.ts +114 -0
  54. package/test/nuxt/useShopBiteConfig.test.ts +22 -0
  55. package/test/nuxt/useTopSellers.test.ts +10 -27
  56. package/test/unit/cachePurge.spec.ts +41 -0
  57. package/test/unit/layoutCacheRoutes.spec.ts +566 -0
  58. package/test/unit/nitroStubs.ts +99 -0
  59. package/test/unit/product.spec.ts +1 -23
  60. package/test/unit/seoPaths.spec.ts +117 -0
  61. package/app/components/Menu/FoodLabelLegend.vue +0 -28
@@ -0,0 +1,98 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { components } from "../../api-types/storeApiTypes";
3
+ import { createResilientLoader } from "./backoff";
4
+ import { isTechnicalPath, loadSeoPaths } from "./seoPaths";
5
+ type SeoUrl = components["schemas"]["SeoUrl"];
6
+
7
+ type Lookup = { field: "pathInfo" | "seoPathInfo"; value: string };
8
+
9
+ /**
10
+ * What Shopware compares a path with: technical URLs by `pathInfo` (without
11
+ * the trailing slash), SEO URLs by `seoPathInfo` (without the leading one).
12
+ */
13
+ export function seoUrlLookup(path: string): Lookup {
14
+ return isTechnicalPath(path)
15
+ ? { field: "pathInfo", value: path.replace(/\/$/, "") }
16
+ : { field: "seoPathInfo", value: path.substring(1) };
17
+ }
18
+
19
+ // backs off during an outage; nothing is remembered (the cache keeps the
20
+ // exact matches)
21
+ const lookupLoader = createResilientLoader<{ elements?: SeoUrl[] }>(
22
+ () => false,
23
+ );
24
+
25
+ /**
26
+ * One SEO URL lookup. `exact` when the match spells the looked-up value
27
+ * (up to case): Shopware's collation also ignores accents and trailing
28
+ * spaces, and caching those variants would add an entry per spelling.
29
+ */
30
+ const cachedLookup = defineCachedFunction(
31
+ async (
32
+ field: Lookup["field"],
33
+ value: string,
34
+ ): Promise<{ match: SeoUrl | null; exact: boolean }> => {
35
+ const result = await lookupLoader(`${field}:${value}`, () =>
36
+ storeApiPost<{ elements?: SeoUrl[] }>("/seo-url", {
37
+ limit: 1,
38
+ filter: [{ type: "equals", field, value }],
39
+ }),
40
+ );
41
+ const match = result.elements?.[0] ?? null;
42
+ const spelled = match?.[field];
43
+ return {
44
+ match,
45
+ exact:
46
+ typeof spelled === "string" &&
47
+ spelled.toLowerCase() === value.toLowerCase(),
48
+ };
49
+ },
50
+ {
51
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.seoUrl,
52
+ // a renamed section must not keep its old match beyond the TTL
53
+ swr: false,
54
+ name: "seo-url",
55
+ // the field keeps `/Navigation/<id>` (a SEO path) apart from the
56
+ // technical `/navigation/<id>`
57
+ getKey: (field: Lookup["field"], value: string) =>
58
+ createHash("sha1")
59
+ .update(`${field}:${value.toLowerCase()}`)
60
+ .digest("hex"),
61
+ // only exact matches: misses and loose spellings (a scanner probing
62
+ // `/wp-admin/` or `/Pizza/%20`) never create an entry
63
+ validate: (entry) =>
64
+ Boolean((entry.value as { exact?: boolean } | undefined)?.exact),
65
+ },
66
+ );
67
+
68
+ /** The canonical SEO URL of a path (/api/seo-url for useNavigationSearch). */
69
+ export async function findSeoUrl(path: string): Promise<SeoUrl | null> {
70
+ const { field, value } = seoUrlLookup(path);
71
+ return (await cachedLookup(field, value)).match;
72
+ }
73
+
74
+ /**
75
+ * All category SEO paths (server/utils/seoPaths.ts). `paths: null` (more
76
+ * than fit the pages) is kept for the TTL like a list; a failure throws and
77
+ * is not cached (/api/seo-url/known backs off instead). `loadedAt` lets the
78
+ * route reuse its Set until the entry changes.
79
+ */
80
+ export const knownSeoPaths = defineCachedFunction(
81
+ async (): Promise<{ paths: string[] | null; loadedAt: number }> => ({
82
+ paths: await loadSeoPaths(async (criteria) => {
83
+ const result = await storeApiPost<{ elements?: SeoUrl[] }>(
84
+ "/seo-url",
85
+ criteria,
86
+ );
87
+ return result.elements ?? [];
88
+ }),
89
+ loadedAt: Date.now(),
90
+ }),
91
+ {
92
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.seoUrl,
93
+ // a new section must not 404 beyond the TTL
94
+ swr: false,
95
+ name: "seo-paths",
96
+ getKey: () => "seo-paths",
97
+ },
98
+ );
@@ -0,0 +1,30 @@
1
+ import type { components } from "../../api-types/storeApiTypes";
2
+ import { createResilientLoader } from "./backoff";
3
+ type ShopBiteConfig = components["schemas"]["ShopBiteConfig"];
4
+
5
+ /**
6
+ * `swr: false`: an answer is never older than `cacheTtl.config`. A failed
7
+ * request throws and is not cached.
8
+ */
9
+ const cachedConfig = defineCachedFunction(
10
+ async (): Promise<ShopBiteConfig> => await storeApiGet("/shopbite/config"),
11
+ {
12
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.config,
13
+ swr: false,
14
+ name: "shopbite-config",
15
+ getKey: () => "shopbite-config",
16
+ },
17
+ );
18
+
19
+ const load = createResilientLoader<ShopBiteConfig>();
20
+
21
+ /**
22
+ * The ShopBite plugin configuration (delivery time, checkout switch, menu
23
+ * root) for server-side rendering, `/api/shopbite/config` and the menu root.
24
+ * When Shopware fails, the last good configuration is kept (the menu stays
25
+ * on its root) and Shopware is asked again only after a pause, so an outage
26
+ * does not multiply the requests; without one it throws.
27
+ */
28
+ export function shopBiteConfig(): Promise<ShopBiteConfig> {
29
+ return load("shopbite-config", () => cachedConfig());
30
+ }
@@ -30,5 +30,27 @@ export function storeApiPost<T>(
30
30
  method: "POST",
31
31
  headers: { "sw-access-key": accessToken, ...options.headers },
32
32
  body,
33
+ // a failing request reaches Shopware once (the cached routes back off
34
+ // instead)
35
+ retry: 0,
36
+ });
37
+ }
38
+
39
+ /**
40
+ * Calls a Store API route that takes no criteria (the ShopBite plugin's
41
+ * config, business hours and holidays) with the storefront's access key.
42
+ */
43
+ export function storeApiGet<T>(
44
+ path: string,
45
+ options: Pick<NitroFetchOptions<string>, "headers" | "query"> = {},
46
+ ): Promise<T> {
47
+ const { endpoint, accessToken } = useRuntimeConfig().public.shopware;
48
+
49
+ return $fetch<T>(`${endpoint}${path}`, {
50
+ headers: { "sw-access-key": accessToken, ...options.headers },
51
+ query: options.query,
52
+ // ofetch retries a GET once by default; during an outage that doubles
53
+ // every request
54
+ retry: 0,
33
55
  });
34
56
  }
@@ -1,5 +1,5 @@
1
1
  // A minimal shop that extends the storefront like the real shops do (La
2
- // Fattoria, quickstart, lead demos). CI builds it to catch imports that only
2
+ // Fattoria, the quickstart). CI builds it to catch imports that only
3
3
  // resolve inside the storefront itself, e.g. the `#shared` alias, which in a
4
4
  // layer points to the shop's shared/ folder (2.0.1).
5
5
  export default defineNuxtConfig({
@@ -3,7 +3,11 @@ import { mountSuspended, mockNuxtImport } from "@nuxt/test-utils/runtime";
3
3
  import { defineComponent, h, onMounted, ref } from "vue";
4
4
  import Summary from "~/components/Checkout/Summary.vue";
5
5
 
6
- const { state } = vi.hoisted(() => ({
6
+ const { state, mocks } = vi.hoisted(() => ({
7
+ mocks: {
8
+ createOrder: vi.fn(),
9
+ checkCheckoutEnabled: vi.fn(),
10
+ },
7
11
  state: {
8
12
  isLoading: true,
9
13
  hasFailed: false,
@@ -19,7 +23,7 @@ mockNuxtImport("useOpeningHoursData", () => () => ({
19
23
  }));
20
24
 
21
25
  mockNuxtImport("useCheckout", () => () => ({
22
- createOrder: vi.fn(),
26
+ createOrder: mocks.createOrder,
23
27
  selectedPaymentMethod: ref({ id: "pm1" }),
24
28
  selectedShippingMethod: ref({ id: "sm1", name: "Lieferung" }),
25
29
  }));
@@ -37,6 +41,7 @@ mockNuxtImport("useUser", () => () => ({
37
41
  mockNuxtImport("useShopBiteConfig", () => () => ({
38
42
  isCheckoutEnabled: ref(true),
39
43
  refresh: vi.fn(),
44
+ checkCheckoutEnabled: mocks.checkCheckoutEnabled,
40
45
  }));
41
46
 
42
47
  mockNuxtImport("useTrackEvent", () => () => ({
@@ -160,4 +165,35 @@ describe("Checkout Summary order button", () => {
160
165
  );
161
166
  expect(page.querySelector('[role="alert"]')).toBeNull();
162
167
  });
168
+
169
+ it("does not order when Shopware says the checkout was switched off", async () => {
170
+ state.isLoading = false;
171
+ state.validTime = true;
172
+ mocks.checkCheckoutEnabled.mockResolvedValue(false);
173
+
174
+ const button = await mountSummary();
175
+ await button.trigger("click");
176
+ await new Promise((resolve) => setTimeout(resolve, 0));
177
+
178
+ expect(mocks.checkCheckoutEnabled).toHaveBeenCalled();
179
+ expect(mocks.createOrder).not.toHaveBeenCalled();
180
+ expect(button.element.closest(".grid")!.textContent).toContain(
181
+ "Es werden aktuell keine weiteren Bestellungen mehr aufgenommen",
182
+ );
183
+ });
184
+
185
+ it("does not order when the checkout switch cannot be checked", async () => {
186
+ state.isLoading = false;
187
+ state.validTime = true;
188
+ mocks.checkCheckoutEnabled.mockResolvedValue(null);
189
+
190
+ const button = await mountSummary();
191
+ await button.trigger("click");
192
+ await new Promise((resolve) => setTimeout(resolve, 0));
193
+
194
+ expect(mocks.createOrder).not.toHaveBeenCalled();
195
+ expect(button.element.closest(".grid")!.textContent).toContain(
196
+ "konnte nicht geprüft werden",
197
+ );
198
+ });
163
199
  });
@@ -0,0 +1,70 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { mountSuspended } from "@nuxt/test-utils/runtime";
3
+ import { flushPromises } from "@vue/test-utils";
4
+ import type { Schemas } from "#shopware";
5
+ import ProductFoodLabels from "~/components/Product/FoodLabels.vue";
6
+
7
+ const option = (code: string, name: string) => ({
8
+ name,
9
+ translated: { name, customFields: { shopbite_code: code } },
10
+ });
11
+
12
+ const dish = (
13
+ allergens: [string, string][],
14
+ checked = false,
15
+ ): Schemas["Product"] =>
16
+ ({
17
+ translated: {
18
+ customFields: checked ? { shopbite_allergens_checked: true } : {},
19
+ },
20
+ sortedProperties: allergens.length
21
+ ? [
22
+ {
23
+ translated: { name: "Allergene" },
24
+ options: allergens.map(([code, name]) => option(code, name)),
25
+ },
26
+ ]
27
+ : [],
28
+ }) as unknown as Schemas["Product"];
29
+
30
+ async function openPopover(product: Schemas["Product"]) {
31
+ const wrapper = await mountSuspended(ProductFoodLabels, {
32
+ props: { product },
33
+ attachTo: document.body,
34
+ });
35
+ const button = wrapper.get("button");
36
+ expect(button.attributes("aria-label")).toBe("Allergene und Zusatzstoffe");
37
+ expect(wrapper.find('[data-testid="food-labels"]').exists()).toBe(false);
38
+ await button.trigger("click");
39
+ await flushPromises();
40
+ return wrapper;
41
+ }
42
+
43
+ describe("food labels behind the info button (#500)", () => {
44
+ it("shows the allergens only after a click", async () => {
45
+ const wrapper = await openPopover(
46
+ dish([
47
+ ["A", "Weizen"],
48
+ ["G", "Milch (inkl. Laktose)"],
49
+ ]),
50
+ );
51
+ expect(wrapper.get('[data-testid="food-labels"]').text()).toContain(
52
+ "Enthält: Weizen, Milch (inkl. Laktose).",
53
+ );
54
+ wrapper.unmount();
55
+ });
56
+
57
+ it("says 'without' only when the restaurant checked the lists", async () => {
58
+ const checked = await openPopover(dish([], true));
59
+ expect(checked.get('[data-testid="food-labels"]').text()).toContain(
60
+ "Ohne kennzeichnungspflichtige Allergene und Zusatzstoffe.",
61
+ );
62
+ checked.unmount();
63
+
64
+ const unchecked = await openPopover(dish([]));
65
+ const text = unchecked.get('[data-testid="food-labels"]').text();
66
+ expect(text).toContain("Angaben erhalten Sie im Restaurant");
67
+ expect(text).not.toContain("Ohne");
68
+ unchecked.unmount();
69
+ });
70
+ });
@@ -0,0 +1,114 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import {
3
+ mockNuxtImport,
4
+ mountSuspended,
5
+ registerEndpoint,
6
+ } from "@nuxt/test-utils/runtime";
7
+ import { defineComponent, h } from "vue";
8
+ import {
9
+ loadShopBiteConfig,
10
+ SHOPBITE_CONFIG_KEY,
11
+ } from "~/composables/useShopBiteConfig";
12
+ import {
13
+ BUSINESS_HOURS_KEY,
14
+ loadBusinessHours,
15
+ } from "~/composables/useBusinessHours";
16
+ import { HOLIDAYS_KEY, loadHolidays } from "~/composables/useHolidays";
17
+ import { useLiveShopData } from "~/composables/useLiveShopData";
18
+
19
+ const { mockRefreshNuxtData, cached } = vi.hoisted(() => ({
20
+ mockRefreshNuxtData: vi.fn(),
21
+ cached: {
22
+ config: vi.fn(),
23
+ hours: vi.fn(),
24
+ holidays: vi.fn(),
25
+ },
26
+ }));
27
+
28
+ mockNuxtImport("refreshNuxtData", () => mockRefreshNuxtData);
29
+
30
+ registerEndpoint("/api/shopbite/config", () => cached.config());
31
+ registerEndpoint("/api/shopbite/business-hours", () => cached.hours());
32
+ registerEndpoint("/api/shopbite/holidays", () => cached.holidays());
33
+
34
+ const invoke = vi.fn();
35
+ const apiClient = { invoke } as unknown as Parameters<
36
+ typeof loadShopBiteConfig
37
+ >[0];
38
+
39
+ describe("shop data sources", () => {
40
+ beforeEach(() => {
41
+ vi.clearAllMocks();
42
+ });
43
+
44
+ it("renders the config from the server cache, the browser asks Shopware", async () => {
45
+ cached.config.mockReturnValue({ isCheckoutEnabled: false });
46
+ invoke.mockResolvedValue({ data: { isCheckoutEnabled: true } });
47
+
48
+ expect(await loadShopBiteConfig(apiClient, true)).toEqual({
49
+ isCheckoutEnabled: false,
50
+ });
51
+ expect(invoke).not.toHaveBeenCalled();
52
+
53
+ expect(await loadShopBiteConfig(apiClient, false)).toEqual({
54
+ isCheckoutEnabled: true,
55
+ });
56
+ expect(invoke).toHaveBeenCalledWith(
57
+ "shopbite.config.get get /shopbite/config",
58
+ );
59
+ });
60
+
61
+ it("retries the config in the browser like the opening hours", async () => {
62
+ invoke
63
+ .mockRejectedValueOnce(new Error("offline"))
64
+ .mockResolvedValue({ data: { isCheckoutEnabled: true } });
65
+
66
+ expect(await loadShopBiteConfig(apiClient, false, [0])).toEqual({
67
+ isCheckoutEnabled: true,
68
+ });
69
+ expect(invoke).toHaveBeenCalledTimes(2);
70
+ });
71
+
72
+ it("reads business hours and holidays from the cache on the server", async () => {
73
+ const hours = [{ dayOfWeek: 1, openingTime: "11:00" }];
74
+ const holidays = [{ start: "2026-12-24", end: "2026-12-26" }];
75
+ cached.hours.mockReturnValue({ businessHours: hours });
76
+ cached.holidays.mockReturnValue({ holidays });
77
+
78
+ expect(await loadBusinessHours(apiClient, true)).toEqual(hours);
79
+ expect(await loadHolidays(apiClient, true)).toEqual(holidays);
80
+ expect(invoke).not.toHaveBeenCalled();
81
+ });
82
+
83
+ it("asks Shopware for business hours and holidays in the browser", async () => {
84
+ invoke.mockImplementation(async (operation: string) =>
85
+ operation.includes("business-hour")
86
+ ? { data: { businessHours: ["h"] } }
87
+ : { data: { holidays: ["d"] } },
88
+ );
89
+
90
+ expect(await loadBusinessHours(apiClient, false, [])).toEqual(["h"]);
91
+ expect(await loadHolidays(apiClient, false, [])).toEqual(["d"]);
92
+ });
93
+ });
94
+
95
+ describe("useLiveShopData", () => {
96
+ it("reloads config, hours and holidays from Shopware after hydration", async () => {
97
+ await mountSuspended(
98
+ defineComponent({
99
+ setup() {
100
+ useLiveShopData();
101
+ return () => h("div");
102
+ },
103
+ }),
104
+ );
105
+
106
+ // refreshNuxtData waits for the end of hydration; a refresh() during
107
+ // hydration would return the server's (cached) payload
108
+ expect(mockRefreshNuxtData).toHaveBeenCalledWith([
109
+ SHOPBITE_CONFIG_KEY,
110
+ BUSINESS_HOURS_KEY,
111
+ HOLIDAYS_KEY,
112
+ ]);
113
+ });
114
+ });
@@ -52,4 +52,26 @@ describe("useShopBiteConfig", () => {
52
52
  expect(deliveryTime.value).toBe(45);
53
53
  expect(isCheckoutEnabled.value).toBe(true);
54
54
  });
55
+
56
+ it("checks the checkout switch with Shopware before an order", async () => {
57
+ mockInvoke.mockResolvedValue({
58
+ data: { deliveryTime: 30, isCheckoutEnabled: false },
59
+ });
60
+
61
+ const { checkCheckoutEnabled, isCheckoutEnabled } = useShopBiteConfig();
62
+
63
+ expect(await checkCheckoutEnabled()).toBe(false);
64
+ expect(isCheckoutEnabled.value).toBe(false);
65
+ expect(mockInvoke).toHaveBeenCalledWith(
66
+ "shopbite.config.get get /shopbite/config",
67
+ );
68
+ });
69
+
70
+ it("reports an unknown checkout switch when Shopware fails", async () => {
71
+ mockInvoke.mockRejectedValue(new Error("offline"));
72
+
73
+ const { checkCheckoutEnabled } = useShopBiteConfig();
74
+
75
+ expect(await checkCheckoutEnabled([])).toBeNull();
76
+ });
55
77
  });
@@ -1,44 +1,27 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import { mockNuxtImport } from "@nuxt/test-utils/runtime";
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import { registerEndpoint } from "@nuxt/test-utils/runtime";
3
3
  import { useTopSellers } from "~/composables/useTopSellers";
4
4
 
5
- const { mockInvoke } = vi.hoisted(() => ({
6
- mockInvoke: vi.fn(),
7
- }));
5
+ const { topSellers } = vi.hoisted(() => ({ topSellers: vi.fn() }));
8
6
 
9
- mockNuxtImport("useShopwareContext", () => {
10
- return () => ({
11
- apiClient: {
12
- invoke: mockInvoke,
13
- },
14
- });
15
- });
7
+ registerEndpoint("/api/top-sellers", () => topSellers());
16
8
 
17
9
  describe("useTopSellers", () => {
18
- beforeEach(() => {
19
- vi.clearAllMocks();
20
- });
21
-
22
- it("should load top sellers successfully", async () => {
10
+ it("should load top sellers from the server cache", async () => {
23
11
  const mockElements = [{ id: "1", name: "Top Product" }];
24
- mockInvoke.mockResolvedValue({
25
- data: {
26
- elements: mockElements,
27
- },
28
- });
12
+ topSellers.mockReturnValue(mockElements);
29
13
 
30
14
  const { loadTopSellers } = useTopSellers();
31
15
  const result = await loadTopSellers();
32
16
 
33
- expect(mockInvoke).toHaveBeenCalledWith(
34
- "readProduct post /product",
35
- expect.any(Object),
36
- );
17
+ expect(topSellers).toHaveBeenCalled();
37
18
  expect(result).toEqual(mockElements);
38
19
  });
39
20
 
40
21
  it("should return empty array on error", async () => {
41
- mockInvoke.mockRejectedValue(new Error("Network error"));
22
+ topSellers.mockImplementation(() => {
23
+ throw new Error("Network error");
24
+ });
42
25
 
43
26
  // Silence console.error for this test
44
27
  const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
@@ -16,6 +16,20 @@ const KEYS = [
16
16
  `cache:nitro:handlers:sitemap:urls.json`,
17
17
  `cache:nitro:routes:_:llmstxt.json`,
18
18
  ];
19
+ // layout data of every page, purged with any target
20
+ const LAYOUT_KEYS = [
21
+ `cache:nitro:handlers:navigation:navigationmenu${PIZZA}.json`,
22
+ `cache:nitro:handlers:navigation:navigationmainmainnavigation.json`,
23
+ `cache:nitro:handlers:breadcrumb:breadcrumb${PIZZA}.json`,
24
+ `cache:nitro:handlers:business-hours:businesshours.json`,
25
+ `cache:nitro:handlers:holidays:holidays.json`,
26
+ `cache:nitro:handlers:payment-methods:paymentmethods.json`,
27
+ `cache:nitro:handlers:top-sellers:topsellers.json`,
28
+ `cache:nitro:functions:seo-url:3f786850e387550fdab836ed7e6dc881de23001b.json`,
29
+ `cache:nitro:functions:seo-paths:seo-paths.json`,
30
+ `cache:nitro:functions:shopbite-config:shopbite-config.json`,
31
+ ];
32
+ const OTHER_FUNCTION = `cache:nitro:functions:_:abc.json`;
19
33
 
20
34
  describe("keysToPurge", () => {
21
35
  it("purges every Store API cache without a target", () => {
@@ -45,6 +59,33 @@ describe("keysToPurge", () => {
45
59
  ]);
46
60
  });
47
61
 
62
+ it("purges the layout data with every target", () => {
63
+ const keys = [...KEYS, ...LAYOUT_KEYS, OTHER_FUNCTION];
64
+ for (const target of [
65
+ {},
66
+ { products: [MARGHERITA] },
67
+ { categories: [PIZZA] },
68
+ ]) {
69
+ const purged = keysToPurge(keys, target);
70
+ expect(purged).toEqual(expect.arrayContaining(LAYOUT_KEYS));
71
+ expect(purged).not.toContain(OTHER_FUNCTION);
72
+ }
73
+ });
74
+
75
+ it("purges only the layout data and llms.txt for a layout target", () => {
76
+ const keys = [...KEYS, ...LAYOUT_KEYS, OTHER_FUNCTION];
77
+ const layout = LAYOUT_KEYS.filter((k) => !k.includes("top-sellers"));
78
+ expect(keysToPurge(keys, { layout: true })).toEqual([KEYS[8], ...layout]);
79
+ });
80
+
81
+ it("adds the layout data to a menu target, not other products", () => {
82
+ const keys = [...KEYS, ...LAYOUT_KEYS];
83
+ const purged = keysToPurge(keys, { products: [SCHNITZEL], layout: true });
84
+ expect(purged).toEqual(expect.arrayContaining(LAYOUT_KEYS));
85
+ expect(purged).toContain(KEYS[1]);
86
+ expect(purged).not.toContain(KEYS[0]);
87
+ });
88
+
48
89
  it("finds ids written with dashes or upper case", () => {
49
90
  const dashed = `0197BAF0-A6A9-71EA-ADA5-9ED5C84138DE`;
50
91
  expect(keysToPurge(KEYS, { products: [dashed] })).toContain(KEYS[0]);