@shopbite-de/storefront 2.2.1 → 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 (52) hide show
  1. package/CLAUDE.md +10 -5
  2. package/app/app.vue +9 -6
  3. package/app/components/Category/Breadcrumb.vue +9 -10
  4. package/app/components/Checkout/Summary.vue +27 -2
  5. package/app/components/Header.vue +2 -2
  6. package/app/composables/useBusinessHours.ts +35 -14
  7. package/app/composables/useHolidays.ts +31 -11
  8. package/app/composables/useHomeMenuCategories.ts +6 -34
  9. package/app/composables/useLiveShopData.ts +17 -0
  10. package/app/composables/useNavigation.ts +14 -66
  11. package/app/composables/useNavigationSearch.ts +8 -31
  12. package/app/composables/useRestaurantSchema.ts +2 -13
  13. package/app/composables/useSeoUrlRoute.ts +21 -0
  14. package/app/composables/useShopBiteConfig.ts +50 -6
  15. package/app/composables/useTopSellers.ts +2 -43
  16. package/app/error.vue +4 -0
  17. package/docs/notes/2026-09-10-issue-275-accessibility.md +2 -2
  18. package/docs/notes/2026-09-12-issue-327-home-hero.md +1 -1
  19. package/docs/notes/2026-09-13-issue-332-home-info-cards.md +1 -3
  20. package/docs/notes/2026-09-21-issue-273-cache-and-demo-video.md +1 -1
  21. package/docs/notes/2026-09-21-issue-363-non-fatal-404.md +1 -1
  22. package/docs/notes/2026-09-23-issue-388-home-sections.md +2 -2
  23. package/docs/notes/2026-10-05-issue-401-restaurant-schema-ordering.md +1 -1
  24. package/modules/theme.ts +1 -1
  25. package/nuxt.config.ts +13 -0
  26. package/package.json +4 -4
  27. package/server/api/_cache/purge.post.ts +6 -3
  28. package/server/api/breadcrumb/[categoryId].get.ts +31 -0
  29. package/server/api/navigation/[type].get.ts +97 -0
  30. package/server/api/payment-methods.get.ts +29 -0
  31. package/server/api/seo-url/index.get.ts +17 -0
  32. package/server/api/seo-url/known.get.ts +33 -0
  33. package/server/api/shopbite/business-hours.get.ts +22 -0
  34. package/server/api/shopbite/config.get.ts +6 -0
  35. package/server/api/shopbite/holidays.get.ts +20 -0
  36. package/server/api/top-sellers.get.ts +59 -0
  37. package/server/utils/backoff.ts +67 -0
  38. package/server/utils/cachePurge.ts +45 -12
  39. package/server/utils/menuRoot.ts +24 -18
  40. package/server/utils/seoPaths.ts +130 -0
  41. package/server/utils/seoUrlCache.ts +98 -0
  42. package/server/utils/shopBiteConfig.ts +30 -0
  43. package/server/utils/storeApi.ts +22 -0
  44. package/test/layer/nuxt.config.ts +1 -1
  45. package/test/nuxt/CheckoutSummary.test.ts +38 -2
  46. package/test/nuxt/liveShopData.test.ts +114 -0
  47. package/test/nuxt/useShopBiteConfig.test.ts +22 -0
  48. package/test/nuxt/useTopSellers.test.ts +10 -27
  49. package/test/unit/cachePurge.spec.ts +41 -0
  50. package/test/unit/layoutCacheRoutes.spec.ts +566 -0
  51. package/test/unit/nitroStubs.ts +99 -0
  52. package/test/unit/seoPaths.spec.ts +117 -0
@@ -1,14 +1,58 @@
1
+ import type { Schemas } from "#shopware";
2
+
3
+ export const SHOPBITE_CONFIG_KEY = "shopbite-config";
4
+
5
+ type ApiClient = ReturnType<typeof useShopwareContext>["apiClient"];
6
+
7
+ /**
8
+ * The plugin configuration: from the server's short-lived cache
9
+ * (`/api/shopbite/config`, `cacheTtl.config`) for server-side rendering,
10
+ * from Shopware in the browser. The plugin does not enforce the checkout
11
+ * switch itself, so the browser's value must be fresh: app.vue reloads it
12
+ * after hydration (useLiveShopData), the checkout every 10 s.
13
+ */
14
+ export async function loadShopBiteConfig(
15
+ apiClient: ApiClient,
16
+ fromServerCache: boolean,
17
+ retryDelays: readonly number[] = OPENING_HOURS_RETRY_DELAYS,
18
+ ): Promise<Schemas["ShopBiteConfig"]> {
19
+ if (fromServerCache) {
20
+ return await $fetch<Schemas["ShopBiteConfig"]>("/api/shopbite/config");
21
+ }
22
+ // retried in the browser like the opening hours (#355)
23
+ const { data } = await withRetries(
24
+ () => apiClient.invoke("shopbite.config.get get /shopbite/config"),
25
+ retryDelays,
26
+ );
27
+ return data;
28
+ }
29
+
1
30
  export function useShopBiteConfig() {
2
31
  const { apiClient } = useShopwareContext();
3
32
 
4
- const { data, refresh } = useAsyncData("shopbite-config", async () => {
5
- const { data } = await apiClient.invoke(
6
- "shopbite.config.get get /shopbite/config",
7
- );
8
- return data;
9
- });
33
+ const { data, refresh } = useAsyncData(SHOPBITE_CONFIG_KEY, () =>
34
+ loadShopBiteConfig(apiClient, import.meta.server),
35
+ );
36
+
37
+ /**
38
+ * Asks Shopware (never the server cache) right before an order: the
39
+ * plugin does not refuse orders itself, so the checkout must not act on
40
+ * a value from the server render. `null` when it cannot be checked.
41
+ */
42
+ async function checkCheckoutEnabled(
43
+ retryDelays?: readonly number[],
44
+ ): Promise<boolean | null> {
45
+ try {
46
+ data.value = await loadShopBiteConfig(apiClient, false, retryDelays);
47
+ } catch (error) {
48
+ console.error("[checkout][checkCheckoutEnabled]", error);
49
+ return null;
50
+ }
51
+ return data.value?.isCheckoutEnabled ?? false;
52
+ }
10
53
 
11
54
  return {
55
+ checkCheckoutEnabled,
12
56
  deliveryTime: computed(() => data.value?.deliveryTime ?? 30),
13
57
  isCheckoutEnabled: computed(() => data.value?.isCheckoutEnabled ?? false),
14
58
  refresh,
@@ -4,52 +4,11 @@ export type useTopSellersReturn = {
4
4
  loadTopSellers(): Promise<Schemas["Product"][]>;
5
5
  };
6
6
 
7
- const TOP_SELLERS_LIMIT = 8;
8
-
9
7
  export function useTopSellers(): useTopSellersReturn {
10
- const { apiClient } = useShopwareContext();
11
8
  async function loadTopSellers() {
12
9
  try {
13
- const result = await apiClient.invoke("readProduct post /product", {
14
- // Variants marked as top sellers inherit name, cover and properties.
15
-
16
- // @ts-expect-error sw-inheritance is missing from the generated header type
17
- headers: { "sw-inheritance": "true", "sw-include-seo-urls": "true" },
18
- body: {
19
- filter: [{ type: "equals", field: "markAsTopseller", value: true }],
20
- limit: TOP_SELLERS_LIMIT,
21
- // What the compact card and the quick view need (#327).
22
- includes: {
23
- product: [
24
- "id",
25
- "productNumber",
26
- "name",
27
- "translated",
28
- "description",
29
- "calculatedPrice",
30
- "available",
31
- "cover",
32
- "sortedProperties",
33
- // Allergens checked (#485); includes filter `translated` as well,
34
- // so custom fields only come back when listed here.
35
- "customFields",
36
- // Card link to the quick view deep link (#289).
37
- "seoUrls",
38
- ],
39
- seo_url: ["seoPathInfo", "isCanonical"],
40
- product_media: ["media"],
41
- media: ["url", "thumbnails"],
42
- media_thumbnail: ["width", "url"],
43
- property_group: ["id", "name", "translated", "options"],
44
- property_group_option: ["id", "name", "translated", "customFields"],
45
- },
46
- associations: {
47
- cover: { associations: { media: {} } },
48
- properties: { associations: { group: {} } },
49
- },
50
- },
51
- });
52
- return result.data.elements;
10
+ // Cached on the server like the listings (server/api/top-sellers).
11
+ return await $fetch<Schemas["Product"][]>("/api/top-sellers");
53
12
  } catch (e) {
54
13
  console.error("[useTopSellers][loadTopSellers]", e);
55
14
  return [];
package/app/error.vue CHANGED
@@ -13,6 +13,10 @@ const pageTitle = computed(() => `${statusCode} | ${site?.name}`);
13
13
 
14
14
  console.error(props.error);
15
15
 
16
+ // error.vue replaces app.vue: load the checkout switch, hours and closing
17
+ // days from Shopware after hydration here as well (useLiveShopData).
18
+ useLiveShopData();
19
+
16
20
  const statusCode = props.error.statusCode;
17
21
 
18
22
  useSeoMeta({
@@ -25,7 +25,7 @@ So the storefront default and both demos fail in light mode as well; nobody had
25
25
  - Contrast: Nuxt UI convention. `--ui-primary` is `brand-600` in light mode and `brand-400` in dark mode; the storefront's own `brand-600` becomes `#c23d00` (5.30 on white, 4.59 on its tint). `--ui-success` is `green-800` light / `green-400` dark. Rule for demos: `brand-600` ≥ 5:1 on white (covers the tint), `brand-400` ≥ 4.5:1 on `#171717`.
26
26
  - Toast proxies: instead of patching `reka-ui` (tried first: a pnpm patch of `dist/Toast/FocusProxy.{js,cjs}` without `aria-hidden` cleared the audit), the **status toasts are gone**. A permanent "closed" toast was a misuse of a transient notification; the status is now a line above the opening hours in the footer (`components/Footer/StoreStatus.vue`, `useStoreStatus`). A chip next to the logo was tried first: on phones only the dot fit, on the desktop the text ran into the navigation, and inside the logo link it broke the link's accessible name. Transient toasts stay on Nuxt UI; their proxies only exist for seconds. Upstream issue for the proxy still worth filing.
27
27
  - The status line is client only (`ClientOnly` with a placeholder of the same size): the open/closed state depends on the current time, and the server's clock/time zone is not the shop's. Server-rendered status would need a configured time zone; separate issue if wanted.
28
- - La Fattoria keeps its own `main.css`; the same `--ui-primary` and `--ui-success` changes went there as veliu/pizzerialafattoria#346.
28
+ - La Fattoria keeps its own `main.css`; the same `--ui-primary` and `--ui-success` changes went there.
29
29
 
30
30
  ## Implementation
31
31
 
@@ -34,7 +34,7 @@ So the storefront default and both demos fail in light mode as well; nobody had
34
34
  - `useStoreStatus`: open → closing time of the current interval; closed → `getNextOpeningTime`. Refreshes the clock every minute. `app.vue` keeps loading business hours and holidays on mount but no longer shows toasts.
35
35
  - `Footer/StoreStatus.vue`: "Geöffnet bis 23:00 Uhr" or "Geschlossen, wir öffnen wieder …", no link (the old toast's "Zur Speisekarte" action was dropped on purpose). `role="status"`, placeholder of the same height while unknown.
36
36
  - `--ui-text-muted` in light mode is `#6b6b6b` (was `#737373`, 4.38:1 on `--ui-bg-elevated`, the header navigation background). `UHeader` gets `:title="site.name"`: Nuxt UI's default made the logo link read "Nuxt UI".
37
- - Docs: contrast rule in `homepage/content/{de,en}/docs/8.storefront/2.configuration.md` and the demo-shop checklist in the root `CLAUDE.md`.
37
+ - Docs: contrast rule in https://shopbite.de/docs/storefront/configuration (DE/EN) and the demo-shop checklist in the root `CLAUDE.md`.
38
38
 
39
39
  ## Not covered
40
40
 
@@ -40,7 +40,7 @@ top sellers as a horizontal scroller.
40
40
  sellers carry the parent's name and cover (La Fattoria marks both the
41
41
  parent "Cordon Bleu" and its three variants; the header type of the
42
42
  generated operation lacks `sw-inheritance`, hence the `@ts-expect-error`).
43
- - Homepage docs (`content/{de,en}/docs/8.storefront/3.content.md`)
43
+ - Docs (https://shopbite.de/docs/storefront/content, DE/EN)
44
44
  describe `hero.title`, the status line, the link order and the top
45
45
  sellers.
46
46
 
@@ -31,9 +31,7 @@ A (three cards with a bold lead, detail text and one action) vs. B
31
31
  - Demo content: the three entries carry `kind`, the hours description
32
32
  keeps only the exceptions (Saturday, closed Tuesday), the reservation
33
33
  card gets a call button.
34
- - Homepage docs (`content/{de,en}/docs/8.storefront/3.content.md`,
35
- branch `docs/storefront-info-cards` stacked on
36
- `docs/storefront-hero-title`).
34
+ - Docs: https://shopbite.de/docs/storefront/content (DE/EN).
37
35
 
38
36
  ## Verification
39
37
 
@@ -6,7 +6,7 @@ Follow-up to `2026-09-10-issue-273-performance-media.md` (PR #308).
6
6
 
7
7
  - Object storage media (demo and La Fattoria) send
8
8
  `public, max-age=31536000, immutable`: done on the buckets.
9
- - Homepage docs cover poster, video size, thumbnails and the bucket header.
9
+ - The docs on shopbite.de cover poster, video size, thumbnails and the bucket header.
10
10
  - Remaining requests without a useful cache lifetime on demo.shopbite.de:
11
11
  - files from `public/` (`/hero-poster.webp`, `/favicon.ico`, `/light/Logo.png`):
12
12
  no `Cache-Control` at all. Nitro only adds one for public asset dirs with
@@ -14,7 +14,7 @@ Container logs in OpenObserve (`docker_logs`, 2026-09-19 to 2026-09-21):
14
14
  | ----------------------- | ------------------------- |
15
15
  | `lafattoria-storefront` | ~2,500 |
16
16
  | `shopbite-storefront` | 565 |
17
- | `shopbite-homepage` | 423 (same pattern, own repo) |
17
+ | shopbite.de website | 423 (same pattern) |
18
18
 
19
19
  `fatal` cannot simply be dropped: Nuxt's root component
20
20
  (`nuxt/dist/app/components/nuxt-root.vue`, `onErrorCaptured`) shows the error
@@ -30,13 +30,13 @@ demos (`leads/demo_create.py` in the monorepo) made the sameness obvious.
30
30
  title, description; all optional, German defaults in the components),
31
31
  `gallery` optional. Existing `index.yml` files keep working; an old
32
32
  `marquee` block is ignored by Zod.
33
- - Homepage docs (`content/{de,en}/docs/8.storefront/3.content.md`).
33
+ - Docs: https://shopbite.de/docs/storefront/content (DE/EN).
34
34
 
35
35
  ## Verification
36
36
 
37
37
  - `HomeMenuCategories.test.ts`: tiles with photo/icon, cap and "all" tile,
38
38
  empty state. Prettier, ESLint, typecheck and the unit suite pass.
39
- - Production build against a lead demo channel (Da Piero): tiles show the
39
+ - Production build against a demo sales channel: tiles show the
40
40
  category photos, the grid the eight top sellers, quick view opens.
41
41
 
42
42
  ## Follow-ups
@@ -18,4 +18,4 @@ As of 2026-10-05, branch `feature/401-restaurant-schema-ordering`. Part of the A
18
18
 
19
19
  Production build against the demo backend with the new env variables: the home page `Restaurant` node carries `geo`, both delivery areas, `acceptsReservations: true`, `paymentAccepted: "Nachnahme"`, `currenciesAccepted: "EUR"` and the `OrderAction` with pickup and own delivery. Without the new variables only `paymentAccepted`, `currenciesAccepted` and `potentialAction` (without `deliveryMethod`) are added. Unit + nuxt tests, typecheck, ESLint green.
20
20
 
21
- Docs: homepage branch `docs/401-restaurant-schema-ordering` (configuration page, DE/EN), including the note that `NUXT_PUBLIC_SITE_CUISINE` is a cuisine name: La Fattoria sets `italienische`, which produces "italienische in Obertshausen" in its meta description.
21
+ Docs: https://shopbite.de/docs/storefront/configuration (DE/EN), including the note that `NUXT_PUBLIC_SITE_CUISINE` is a cuisine name: La Fattoria sets `italienische`, which produces "italienische in Obertshausen" in its meta description.
package/modules/theme.ts CHANGED
@@ -68,7 +68,7 @@ function registerFonts(preset: ThemePreset, nuxt: Nuxt) {
68
68
  * browsers download only the faces the active preset uses) and makes the
69
69
  * configured preset the default of `runtimeConfig.public.shopBite.themePreset`.
70
70
  * One build can so serve every preset: `NUXT_PUBLIC_SHOP_BITE_THEME_PRESET`
71
- * switches it at runtime (the lead demos run one image for all restaurants),
71
+ * switches it at runtime (one image can run several restaurants),
72
72
  * plugins/theme-preset.ts sets `data-preset` on `<html>`.
73
73
  */
74
74
  export default defineNuxtModule<ShopBiteThemeOptions>({
package/nuxt.config.ts CHANGED
@@ -74,6 +74,19 @@ export default defineNuxtConfig({
74
74
  listing: 86400,
75
75
  variant: 3600,
76
76
  category: 86400,
77
+ // Layout data of every page (navigation, SEO URLs, breadcrumbs,
78
+ // plugin config, hours): the server renders it from these caches,
79
+ // so a request (also a 404) does not ask Shopware for it again.
80
+ navigation: 86400,
81
+ // SEO URL matches and the list of known category paths: a new or
82
+ // renamed section must not 404 for long without a purge.
83
+ seoUrl: 600,
84
+ paymentMethods: 3600,
85
+ // Carries the checkout switch, so short; the browser reloads it
86
+ // from Shopware after hydration (useLiveShopData).
87
+ config: 60,
88
+ businessHours: 300,
89
+ holidays: 300,
77
90
  },
78
91
  menuCategoryId: "",
79
92
  searchFallbackCategoryId: "",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopbite-de/storefront",
3
- "version": "2.2.1",
3
+ "version": "2.3.0",
4
4
  "main": "nuxt.config.ts",
5
5
  "description": "Shopware storefront for food delivery shops",
6
6
  "keywords": [
@@ -18,7 +18,7 @@
18
18
  "license": "MIT",
19
19
  "type": "module",
20
20
  "dependencies": {
21
- "@nuxt/content": "3.16.1",
21
+ "@nuxt/content": "3.16.2",
22
22
  "@nuxt/fonts": "^0.14.0",
23
23
  "@nuxt/image": "^2.1.0",
24
24
  "@nuxt/scripts": "1.3.12",
@@ -52,7 +52,7 @@
52
52
  "@typescript-eslint/eslint-plugin": "^8.70.1",
53
53
  "@typescript-eslint/parser": "^8.70.1",
54
54
  "@vitejs/plugin-vue": "^6.0.9",
55
- "@vitest/ui": "5.0.3",
55
+ "@vitest/ui": "5.0.5",
56
56
  "@vue/compiler-dom": "^3.5.43",
57
57
  "@vue/server-renderer": "^3.5.43",
58
58
  "@vue/test-utils": "^2.5.1",
@@ -66,7 +66,7 @@
66
66
  "tailwindcss": "^4.3.3",
67
67
  "typescript": "^6.0.3",
68
68
  "vitest": "^5.0.1",
69
- "vue-tsc": "3.3.12"
69
+ "vue-tsc": "3.3.13"
70
70
  },
71
71
  "scripts": {
72
72
  "build": "nuxt build",
@@ -5,13 +5,16 @@ const Body = z
5
5
  .object({
6
6
  products: z.array(Id).max(1000).optional(),
7
7
  categories: z.array(Id).max(1000).optional(),
8
+ // only the layout data (hours, closing days, checkout switch, ...)
9
+ layout: z.boolean().optional(),
8
10
  })
9
11
  .default({});
10
12
 
11
13
  /**
12
- * Empties the Store API caches after the backoffice changed the menu (#484).
13
- * Protected by NUXT_CACHE_PURGE_SECRET; without the variable the route is
14
- * off. An empty body purges everything.
14
+ * Empties the Store API caches after the backoffice changed the menu (#484)
15
+ * or the shop settings (`{ "layout": true }`). Protected by
16
+ * NUXT_CACHE_PURGE_SECRET; without the variable the route is off. An empty
17
+ * body purges everything.
15
18
  */
16
19
  export default defineEventHandler(async (event) => {
17
20
  const secret = useRuntimeConfig(event).cachePurgeSecret;
@@ -0,0 +1,31 @@
1
+ import type { components } from "~~/api-types/storeApiTypes";
2
+ import { createResilientLoader } from "../../utils/backoff";
3
+
4
+ const Id = /^[0-9a-f]{32}$/i;
5
+ type Breadcrumb = components["schemas"]["BreadcrumbCollection"];
6
+
7
+ // only real breadcrumbs are remembered, not the empty list of random ids
8
+ const load = createResilientLoader<Breadcrumb>((crumbs) => crumbs.length > 0);
9
+
10
+ /** Breadcrumb of a menu section (Category/Breadcrumb.vue). */
11
+ export default defineCachedEventHandler(
12
+ async (event): Promise<components["schemas"]["BreadcrumbCollection"]> => {
13
+ const categoryId = getRouterParam(event, "categoryId") ?? "";
14
+ if (!Id.test(categoryId)) throw createError({ statusCode: 400 });
15
+
16
+ const breadcrumb = await load(categoryId, () =>
17
+ storeApiGet<Breadcrumb>(`/breadcrumb/${categoryId}`, {
18
+ query: { type: "category" },
19
+ }),
20
+ );
21
+ // Shopware answers an unknown id with an empty list; a 404 is not
22
+ // cached, so random ids cannot fill the cache.
23
+ if (!breadcrumb?.length) throw createError({ statusCode: 404 });
24
+ return breadcrumb;
25
+ },
26
+ {
27
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.category,
28
+ name: "breadcrumb",
29
+ getKey: (event) => `breadcrumb-${getRouterParam(event, "categoryId")}`,
30
+ },
31
+ );
@@ -0,0 +1,97 @@
1
+ import type { components } from "~~/api-types/storeApiTypes";
2
+ import { createResilientLoader } from "../../utils/backoff";
3
+ type Schemas = components["schemas"];
4
+
5
+ // What the header, footer and menu navigation read (useNavigation).
6
+ const NAVIGATION_CRITERIA = {
7
+ includes: {
8
+ category: [
9
+ "id",
10
+ "name",
11
+ "translated",
12
+ "seoUrl",
13
+ "customFields",
14
+ "children",
15
+ "linkNewTab",
16
+ ],
17
+ },
18
+ };
19
+
20
+ // The menu sections of the home page with their photo (useHomeMenuCategories).
21
+ const HOME_CRITERIA = {
22
+ depth: 1,
23
+ includes: {
24
+ category: ["id", "name", "translated", "seoUrl", "customFields", "media"],
25
+ media: ["url", "thumbnails", "metaData"],
26
+ media_thumbnail: ["url", "width"],
27
+ },
28
+ };
29
+
30
+ const NAVIGATIONS = {
31
+ main: { activeId: "main-navigation", root: "main-navigation" },
32
+ footer: { activeId: "footer-navigation", root: "footer-navigation" },
33
+ menu: { activeId: "main-navigation", root: "menu" },
34
+ home: { activeId: "main-navigation", root: "menu" },
35
+ } as const;
36
+
37
+ type NavigationType = keyof typeof NAVIGATIONS;
38
+
39
+ const load = createResilientLoader<Schemas["Category"][]>();
40
+
41
+ function navigationOf(type: string | undefined) {
42
+ if (!type || !Object.hasOwn(NAVIGATIONS, type)) return null;
43
+ return NAVIGATIONS[type as NavigationType];
44
+ }
45
+
46
+ type RootContext = { context?: Record<string, unknown> };
47
+
48
+ /**
49
+ * The root of a navigation, resolved once per request (key and request
50
+ * share `event.context`): the plugin config may expire in between, and a
51
+ * second answer would cache one root's sections under the other's key.
52
+ */
53
+ async function rootIdOf(
54
+ event: RootContext,
55
+ type: string | undefined,
56
+ ): Promise<string> {
57
+ const context = (event.context ??= {});
58
+ if (typeof context.navigationRoot === "string") return context.navigationRoot;
59
+ const navigation = navigationOf(type);
60
+ if (!navigation) return "";
61
+ const root =
62
+ navigation.root === "menu" ? await menuRootIdStrict() : navigation.root;
63
+ context.navigationRoot = root;
64
+ return root;
65
+ }
66
+
67
+ /**
68
+ * The navigations every page renders: `main` (header), `footer`, `menu` (the
69
+ * menu sections below the menu root, #486) and `home` (the sections with
70
+ * their photo). Shared by all visitors, so the server keeps them instead of
71
+ * asking Shopware on each request; the key carries the menu root, which the
72
+ * plugin configuration may change. Without the plugin configuration the
73
+ * request fails rather than caching a menu of the fallback root.
74
+ */
75
+ export default defineCachedEventHandler(
76
+ async (event): Promise<Schemas["Category"][]> => {
77
+ const type = getRouterParam(event, "type");
78
+ const navigation = navigationOf(type);
79
+ if (!navigation) throw createError({ statusCode: 404 });
80
+
81
+ const root = await rootIdOf(event, type);
82
+ return await load(`${type}-${root}`, () =>
83
+ storeApiPost(
84
+ `/navigation/${navigation.activeId}/${root}`,
85
+ type === "home" ? HOME_CRITERIA : NAVIGATION_CRITERIA,
86
+ ),
87
+ );
88
+ },
89
+ {
90
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.navigation,
91
+ name: "navigation",
92
+ getKey: async (event) => {
93
+ const type = getRouterParam(event, "type");
94
+ return `navigation-${type}-${await rootIdOf(event, type)}`;
95
+ },
96
+ },
97
+ );
@@ -0,0 +1,29 @@
1
+ import type { components } from "~~/api-types/storeApiTypes";
2
+ import { createResilientLoader } from "../utils/backoff";
3
+
4
+ const load = createResilientLoader<string[]>();
5
+
6
+ /**
7
+ * Names of the payment methods for the Restaurant schema of the home page
8
+ * (useRestaurantSchema). Asked without a visitor's context, so it lists what
9
+ * a new guest can pay with.
10
+ */
11
+ export default defineCachedEventHandler(
12
+ (): Promise<string[]> =>
13
+ load("payment-methods", async () => {
14
+ const result = await storeApiPost<{
15
+ elements?: components["schemas"]["PaymentMethod"][];
16
+ }>("/payment-method", {
17
+ onlyAvailable: true,
18
+ includes: { payment_method: ["name", "translated"] },
19
+ });
20
+ return (result.elements ?? []).map(
21
+ (method) => method.translated?.name ?? method.name,
22
+ );
23
+ }),
24
+ {
25
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.paymentMethods,
26
+ name: "payment-methods",
27
+ getKey: () => "payment-methods",
28
+ },
29
+ );
@@ -0,0 +1,17 @@
1
+ import { isHostilePath } from "../../utils/seoPaths";
2
+
3
+ /**
4
+ * The canonical SEO URL of a path (useNavigationSearch); matches are cached
5
+ * (findSeoUrl). `{ seoUrl: null }` for an unknown path: not an error (see
6
+ * content/page).
7
+ */
8
+ export default defineEventHandler(async (event) => {
9
+ const { path } = getQuery(event);
10
+ if (typeof path !== "string" || !path.startsWith("/")) {
11
+ throw createError({ statusCode: 400, statusMessage: "Invalid path" });
12
+ }
13
+ // longer than Shopware stores a SEO path, or a probe no SEO URL can match
14
+ if (path.length > 750 || isHostilePath(path)) return { seoUrl: null };
15
+
16
+ return { seoUrl: await findSeoUrl(path) };
17
+ });
@@ -0,0 +1,33 @@
1
+ import { createBackoff } from "../../utils/backoff";
2
+ import { isHostilePath, mayBeSeoPath } from "../../utils/seoPaths";
3
+
4
+ /** After a failed load, let every path through for the backoff. */
5
+ const backoff = createBackoff();
6
+ let memo: { loadedAt: number; known: Set<string> } | null = null;
7
+
8
+ /**
9
+ * Whether a path may be a category SEO URL (useSeoUrlRoute asks before its
10
+ * lookups on the server): `false` for a hostile path (isHostilePath) and
11
+ * for one no category ever had. When the list is too long or Shopware
12
+ * fails, every other path may.
13
+ */
14
+ export default defineEventHandler(async (event) => {
15
+ const { path } = getQuery(event);
16
+ if (typeof path !== "string" || !path.startsWith("/")) {
17
+ throw createError({ statusCode: 400, statusMessage: "Invalid path" });
18
+ }
19
+ // before the branches that let every path through
20
+ if (isHostilePath(path)) return { known: false };
21
+ if (backoff.active()) return { known: true };
22
+
23
+ try {
24
+ const { paths, loadedAt } = await knownSeoPaths();
25
+ if (!paths) return { known: true };
26
+ if (memo?.loadedAt !== loadedAt) memo = { loadedAt, known: new Set(paths) };
27
+ return { known: mayBeSeoPath(path, memo.known) };
28
+ } catch (error) {
29
+ backoff.trip();
30
+ console.error("Failed to load the SEO paths", error);
31
+ return { known: true };
32
+ }
33
+ });
@@ -0,0 +1,22 @@
1
+ import type { components } from "~~/api-types/storeApiTypes";
2
+ import { createResilientLoader } from "../../utils/backoff";
3
+
4
+ const load =
5
+ createResilientLoader<components["schemas"]["BusinessHourStruct"]>();
6
+
7
+ /**
8
+ * Weekly opening hours for server-side rendering (footer, home page,
9
+ * Restaurant schema); the browser loads them from Shopware again after
10
+ * hydration (useLiveShopData).
11
+ */
12
+ export default defineCachedEventHandler(
13
+ (): Promise<components["schemas"]["BusinessHourStruct"]> =>
14
+ load("business-hours", () => storeApiGet("/shopbite/business-hour")),
15
+ {
16
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.businessHours,
17
+ // never older than the TTL (default swr would serve a stale answer once)
18
+ swr: false,
19
+ name: "business-hours",
20
+ getKey: () => "business-hours",
21
+ },
22
+ );
@@ -0,0 +1,6 @@
1
+ /**
2
+ * ShopBite plugin configuration (delivery time, checkout switch, menu root)
3
+ * for server-side rendering, cached `cacheTtl.config` (shopBiteConfig). The
4
+ * browser loads it from Shopware again after hydration (useLiveShopData).
5
+ */
6
+ export default defineEventHandler(() => shopBiteConfig());
@@ -0,0 +1,20 @@
1
+ import type { components } from "~~/api-types/storeApiTypes";
2
+ import { createResilientLoader } from "../../utils/backoff";
3
+
4
+ const load = createResilientLoader<components["schemas"]["HolidayStruct"]>();
5
+
6
+ /**
7
+ * Closing days for server-side rendering (home page, Restaurant schema); the
8
+ * browser loads them from Shopware again after hydration (useLiveShopData).
9
+ */
10
+ export default defineCachedEventHandler(
11
+ (): Promise<components["schemas"]["HolidayStruct"]> =>
12
+ load("holidays", () => storeApiGet("/shopbite/holiday")),
13
+ {
14
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.holidays,
15
+ // never older than the TTL (default swr would serve a stale answer once)
16
+ swr: false,
17
+ name: "holidays",
18
+ getKey: () => "holidays",
19
+ },
20
+ );
@@ -0,0 +1,59 @@
1
+ import type { components } from "~~/api-types/storeApiTypes";
2
+ import { createResilientLoader } from "../utils/backoff";
3
+
4
+ const TOP_SELLERS_LIMIT = 8;
5
+
6
+ const criteria = {
7
+ filter: [{ type: "equals", field: "markAsTopseller", value: true }],
8
+ limit: TOP_SELLERS_LIMIT,
9
+ // What the compact card and the quick view need (#327).
10
+ includes: {
11
+ product: [
12
+ "id",
13
+ "productNumber",
14
+ "name",
15
+ "translated",
16
+ "description",
17
+ "calculatedPrice",
18
+ "available",
19
+ "cover",
20
+ "sortedProperties",
21
+ // Allergens checked (#485); includes filter `translated` as well,
22
+ // so custom fields only come back when listed here.
23
+ "customFields",
24
+ // Card link to the quick view deep link (#289).
25
+ "seoUrls",
26
+ ],
27
+ seo_url: ["seoPathInfo", "isCanonical"],
28
+ product_media: ["media"],
29
+ media: ["url", "thumbnails"],
30
+ media_thumbnail: ["width", "url"],
31
+ property_group: ["id", "name", "translated", "options"],
32
+ property_group_option: ["id", "name", "translated", "customFields"],
33
+ },
34
+ associations: {
35
+ cover: { associations: { media: {} } },
36
+ properties: { associations: { group: {} } },
37
+ },
38
+ };
39
+
40
+ const load = createResilientLoader<components["schemas"]["Product"][]>();
41
+
42
+ /** The dishes marked as top sellers, for the home page (useTopSellers). */
43
+ export default defineCachedEventHandler(
44
+ (): Promise<components["schemas"]["Product"][]> =>
45
+ load("top-sellers", async () => {
46
+ const result = await storeApiPost<{
47
+ elements?: components["schemas"]["Product"][];
48
+ }>("/product", criteria, {
49
+ // Variants marked as top sellers inherit name, cover and properties.
50
+ headers: { "sw-inheritance": "true", "sw-include-seo-urls": "true" },
51
+ });
52
+ return result.elements ?? [];
53
+ }),
54
+ {
55
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.listing,
56
+ name: "top-sellers",
57
+ getKey: () => "top-sellers",
58
+ },
59
+ );