@eldrajs/theme-cli 0.1.0 → 0.2.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 (84) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/cli.js +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/{validate-C6jB8_Oc.js → validate-DprFpjV7.js} +29 -4
  5. package/package.json +3 -3
  6. package/template/.eldra/block-types.d.ts +12 -3
  7. package/template/.eldra/manifest.json +317 -26
  8. package/template/.eldra/previews.json +35 -34
  9. package/template/.github/workflows/eldra-deploy.yml +2 -0
  10. package/template/.gitlab-ci.yml +2 -0
  11. package/template/.storybook/main.ts +3 -0
  12. package/template/.storybook/preview.ts +2 -1
  13. package/template/.storybook/virtual-eldra.d.ts +5 -0
  14. package/template/README.md +31 -14
  15. package/template/app/components/FormHoneypot.vue +21 -0
  16. package/template/app/composables/useFormSpam.ts +55 -0
  17. package/template/app/composables/usePageStructuredData.ts +112 -0
  18. package/template/app/composables/useTurnstile.ts +111 -0
  19. package/template/app/formSeeds.ts +93 -0
  20. package/template/app/pages/[...slug].vue +48 -12
  21. package/template/app/plugins/eldra-storefront.ts +19 -2
  22. package/template/app/plugins/eldra-ui-messages.ts +1 -1
  23. package/template/app/seededPages.ts +7 -0
  24. package/template/app/storefront/analytics.ts +202 -0
  25. package/template/app/storefront/cart.ts +7 -0
  26. package/template/app/storefront/demo.ts +48 -2
  27. package/template/app/storefront/forms.ts +133 -0
  28. package/template/app/storefront/gateway.ts +113 -7
  29. package/template/app/storefront/money.ts +18 -17
  30. package/template/app/storefront/structuredData.ts +161 -0
  31. package/template/app/storefront/types.ts +101 -2
  32. package/template/app/utils/seoInput.ts +172 -0
  33. package/template/bitbucket-pipelines.yml +3 -1
  34. package/template/blocks/breadcrumbs/Block.vue +1 -0
  35. package/template/blocks/cart/Block.vue +1 -0
  36. package/template/blocks/cart/parts/Summary.vue +1 -0
  37. package/template/blocks/contact/Block.vue +50 -21
  38. package/template/blocks/contact/__tests__/Block.spec.ts +89 -8
  39. package/template/blocks/contact/block.json +2 -9
  40. package/template/blocks/contact/mock.json +1 -2
  41. package/template/blocks/footer/Block.vue +58 -8
  42. package/template/blocks/footer/__tests__/Block.spec.ts +70 -16
  43. package/template/blocks/footer/preview.png +0 -0
  44. package/template/blocks/form/Block.vue +614 -0
  45. package/template/blocks/form/__tests__/Block.spec.ts +536 -0
  46. package/template/blocks/form/block.json +69 -0
  47. package/template/blocks/form/mock.json +25 -0
  48. package/template/blocks/form/preview.png +0 -0
  49. package/template/blocks/form/validate.ts +68 -0
  50. package/template/blocks/newsletter/Block.vue +57 -3
  51. package/template/blocks/newsletter/__tests__/Block.spec.ts +89 -31
  52. package/template/blocks/newsletter/block.json +4 -5
  53. package/template/blocks/newsletter/mock.json +1 -1
  54. package/template/blocks/newsletter/preview.png +0 -0
  55. package/template/blocks/product-detail/__tests__/Block.spec.ts +7 -10
  56. package/template/i18n/en-US.json +33 -2
  57. package/template/i18n/is-IS.json +33 -2
  58. package/template/nuxt.config.ts +15 -1
  59. package/template/package.json +1 -0
  60. package/template/public/apple-touch-icon.png +0 -0
  61. package/template/public/favicon.ico +0 -0
  62. package/template/stories/generated/form.stories.ts +68 -0
  63. package/template/test/formValidate.spec.ts +46 -0
  64. package/template/test/inlineEditable.spec.ts +2 -1
  65. package/template/test/moneyFormatting.spec.ts +4 -8
  66. package/template/test/pages/ssr.spec.ts +5 -11
  67. package/template/test/prerenderFailure.spec.ts +1 -1
  68. package/template/test/prerenderRefresh.browser.spec.ts +5 -1
  69. package/template/test/richText.spec.ts +12 -9
  70. package/template/test/seededPages.spec.ts +13 -0
  71. package/template/test/seoInput.spec.ts +119 -0
  72. package/template/test/slugPage.spec.ts +62 -26
  73. package/template/test/slugPageTemplate.spec.ts +5 -1
  74. package/template/test/starter.spec.ts +42 -4
  75. package/template/test/storefront/analytics.spec.ts +283 -0
  76. package/template/test/storefront/forms.spec.ts +385 -0
  77. package/template/test/storefront/money.spec.ts +11 -12
  78. package/template/test/storefront/structuredData.spec.ts +138 -0
  79. package/template/test/structuredData.generate.spec.ts +159 -0
  80. package/template/test/support/mockGateway.ts +29 -1
  81. package/template/test/support/turnstileForms.ts +53 -0
  82. package/template/test/useBlockData.spec.ts +7 -4
  83. package/template/app/utils/pageTitle.ts +0 -37
  84. package/template/test/pageTitle.spec.ts +0 -49
@@ -1,5 +1,6 @@
1
1
  import type { ComputedRef } from 'vue';
2
2
  import {
3
+ createNumberFormat,
3
4
  currencyFractionDigits,
4
5
  currencySymbol,
5
6
  formatCurrency,
@@ -16,14 +17,14 @@ import {
16
17
  * read **minor** units (their own `amount` docs say so), so anything handed to one of those
17
18
  * components goes through `toMinorUnits` first, while money that has to appear inside a sentence
18
19
  * ("Add to cart · 2.800 kr.") is formatted here with `formatMoney`. A third shape names the
19
- * currency itself rather than an amount in it ("ISK kr"): `currencyLabel`.
20
+ * currency itself rather than an amount in it ("ISK kr."): `currencyLabel`.
20
21
  *
21
22
  * **Nothing here builds an `Intl.NumberFormat` of its own.** Both money shapes go through
22
23
  * `@eldrajs/ui`'s `formatCurrency`/`currencySymbol`, which is the same formatter — and therefore
23
- * the same **narrow** currency sign — that every `<Price>`, `<ProductCard>` and `<CurrencyInput>`
24
- * on the page renders with. A hand-built `{ style: 'currency' }` formatter writes the *wide* sign
25
- * instead, and that is exactly how this theme came to read "ISK 2,800" in a button label beside a
26
- * `<Price>` reading "kr 2,800" for the same money.
24
+ * the same currency sign — that every `<Price>`, `<ProductCard>` and `<CurrencyInput>` on the page
25
+ * renders with: the **wide** one, so English reads `ISK 2,800` and Icelandic `2.800 kr.`. A second
26
+ * formatter with its own sign is how a button label once read "ISK 2,800" beside a `<Price>`
27
+ * reading "kr 2,800" for the same money.
27
28
  *
28
29
  * **The currency is the store's, and it is never guessed.** It comes from the platform — the
29
30
  * organisation's own commerce settings, read once at build and put on
@@ -58,11 +59,11 @@ interface MoneyFormat {
58
59
  * `useMoney().format` is a fresh call on every render of every price and a collection grid renders
59
60
  * one or two per card, so what this saves is worth saving: the `currencyFractionDigits` lookup, the
60
61
  * one probe that decides whether `Intl` will accept the store's code at all, and — for a store with
61
- * no currency — the one `Intl.NumberFormat` this module still constructs itself. A store has one
62
+ * no currency — the one plain-decimal formatter this module still asks for itself. A store has one
62
63
  * currency and a handful of locales, so the cache is a few entries that never need evicting.
63
64
  *
64
65
  * What it deliberately does **not** cache is a currency formatter. `formatCurrency` is
65
- * `@eldrajs/ui`'s own, stateless by design, and the single place the narrow sign and the
66
+ * `@eldrajs/ui`'s own, stateless by design, and the single place the sign and the
66
67
  * fraction-digit rule are decided; a formatter cached here would be a second definition of both,
67
68
  * which is precisely the bug this module had. Its per-amount construction is a few microseconds
68
69
  * against a render that costs far more.
@@ -86,7 +87,7 @@ function resolveFormat(currency: string | undefined, locale: string): MoneyForma
86
87
  * dangling separator would reach the DOM and the accessible text of every price on the page.
87
88
  */
88
89
  const decimal = (): MoneyFormat => {
89
- const formatter = new Intl.NumberFormat(locale, { style: 'decimal' });
90
+ const formatter = createNumberFormat({ locale, style: 'decimal' });
90
91
  return {
91
92
  format: (amount) =>
92
93
  code === '' ? formatter.format(amount) : `${formatter.format(amount)} ${code}`,
@@ -102,15 +103,15 @@ function resolveFormat(currency: string | undefined, locale: string): MoneyForma
102
103
  // helper it ports does, and this runs inside `computed`s where a throw takes the whole block
103
104
  // down. So the code is probed once per pair here rather than guarded once per amount.
104
105
  try {
105
- formatCurrency(0, locale, code, true, digits, digits);
106
+ formatCurrency(0, locale, code, false, digits, digits);
106
107
  resolved = {
107
- // The narrow sign is the util's own default and the whole reason to go through it. The
108
- // currency's own count goes in twice: as the cap, because the util's default of 2 would
108
+ // The wide sign, as every `<Price>` writes it. The currency's own count goes in twice: as
109
+ // the cap, because the util's default of 2 would
109
110
  // print a fractional króna and round a three-decimal currency to two; and as the
110
111
  // **minimum**, which is the util's display rule — without it `$96` and `$96.50` sit in the
111
112
  // same column. Both are exactly what `<Price>` passes, so a formatted sentence and the
112
113
  // `<Price>` beside it cannot disagree about either.
113
- format: (amount) => formatCurrency(amount, locale, code, true, digits, digits),
114
+ format: (amount) => formatCurrency(amount, locale, code, false, digits, digits),
114
115
  digits,
115
116
  };
116
117
  } catch {
@@ -123,8 +124,8 @@ function resolveFormat(currency: string | undefined, locale: string): MoneyForma
123
124
  }
124
125
 
125
126
  /**
126
- * A major-unit amount as text, in the currency's own shape and its **narrow** sign: `$28.00` for
127
- * `USD`, `2.800 kr.` for `ISK` on an Icelandic page, `kr 2,800` for the same money on an English
127
+ * A major-unit amount as text, in the currency's own shape and its **wide** sign: `$28.00` for
128
+ * `USD`, `2.800 kr.` for `ISK` on an Icelandic page, `ISK 2,800` for the same money on an English
128
129
  * one. The fraction count is the currency's own, as both the maximum and the minimum, so a
129
130
  * zero-decimal currency never renders phantom decimals and a two-decimal one never renders a
130
131
  * ragged column.
@@ -147,19 +148,19 @@ export function formatMoney(
147
148
 
148
149
  /**
149
150
  * A currency *code* as text naming itself, not an amount: `"ISK kr."` on an Icelandic page,
150
- * `"ISK kr"` on an English one, `"USD $"` — the code plus the sign `formatMoney` prints in front
151
+ * `"ISK"` on an English one, `"USD $"` — the code plus the sign `formatMoney` prints in front
151
152
  * of the amounts on the same page, for a place that names the store's currency rather than
152
153
  * formatting a price in it (the footer's currency selector, with one option now that the platform
153
154
  * publishes one currency).
154
155
  *
155
- * `@eldrajs/ui`'s `currencySymbol` is where the sign comes from — the **narrow** one, read out of
156
+ * `@eldrajs/ui`'s `currencySymbol` is where the sign comes from — the **wide** one, read out of
156
157
  * `formatToParts`, never a hand-maintained code → symbol table — so this label and every price on
157
158
  * the page are written with the same character. One fallback, and it is the honest one: the code
158
159
  * appended to itself is noise, so a currency with no sign distinct from its code in this locale
159
160
  * (which is also what `currencySymbol` answers for a code `Intl` rejects) prints just the code.
160
161
  */
161
162
  export function currencyLabel(code: string, locale: string = DEFAULT_LOCALE): string {
162
- const symbol = currencySymbol(code, locale);
163
+ const symbol = currencySymbol(code, locale, false);
163
164
  return symbol === code ? code : `${code} ${symbol}`;
164
165
  }
165
166
 
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The page's schema.org JSON-LD, from data the page already renders: the **same** product, the same
3
+ * variant prices, the same store currency and the same stock states (`variantStock` in
4
+ * `gateway.ts`) the buy box and `<Price>` read, so the markup cannot disagree with the page.
5
+ *
6
+ * Pure — no Vue, no Nuxt, no storefront — so `test/storefront/structuredData.spec.ts` pins every
7
+ * page type without mounting anything. The builders themselves are `@eldrajs/theme-core`'s
8
+ * (framework-free, theme-agnostic); this file is what is specific to this theme: which nodes a
9
+ * page type writes and how a `StorefrontProduct` maps onto them.
10
+ *
11
+ * | Page | Nodes |
12
+ * | --------------- | ---------------------------------------------- |
13
+ * | home | `Organization`, `WebSite` (+ `SearchAction`) |
14
+ * | product | `BreadcrumbList`, `Product` |
15
+ * | category/collection | `BreadcrumbList`, `ItemList` of the products shown |
16
+ * | any other page | `BreadcrumbList` |
17
+ * | not found | nothing |
18
+ *
19
+ * `Organization` and `WebSite` need an absolute URL, so they are written only when the build knows
20
+ * the site's origin; the others fall back to relative URLs without one (see `docs/theme-seo.md`).
21
+ */
22
+ import {
23
+ buildBreadcrumbLd,
24
+ buildItemListLd,
25
+ buildOrganizationLd,
26
+ buildProductLd,
27
+ buildWebSiteLd,
28
+ ldPlainText,
29
+ type LdAvailability,
30
+ type ProductLdVariant,
31
+ type StructuredDataEntry,
32
+ } from '@eldrajs/theme-core';
33
+ import type { StorefrontProduct } from './types';
34
+
35
+ export type PageLdKind = 'home' | 'product' | 'category' | 'collection' | 'page' | 'notFound';
36
+
37
+ export interface PageLdParts {
38
+ kind: PageLdKind;
39
+ /** The current page's name: the last breadcrumb level. */
40
+ title: string;
41
+ /** The current page's own URL (canonical when the build knows one). */
42
+ currentUrl: string;
43
+ /** A site path (`/products/x`) as the URL to write: locale-prefixed, absolute when possible. */
44
+ url: (path: string) => string;
45
+ /** Whether the build knows the site's origin, i.e. `url()` is absolute. */
46
+ absolute: boolean;
47
+ homeLabel: string;
48
+ /** The levels between Home and the current page, root first. */
49
+ trail: ReadonlyArray<{ label: string; path: string }>;
50
+ /** The product, on a product page. */
51
+ product: StorefrontProduct | null;
52
+ /** The store currency (`useMoney().currency`), or `undefined` when the platform published none. */
53
+ currency: string | undefined;
54
+ /** The products a listing page shows, in order. */
55
+ items: ReadonlyArray<{ title: string; url: string }>;
56
+ profile: {
57
+ name: string;
58
+ logoUrl: string | null;
59
+ sameAs: readonly string[];
60
+ contact: { email: string | null; telephone: string | null };
61
+ };
62
+ /** The site's search page path (`/search`, unprefixed: it follows the home URL), or `null` when
63
+ * the site has none. */
64
+ searchPath: string | null;
65
+ }
66
+
67
+ const AVAILABILITY: Record<StorefrontProduct['stock'], LdAvailability> = {
68
+ in: 'InStock',
69
+ low: 'LimitedAvailability',
70
+ out: 'OutOfStock',
71
+ preorder: 'PreOrder',
72
+ };
73
+
74
+ /** One offer per variant; a source without variants gets one from the product's own price. */
75
+ function variantsOf(product: StorefrontProduct, url: string): ProductLdVariant[] {
76
+ if (product.variants !== undefined && product.variants.length > 0) {
77
+ return product.variants.map((variant) => ({
78
+ sku: variant.sku,
79
+ gtin: variant.barcode,
80
+ price: variant.price,
81
+ compareAt: variant.compareAt,
82
+ availability: AVAILABILITY[variant.stock],
83
+ url,
84
+ }));
85
+ }
86
+ return [
87
+ {
88
+ price: product.price.amount,
89
+ compareAt: product.price.compareAt,
90
+ availability: AVAILABILITY[product.stock],
91
+ url,
92
+ },
93
+ ];
94
+ }
95
+
96
+ export function pageStructuredData(parts: PageLdParts): StructuredDataEntry[] {
97
+ if (parts.kind === 'notFound') return [];
98
+
99
+ if (parts.kind === 'home') {
100
+ // Both need an absolute URL and say nothing useful without one.
101
+ if (!parts.absolute) return [];
102
+ const origin = parts.url('/');
103
+ return [
104
+ {
105
+ type: 'organization',
106
+ node: buildOrganizationLd({
107
+ name: parts.profile.name,
108
+ url: origin,
109
+ logo: parts.profile.logoUrl,
110
+ sameAs: parts.profile.sameAs,
111
+ contact: parts.profile.contact,
112
+ }),
113
+ },
114
+ {
115
+ type: 'website',
116
+ node: buildWebSiteLd({
117
+ name: parts.profile.name,
118
+ url: origin,
119
+ searchPath: parts.searchPath,
120
+ }),
121
+ },
122
+ ];
123
+ }
124
+
125
+ const entries: StructuredDataEntry[] = [
126
+ {
127
+ type: 'breadcrumb',
128
+ node: buildBreadcrumbLd([
129
+ { name: parts.homeLabel, url: parts.url('/') },
130
+ ...parts.trail.map((level) => ({ name: level.label, url: parts.url(level.path) })),
131
+ { name: parts.title, url: parts.currentUrl },
132
+ ]),
133
+ },
134
+ ];
135
+
136
+ if (parts.kind === 'product' && parts.product !== null) {
137
+ const product = parts.product;
138
+ entries.push({
139
+ type: 'product',
140
+ node: buildProductLd({
141
+ url: parts.currentUrl,
142
+ name: product.title,
143
+ description: ldPlainText(product.description),
144
+ images: product.images.map((image) => image.src),
145
+ // A product with no brand of its own is sold under the shop's name (the site profile's).
146
+ brand: product.brand ?? parts.profile.name,
147
+ variants: variantsOf(product, parts.currentUrl),
148
+ currency: parts.currency,
149
+ ratings: product.rating,
150
+ }),
151
+ });
152
+ }
153
+
154
+ if ((parts.kind === 'category' || parts.kind === 'collection') && parts.items.length > 0) {
155
+ entries.push({
156
+ type: 'itemList',
157
+ node: buildItemListLd(parts.items.map((item) => ({ name: item.title, url: item.url }))),
158
+ });
159
+ }
160
+ return entries;
161
+ }
@@ -179,6 +179,28 @@ export interface StorefrontProduct extends StorefrontProductListItem {
179
179
  */
180
180
  inventory: number | null;
181
181
  shipsBy?: string | null;
182
+ /**
183
+ * The product's brand, when the platform carries one (`brand` on the public product read). Read
184
+ * by the page's structured data only; the page itself does not show it.
185
+ */
186
+ brand?: string | null;
187
+ /**
188
+ * **Every variant, with the price and stock the page's own variant resolves from** — what the
189
+ * page's structured data writes one offer per. Absent from a source that has no variants to
190
+ * list (the demo), where the structured data falls back to one offer from `price` and `stock`.
191
+ * `barcode` is the catalog's free text; the structured-data builder validates it as a GTIN.
192
+ */
193
+ variants?: StorefrontProductVariant[];
194
+ }
195
+
196
+ export interface StorefrontProductVariant {
197
+ sku: string;
198
+ barcode: string | null;
199
+ /** Major units, like every amount in this file. */
200
+ price: number;
201
+ compareAt: number | null;
202
+ /** `variantStock`'s four states for this variant: `out` for an unpublished one. */
203
+ stock: 'in' | 'low' | 'out' | 'preorder';
182
204
  }
183
205
 
184
206
  export interface StorefrontCollectionInfo {
@@ -717,9 +739,86 @@ export interface StorefrontCatalog {
717
739
  notifyBackInStock(input: { email: string; variantId: string }): Promise<StorefrontAck>;
718
740
  }
719
741
 
742
+ /** The field types a form definition carries (the platform's `site/v1/forms` contract). */
743
+ export type StorefrontFormFieldType =
744
+ | 'text'
745
+ | 'email'
746
+ | 'phone'
747
+ | 'textarea'
748
+ | 'select'
749
+ | 'checkbox'
750
+ | 'consent'
751
+ | 'number'
752
+ | 'url';
753
+
754
+ /**
755
+ * A form field with its text already resolved to the active content locale (`pickLocalized` in
756
+ * `forms.ts`): a block renders strings, never a per-locale map.
757
+ */
758
+ export interface StorefrontFormField {
759
+ /** The key of this field's value in a submission and of its messages in a `422`. */
760
+ id: string;
761
+ type: StorefrontFormFieldType;
762
+ required: boolean;
763
+ label: string;
764
+ placeholder?: string;
765
+ options?: Array<{ value: string; label: string }>;
766
+ validation?: { minLength?: number; maxLength?: number; pattern?: string };
767
+ }
768
+
769
+ /** A form as the platform serves it (`GET /site/v1/forms/{key}`), localized for the page. */
770
+ export interface StorefrontFormDefinition {
771
+ key: string;
772
+ name: string;
773
+ fields: StorefrontFormField[];
774
+ /** A field name a person never fills: render it off-screen and send its value as `hp`. */
775
+ honeypotField: string;
776
+ /** Cloudflare Turnstile site key; `null` when the merchant has not turned it on. */
777
+ turnstileSiteKey: string | null;
778
+ /** The merchant's confirmation text. */
779
+ successMessage: string;
780
+ /** Where to send the visitor after a success, or `null` to stay and show the message. */
781
+ successRedirect: string | null;
782
+ /**
783
+ * The consent sentence of a subscribing form, in the page's locale, `{shop}` already replaced.
784
+ * `''` when the form does not subscribe. Rendered as plain text beside the submit button.
785
+ */
786
+ consentText: string;
787
+ }
788
+
789
+ export interface StorefrontFormSubmitInput {
790
+ /** `fieldId` to the entered value; a checkbox is a boolean, every other type a string. */
791
+ values: Record<string, string | boolean>;
792
+ turnstileToken?: string;
793
+ /** The honeypot field's value. */
794
+ hp?: string;
795
+ }
796
+
797
+ /**
798
+ * What a submission came to. `invalid` carries the platform's own field-keyed messages (the
799
+ * `422` body), which a form shows inline under each field; every other failure is a reason the
800
+ * visitor can act on. `pending` on a success means a confirmation email (double opt-in) is on its
801
+ * way, so a block says "check your inbox" rather than "you're subscribed".
802
+ */
803
+ export type StorefrontFormSubmitResult =
804
+ | { ok: true; pending: boolean }
805
+ | { ok: false; reason: 'invalid'; errors: Record<string, string[]>; form: string[] }
806
+ | { ok: false; reason: 'rate-limited' | 'too-large' | 'unavailable' | 'unsupported' };
807
+
720
808
  export interface StorefrontForms {
721
- subscribe(i: { email: string; list: string }): Promise<StorefrontAck>;
722
- sendMessage(i: Record<string, string>): Promise<StorefrontAck>;
809
+ /**
810
+ * The definition of the form `key` names, in the page's content locale. Baked into the site at
811
+ * build time when the build could read it (`@eldrajs/theme-nuxt`'s `forms` read); fetched when a
812
+ * visitor opens the page otherwise. `data` stays `null` for a key the platform does not know
813
+ * (`error` is then set), and a block renders nothing for it rather than an empty form.
814
+ */
815
+ definition(key: Ref<string>): StorefrontResult<StorefrontFormDefinition>;
816
+ /**
817
+ * Sends one submission. Never throws: a refusal is a `{ ok: false, reason }`. With the theme's
818
+ * `formsEndpoint` configured the submission goes there instead of the platform
819
+ * (`{ kind: 'form', key, values, locale, pagePath }` as JSON, any 2xx is a success).
820
+ */
821
+ submit(key: string, input: StorefrontFormSubmitInput): Promise<StorefrontFormSubmitResult>;
723
822
  }
724
823
 
725
824
  export interface StorefrontSearch {
@@ -0,0 +1,172 @@
1
+ import { imageUrl } from '@eldrajs/sdk';
2
+ import type { SeoContext, SeoData, SeoEntryValue } from '@eldrajs/theme-core';
3
+
4
+ /** The shapes this reads are CMS data and catalog projections, so every access is guarded. */
5
+ type Doc = { data?: Record<string, unknown> } | null | undefined;
6
+
7
+ export interface SeoInputParts {
8
+ /** The route is showing the not-found shell. */
9
+ isNotFound: boolean;
10
+ /** The translated not-found title. */
11
+ notFoundTitle: string;
12
+ /** Which catalog object the route shows, or `null` for an ordinary page. */
13
+ catalog: { kind: 'product' | 'collection' | 'category'; slug: string } | null;
14
+ /** The resolved catalog object (a product, collection or category), or the page's own. */
15
+ entry: Doc;
16
+ page: Doc;
17
+ template: Doc;
18
+ /** The request path as served, locale prefix included. */
19
+ path: string;
20
+ /** Every locale the site serves; used to tell `/` from `/is-IS`. */
21
+ locales: readonly string[];
22
+ /**
23
+ * The name of the product's own (deepest) category, for `product.category`. The product
24
+ * projection serves only `categoryIds`; the name comes from the category list the storefront
25
+ * already loads (`categoryTrailFor`), so the caller resolves it.
26
+ */
27
+ productCategory?: string | null;
28
+ /** Formats a major-unit amount in the store's currency and locale. */
29
+ formatPrice: (amount: number) => string;
30
+ }
31
+
32
+ export interface SeoInput {
33
+ context: SeoContext;
34
+ data: SeoData;
35
+ options: {
36
+ entry: SeoEntryValue | null;
37
+ template: SeoEntryValue | null;
38
+ contentImage: string | null;
39
+ };
40
+ }
41
+
42
+ /** The meta description a product's own text may give the `product.shortDescription` variable. */
43
+ const SHORT_DESCRIPTION_MAX = 160;
44
+
45
+ /**
46
+ * Everything `useEldraSeo` needs for one route: the context, the variables that context offers
47
+ * (`page.title`, `product.name`, ... — the platform's registry names them), the route's own `seo`
48
+ * field values and the content's own image.
49
+ *
50
+ * The page's title follows the rule the document title always had: a catalog route is named by
51
+ * the object it shows (the shared route template's own title only names the template), anything
52
+ * else by its own document. The not-found shell names itself and is never indexed.
53
+ */
54
+ export function seoInput(parts: SeoInputParts): SeoInput {
55
+ const entryData = parts.entry?.data ?? {};
56
+ const own = parts.template?.data ?? parts.page?.data ?? {};
57
+ const catalogKind = parts.catalog?.kind ?? null;
58
+
59
+ const title = text(catalogKind === null ? own.title : entryData.title) ?? text(own.title) ?? '';
60
+ const data: SeoData = {
61
+ 'page.title': title,
62
+ 'page.slug': text(own.slug) ?? text(entryData.slug) ?? lastSegment(parts.path),
63
+ };
64
+ let contentImage: string | null = null;
65
+
66
+ if (catalogKind === 'product') {
67
+ const variants = list(entryData.variants);
68
+ const prices = variants
69
+ .map((variant) => variant.price)
70
+ .filter((price): price is number => typeof price === 'number' && Number.isFinite(price));
71
+ data['product.name'] = title;
72
+ data['product.sku'] = text(variants[0]?.sku) ?? '';
73
+ data['product.price'] = prices.length === 0 ? '' : parts.formatPrice(Math.min(...prices));
74
+ data['product.shortDescription'] = shortDescription(entryData.description);
75
+ data['product.brand'] = text(entryData.brand) ?? '';
76
+ data['product.category'] = text(parts.productCategory) ?? '';
77
+ contentImage = shareImage(list(entryData.images)[0]);
78
+ } else if (catalogKind !== null) {
79
+ data[`${catalogKind}.name`] = title;
80
+ data[`${catalogKind}.description`] = shortDescription(entryData.description);
81
+ data[`${catalogKind}.productCount`] =
82
+ typeof entryData.productCount === 'number' ? entryData.productCount : '';
83
+ if (catalogKind === 'collection') contentImage = shareImage(entryData.image);
84
+ }
85
+
86
+ // A catalog object is not an authored document: its own fields are not an `seo` value, only the
87
+ // shared route template's are.
88
+ const entry = catalogKind === null ? seoValue(parts.page?.data?.seo) : null;
89
+ const template = seoValue(parts.template?.data?.seo);
90
+
91
+ if (parts.isNotFound) {
92
+ return {
93
+ context: 'page',
94
+ data: { 'page.title': parts.notFoundTitle },
95
+ options: {
96
+ entry: { title: parts.notFoundTitle, noindex: true },
97
+ template: null,
98
+ contentImage: null,
99
+ },
100
+ };
101
+ }
102
+
103
+ return {
104
+ context:
105
+ catalogKind !== null
106
+ ? `catalog:${catalogKind}`
107
+ : isHome(parts.path, parts.locales)
108
+ ? 'home'
109
+ : 'page',
110
+ data,
111
+ options: { entry, template, contentImage },
112
+ };
113
+ }
114
+
115
+ function isHome(path: string, locales: readonly string[]): boolean {
116
+ const clean = path.split(/[?#]/)[0]!.replace(/\/+$/, '');
117
+ return clean === '' || locales.some((locale) => clean === `/${locale}`);
118
+ }
119
+
120
+ function lastSegment(path: string): string {
121
+ const segments = path
122
+ .split(/[?#]/)[0]!
123
+ .split('/')
124
+ .filter((part) => part !== '');
125
+ return segments[segments.length - 1] ?? '';
126
+ }
127
+
128
+ function text(value: unknown): string | null {
129
+ return typeof value === 'string' && value.trim() !== '' ? value : null;
130
+ }
131
+
132
+ function list(value: unknown): Record<string, unknown>[] {
133
+ return Array.isArray(value)
134
+ ? value.filter(
135
+ (item): item is Record<string, unknown> =>
136
+ typeof item === 'object' && item !== null && !Array.isArray(item)
137
+ )
138
+ : [];
139
+ }
140
+
141
+ /** A media item's 1200 px rendering, the width the share card wants. */
142
+ function shareImage(value: unknown): string | null {
143
+ if (typeof value !== 'object' || value === null) return null;
144
+ const url = text((value as { url?: unknown }).url);
145
+ return url === null ? null : imageUrl(url, 'lg');
146
+ }
147
+
148
+ function seoValue(value: unknown): SeoEntryValue | null {
149
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
150
+ ? (value as SeoEntryValue)
151
+ : null;
152
+ }
153
+
154
+ /** A description as one line of plain text: a string as it is, a rich-text document flattened. */
155
+ function shortDescription(value: unknown): string {
156
+ const plain = (typeof value === 'string' ? value : flatten(value)).replace(/\s+/g, ' ').trim();
157
+ if (plain.length <= SHORT_DESCRIPTION_MAX) return plain;
158
+ const cut = plain.slice(0, SHORT_DESCRIPTION_MAX - 1);
159
+ return `${cut.slice(0, cut.lastIndexOf(' ') > 40 ? cut.lastIndexOf(' ') : cut.length)}…`;
160
+ }
161
+
162
+ function flatten(node: unknown): string {
163
+ if (typeof node !== 'object' || node === null) return '';
164
+ const {
165
+ type,
166
+ text: own,
167
+ content,
168
+ } = node as { type?: unknown; text?: unknown; content?: unknown };
169
+ if (type === 'text') return typeof own === 'string' ? own : '';
170
+ if (!Array.isArray(content)) return '';
171
+ return content.map(flatten).join(' ');
172
+ }
@@ -7,7 +7,9 @@ definitions:
7
7
  script:
8
8
  - corepack enable && corepack prepare pnpm@9.15.0 --activate
9
9
  - pnpm install --frozen-lockfile
10
- - pnpm exec nuxi generate
10
+ # A build is production unless ELDRA_BUILD_TARGET=preview (noindex, `Disallow: /`).
11
+ # Set ELDRA_SITE_URL as a repository variable.
12
+ - ELDRA_SITE_URL="$ELDRA_SITE_URL" pnpm exec nuxi generate
11
13
  - pnpm exec eldra-theme deploy
12
14
 
13
15
  pipelines:
@@ -266,6 +266,7 @@ watchEffect(() => {
266
266
  :keep-last="2"
267
267
  :link-as="linkAs"
268
268
  :classes="currentClasses"
269
+ :structured-data="false"
269
270
  />
270
271
  </div>
271
272
  </Container>
@@ -282,6 +282,7 @@ const DRAWER_CLASSES = {
282
282
  block
283
283
  :href="checkoutHref"
284
284
  :as="checkoutAs"
285
+ @click="cart.beginCheckout()"
285
286
  >
286
287
  <template #leadingIcon>
287
288
  <EldraIcon name="lock" size="sm" />
@@ -270,6 +270,7 @@ const VALUE_CLASS = 'text-text text-body-sm font-medium tabular-nums';
270
270
  block
271
271
  :href="checkoutHref"
272
272
  :as="checkoutAs"
273
+ @click="cart.beginCheckout()"
273
274
  >
274
275
  <template #leadingIcon>
275
276
  <EldraIcon name="lock" size="sm" />