@revenexx/cover 0.22.0 → 0.22.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.
Files changed (91) hide show
  1. package/app/api/categories.ts +1 -0
  2. package/app/api/offers.ts +1 -0
  3. package/app/app.config.ts +13 -0
  4. package/app/components/OgImage/CoverPage.takumi.vue +37 -0
  5. package/app/components/RevenexxForm.vue +21 -6
  6. package/app/components/account/approvals/AccountPendingApprovals.vue +19 -1
  7. package/app/components/account/approvals/AccountPendingOrderDetail.vue +3 -0
  8. package/app/components/account/carts/AccountCartsTable.vue +11 -1
  9. package/app/components/account/orderlists/AccountOrderListDetail.vue +32 -3
  10. package/app/components/account/organization/AccountOrganization.vue +1 -1
  11. package/app/components/auth/AuthForgotPasswordPanel.vue +7 -2
  12. package/app/components/auth/AuthLoginPanel.vue +23 -8
  13. package/app/components/auth/AuthRegisterTeaser.vue +1 -1
  14. package/app/components/cart/position/CartPosition.vue +11 -4
  15. package/app/components/cart/quickadd/CartQuickAdd.vue +4 -2
  16. package/app/components/cart/recommend/CartRecommendCard.vue +1 -0
  17. package/app/components/cart/switcher/CartSwitcher.vue +1 -0
  18. package/app/components/cart/view/CartListHeader.vue +5 -0
  19. package/app/components/cart/view/CartSummaryPanel.vue +7 -2
  20. package/app/components/cart/view/CartView.vue +4 -2
  21. package/app/components/checkout/onepage/CheckoutGate.vue +4 -2
  22. package/app/components/checkout/onepage/CheckoutGuestDetailsSection.vue +2 -1
  23. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +1 -1
  24. package/app/components/layout/header/LocaleSwitcher.vue +7 -9
  25. package/app/components/product/detail/ProductDetailAddToCart.vue +17 -11
  26. package/app/components/product/detail/ProductDetailImageGallery.vue +101 -8
  27. package/app/components/product/detail/ProductDetailVariantRow.vue +84 -4
  28. package/app/components/product/detail/ProductDetailVariants.vue +75 -11
  29. package/app/components/product/detail/ProductDetailView.vue +64 -69
  30. package/app/composables/useAuthStore.ts +21 -4
  31. package/app/composables/useCategories.ts +24 -0
  32. package/app/composables/useCategoryAnswer.ts +30 -0
  33. package/app/composables/useCategorySeo.ts +62 -0
  34. package/app/composables/useDefaultUiLanguage.ts +14 -0
  35. package/app/composables/useOgImageReady.ts +16 -0
  36. package/app/composables/useProductAnswer.ts +121 -0
  37. package/app/composables/useProductLocales.ts +21 -10
  38. package/app/composables/useProductSeo.ts +145 -0
  39. package/app/composables/useRouteSubject.ts +23 -3
  40. package/app/composables/useSeoContext.ts +164 -0
  41. package/app/composables/useSeoHead.ts +189 -0
  42. package/app/composables/useSeoRules.ts +23 -0
  43. package/app/interfaces/seo.ts +48 -0
  44. package/app/layouts/default.vue +2 -8
  45. package/app/layouts/focus.vue +3 -1
  46. package/app/payments/psp/novalnet.ts +25 -3
  47. package/app/payments/psp/novalnetStyle.ts +186 -0
  48. package/app/shared/categoryTree.ts +7 -0
  49. package/app/shared/locale.ts +8 -0
  50. package/app/shared/productLocales.ts +62 -1
  51. package/app/shared/seoRules.ts +297 -0
  52. package/app/shared/structuredData.ts +104 -0
  53. package/i18n/locales/de/account.json +4 -0
  54. package/i18n/locales/de/common.json +6 -0
  55. package/i18n/locales/de/pages.json +109 -0
  56. package/i18n/locales/en/account.json +4 -0
  57. package/i18n/locales/en/common.json +6 -0
  58. package/i18n/locales/en/pages.json +109 -0
  59. package/nuxt.config.ts +140 -1
  60. package/package.json +10 -3
  61. package/server/api/auth/otp.post.ts +4 -8
  62. package/server/api/auth/otp.put.ts +20 -11
  63. package/server/api/categories/[slug]/exists.get.ts +28 -0
  64. package/server/api/offers/guest.get.ts +53 -0
  65. package/server/api/orders/index.post.ts +1 -11
  66. package/server/api/payment/methods.post.ts +2 -33
  67. package/server/api/product/[id]/locales.get.ts +9 -3
  68. package/server/data/product-detail.json +0 -20
  69. package/server/dev/errorHandler.ts +9 -5
  70. package/server/dev/typesense/autoSeed.ts +63 -0
  71. package/server/dev/typesense/seed.ts +4 -43
  72. package/server/dev/typesense/seedProducts.ts +87 -0
  73. package/server/interfaces/category.ts +5 -0
  74. package/server/interfaces/product.ts +13 -6
  75. package/server/middleware/missing-media.ts +2 -2
  76. package/server/plugins/previewHostNoindex.ts +21 -0
  77. package/server/plugins/seoSiteConfig.ts +62 -0
  78. package/server/routes/robots.txt.ts +21 -0
  79. package/server/services/ApiCategoryService.ts +6 -0
  80. package/server/services/ApiProductService.ts +2 -2
  81. package/server/services/LocalFileCategoryService.ts +6 -0
  82. package/server/utils/liveCatalog.ts +83 -18
  83. package/server/utils/livePrices.ts +12 -3
  84. package/server/utils/locale.ts +3 -8
  85. package/server/utils/offerService.ts +8 -3
  86. package/server/utils/paymentOptions.ts +49 -0
  87. package/server/utils/promotionsService.ts +25 -0
  88. package/server/utils/revenexxSdk.ts +7 -1
  89. package/server/utils/seoRequestHost.ts +21 -0
  90. package/server/utils/storefrontMessages.ts +5 -5
  91. package/server/utils/storefrontSeoRules.ts +298 -0
@@ -13,20 +13,20 @@ import type { ProductDetailCategory } from "../../../interfaces/product-detail";
13
13
  */
14
14
  const localePath = useLocalePath();
15
15
 
16
- const { slug, id } = useRouteProductSubject();
16
+ const { slug, id, categorySegments } = useRouteProductSubject();
17
17
 
18
+ const detail = useProductDetail(id);
18
19
  const {
19
- status,
20
+ status, error,
20
21
  productInfo, mainImages, model3d, longDescription,
21
22
  stocks, attributes, prices, taxRate, offerPending,
22
23
  productCategories, categorySlug, subcategorySlug,
23
24
  formatPrice, getDetailImageUrl, ready,
24
- } = useProductDetail(id);
25
+ } = detail;
25
26
  await ready();
26
27
 
27
28
  const { icon } = useIcons();
28
29
  const { t } = useI18n();
29
- const toast = useToast();
30
30
  const cartStore = useCartStore();
31
31
 
32
32
  const currentCartQuantity = computed(() => {
@@ -62,22 +62,17 @@ const notFound = computed(
62
62
  () => !slug.value || (status.value !== "pending" && !productInfo.value),
63
63
  );
64
64
 
65
- // Reflect not-found as a real 404. Checked synchronously AFTER the await above:
66
- // on the server a non-sync watcher runs once at setup and is then stopped, so a
67
- // watchEffect here would evaluate before the fetch resolved and always see a
68
- // product. (Never let an empty product crash the render into a 500 — see the
69
- // guarded template below.)
70
- if (import.meta.server && notFound.value) {
71
- setResponseStatus(useRequestEvent(), 404);
72
- }
65
+ // The HTTP answer: 404, 410 or a 301 for no product, a 301 for an outdated
66
+ // slug (PE-1236). Decided AFTER the await above: on the server a non-sync
67
+ // watcher runs once at setup and is then stopped, so a watchEffect here would
68
+ // evaluate before the fetch resolved and always see a product. (Never let an
69
+ // empty product crash the render into a 500 — see the guarded template below.)
70
+ const answersItself = await useProductAnswer({
71
+ slug, requestedCategory: categorySegments, productInfo, error, categorySlug, subcategorySlug,
72
+ });
73
73
 
74
- async function copySku(): Promise<void> {
75
- if (!productInfo.value) {
76
- return;
77
- }
78
- await navigator.clipboard.writeText(productInfo.value.sku);
79
- toast.add({ title: t("product.detail.skuCopied"), duration: 1200, icon: icon("copy-check") });
80
- }
74
+ // Title, description, robots and canonical from the domain's SEO rules (PE-1235).
75
+ useProductSeo(detail, { notFound: () => !answersItself || notFound.value });
81
76
 
82
77
  const rootCategory = computed(() =>
83
78
  productCategories.value.find((c: ProductDetailCategory) => c.type === "root"),
@@ -99,11 +94,33 @@ const breadcrumb = computed(() => [
99
94
  : []),
100
95
  { label: productInfo.value?.name ?? (status.value === "pending" ? "..." : t("product.detail.notFoundTitle")) },
101
96
  ]);
97
+
98
+ /**
99
+ * Phones collapse the trail to its nearest linked parent (PO-23): the full
100
+ * trail squeezed every crumb to an ellipsis, and the product name is the H1
101
+ * right below anyway.
102
+ */
103
+ const breadcrumbParent = computed(() => breadcrumb.value.findLast(item => item.to !== undefined));
102
104
  </script>
103
105
 
104
106
  <template>
105
107
  <UContainer class="py-6">
106
- <UBreadcrumb :items="breadcrumb" />
108
+ <UBreadcrumb
109
+ class="hidden md:block"
110
+ :items="breadcrumb"
111
+ />
112
+ <NuxtLink
113
+ v-if="breadcrumbParent?.to"
114
+ :to="breadcrumbParent.to"
115
+ class="md:hidden -ms-1 inline-flex items-center gap-1 min-h-11 pe-2 text-sm text-muted
116
+ hover:text-highlighted transition-colors"
117
+ >
118
+ <UIcon
119
+ :name="icon('chevron-left')"
120
+ class="size-4 shrink-0"
121
+ />
122
+ {{ breadcrumbParent.label }}
123
+ </NuxtLink>
107
124
 
108
125
  <CategorySkeletonCategoryDetailSkeleton v-if="status === 'pending'" />
109
126
 
@@ -116,11 +133,11 @@ const breadcrumb = computed(() => [
116
133
 
117
134
  <div
118
135
  v-else
119
- class="mt-8"
136
+ class="mt-4 md:mt-8"
120
137
  >
121
- <div class="grid grid-cols-1 lg:grid-cols-2 gap-10 xl:gap-14 items-start">
138
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-8 lg:gap-10 xl:gap-14 items-start">
122
139
  <ProductDetailImageGallery
123
- class="lg:sticky lg:top-(--ui-header-height)"
140
+ class="md:sticky md:top-(--ui-header-height)"
124
141
  :images="mainImages"
125
142
  :get-image-url="getDetailImageUrl"
126
143
  :model-url="model3d?.url"
@@ -129,28 +146,12 @@ const breadcrumb = computed(() => [
129
146
 
130
147
  <div class="flex flex-col gap-6">
131
148
  <!-- Identity -->
132
- <div>
133
- <p class="text-xs font-semibold uppercase tracking-wide text-muted">
134
- {{ productInfo.manufacturer }}
135
- </p>
136
- <h1 class="mt-1 text-3xl font-semibold tracking-tight text-highlighted">
137
- {{ productInfo.name }}
138
- </h1>
139
- <button
140
- type="button"
141
- tabindex="0"
142
- class="mt-2 inline-flex items-center gap-1.5 text-sm text-muted
143
- hover:text-highlighted transition-colors cursor-pointer"
144
- :title="t('product.detail.copySku')"
145
- @click="copySku"
146
- >
147
- {{ t('product.detail.sku') }}: {{ productInfo.sku }}
148
- <UIcon
149
- :name="icon('copy')"
150
- class="size-3.5"
151
- />
152
- </button>
153
- </div>
149
+ <ProductDetailIdentity
150
+ :manufacturer="productInfo.manufacturer"
151
+ :name="productInfo.name"
152
+ :sku="productInfo.sku"
153
+ :logo="productInfo.manufacturerLogo"
154
+ />
154
155
 
155
156
  <!-- Price (Offer domain — hydrates after first paint) -->
156
157
  <USkeleton
@@ -237,35 +238,29 @@ const breadcrumb = computed(() => [
237
238
  </div>
238
239
 
239
240
  <!-- The siblings of this article: one row each, with a column per axis
240
- that distinguishes them. Rendered only where the model has any. -->
241
- <div
241
+ that distinguishes them. Rendered only where the model has any.
242
+ Both sections below draw their own top border and spacing (they
243
+ also stand alone as blokkli blocks), so no wrapper adds a second. -->
244
+ <ProductDetailVariants
242
245
  v-if="variants.length"
243
- class="mt-14 pt-10 border-t border-(--ui-border)"
244
- >
245
- <ProductDetailVariants
246
- :variants="variants"
247
- :axes="axes"
248
- :model="model"
249
- :tax-rate="taxRate"
250
- :link-for="variantLink"
251
- :category-slug="categorySlug ?? ''"
252
- :subcategory-slug="subcategorySlug"
253
- show-filters
254
- show-order-button
255
- />
256
- </div>
246
+ :variants="variants"
247
+ :axes="axes"
248
+ :model="model"
249
+ :tax-rate="taxRate"
250
+ :link-for="variantLink"
251
+ :category-slug="categorySlug ?? ''"
252
+ :subcategory-slug="subcategorySlug"
253
+ show-filters
254
+ show-order-button
255
+ />
257
256
 
258
257
  <!-- What is sold alongside it. A way into the catalogue rather than a
259
258
  second buy box, so the tiles carry no price and cost no offer call. -->
260
- <div
259
+ <ProductDetailAssociations
261
260
  v-if="associationGroups.length"
262
- class="mt-14 pt-10 border-t border-(--ui-border)"
263
- >
264
- <ProductDetailAssociations
265
- :groups="associationGroups"
266
- :link-for="variantLink"
267
- />
268
- </div>
261
+ :groups="associationGroups"
262
+ :link-for="variantLink"
263
+ />
269
264
  </div>
270
265
  </UContainer>
271
266
  </template>
@@ -73,11 +73,19 @@ export const useAuthStore = defineStore("auth", () => {
73
73
  const session = ref<StoredSession | null>(null);
74
74
 
75
75
  const isLoggedIn = computed(() => user.value !== null);
76
+ /**
77
+ * Whether the signed-in user is known yet. The user is resolved in the
78
+ * browser only (auth-init.client.ts), so during SSR and until /api/auth/me
79
+ * answers, `user` is null for everybody — a view that shows more to its
80
+ * owner can wait on this instead of rendering the stranger's version first.
81
+ */
82
+ const resolved = ref(false);
76
83
 
77
84
  const loading = ref(false);
78
85
  const error = ref<string | null>(null);
79
86
 
80
87
  function markAuthenticated() {
88
+ resolved.value = true;
81
89
  localStorage.setItem(WAS_AUTHENTICATED_KEY, "1");
82
90
  }
83
91
 
@@ -167,17 +175,23 @@ export const useAuthStore = defineStore("auth", () => {
167
175
  }
168
176
  };
169
177
 
170
- /** Hand the secret back and become signed in, exactly as a password would. */
178
+ /**
179
+ * Hand the secret back and become signed in, exactly as a password would.
180
+ *
181
+ * A link carries its `userId`. A code is confirmed with the address it was
182
+ * asked for: the customers app answers no user to a code request since 5.0,
183
+ * and a `userId` an older one answered goes along while it still does.
184
+ */
171
185
  const confirmSignInMail = async (
172
186
  kind: "magic-link" | "otp",
173
- { userId, secret }: { userId: string; secret: string },
187
+ { userId, email, secret }: { userId?: string | null; email?: string; secret: string },
174
188
  ) => {
175
189
  loading.value = true;
176
190
  error.value = null;
177
191
  try {
178
192
  const result = await $fetch<{ user: AuthUser; session: StoredSession }>(`/api/auth/${kind}`, {
179
193
  method: "PUT",
180
- body: { userId, secret },
194
+ body: { ...(userId ? { userId } : {}), ...(email ? { email } : {}), secret },
181
195
  });
182
196
  user.value = result.user;
183
197
  session.value = result.session;
@@ -274,10 +288,13 @@ export const useAuthStore = defineStore("auth", () => {
274
288
  session.value = null;
275
289
  await handleAuthExpiry();
276
290
  }
291
+ finally {
292
+ resolved.value = true;
293
+ }
277
294
  };
278
295
 
279
296
  return {
280
- user, session, isLoggedIn, loading, error,
297
+ user, session, isLoggedIn, resolved, loading, error,
281
298
  register, login, logout,
282
299
  requestSignInMail, confirmSignInMail,
283
300
  requestRecovery, confirmRecovery,
@@ -52,6 +52,30 @@ export function chunkIntoColumns(
52
52
  return columns;
53
53
  }
54
54
 
55
+ /**
56
+ * Asks the BFF whether a category URL's segments name a category the
57
+ * catalogue has (PE-1236): true or false, null when the catalogue could not be
58
+ * read. The navigation tree cannot answer it: live, it is cut to two levels,
59
+ * while products (and their breadcrumbs) hang at a leaf of any depth.
60
+ *
61
+ * Call it in setup, before the first await; the returned function forwards
62
+ * the request's cookies, so the demo/live switch applies.
63
+ */
64
+ export function useCategoryExists(): (slug: string, subcategory?: string) => Promise<boolean | null> {
65
+ const requestFetch = useRequestFetch();
66
+ return async (slug, subcategory) => {
67
+ try {
68
+ const answer = await requestFetch<{ exists: boolean }>(categoriesApi.exists(slug), {
69
+ query: subcategory ? { subcategory } : undefined,
70
+ });
71
+ return answer.exists;
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ };
77
+ }
78
+
55
79
  export const useCategories = () => {
56
80
  const localePath = useLocalePath();
57
81
  const { icon } = useIcons();
@@ -0,0 +1,30 @@
1
+ import type { MaybeRefOrGetter } from "vue";
2
+
3
+ /**
4
+ * The HTTP answer of a category URL (PE-1236): a category or subcategory the
5
+ * catalogue does not have is a 404, not a listing of nothing under the slug
6
+ * with a 200 (a soft 404). Asked of the BFF, which knows every code of the
7
+ * catalogue, a leaf deeper than the navigation's two levels too; when the
8
+ * catalogue could not be read the page renders as before rather than turn
9
+ * every category away.
10
+ *
11
+ * A category's previous slug gets no 301 here: the slug is the catalogue's
12
+ * category code, which carries no id and no history, so Cover cannot tell a
13
+ * renamed category from one that never existed. Until the catalogue keeps
14
+ * that history, a renamed category's old URL is redirected at the edge (seo
15
+ * redirects, G1).
16
+ */
17
+ export async function useCategoryAnswer(page: {
18
+ readonly categorySlug: MaybeRefOrGetter<string | undefined>;
19
+ readonly subcategorySlug: MaybeRefOrGetter<string | undefined>;
20
+ }): Promise<void> {
21
+ // The status code is the server's to send; a client navigation is not held up.
22
+ if (!import.meta.server) {
23
+ return;
24
+ }
25
+ const slug = toValue(page.categorySlug);
26
+ const exists = slug ? await useCategoryExists()(slug, toValue(page.subcategorySlug)) : false;
27
+ if (exists === false) {
28
+ throw createError({ statusCode: 404, statusMessage: "Category not found", fatal: true });
29
+ }
30
+ }
@@ -0,0 +1,62 @@
1
+ import type { MaybeRefOrGetter } from "vue";
2
+
3
+ import { hasListingFilters } from "../shared/seoRules";
4
+ import type { ListingResponse } from "./useProductListing";
5
+
6
+ /**
7
+ * The category page's SEO from the domain's rules (PE-1235), for every page
8
+ * that lists a category: the blökkli theme's template page and the demo shop's.
9
+ *
10
+ * The clean category URL and its pages are indexable, each page its own
11
+ * canonical. Facet, price and in-category search permutations are
12
+ * near-duplicates of it: they stay out of the index and name the clean
13
+ * category URL as their canonical, whatever page they are on. An empty
14
+ * category or a page beyond its last is thin content and stays out of the
15
+ * index too; sort and tracking parameters are stripped from the canonical.
16
+ * Emptiness is read from the listing the page already fetched
17
+ * (useCategoryListing, key `category`).
18
+ */
19
+ export function useCategorySeo(category: {
20
+ readonly name: MaybeRefOrGetter<string | undefined>;
21
+ /** The parent category's name, on a subcategory. */
22
+ readonly parent?: MaybeRefOrGetter<string | undefined>;
23
+ /** A preview or anything else that must not be indexed. */
24
+ readonly noindex?: MaybeRefOrGetter<boolean>;
25
+ /** A preview, whose links must not be followed either. */
26
+ readonly nofollow?: MaybeRefOrGetter<boolean>;
27
+ }): void {
28
+ const route = useRoute();
29
+ const rules = useSeoRules();
30
+ const { data: listing } = useNuxtData<ListingResponse | null>("listing:category");
31
+
32
+ const filtered = computed(() => hasListingFilters(route.query, rules.value));
33
+ /** Nothing listed: an empty category, or a page beyond its last (`?page=9999`). */
34
+ const empty = computed(() => listing.value?.products.length === 0);
35
+
36
+ useSeoContext({
37
+ type: "category",
38
+ values: () => ({ name: toValue(category.name), parent: toValue(category.parent) }),
39
+ title: () => toValue(category.name),
40
+ noindex: () => Boolean(toValue(category.noindex)) || filtered.value || empty.value,
41
+ nofollow: category.nofollow,
42
+ canonicalPath: () => (filtered.value ? route.path : undefined),
43
+ });
44
+
45
+ // The trail in the structured data (PE-1103), from the category routes'
46
+ // own params: /category/<category>[/<subcategory>].
47
+ const { t } = useI18n();
48
+ const localePath = useLocalePath();
49
+ useSchemaOrg([
50
+ defineBreadcrumb(computed(() => {
51
+ const parent = toValue(category.parent);
52
+ const parentSlug = route.params.subcategory ? String(route.params.category) : undefined;
53
+ return {
54
+ itemListElement: [
55
+ { name: t("nav.home"), item: localePath("/") },
56
+ ...(parentSlug && parent ? [{ name: parent, item: localePath(`/category/${parentSlug}`) }] : []),
57
+ { name: toValue(category.name) ?? "", item: route.path },
58
+ ],
59
+ };
60
+ })),
61
+ ]);
62
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The shop's default UI language: the i18n default locale, else its first
3
+ * locale. The language the pages render in for a content locale without UI
4
+ * strings of its own (PE-866). One rule for the language switcher and the
5
+ * document head, so `<html lang>` and the switcher never disagree.
6
+ */
7
+ export function useDefaultUiLanguage() {
8
+ const { locales } = useI18n();
9
+ const runtimeConfig = useRuntimeConfig();
10
+ return computed(() => {
11
+ const i18nConfig = runtimeConfig.public as { i18n?: { defaultLocale?: string }; defaultLocale?: string };
12
+ return i18nConfig.i18n?.defaultLocale || i18nConfig.defaultLocale || locales.value[0]?.code || "de";
13
+ });
14
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Whether this Site can serve generated link preview images (PE-1237).
3
+ *
4
+ * nuxt-og-image signs its image URLs with a key derived from the app secret,
5
+ * and in production a missing or short secret (`NUXT_APP_SECRET`, at least 32
6
+ * characters) makes every image request a 500 — a broken preview in every
7
+ * share. Without one a page names no generated image at all. Decided on the
8
+ * server, where the secret is, and carried to the client in the payload so a
9
+ * client navigation decides the same way: useSeoHead() reads it on every
10
+ * server render (every layout calls it), so the state is in the payload even
11
+ * when the first page served generated no card.
12
+ */
13
+ export function useOgImageReady() {
14
+ return useState("cover:og-image-ready", () =>
15
+ import.meta.server && (import.meta.dev || String(useRuntimeConfig().appSecret ?? "").length >= 32));
16
+ }
@@ -0,0 +1,121 @@
1
+ import type { Ref } from "vue";
2
+
3
+ import { productApi } from "../api/product";
4
+ import type { ProductDetailProduct } from "../interfaces/product-detail";
5
+ import { productFallbackPath, productListingSegments } from "../shared/productLocales";
6
+ import type { Product } from "./useProducts";
7
+
8
+ /**
9
+ * The HTTP answer of a product URL (PE-1236), decided on the server once the
10
+ * product fetch has settled. A page awaits it in place of setting a 404:
11
+ *
12
+ * - **Outdated slug.** The page finds the product by the id in front of the
13
+ * slug, so an old name still reached it with a 200 and a duplicate of the
14
+ * page (the gap ADR-0031 left). It now answers 301 to the product's current
15
+ * path, query kept. A shallower category path or the `_` placeholder keep
16
+ * their 200 and the canonical: internal links are built that way, and each
17
+ * would otherwise cost a hop.
18
+ * - **No answer.** A product fetch that failed for any reason but a 404 (the
19
+ * catalogue down, a timeout) says nothing about the product: 503 with a
20
+ * Retry-After, so crawlers come back instead of dropping or moving a live URL.
21
+ * - **No product.** The catalogue cannot tell a deleted product from one that
22
+ * never existed, so the domain's seo rules decide (`removed_products`):
23
+ * `category` sends the buyer to the category the URL names with a 301,
24
+ * `gone` answers 410. A URL that names no category, or one the catalogue
25
+ * does not have, or no product at all, is a 404: otherwise any made-up
26
+ * product URL would be a 301 to whatever it names. So is one whose
27
+ * category could not be checked.
28
+ * - **Not in this language.** A catalogue that hides untranslated products
29
+ * (`search_untranslated=hide`) has no document for a product in a language
30
+ * it is not translated into, and the fetch says 404 there too. When the
31
+ * product has a page in another language it is a 404, which crawlers ask
32
+ * again, never a 301 or 410 that writes the URL off before the translation
33
+ * comes. A lookup that fails or a catalogue that cannot tell treats the
34
+ * product as missing everywhere, as before.
35
+ *
36
+ * @returns Whether the page answers with itself (`true`), or this answered
37
+ * for it: a 301, 404, 410 or 503.
38
+ */
39
+ export async function useProductAnswer(product: {
40
+ /** The `<id>-<name>` segment as requested. */
41
+ readonly slug: Readonly<Ref<string>>;
42
+ /** The category segments the URL names before `product`. */
43
+ readonly requestedCategory: Readonly<Ref<readonly string[]>>;
44
+ readonly productInfo: Readonly<Ref<ProductDetailProduct | undefined>>;
45
+ /** The product fetch's error, if it failed. */
46
+ readonly error: Readonly<Ref<{ readonly statusCode?: number } | null | undefined>>;
47
+ readonly categorySlug: Readonly<Ref<string | undefined>>;
48
+ readonly subcategorySlug: Readonly<Ref<string | undefined>>;
49
+ }): Promise<boolean> {
50
+ if (!import.meta.server) {
51
+ return true;
52
+ }
53
+ const nuxtApp = useNuxtApp();
54
+ const event = useRequestEvent();
55
+ if (!event) {
56
+ return true;
57
+ }
58
+ const route = useRoute();
59
+ const localePath = useLocalePath();
60
+ const rules = useSeoRules();
61
+ // Before the first await, while the setup context is still current.
62
+ const categoryExists = useCategoryExists();
63
+ const requestFetch = useRequestFetch();
64
+ const { locales } = useI18n();
65
+
66
+ /** Whether the product has a page in any storefront language (this one has none). */
67
+ async function translatedElsewhere(): Promise<boolean> {
68
+ const id = parseProductIdFromSlug(product.slug.value);
69
+ const answer = await requestFetch<{ locales: string[] | null }>(productApi.locales(id), {
70
+ query: { locales: locales.value.map(entry => entry.code).join(",") },
71
+ }).catch(() => null);
72
+ return Boolean(answer?.locales?.length);
73
+ }
74
+
75
+ const info = product.productInfo.value as Product | undefined;
76
+ if (info) {
77
+ if (product.slug.value && product.slug.value !== slugify(info)) {
78
+ const path = categoryProductPath([product.categorySlug.value, product.subcategorySlug.value], info);
79
+ await navigateTo({ path: localePath(path), query: route.query }, { redirectCode: 301 });
80
+ return false;
81
+ }
82
+ return true;
83
+ }
84
+
85
+ const failure = product.error.value;
86
+ if (failure && failure.statusCode !== 404) {
87
+ setResponseStatus(event, 503);
88
+ setResponseHeader(event, "Retry-After", 120);
89
+ return false;
90
+ }
91
+
92
+ if (!product.slug.value) {
93
+ setResponseStatus(event, 404);
94
+ return false;
95
+ }
96
+ // The category first, also where removed products are gone: a URL under
97
+ // a category the catalogue lacks never named a product (AC-4).
98
+ const [category, subcategory] = productListingSegments(product.requestedCategory.value);
99
+ if (!category) {
100
+ setResponseStatus(event, 404);
101
+ return false;
102
+ }
103
+ if (await categoryExists(category, subcategory) !== true) {
104
+ setResponseStatus(event, 404);
105
+ return false;
106
+ }
107
+ if (await translatedElsewhere()) {
108
+ setResponseStatus(event, 404);
109
+ return false;
110
+ }
111
+ if (rules.value.removed_products === "gone") {
112
+ setResponseStatus(event, 410);
113
+ return false;
114
+ }
115
+ // The await above left the Nuxt context, which navigateTo needs.
116
+ await nuxtApp.runWithContext(() => navigateTo(
117
+ { path: localePath(productFallbackPath(product.requestedCategory.value)), query: route.query },
118
+ { redirectCode: 301 },
119
+ ));
120
+ return false;
121
+ }
@@ -1,10 +1,13 @@
1
1
  import { productApi } from "../api/product";
2
- import { normalizeLocaleCode } from "../shared/locale";
3
- import { productFallbackPath, productRouteCategorySegments } from "../shared/productLocales";
4
- import { routeSegments, useRouteProductSubject } from "./useRouteSubject";
2
+ import { localeLanguage, normalizeLocaleCode } from "../shared/locale";
3
+ import { productFallbackPath, withProductSlug } from "../shared/productLocales";
4
+ import { slugify } from "./useProducts";
5
+ import type { Product } from "./useProducts";
6
+ import { useRouteProductSubject } from "./useRouteSubject";
5
7
 
6
8
  interface ProductLocalesResponse {
7
9
  locales: string[] | null;
10
+ names?: Record<string, string> | null;
8
11
  }
9
12
 
10
13
  /**
@@ -20,8 +23,7 @@ interface ProductLocalesResponse {
20
23
  * locale is linked then, exactly as before. Only a product page narrows.
21
24
  */
22
25
  export function useProductLocales() {
23
- const route = useRoute();
24
- const { id } = useRouteProductSubject();
26
+ const { id, slug, categorySegments } = useRouteProductSubject();
25
27
  const { locales } = useI18n();
26
28
  const requestFetch = useRequestFetch();
27
29
 
@@ -46,11 +48,20 @@ export function useProductLocales() {
46
48
  return available.value?.includes(normalizeLocaleCode(code)) ?? true;
47
49
  }
48
50
 
51
+ /**
52
+ * A path of this page in another locale with the product's slug in that
53
+ * locale (PE-1236): its name, and so its slug, may be translated, and a
54
+ * link with this locale's slug would land on the outdated-slug 301. Off a
55
+ * product page, or without a name for the locale, the path stays as given.
56
+ */
57
+ function localizePath(path: string, code: string): string {
58
+ const names = id.value ? data.value?.names : undefined;
59
+ const name = names?.[code] ?? names?.[normalizeLocaleCode(code)] ?? names?.[localeLanguage(code)];
60
+ return name ? withProductSlug(path, slug.value, slugify({ id: id.value, name } as Product)) : path;
61
+ }
62
+
49
63
  /** Where a locale without the product goes instead: its category listing, or home. */
50
- const fallbackPath = computed(() => productFallbackPath(productRouteCategorySegments(
51
- routeSegments(route.params.category),
52
- routeSegments(route.params.rest),
53
- )));
64
+ const fallbackPath = computed(() => productFallbackPath(categorySegments.value));
54
65
 
55
- return { available, hasPage, fallbackPath };
66
+ return { available, hasPage, fallbackPath, localizePath };
56
67
  }