@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
@@ -1,3 +1,4 @@
1
+ import { type NovalnetIframeStyle, novalnetIframeStyle, readNovalnetFieldTokens } from "./novalnetStyle";
1
2
  import { type PspInstrument, PspInputError, type PspMountContext, type PspTokenizer } from "./types";
2
3
 
3
4
  /**
@@ -41,7 +42,7 @@ interface NovalnetFormConfig {
41
42
  on_show_overlay?: () => void;
42
43
  on_hide_overlay?: () => void;
43
44
  };
44
- iframe: { id: string; inline: number; style?: Record<string, string> };
45
+ iframe: { id: string; inline: number; style?: NovalnetIframeStyle };
45
46
  customer?: Record<string, unknown>;
46
47
  transaction?: Record<string, unknown>;
47
48
  custom?: { lang?: string };
@@ -96,13 +97,15 @@ export function novalnetFormConfig(
96
97
  ctx: Pick<PspMountContext, "testMode" | "locale" | "amount" | "currency" | "customer">,
97
98
  iframeId: string,
98
99
  callback: NovalnetFormConfig["callback"],
100
+ style?: NovalnetIframeStyle,
99
101
  ): NovalnetFormConfig {
100
102
  const customer = ctx.customer;
101
103
  const billing = customer?.billing;
102
104
  const amount = novalnetAmount(ctx.amount);
103
105
  const config: NovalnetFormConfig = {
104
106
  callback,
105
- iframe: { id: iframeId, inline: 1 },
107
+ // The shop's look (FE-6); without it the iframe draws Novalnet's own.
108
+ iframe: { id: iframeId, inline: 1, ...(style ? { style } : {}) },
106
109
  custom: { lang: (ctx.locale ?? "de").slice(0, 2).toUpperCase() },
107
110
  transaction: {
108
111
  ...(amount !== undefined ? { amount } : {}),
@@ -151,6 +154,7 @@ let instanceCounter = 0;
151
154
  export function createNovalnetTokenizer(): PspTokenizer {
152
155
  let utility: NovalnetUtilityApi | null = null;
153
156
  let iframe: HTMLIFrameElement | null = null;
157
+ let host: HTMLElement | null = null;
154
158
  let pending: { resolve: (v: PspInstrument) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> } | null = null;
155
159
 
156
160
  function settle(fn: (p: NonNullable<typeof pending>) => void) {
@@ -191,6 +195,20 @@ export function createNovalnetTokenizer(): PspTokenizer {
191
195
  if (!utility.setClientKey(ctx.publishableKey)) {
192
196
  throw new Error("Novalnet client key was refused");
193
197
  }
198
+ // Read before the iframe goes in, so the probe measures the theme
199
+ // and nothing Novalnet adds. A theme that cannot be read still gets
200
+ // a working field, in Novalnet's own look.
201
+ let style: NovalnetIframeStyle | undefined;
202
+ try {
203
+ style = novalnetIframeStyle(readNovalnetFieldTokens(ctx.el));
204
+ }
205
+ catch {
206
+ style = undefined;
207
+ }
208
+ // The iframe draws a box around every field, so the mount element
209
+ // drops its own (the checkout styles `data-psp-fields="own"`).
210
+ host = ctx.el;
211
+ host.dataset.pspFields = "own";
194
212
  instanceCounter += 1;
195
213
  iframe = document.createElement("iframe");
196
214
  iframe.id = `novalnet-card-iframe-${instanceCounter}`;
@@ -222,7 +240,7 @@ export function createNovalnetTokenizer(): PspTokenizer {
222
240
  }
223
241
  frame.addEventListener("load", onload);
224
242
  // The library sets the iframe's src and its own onload handler.
225
- const created = utility!.createCreditCardForm(novalnetFormConfig(ctx, frame.id, callback));
243
+ const created = utility!.createCreditCardForm(novalnetFormConfig(ctx, frame.id, callback, style));
226
244
  if (created === false) {
227
245
  finish(new Error("Novalnet card form could not be created"));
228
246
  }
@@ -248,6 +266,10 @@ export function createNovalnetTokenizer(): PspTokenizer {
248
266
  settle(p => p.reject(new Error("card field was removed")));
249
267
  iframe?.remove();
250
268
  iframe = null;
269
+ if (host) {
270
+ delete host.dataset.pspFields;
271
+ host = null;
272
+ }
251
273
  utility = null;
252
274
  },
253
275
  };
@@ -0,0 +1,186 @@
1
+ /**
2
+ * The shop's look for Novalnet's card iframe (FE-6).
3
+ *
4
+ * The card form lives in an iframe on secure.novalnet.de, so none of the
5
+ * shop's CSS reaches it. `createCreditCardForm` takes the look as text instead,
6
+ * under `iframe.style`:
7
+ *
8
+ * - `container` — a style sheet the iframe adds to its own document
9
+ * (selectors allowed, so `:focus` and `::placeholder` work there);
10
+ * - `input` / `label` — inline styles put on every input and label.
11
+ *
12
+ * The values are not written per shop. They are read from the theme's design
13
+ * tokens at mount time (Nuxt UI's `--ui-*` variables and the body font), so
14
+ * every theme gets its own look. A theme that wants the card field to differ
15
+ * from its other inputs sets the `--cover-psp-field-*` variables below on the
16
+ * mount element or any ancestor.
17
+ */
18
+
19
+ /** Resolved values, as the browser computed them (`rgb(...)`, `px`). */
20
+ export interface NovalnetFieldTokens {
21
+ fontFamily: string;
22
+ fontSize: string;
23
+ text: string;
24
+ background: string;
25
+ border: string;
26
+ radius: string;
27
+ height: string;
28
+ paddingX: string;
29
+ focus: string;
30
+ placeholder: string;
31
+ label: string;
32
+ labelSize: string;
33
+ /** `@font-face` rules for `fontFamily`, with absolute URLs; may be empty. */
34
+ fontFaces?: string[];
35
+ }
36
+
37
+ export interface NovalnetIframeStyle {
38
+ container: string;
39
+ input: string;
40
+ label: string;
41
+ }
42
+
43
+ /**
44
+ * Each token, the CSS property the probe resolves it through, and the theme
45
+ * variable it defaults to. The defaults are Nuxt UI's own input (`UInput`, size
46
+ * md, variant outline): text-base/5, px-2.5, rounded-md, a 1px ring in the
47
+ * accented border colour, a 2px primary ring on focus, a dimmed placeholder.
48
+ */
49
+ const PROBE: Array<[keyof NovalnetFieldTokens, string, string]> = [
50
+ ["text", "color", "var(--cover-psp-field-text, var(--ui-text-highlighted, currentColor))"],
51
+ ["background", "background-color", "var(--cover-psp-field-bg, var(--ui-bg, transparent))"],
52
+ ["border", "border-top-color", "var(--cover-psp-field-border, var(--ui-border-accented, #d4d4d4))"],
53
+ ["focus", "border-right-color", "var(--cover-psp-field-focus, var(--ui-primary, #2563eb))"],
54
+ ["placeholder", "border-bottom-color", "var(--cover-psp-field-placeholder, var(--ui-text-dimmed, #a3a3a3))"],
55
+ ["label", "border-left-color", "var(--cover-psp-field-label, var(--ui-text, currentColor))"],
56
+ ["height", "height", "var(--cover-psp-field-height, 2rem)"],
57
+ ["paddingX", "padding-left", "var(--cover-psp-field-padding-x, 0.625rem)"],
58
+ ["radius", "border-top-left-radius", "var(--cover-psp-field-radius, calc(var(--ui-radius, 0.25rem) * 1.5))"],
59
+ ["fontSize", "font-size", "var(--cover-psp-field-font-size, 1rem)"],
60
+ ["labelSize", "width", "var(--cover-psp-field-label-size, 0.875rem)"],
61
+ ];
62
+
63
+ /** A value that cannot leave its declaration: no `;`, braces or markup. */
64
+ function clean(value: string | undefined): string {
65
+ return String(value ?? "").replace(/[;{}<>]/g, "").trim();
66
+ }
67
+
68
+ /**
69
+ * The `iframe.style` block for the tokens. Pure, so it can be tested.
70
+ *
71
+ * Focus and placeholder go into the style sheet, since an inline style cannot
72
+ * name a state. They are `!important` there because the inline `input` style
73
+ * would win over a rule without it.
74
+ */
75
+ export function novalnetIframeStyle(tokens: NovalnetFieldTokens): NovalnetIframeStyle {
76
+ const t = Object.fromEntries(
77
+ Object.entries(tokens).map(([k, v]) => [k, Array.isArray(v) ? v : clean(v as string)]),
78
+ ) as unknown as NovalnetFieldTokens;
79
+ const font = t.fontFamily ? `font-family:${t.fontFamily};` : "";
80
+ const input = [
81
+ font,
82
+ `font-size:${t.fontSize};`,
83
+ "line-height:1.25;",
84
+ `color:${t.text};`,
85
+ `background:${t.background};`,
86
+ `border:1px solid ${t.border};`,
87
+ `border-radius:${t.radius};`,
88
+ `height:${t.height};`,
89
+ `padding:0 ${t.paddingX};`,
90
+ "box-sizing:border-box;",
91
+ "width:100%;",
92
+ "box-shadow:none;",
93
+ "outline:0;",
94
+ "transition:border-color .15s,box-shadow .15s;",
95
+ ].join("");
96
+ const label = [
97
+ font,
98
+ `font-size:${t.labelSize};`,
99
+ "font-weight:500;",
100
+ `color:${t.label};`,
101
+ ].join("");
102
+ const container = [
103
+ ...(tokens.fontFaces ?? []),
104
+ `html,body{${font}margin:0;background:transparent;color:${t.text};}`,
105
+ `input:focus{border-color:${t.focus}!important;box-shadow:inset 0 0 0 1px ${t.focus}!important;}`,
106
+ `input::placeholder{color:${t.placeholder}!important;opacity:1;}`,
107
+ `.label-group{${label}}`,
108
+ ".form-group{margin:0 0 .75rem;}",
109
+ ].join("");
110
+ return { container, input, label };
111
+ }
112
+
113
+ /** `url(...)` in a rule, made absolute against the sheet the rule came from. */
114
+ function absoluteUrls(cssText: string, base: string): string {
115
+ return cssText.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (_m, quote: string, url: string) => {
116
+ try {
117
+ return `url(${quote}${new URL(url, base).href}${quote})`;
118
+ }
119
+ catch {
120
+ return _m;
121
+ }
122
+ });
123
+ }
124
+
125
+ /**
126
+ * The page's `@font-face` rules for the first family of `fontFamily`. The
127
+ * iframe is another origin, so it cannot see the shop's web font unless the
128
+ * rule travels along. Whether the browser then loads the file depends on the
129
+ * font being served with CORS; without it the fallback families apply.
130
+ */
131
+ export function pageFontFaces(fontFamily: string, doc: Document = document, limit = 6): string[] {
132
+ const family = fontFamily.split(",")[0]?.trim().replace(/^['"]|['"]$/g, "").toLowerCase();
133
+ if (!family) {
134
+ return [];
135
+ }
136
+ const out: string[] = [];
137
+ for (const sheet of Array.from(doc.styleSheets)) {
138
+ let rules: CSSRuleList;
139
+ try {
140
+ rules = sheet.cssRules;
141
+ }
142
+ catch {
143
+ continue; // a cross-origin sheet does not let its rules be read
144
+ }
145
+ for (const rule of Array.from(rules)) {
146
+ if (out.length >= limit) {
147
+ return out;
148
+ }
149
+ if (rule.constructor?.name !== "CSSFontFaceRule" && !rule.cssText.startsWith("@font-face")) {
150
+ continue;
151
+ }
152
+ const declared = (rule as CSSFontFaceRule).style?.getPropertyValue("font-family")?.trim().replace(/^['"]|['"]$/g, "").toLowerCase();
153
+ if (declared === family) {
154
+ out.push(absoluteUrls(rule.cssText, sheet.href ?? doc.baseURI));
155
+ }
156
+ }
157
+ }
158
+ return out;
159
+ }
160
+
161
+ /**
162
+ * The theme's tokens, resolved by the browser. A probe inside `el` carries
163
+ * each variable on a property of its own, so it inherits whatever `el` sits in
164
+ * (a theme, a dark section) and comes back as a plain colour or length.
165
+ */
166
+ export function readNovalnetFieldTokens(el: HTMLElement): NovalnetFieldTokens {
167
+ const probe = document.createElement("div");
168
+ probe.setAttribute("aria-hidden", "true");
169
+ probe.style.cssText = "position:absolute;visibility:hidden;pointer-events:none;border:1px solid;";
170
+ for (const [, property, value] of PROBE) {
171
+ probe.style.setProperty(property, value);
172
+ }
173
+ el.appendChild(probe);
174
+ try {
175
+ const computed = getComputedStyle(probe);
176
+ const tokens = { fontFamily: getComputedStyle(el).fontFamily } as NovalnetFieldTokens;
177
+ for (const [key, property] of PROBE) {
178
+ (tokens as unknown as Record<string, string>)[key] = computed.getPropertyValue(property);
179
+ }
180
+ tokens.fontFaces = pageFontFaces(tokens.fontFamily);
181
+ return tokens;
182
+ }
183
+ finally {
184
+ probe.remove();
185
+ }
186
+ }
@@ -0,0 +1,7 @@
1
+ import type { ProductCategory } from "../config/navigation";
2
+
3
+ /** Whether a two-level category tree has the category, and the subcategory under it when one is named. */
4
+ export function treeHasCategory(categories: readonly ProductCategory[], slug: string | undefined, subcategory?: string): boolean {
5
+ const category = categories.find(c => c.slug === slug);
6
+ return !!category && (!subcategory || category.subcategories.some(s => s.slug === subcategory));
7
+ }
@@ -13,6 +13,14 @@
13
13
  * client (facet labels), so both resolve a label the same way.
14
14
  */
15
15
 
16
+ /**
17
+ * Cookie the language choice persists the chosen MARKET locale in (`de-CH`,
18
+ * `fr-FR`). The URL prefix only says which UI strings render; this says
19
+ * which catalogue language the buyer asked for, which differs when the
20
+ * market offers a language the storefront has no UI strings for (PE-866).
21
+ */
22
+ export const CONTENT_LOCALE_COOKIE = "cover-content-locale";
23
+
16
24
  /** The region a bare UI language stands for when a full code is needed. */
17
25
  export const DEFAULT_LOCALE_REGIONS: Readonly<Record<string, string>> = {
18
26
  de: "DE",
@@ -32,6 +32,44 @@ export function languagesWithDocuments(
32
32
  searchLocaleKeys(language).some(key => present.has(key)));
33
33
  }
34
34
 
35
+ /**
36
+ * The product's name in each language (of `languages`) it has a document in:
37
+ * the document the product page would find, under the first of the
38
+ * language's search keys that has one (PE-1236). A product's slug carries its
39
+ * name, so a link into another language needs that language's name, or it
40
+ * lands on the outdated-slug 301.
41
+ */
42
+ export function namesByLanguage(
43
+ docs: readonly { readonly locale: string; readonly name?: string }[],
44
+ languages: readonly string[],
45
+ ): Record<string, string> {
46
+ const byLocale = new Map(docs
47
+ .filter(doc => doc.locale && doc.name)
48
+ .map(doc => [normalizeLocaleCode(doc.locale), doc.name as string]));
49
+ const names: Record<string, string> = {};
50
+ for (const language of languages) {
51
+ const key = searchLocaleKeys(language).find(candidate => byLocale.has(candidate));
52
+ if (key) {
53
+ names[language] = byLocale.get(key) as string;
54
+ }
55
+ }
56
+ return names;
57
+ }
58
+
59
+ /**
60
+ * A product page's path with its slug swapped for another language's. The
61
+ * slug is the path's last segment; a path that does not end in `current` is
62
+ * returned as it is.
63
+ */
64
+ export function withProductSlug(path: string, current: string, target: string): string {
65
+ const [pathname = "", ...rest] = path.split(/(?=[?#])/);
66
+ const suffix = `/${encodeURIComponent(current)}`;
67
+ if (!current || !target || current === target || !pathname.endsWith(suffix)) {
68
+ return path;
69
+ }
70
+ return `${pathname.slice(0, -suffix.length)}/${encodeURIComponent(target)}${rest.join("")}`;
71
+ }
72
+
35
73
  /**
36
74
  * The listing a language without the product sends the buyer to: the
37
75
  * product's own category, as deep as a listing URL goes
@@ -41,10 +79,15 @@ export function languagesWithDocuments(
41
79
  * translated, so the same path exists in every language.
42
80
  */
43
81
  export function productFallbackPath(categorySegments: readonly string[]): string {
44
- const path = categorySegments.filter(segment => segment && segment !== "_").slice(0, 2);
82
+ const path = productListingSegments(categorySegments);
45
83
  return path.length ? `/category/${path.map(encodeURIComponent).join("/")}` : "/";
46
84
  }
47
85
 
86
+ /** The category and subcategory of productFallbackPath(), none for `_` or a URL without a category. */
87
+ export function productListingSegments(categorySegments: readonly string[]): string[] {
88
+ return categorySegments.filter(segment => segment && segment !== "_").slice(0, 2);
89
+ }
90
+
48
91
  /** The category segments of a `/category/<…>/product/<slug>` route. */
49
92
  export function productRouteCategorySegments(category: readonly string[], rest: readonly string[]): string[] {
50
93
  const marker = rest.lastIndexOf("product");
@@ -67,6 +110,24 @@ export interface LocaleHeadMeta {
67
110
  [key: string]: unknown;
68
111
  }
69
112
 
113
+ /**
114
+ * The locale head with each alternate's href put through `localize` for its
115
+ * language (`x-default` for `defaultLocale`): a product page's alternates
116
+ * carry the slug of the language they link (PE-1236).
117
+ */
118
+ export function localizeLocaleHeadAlternates<L extends LocaleHeadLink, M extends LocaleHeadMeta>(
119
+ head: { link?: L[]; meta?: M[] },
120
+ localize: (href: string, code: string) => string,
121
+ defaultLocale: string,
122
+ ): { link: L[]; meta: M[] } {
123
+ return {
124
+ link: (head.link ?? []).map(entry => (entry.rel === "alternate" && entry.hreflang && entry.href
125
+ ? { ...entry, href: localize(entry.href, entry.hreflang === "x-default" ? defaultLocale : entry.hreflang) }
126
+ : entry)),
127
+ meta: head.meta ?? [],
128
+ };
129
+ }
130
+
70
131
  /**
71
132
  * The locale head with alternates only for the languages that have the page.
72
133
  *
@@ -0,0 +1,297 @@
1
+ import type { SeoRules } from "../interfaces/seo";
2
+ import { localeLanguage } from "./locale";
3
+ import type { LocaleHeadLink, LocaleHeadMeta } from "./productLocales";
4
+
5
+ /**
6
+ * The seo service's defaults for a domain nobody configured — the same values
7
+ * its bundle carries then. The storefront falls back to these when the rules
8
+ * cannot be read, so a page never waits on SEO and never renders without it.
9
+ */
10
+ const DEFAULT_STRIP_PARAMS: readonly string[] = ["utm_*", "gclid", "fbclid", "msclkid", "sort", "order"];
11
+
12
+ export function defaultSeoRules(host: string): SeoRules {
13
+ return {
14
+ schema: 1,
15
+ host,
16
+ site_name: host,
17
+ canonical: { host: null, cross_domain_page_types: ["product", "category"], strip_params: DEFAULT_STRIP_PARAMS },
18
+ hreflang: { x_default: null, locales: null },
19
+ max_length: { title: 60, description: 160 },
20
+ page_types: {
21
+ home: { title: "{site}", description: null, robots: "index,follow" },
22
+ product: { title: "{name} | {site}", description: "{description}", robots: "index,follow" },
23
+ category: { title: "{name} | {site}", description: "{description}", robots: "index,follow" },
24
+ page: { title: "{name} | {site}", description: "{description}", robots: "index,follow" },
25
+ search: { robots: "noindex,follow" },
26
+ cart: { robots: "noindex,nofollow" },
27
+ checkout: { robots: "noindex,nofollow" },
28
+ "checkout-confirmation": { robots: "noindex,nofollow" },
29
+ login: { robots: "noindex,nofollow" },
30
+ register: { robots: "noindex,nofollow" },
31
+ "forgot-password": { robots: "noindex,nofollow" },
32
+ "reset-password": { robots: "noindex,nofollow" },
33
+ account: { robots: "noindex,nofollow" },
34
+ preview: { robots: "noindex,nofollow" },
35
+ },
36
+ organisation: null,
37
+ structured_data: { prices: true },
38
+ removed_products: "category",
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Hosts the theme editor and previews render on (`<tenant>.theme.rvnxx.site`).
44
+ * Never indexable, whatever the rules of the tenant's domains say.
45
+ */
46
+ export function isPreviewHost(host: string): boolean {
47
+ return host.toLowerCase().endsWith(".theme.rvnxx.site");
48
+ }
49
+
50
+ /** Whether a query parameter is one the canonical leaves out (`utm_*` matches by prefix). */
51
+ function isStrippedParam(name: string, stripParams: readonly string[]): boolean {
52
+ const lower = name.toLowerCase();
53
+ return stripParams.some(rule => rule.endsWith("*")
54
+ ? lower.startsWith(rule.slice(0, -1).toLowerCase())
55
+ : lower === rule.toLowerCase());
56
+ }
57
+
58
+ /**
59
+ * The only query parameters a canonical carries, each with the values it
60
+ * carries them with. Any other parameter (a tracking id the rules do not know,
61
+ * a session id, one made up) would make each URL its own canonical and write
62
+ * foreign values into `canonical` and `og:url`; facets and searches name the
63
+ * clean listing instead. `page` only from 2: page 1 is the listing itself,
64
+ * and `?page=abc` no page at all.
65
+ */
66
+ const CANONICAL_PARAMS: ReadonlyMap<string, (value: string) => boolean> = new Map([
67
+ ["page", value => /^[1-9]\d*$/.test(value) && value !== "1"],
68
+ ]);
69
+
70
+ /**
71
+ * `path` (or an href) on `origin`, never on another host: `new URL(path, base)`
72
+ * would read a protocol-relative `//other.example/x` as that host.
73
+ */
74
+ function onOrigin(path: string, origin: string): URL {
75
+ return path.startsWith("/") ? new URL(`${origin}${path}`) : new URL(path, origin);
76
+ }
77
+
78
+ /**
79
+ * The canonical URL of a page: the site's origin (or the main domain for a
80
+ * page type that canonicalises across domains), the path as served, and of
81
+ * the query only `page`, from 2 on, so every page of a listing is its own
82
+ * canonical; `page=1` and a page that is no page number at all name the
83
+ * listing itself. A parameter the rules strip is left out even then.
84
+ */
85
+ export function seoCanonicalUrl(options: {
86
+ readonly origin: string;
87
+ readonly path: string;
88
+ readonly query: Readonly<Record<string, unknown>>;
89
+ readonly rules: SeoRules;
90
+ readonly pageType?: string;
91
+ }): string {
92
+ const { rules, pageType } = options;
93
+ const crossDomain = rules.canonical.host && pageType && rules.canonical.cross_domain_page_types.includes(pageType);
94
+ const url = onOrigin(options.path, crossDomain ? `https://${rules.canonical.host}` : options.origin);
95
+ const kept = Object.entries(options.query)
96
+ .filter(([name]) => CANONICAL_PARAMS.has(name) && !isStrippedParam(name, rules.canonical.strip_params))
97
+ .sort(([a], [b]) => a.localeCompare(b));
98
+ for (const [name, value] of kept) {
99
+ // One value per parameter: `?page=2&page=3` is not two pages.
100
+ const carried = (Array.isArray(value) ? value : [value])
101
+ .map(item => (item === null || item === undefined ? "" : String(item)))
102
+ .find(item => CANONICAL_PARAMS.get(name)?.(item));
103
+ if (carried !== undefined) {
104
+ url.searchParams.set(name, carried);
105
+ }
106
+ }
107
+ return url.href;
108
+ }
109
+
110
+ /**
111
+ * An x-default link from another hreflang link. i18n keys its head links by
112
+ * `id` or, under strict SEO, `key`; whichever the source carries becomes
113
+ * i18n's x-default key, so the copy never replaces the alternate it came from.
114
+ */
115
+ function xDefaultEntry<L extends LocaleHeadLink>(source: L, href: string): L {
116
+ const entry: L = { ...source, hreflang: "x-default", href };
117
+ for (const attribute of ["id", "key"] as const) {
118
+ if (attribute in entry) {
119
+ (entry as LocaleHeadLink)[attribute] = "i18n-xd";
120
+ }
121
+ }
122
+ return entry;
123
+ }
124
+
125
+ /**
126
+ * `useLocaleHead({ seo: true })` with the domain's rules applied.
127
+ *
128
+ * @nuxtjs/i18n writes every URL without a host (it has no per-request
129
+ * `baseUrl`), and search engines ignore relative hreflang links. So:
130
+ *
131
+ * - alternates become absolute on the request's origin;
132
+ * - with `hreflang.locales` set, only those languages are linked (matched by
133
+ * language subtag, as i18n writes both `de` and `de-DE`);
134
+ * - with `hreflang.x_default` set, `x-default` points at that language's URL,
135
+ * and is dropped when that language is not linked;
136
+ * - the canonical and `og:url` go: the page's canonical follows the rules
137
+ * (seoCanonicalUrl), and nuxt-seo-utils derives `og:url` from it.
138
+ */
139
+ export function applySeoRulesToLocaleHead<L extends LocaleHeadLink, M extends LocaleHeadMeta>(
140
+ head: { link?: L[]; meta?: M[] },
141
+ options: { readonly origin: string; readonly rules: SeoRules },
142
+ ): { link: L[]; meta: M[] } {
143
+ const { locales, x_default: xDefault } = options.rules.hreflang;
144
+ const languages = locales ? new Set(locales.map(localeLanguage)) : null;
145
+ const linked = (code: string): boolean => !languages || languages.has(localeLanguage(code));
146
+ const absolute = (href: string | undefined): string | undefined =>
147
+ href === undefined ? undefined : onOrigin(href, options.origin).href;
148
+
149
+ const alternates = (head.link ?? [])
150
+ .filter(entry => entry.rel === "alternate" && entry.hreflang && entry.hreflang !== "x-default")
151
+ .filter(entry => linked(entry.hreflang as string))
152
+ .map(entry => ({ ...entry, href: absolute(entry.href) }));
153
+
154
+ // i18n's own x-default is gone where the default language has no page
155
+ // (filterLocaleHeadAlternates, PE-859); the rules' x-default then grows out
156
+ // of the alternate it points at, under i18n's x-default identity.
157
+ const defaultLink = (head.link ?? []).find(entry => entry.rel === "alternate" && entry.hreflang === "x-default");
158
+ const xDefaultTarget = xDefault
159
+ ? alternates.find(entry => localeLanguage(entry.hreflang as string) === localeLanguage(xDefault))
160
+ : undefined;
161
+ const defaultHref = xDefault ? xDefaultTarget?.href : absolute(defaultLink?.href);
162
+ const keptHrefs = new Set(alternates.map(entry => entry.href));
163
+ const xDefaultBase = defaultLink ?? xDefaultTarget;
164
+ const xDefaultLink = xDefaultBase && defaultHref && keptHrefs.has(defaultHref)
165
+ ? [xDefaultEntry(xDefaultBase, defaultHref)]
166
+ : [];
167
+
168
+ const others = (head.link ?? []).filter(entry => entry.rel !== "alternate" && entry.rel !== "canonical");
169
+
170
+ return {
171
+ link: [...others, ...xDefaultLink, ...alternates],
172
+ meta: (head.meta ?? []).filter(entry => entry.property !== "og:url"
173
+ && (entry.property !== "og:locale:alternate" || !entry.content || linked(entry.content))),
174
+ };
175
+ }
176
+
177
+ /**
178
+ * The regional hreflang alternates in the region the shop's market speaks
179
+ * each language in: i18n writes its own config's codes (`de-DE`, `en-US`),
180
+ * so a Swiss market gets `de-CH` instead, the same locale `<html lang>`
181
+ * names (PE-1237). `marketLocale` answers the market's locale for a code's
182
+ * language, or null while the markets carry none; the i18n code then stands.
183
+ * The bare language alternates (`de`) and `x-default` stay as they are, and
184
+ * an alternate whose new code is already linked goes.
185
+ */
186
+ export function marketHreflangAlternates<L extends LocaleHeadLink>(
187
+ links: readonly L[],
188
+ marketLocale: (code: string) => string | null,
189
+ ): L[] {
190
+ const linked = new Set<string>();
191
+ return links
192
+ .map((entry) => {
193
+ const code = entry.rel === "alternate" ? entry.hreflang : undefined;
194
+ if (!code || code === "x-default" || !code.includes("-")) {
195
+ return entry;
196
+ }
197
+ const market = marketLocale(code);
198
+ return market ? { ...entry, hreflang: market } : entry;
199
+ })
200
+ .filter((entry) => {
201
+ if (entry.rel !== "alternate" || !entry.hreflang) {
202
+ return true;
203
+ }
204
+ const code = entry.hreflang.toLowerCase();
205
+ if (linked.has(code)) {
206
+ return false;
207
+ }
208
+ linked.add(code);
209
+ return true;
210
+ });
211
+ }
212
+
213
+ /** What a page's title and description patterns are filled from. */
214
+ export interface SeoPatternValues {
215
+ readonly name?: string;
216
+ readonly category?: string;
217
+ readonly brand?: string;
218
+ readonly parent?: string;
219
+ readonly description?: string;
220
+ }
221
+
222
+ /**
223
+ * A title or description pattern of the rules (`{name} | {site}`) filled in
224
+ * and cut at its maximum length. A placeholder without a value is left empty
225
+ * and a separator left dangling at either end goes with it; the service
226
+ * refuses unknown placeholders, so none reach here.
227
+ */
228
+ export function fillSeoPattern(pattern: string, values: SeoPatternValues & { readonly site: string }, maxLength: number): string {
229
+ const filled = pattern
230
+ .replace(/\{(\w+)\}/g, (_, key: string) => (values as Record<string, string | undefined>)[key]?.trim() ?? "")
231
+ .replace(/^\s*[|–—-]\s*|\s*[|–—-]\s*$/g, "")
232
+ .replace(/\s{2,}/g, " ")
233
+ .trim();
234
+ return filled.length > maxLength ? `${filled.slice(0, maxLength - 1).trimEnd()}…` : filled;
235
+ }
236
+
237
+ /**
238
+ * A page's title from its type's pattern, or undefined where the page's own
239
+ * title stands instead: the type has no pattern, the subject the pattern names
240
+ * (`{name}`) is not known yet, or the pattern is the bare `{site}` (the home
241
+ * page's default) and the page brings a title of its own — the shop's curated
242
+ * home title, or the one the home page's author stored. A pattern a tenant
243
+ * wrote for the home page (`{site} – Werkzeug online`) is used as written.
244
+ */
245
+ export function seoPatternTitle(
246
+ pattern: string | undefined,
247
+ values: SeoPatternValues & { readonly site: string },
248
+ maxLength: number,
249
+ ownTitle?: string,
250
+ ): string | undefined {
251
+ const ownTitleStands = pattern?.includes("{name}")
252
+ ? !values.name
253
+ : pattern?.trim() === "{site}" && Boolean(ownTitle);
254
+ if (!pattern || ownTitleStands) {
255
+ return undefined;
256
+ }
257
+ return fillSeoPattern(pattern, values, maxLength) || undefined;
258
+ }
259
+
260
+ /** The directives of a robots rule, lower-cased, with `none` and `all` spelled out. */
261
+ function robotsDirectives(rule: string): string[] {
262
+ return rule.split(",").map(d => d.trim().toLowerCase()).filter(Boolean)
263
+ .flatMap(d => (d === "none" ? ["noindex", "nofollow"] : d === "all" ? ["index", "follow"] : [d]));
264
+ }
265
+
266
+ /** Whether a robots rule lets the page into the index. */
267
+ export function isIndexableRobotsRule(rule: string): boolean {
268
+ return !robotsDirectives(rule).includes("noindex");
269
+ }
270
+
271
+ /**
272
+ * The robots directive for a page: its type's rule from the rules, turned to
273
+ * `noindex` when this URL must not be indexed although its type may be (a
274
+ * filtered listing, an empty category, a missing product), and to `nofollow`
275
+ * when its links must not be followed either (a preview). Any other directive
276
+ * of the rule (`noarchive`, `max-image-preview:large`, …) is kept.
277
+ */
278
+ export function seoRobotsRule(typeRule: string, flags: { readonly noindex?: boolean; readonly nofollow?: boolean } = {}): string {
279
+ const directives = robotsDirectives(typeRule);
280
+ const index = flags.noindex || directives.includes("noindex") ? "noindex" : "index";
281
+ const follow = flags.nofollow || directives.includes("nofollow") ? "nofollow" : "follow";
282
+ const others = directives.filter(d => !["index", "noindex", "follow", "nofollow"].includes(d));
283
+ return [index, follow, ...others].join(", ");
284
+ }
285
+
286
+ /**
287
+ * Whether a listing URL is filtered, searched within or priced — anything the
288
+ * clean listing is not, apart from paging and the parameters the canonical
289
+ * strips anyway. Such a URL is a near-duplicate of its listing and stays out
290
+ * of the index until filter pages can be released (phase 3).
291
+ */
292
+ export function hasListingFilters(query: Readonly<Record<string, unknown>>, rules: SeoRules): boolean {
293
+ return Object.entries(query).some(([name, value]) =>
294
+ value !== undefined && value !== null && value !== ""
295
+ && name !== "page"
296
+ && !isStrippedParam(name, rules.canonical.strip_params));
297
+ }