@eldrajs/theme-cli 0.2.0 → 0.2.2

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 (66) hide show
  1. package/package.json +3 -3
  2. package/template/.eldra/block-types.d.ts +12 -3
  3. package/template/.eldra/manifest.json +315 -25
  4. package/template/.eldra/previews.json +35 -34
  5. package/template/.github/workflows/eldra-deploy.yml +31 -2
  6. package/template/.gitlab-ci.yml +37 -8
  7. package/template/.storybook/main.ts +3 -0
  8. package/template/README.md +25 -13
  9. package/template/app/components/FormHoneypot.vue +21 -0
  10. package/template/app/composables/useFormSpam.ts +56 -0
  11. package/template/app/composables/usePageStructuredData.ts +112 -0
  12. package/template/app/composables/useTurnstile.ts +111 -0
  13. package/template/app/formSeeds.ts +93 -0
  14. package/template/app/pages/[...slug].vue +48 -12
  15. package/template/app/plugins/eldra-storefront.ts +22 -2
  16. package/template/app/seededPages.ts +7 -0
  17. package/template/app/storefront/analytics.ts +202 -0
  18. package/template/app/storefront/cart.ts +7 -0
  19. package/template/app/storefront/demo.ts +48 -2
  20. package/template/app/storefront/forms.ts +133 -0
  21. package/template/app/storefront/gateway.ts +113 -7
  22. package/template/app/storefront/structuredData.ts +161 -0
  23. package/template/app/storefront/types.ts +101 -2
  24. package/template/app/utils/seoInput.ts +172 -0
  25. package/template/bitbucket-pipelines.yml +25 -3
  26. package/template/blocks/breadcrumbs/Block.vue +1 -0
  27. package/template/blocks/cart/Block.vue +1 -0
  28. package/template/blocks/cart/parts/Summary.vue +1 -0
  29. package/template/blocks/contact/Block.vue +50 -21
  30. package/template/blocks/contact/__tests__/Block.spec.ts +89 -8
  31. package/template/blocks/contact/block.json +2 -9
  32. package/template/blocks/contact/mock.json +1 -2
  33. package/template/blocks/footer/Block.vue +66 -9
  34. package/template/blocks/footer/__tests__/Block.spec.ts +136 -17
  35. package/template/blocks/footer/preview.png +0 -0
  36. package/template/blocks/form/Block.vue +614 -0
  37. package/template/blocks/form/__tests__/Block.spec.ts +536 -0
  38. package/template/blocks/form/block.json +69 -0
  39. package/template/blocks/form/mock.json +25 -0
  40. package/template/blocks/form/preview.png +0 -0
  41. package/template/blocks/form/validate.ts +68 -0
  42. package/template/blocks/newsletter/Block.vue +57 -3
  43. package/template/blocks/newsletter/__tests__/Block.spec.ts +89 -31
  44. package/template/blocks/newsletter/block.json +4 -5
  45. package/template/blocks/newsletter/mock.json +1 -1
  46. package/template/blocks/newsletter/preview.png +0 -0
  47. package/template/i18n/en-US.json +33 -2
  48. package/template/i18n/is-IS.json +33 -2
  49. package/template/nuxt.config.ts +6 -0
  50. package/template/stories/generated/form.stories.ts +68 -0
  51. package/template/test/formValidate.spec.ts +46 -0
  52. package/template/test/prerenderFailure.spec.ts +1 -1
  53. package/template/test/prerenderRefresh.browser.spec.ts +5 -1
  54. package/template/test/seededPages.spec.ts +13 -0
  55. package/template/test/seoInput.spec.ts +119 -0
  56. package/template/test/slugPage.spec.ts +62 -26
  57. package/template/test/slugPageTemplate.spec.ts +5 -1
  58. package/template/test/starter.spec.ts +41 -3
  59. package/template/test/storefront/analytics.spec.ts +283 -0
  60. package/template/test/storefront/forms.spec.ts +385 -0
  61. package/template/test/storefront/structuredData.spec.ts +138 -0
  62. package/template/test/structuredData.generate.spec.ts +159 -0
  63. package/template/test/support/mockGateway.ts +29 -1
  64. package/template/test/support/turnstileForms.ts +53 -0
  65. package/template/app/utils/pageTitle.ts +0 -37
  66. package/template/test/pageTitle.spec.ts +0 -49
@@ -1,8 +1,19 @@
1
1
  import { onWatcherCleanup, ref, watch, type Ref } from 'vue';
2
- import { createCartSession, EldraHttpError, type EldraClient } from '@eldrajs/sdk';
2
+ import {
3
+ createCartSession,
4
+ EldraHttpError,
5
+ type EldraClient,
6
+ type EldraFormDefinition,
7
+ } from '@eldrajs/sdk';
3
8
  import { safeHref } from '../utils/links';
4
9
  import { createCartStore, type CartOps, type CartSnapshot } from './cart';
5
10
  import { createHistoryStore, createWishlistStore } from './history';
11
+ import {
12
+ localizeFormDefinition,
13
+ postToFormsEndpoint,
14
+ submitFailure,
15
+ toSubmitResult,
16
+ } from './forms';
6
17
  import { fromMinorUnits, roundMoney, toMinorUnits } from './money';
7
18
  import { chunkIds, collectVolatileTargets } from './volatile';
8
19
  import { canonicalAvailabilityValues, OPTION_SOURCE_PREFIX } from './facets';
@@ -51,9 +62,10 @@ import type {
51
62
  * generated *test* fixture never imported here) — the same thing a real customer theme has to do
52
63
  * before its own `eldra()` Vite plugin has generated a contract against their tenant.
53
64
  *
54
- * `forms.subscribe`/`forms.sendMessage`/`catalog.notifyBackInStock` have no gateway endpoint
55
- * today: this posts to `options.formsEndpoint` when the plugin configured one, and resolves
56
- * `{ ok: false, reason: 'unsupported' }` otherwise.
65
+ * `catalog.notifyBackInStock` has no gateway endpoint today: this posts to `options.formsEndpoint`
66
+ * when the plugin configured one, and resolves `{ ok: false, reason: 'unsupported' }` otherwise.
67
+ * Forms are the platform's own (`client.forms`, `GET /site/v1/forms/{key}`); `formsEndpoint` only
68
+ * overrides where a *submission* goes.
57
69
  */
58
70
 
59
71
  // ---------------------------------------------------------------------------------------------
@@ -189,6 +201,8 @@ interface RawProductOption {
189
201
  interface RawProductVariant {
190
202
  id: string;
191
203
  sku: string;
204
+ /** Free text; the structured data validates it as a GTIN before it writes one. */
205
+ barcode?: string | null;
192
206
  price: number;
193
207
  compareAtPrice?: number;
194
208
  status: string;
@@ -223,6 +237,8 @@ interface RawProductDetails {
223
237
  * knows the response carries it rather than inferring the catalogue only ever assigns one.
224
238
  */
225
239
  categoryIds?: string[] | null;
240
+ /** Per-product brand, for `Product.brand` in the structured data. */
241
+ brand?: string | null;
226
242
  description?: Record<string, unknown>;
227
243
  mediaLinks?: RawMediaItem[] | null;
228
244
  options?: RawProductOption[] | null;
@@ -584,6 +600,16 @@ function mapProductDetails(
584
600
  ? (stock?.get(countableVariant.id)?.availableQuantity ?? null)
585
601
  : null,
586
602
  stock: variantStock(firstAvailable, stock),
603
+ brand: raw.brand?.trim() || null,
604
+ // Each variant's own price and stock state, for the page's structured data: the same
605
+ // `variantStock` rule the buy box's line uses, so the markup and the page cannot disagree.
606
+ variants: variants.map((variant) => ({
607
+ sku: variant.sku,
608
+ barcode: variant.barcode ?? null,
609
+ price: variant.price,
610
+ compareAt: variant.compareAtPrice ?? null,
611
+ stock: variantStock(variant, stock),
612
+ })),
587
613
  available: raw.status === 'ACTIVE',
588
614
  productId: raw.id,
589
615
  // The variant an add would send, paired with `productId` above: the cart service looks the two
@@ -1869,7 +1895,24 @@ async function detailSnapshots(
1869
1895
 
1870
1896
  export interface GatewayStorefrontOptions {
1871
1897
  route: StorefrontRoute;
1898
+ /**
1899
+ * Overrides where form submissions go (`forms.submit`); see `postToFormsEndpoint`. Form
1900
+ * definitions still come from the platform. Also the endpoint `catalog.notifyBackInStock` posts to.
1901
+ */
1872
1902
  formsEndpoint?: string;
1903
+ /**
1904
+ * The form definitions the build baked (`@eldrajs/theme-nuxt`, `eldra.forms` in the runtime
1905
+ * config), by form key. A key found here is the first paint (and the prerendered HTML); the
1906
+ * browser then re-reads it live, because the platform serves definitions with no rebuild. Any
1907
+ * other key is fetched.
1908
+ */
1909
+ formDefinitions?: Record<string, EldraFormDefinition>;
1910
+ /**
1911
+ * The locale a submission reports and a definition's text resolves to: the page's active content
1912
+ * locale, the default locale included (unlike `locale`, which is `undefined` there so reads keep
1913
+ * their pre-locale keys). Omitted — a story, a spec — `en-US`.
1914
+ */
1915
+ formLocale?: () => string | undefined;
1873
1916
  /**
1874
1917
  * What the store sells in (`StorefrontCommerce`) — the platform's own answer, which only the app
1875
1918
  * layer can read (`app/plugins/eldra-storefront.ts`, off the runtime config). Omitted — a
@@ -2235,10 +2278,73 @@ export function createGatewayStorefront(
2235
2278
  ),
2236
2279
  };
2237
2280
 
2281
+ const formLocale = (): string => options.formLocale?.() ?? locale?.() ?? 'en-US';
2238
2282
  const forms: StorefrontForms = {
2239
- subscribe: (input) => postToEndpoint(options.formsEndpoint, { kind: 'subscribe', ...input }),
2240
- sendMessage: (input) =>
2241
- postToEndpoint(options.formsEndpoint, { kind: 'sendMessage', ...input }),
2283
+ definition: (key) => {
2284
+ const result = createGatewayResult(
2285
+ [key],
2286
+ async (signal) => {
2287
+ // Re-resolved against the page's locale on every read, so a language switch relabels a
2288
+ // baked definition too: only the platform's per-locale maps are baked, never one language.
2289
+ if (key.value === '') return null;
2290
+ const raw =
2291
+ options.formDefinitions?.[key.value] ??
2292
+ (await rawClient.forms.get(key.value, { signal }));
2293
+ return localizeFormDefinition(raw, formLocale());
2294
+ },
2295
+ { method: 'forms.definition', runtime, locale: () => formLocale() }
2296
+ );
2297
+ // The platform serves a definition live (`GET /site/v1/forms/{key}`, no rebuild when a
2298
+ // merchant edits a form), so the baked copy is only the first paint: once the page is open
2299
+ // in a browser the live definition replaces it, which is what makes a field added in Studio
2300
+ // render, and what turns the spam-check widget on when Turnstile was enabled after the
2301
+ // build. A failed read keeps the baked definition on screen.
2302
+ if (typeof window !== 'undefined' && options.formDefinitions !== undefined) {
2303
+ let generation = 0;
2304
+ const revalidate = async (): Promise<void> => {
2305
+ const requested = key.value;
2306
+ if (requested === '' || options.formDefinitions?.[requested] === undefined) return;
2307
+ generation += 1;
2308
+ const mine = generation;
2309
+ try {
2310
+ const raw = await rawClient.forms.get(requested);
2311
+ if (mine !== generation || key.value !== requested) return;
2312
+ result.data.value = localizeFormDefinition(raw, formLocale());
2313
+ } catch {
2314
+ // Offline, a transient 5xx, or a type this theme cannot render: keep what is shown.
2315
+ }
2316
+ };
2317
+ void revalidate();
2318
+ watch(key, () => void revalidate());
2319
+ }
2320
+ return result;
2321
+ },
2322
+ submit: async (key, input) => {
2323
+ const pagePath = typeof location === 'undefined' ? '/' : location.pathname;
2324
+ if (options.formsEndpoint) {
2325
+ return postToFormsEndpoint(options.formsEndpoint, {
2326
+ key,
2327
+ values: input.values,
2328
+ locale: formLocale(),
2329
+ pagePath,
2330
+ ...(input.turnstileToken ? { turnstileToken: input.turnstileToken } : {}),
2331
+ ...(input.hp ? { hp: input.hp } : {}),
2332
+ });
2333
+ }
2334
+ try {
2335
+ return toSubmitResult(
2336
+ await rawClient.forms.submit(key, {
2337
+ values: input.values,
2338
+ locale: formLocale(),
2339
+ pagePath,
2340
+ ...(input.turnstileToken ? { turnstileToken: input.turnstileToken } : {}),
2341
+ ...(input.hp ? { hp: input.hp } : {}),
2342
+ })
2343
+ );
2344
+ } catch (error) {
2345
+ return submitFailure(error);
2346
+ }
2347
+ },
2242
2348
  };
2243
2349
 
2244
2350
  return {
@@ -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
+ }
@@ -2,18 +2,40 @@ image: node:20
2
2
 
3
3
  definitions:
4
4
  steps:
5
- - step: &eldra-deploy
6
- name: Build and deploy to Eldra
5
+ # The build runs every npm dependency's code (install scripts, the Nuxt build), so it must never
6
+ # receive the deploy token. Define these variables:
7
+ # ELDRA_BUILD_TOKEN, ELDRA_GATEWAY_URL, ELDRA_ORG_ID, ELDRA_SITE_URL (the public origin):
8
+ # repository variables. ELDRA_BUILD_TOKEN is secured (a read-only build token: Studio →
9
+ # Settings → Developers → Build tokens).
10
+ # ELDRA_DEPLOY_TOKEN and ELDRA_API_URL: deployment variables of the Production environment
11
+ # (Repository settings → Deployments), NOT repository variables. The deploy token can
12
+ # publish the site; as a deployment variable only the deploy step receives it.
13
+ # A build is production unless ELDRA_BUILD_TARGET=preview (noindex, `Disallow: /`).
14
+ - step: &eldra-build
15
+ name: Build the theme
7
16
  script:
8
17
  - corepack enable && corepack prepare pnpm@9.15.0 --activate
9
18
  - pnpm install --frozen-lockfile
10
19
  - pnpm exec nuxi generate
11
- - pnpm exec eldra-theme deploy
20
+ artifacts:
21
+ # The manifest is in .output/public/.eldra, a hidden directory: listed explicitly.
22
+ - .output/public/**
23
+ - .output/public/.eldra/**
24
+ # Runs none of the project's code: no `pnpm install`, only the pinned CLI, installed with
25
+ # scripts disabled. Keep the version in step with @eldrajs/theme-cli in package.json.
26
+ - step: &eldra-deploy
27
+ name: Deploy to Eldra
28
+ deployment: production
29
+ script:
30
+ - export npm_config_ignore_scripts=true
31
+ - npx --yes @eldrajs/theme-cli@0.2.1 deploy
12
32
 
13
33
  pipelines:
14
34
  branches:
15
35
  main:
36
+ - step: *eldra-build
16
37
  - step: *eldra-deploy
17
38
  custom:
18
39
  eldra-rebuild:
40
+ - step: *eldra-build
19
41
  - step: *eldra-deploy
@@ -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" />