@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
@@ -5,7 +5,9 @@ on:
5
5
  repository_dispatch:
6
6
  types: [eldra.rebuild]
7
7
  jobs:
8
- deploy:
8
+ # The build runs every npm dependency's code (install scripts, the Nuxt build), so it never gets
9
+ # the deploy token. Only the build token, which is read-only.
10
+ build:
9
11
  runs-on: ubuntu-latest
10
12
  steps:
11
13
  - uses: actions/checkout@v4
@@ -17,8 +19,35 @@ jobs:
17
19
  env:
18
20
  ELDRA_GATEWAY_URL: ${{ vars.ELDRA_GATEWAY_URL }}
19
21
  ELDRA_ORG_ID: ${{ vars.ELDRA_ORG_ID }}
20
- - run: pnpm exec eldra-theme deploy
22
+ # Read-only build token (Studio → Settings → Developers → Build tokens): gives the build's
23
+ # gateway reads their own rate-limit bucket.
24
+ ELDRA_BUILD_TOKEN: ${{ secrets.ELDRA_BUILD_TOKEN }}
25
+ # A build is production unless ELDRA_BUILD_TARGET=preview, so none is set here.
26
+ ELDRA_SITE_URL: ${{ vars.ELDRA_SITE_URL }}
27
+ - uses: actions/upload-artifact@v4
28
+ with:
29
+ name: eldra-build
30
+ path: .output/public
31
+ # The manifest lives in .output/public/.eldra, a hidden directory.
32
+ include-hidden-files: true
33
+ if-no-files-found: error
34
+ retention-days: 1
35
+ # The deploy job has the deploy token (it can publish the site) and runs none of the project's
36
+ # code: no checkout, no `pnpm install`, only the pinned CLI, installed with scripts disabled.
37
+ deploy:
38
+ needs: build
39
+ runs-on: ubuntu-latest
40
+ steps:
41
+ - uses: actions/setup-node@v4
42
+ with: { node-version: 20 }
43
+ - uses: actions/download-artifact@v4
44
+ with:
45
+ name: eldra-build
46
+ path: .output/public
47
+ # Keep this version in step with @eldrajs/theme-cli in package.json.
48
+ - run: npx --yes @eldrajs/theme-cli@0.2.1 deploy
21
49
  env:
50
+ npm_config_ignore_scripts: 'true'
22
51
  ELDRA_API_URL: ${{ vars.ELDRA_API_URL }}
23
52
  ELDRA_DEPLOY_TOKEN: ${{ secrets.ELDRA_DEPLOY_TOKEN }}
24
53
  ELDRA_TRIGGER_DEPLOYMENT_ID: ${{ github.event.client_payload.deploymentId }}
@@ -1,16 +1,45 @@
1
- stages: [deploy]
1
+ stages: [build, deploy]
2
2
 
3
- eldra-deploy:
4
- stage: deploy
3
+ # The build runs every npm dependency's code (install scripts, the Nuxt build), so it must never
4
+ # receive the deploy token. Create these in Settings → CI/CD → Variables:
5
+ # ELDRA_BUILD_TOKEN masked. A read-only build token (Studio → Settings → Developers → Build
6
+ # tokens): gives the build's gateway reads their own rate-limit bucket.
7
+ # ELDRA_DEPLOY_TOKEN masked, protected, with the environment scope `production`. It can publish
8
+ # the site; scoped like this only the deploy job (environment: production, on
9
+ # a protected branch) receives it, never the build job.
10
+ # ELDRA_GATEWAY_URL, ELDRA_ORG_ID, ELDRA_SITE_URL (the public origin) and ELDRA_API_URL: plain
11
+ # variables.
12
+ # A build is production unless ELDRA_BUILD_TARGET=preview, so none is set here.
13
+ # The platform's trigger passes ELDRA_TRIGGER_DEPLOYMENT_ID as a pipeline variable.
14
+
15
+ .rules: &rules
16
+ - if: '$CI_PIPELINE_SOURCE == "trigger"'
17
+ - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
18
+
19
+ eldra-build:
20
+ stage: build
5
21
  image: node:20
6
- rules:
7
- - if: '$CI_PIPELINE_SOURCE == "trigger"'
8
- - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
22
+ rules: *rules
9
23
  before_script:
10
24
  - corepack enable && corepack prepare pnpm@9.15.0 --activate
11
25
  script:
12
26
  - pnpm install --frozen-lockfile
13
27
  - pnpm exec nuxi generate
14
- - pnpm exec eldra-theme deploy
28
+ artifacts:
29
+ # .output/public/.eldra/manifest.json is a hidden path; artifacts keep it.
30
+ paths:
31
+ - .output/public
32
+ expire_in: 1 hour
33
+
34
+ # Runs none of the project's code: no `pnpm install`, only the pinned CLI, installed with scripts
35
+ # disabled. Keep the version in step with @eldrajs/theme-cli in package.json.
36
+ eldra-deploy:
37
+ stage: deploy
38
+ image: node:20
39
+ needs: [eldra-build]
40
+ rules: *rules
41
+ environment: production
15
42
  variables:
16
- ELDRA_TRIGGER_DEPLOYMENT_ID: $ELDRA_TRIGGER_DEPLOYMENT_ID
43
+ npm_config_ignore_scripts: 'true'
44
+ script:
45
+ - npx --yes @eldrajs/theme-cli@0.2.1 deploy
@@ -4,6 +4,7 @@ import tailwindcss from '@tailwindcss/vite';
4
4
  import vue from '@vitejs/plugin-vue';
5
5
  import eldraTheme from '@eldrajs/vite-plugin-theme';
6
6
  import { generateStories } from '../scripts/generate-stories.mjs';
7
+ import { starterFormSeeds } from '../app/formSeeds';
7
8
  import { starterSeeds, starterTemplateRoles } from '../app/templates';
8
9
 
9
10
  const themeDir = fileURLToPath(new URL('..', import.meta.url));
@@ -47,6 +48,8 @@ const config: StorybookConfig = {
47
48
  tailwind: false,
48
49
  templates: starterSeeds(),
49
50
  templateRoles: starterTemplateRoles(),
51
+ // Declared for the same reason: this instance writes `.eldra/manifest.json` too.
52
+ formSeeds: starterFormSeeds(),
50
53
  }),
51
54
  ];
52
55
  config.resolve = {
@@ -102,7 +102,7 @@ alongside it.
102
102
 
103
103
  - **structure** — `navigation` ("Header"), `announcement-bar`, `breadcrumbs`, `footer`.
104
104
  - **marketing** — `hero`, `cta` ("Call to action"), `feature-grid`, `split-content`, `stats`,
105
- `logo-cloud`, `testimonials`, `faq`, `pricing-table`, `newsletter`, `contact`
105
+ `logo-cloud`, `testimonials`, `faq`, `pricing-table`, `newsletter`, `contact`, `form`
106
106
  ("Contact and map"), `video-embed`, `team`, `timeline`.
107
107
  - **content** — `article`, `article-list`, `rich-text`, `gallery`, `image`, `quote`, `tabs`.
108
108
  - **commerce** — `collection-header`, `product-carousel`, `collection-grid`, `product-detail`,
@@ -126,10 +126,14 @@ your own site's pages, or as a reference for how a set of blocks composes.
126
126
 
127
127
  ## Storefront forms
128
128
 
129
- The newsletter (`forms.subscribe`), contact (`forms.sendMessage`) and back-in-stock
130
- (`catalog.notifyBackInStock`) forms have no gateway endpoint by default: without one configured,
131
- they resolve `{ ok: false, reason: 'unsupported' }` and the block renders its own "isn't set up
132
- yet" copy rather than crashing. Wire a real endpoint by adding it to `nuxt.config.ts`:
129
+ Forms come from the platform: a merchant builds them on Studio's Forms page, and the `form` block
130
+ (plus `contact`, `newsletter` and the footer's sign-up, which submit to the seeded `contact` and
131
+ `newsletter` forms) renders and submits them through `useStorefront().forms`. `app/formSeeds.ts` is
132
+ what a fresh site starts with (the `newsletter` seed carries its consent sentence per locale, which the `form` block shows under the button). See `docs/starter-kit.md`, "Forms".
133
+
134
+ `formsEndpoint` overrides where a form _submission_ goes, and is where the back-in-stock form
135
+ (`catalog.notifyBackInStock`, which has no platform endpoint) posts. Without it that one resolves
136
+ `{ ok: false, reason: 'unsupported' }` and the block renders its own "isn't set up yet" copy:
133
137
 
134
138
  ```ts
135
139
  export default defineNuxtConfig({
@@ -141,10 +145,10 @@ export default defineNuxtConfig({
141
145
  });
142
146
  ```
143
147
 
144
- or by setting the matching `NUXT_PUBLIC_FORMS_ENDPOINT` environment variable at build/deploy time.
145
- Once set, `app/storefront/gateway.ts` posts `{ kind: 'subscribe' | 'sendMessage' |
146
- 'notifyBackInStock', ...input }` as JSON to that endpoint and treats a non-2xx response as a
147
- recoverable failure (the same retry-on-resubmit path each form's own spec proves).
148
+ or set the matching `NUXT_PUBLIC_FORMS_ENDPOINT` environment variable at build/deploy time. A form
149
+ submission is posted as `{ kind: 'form', key, values, locale, pagePath, turnstileToken?, hp? }` JSON (the last two are the
150
+ spam signals the form collected; verify them or ignore them), a back-in-stock
151
+ request as `{ kind: 'notifyBackInStock', ... }`; a non-2xx is a recoverable failure.
148
152
 
149
153
  ## Checkout
150
154
 
@@ -155,6 +159,14 @@ button appears when that resolves. If the platform publishes no checkout URL, or
155
159
  come back, the cart still adds, updates and persists lines normally; it just has no Check out
156
160
  button to show, since there is nowhere to hand the cart off to.
157
161
 
162
+ ## Analytics
163
+
164
+ On a production build the theme reports to Studio's analytics through `@eldrajs/theme-nuxt` (see
165
+ `docs/themes.md`, _Built-in analytics_), and `app/storefront/analytics.ts` sends `product_view`,
166
+ `add_to_cart`, `remove_from_cart`, `begin_checkout` and `search` by wrapping the storefront source in
167
+ `app/plugins/eldra-storefront.ts`, so blocks never call it. Opt out with `eldra: { analytics: false }`
168
+ in `nuxt.config.ts` or `ELDRA_ANALYTICS=off`. Nothing is written to cookies or storage.
169
+
158
170
  ## Prices and the store currency
159
171
 
160
172
  Nothing to configure here either, and nothing to guess: the organisation's own commerce settings
@@ -284,10 +296,10 @@ The deploy command uploads the generated static site and exact `.eldra/manifest.
284
296
 
285
297
  ## Wiring rebuilds
286
298
 
287
- The starter includes GitHub Actions, GitLab CI, and Bitbucket Pipelines examples. All build locally with Node 20 and pnpm, run `nuxi generate`, then push the static output with `eldra-theme deploy`.
299
+ The starter includes GitHub Actions, GitLab CI, and Bitbucket Pipelines examples. Each is split into a **build job** and a **deploy job**. The build job checks out the theme, installs with Node 20 and pnpm, runs `nuxi generate` (with `ELDRA_BUILD_TOKEN`, a read-only build token, so the build's gateway reads get their own rate-limit budget; it is sent only from the build in `X-Eldra-Build-Token`) and uploads `.output/public` as an artifact. The deploy job downloads the artifact and pushes it with `eldra-theme deploy` and `ELDRA_DEPLOY_TOKEN`, which can publish the site. The build job never receives the deploy token, because it runs every npm dependency's code. The deploy job installs none of the project's dependencies: it runs the pinned `@eldrajs/theme-cli` with install scripts disabled (keep its version in step with `package.json`).
288
300
 
289
- - GitHub: set repository variables `ELDRA_GATEWAY_URL`, `ELDRA_ORG_ID`, and `ELDRA_API_URL`, plus secret `ELDRA_DEPLOY_TOKEN`. In Studio choose the GitHub trigger and configure `https://api.github.com/repos/<owner>/<repo>/dispatches` with a token allowed to dispatch workflows.
290
- - GitLab: configure those four names as project CI/CD variables, masking `ELDRA_DEPLOY_TOKEN`. In Studio use the project pipeline-trigger URL, trigger token, and branch/tag ref.
291
- - Bitbucket: configure repository variables, securing `ELDRA_DEPLOY_TOKEN`. In Studio use the pipelines endpoint, `username:app-password` token, and ref; the backend selects the `eldra-rebuild` custom pipeline.
301
+ - GitHub: set repository variables `ELDRA_GATEWAY_URL`, `ELDRA_ORG_ID`, `ELDRA_API_URL` and `ELDRA_SITE_URL` (the public origin, for canonical and `og:url`), plus repository secrets `ELDRA_BUILD_TOKEN` (used by the `build` job only) and `ELDRA_DEPLOY_TOKEN` (used by the `deploy` job only). Create the build token in Studio under Settings → Developers → Build tokens. In Studio choose the GitHub trigger and configure `https://api.github.com/repos/<owner>/<repo>/dispatches` with a token allowed to dispatch workflows.
302
+ - GitLab: configure `ELDRA_GATEWAY_URL`, `ELDRA_ORG_ID`, `ELDRA_API_URL` and `ELDRA_SITE_URL` as project CI/CD variables and `ELDRA_BUILD_TOKEN` as a masked variable. Create `ELDRA_DEPLOY_TOKEN` as a **masked, protected variable scoped to the `production` environment**; the deploy job declares `environment: production`, so the build job never receives it. In Studio use the project pipeline-trigger URL, trigger token, and branch/tag ref.
303
+ - Bitbucket: configure `ELDRA_GATEWAY_URL`, `ELDRA_ORG_ID` and `ELDRA_SITE_URL` as repository variables, securing `ELDRA_BUILD_TOKEN`. Define `ELDRA_DEPLOY_TOKEN` (secured) and `ELDRA_API_URL` as **deployment variables** of the Production environment, not repository variables; the deploy step declares `deployment: production`, so the build step never receives them. In Studio use the pipelines endpoint, `username:app-password` token, and ref; the backend selects the `eldra-rebuild` custom pipeline.
292
304
 
293
305
  Trigger tokens and app passwords are write-only in Studio. Rebuild requests supply `ELDRA_TRIGGER_DEPLOYMENT_ID`; the deploy command returns it as multipart `triggerDeploymentId`, completing the existing MANUAL or CONTENT_PUBLISH deployment rather than creating a duplicate.
@@ -0,0 +1,21 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * The honeypot of a platform form: a text input named by the form's definition, off-screen and
4
+ * inert so a person never reaches it, and a bot that fills every input does. Its value is sent as
5
+ * `hp` and the platform drops the submission when it is not empty. Renders nothing until the
6
+ * definition names the field.
7
+ */
8
+ defineProps<{ name: string | null }>();
9
+ const value = defineModel<string>({ default: '' });
10
+ </script>
11
+
12
+ <template>
13
+ <div
14
+ v-if="name"
15
+ aria-hidden="true"
16
+ inert
17
+ class="absolute -left-[10000px] size-px overflow-hidden opacity-0"
18
+ >
19
+ <input v-model="value" type="text" :name="name" tabindex="-1" autocomplete="off" />
20
+ </div>
21
+ </template>
@@ -0,0 +1,56 @@
1
+ import { computed, ref, type Ref } from 'vue';
2
+ import { useI18n } from 'vue-i18n';
3
+ import { useStorefront } from './useStorefront';
4
+ import { useTurnstile } from './useTurnstile';
5
+
6
+ /**
7
+ * The spam protection of a platform form for a block that renders its own fields (`contact`,
8
+ * `newsletter`, the footer's sign-up): the honeypot and the Cloudflare Turnstile the merchant may
9
+ * turn on, both read from the form's definition (`forms.definition`), the way `blocks/form` does.
10
+ * Without it Core rejects every submission of a form that has Turnstile on.
11
+ *
12
+ * A block renders `<FormHoneypot v-model="honeypot" :name="honeypotField" />` and, when `siteKey`
13
+ * is set, an element bound to `turnstileRoot`; before it submits it asks `challenge()` (a message
14
+ * to show, or `null` to go ahead) and spreads `signals()` into the submission. A definition that
15
+ * has not loaded is not a reason to block: the platform decides.
16
+ *
17
+ * @param formKey the key of the form; empty reads nothing (a block that is not showing the form)
18
+ */
19
+ export function useFormSpam(formKey: Ref<string>) {
20
+ const { t } = useI18n();
21
+ const definition = useStorefront().forms.definition(formKey);
22
+
23
+ const honeypot = ref('');
24
+ const turnstileRoot = ref<HTMLElement | null>(null);
25
+ const honeypotField = computed(() => definition.data.value?.honeypotField ?? null);
26
+ const siteKey = computed(() => definition.data.value?.turnstileSiteKey ?? null);
27
+ /** The platform's consent sentence of a subscribing form (`{shop}` filled in, page locale), or ''. */
28
+ const consentSentence = computed(() => (definition.data.value?.consentText ?? '').trim());
29
+ const turnstile = useTurnstile(siteKey, turnstileRoot);
30
+
31
+ /** Why the visitor cannot submit yet (Turnstile is on and not passed), or `null`. */
32
+ function challenge(): string | null {
33
+ if (siteKey.value === null || turnstile.token.value !== null) return null;
34
+ return turnstile.failed.value ? t('form.turnstileFailed') : t('form.turnstileRequired');
35
+ }
36
+
37
+ /** The spam signals to send with a submission: a token is single-use, so reset after it. */
38
+ function signals(): { turnstileToken?: string; hp?: string } {
39
+ return {
40
+ ...(turnstile.token.value ? { turnstileToken: turnstile.token.value } : {}),
41
+ ...(honeypot.value ? { hp: honeypot.value } : {}),
42
+ };
43
+ }
44
+
45
+ return {
46
+ definition: definition.data,
47
+ honeypot,
48
+ honeypotField,
49
+ siteKey,
50
+ consentSentence,
51
+ turnstileRoot,
52
+ challenge,
53
+ signals,
54
+ reset: turnstile.reset,
55
+ };
56
+ }
@@ -0,0 +1,112 @@
1
+ import { computed, ref, type ComputedRef, type Ref } from 'vue';
2
+ import { siteOrigin, type ResolvedSeo } from '@eldrajs/theme-core';
3
+ import { useEldraLocale } from '@eldrajs/theme-vue';
4
+ import { useI18n } from 'vue-i18n';
5
+ import { SEEDED_PAGE_SLUGS } from '../seededPages';
6
+ import { categoryHref } from '../utils/links';
7
+ import { useMoney } from '../storefront/money';
8
+ import { pageStructuredData, type PageLdKind } from '../storefront/structuredData';
9
+ import { useStorefront } from './useStorefront';
10
+
11
+ /** The listing's own first page: what a shopper sees before they scroll, and what Google reads. */
12
+ const ITEM_LIST_SIZE = 24;
13
+
14
+ /** The search page the seeded `search` page lives at (`app/templates.ts`): its `SearchAction`. */
15
+ const SEARCH_PATH = '/search';
16
+ /** Advertised only when the theme seeds that page: a `SearchAction` into a 404 is worse than none. */
17
+ const SEARCH_ACTION_PATH = SEEDED_PAGE_SLUGS.includes('search') ? SEARCH_PATH : null;
18
+
19
+ export interface PageStructuredDataInput {
20
+ catalog: Ref<{ kind: 'product' | 'collection' | 'category'; slug: string; path?: string } | null>;
21
+ isNotFound: Ref<boolean>;
22
+ isHome: Ref<boolean>;
23
+ /** `useEldraSeo`'s answer: the canonical, and `noindex`, which carries no markup. */
24
+ seo: Ref<ResolvedSeo>;
25
+ /** The page's (or catalog object's) own name, the last breadcrumb level. */
26
+ title: ComputedRef<string>;
27
+ /** The request path as served. */
28
+ path: Ref<string>;
29
+ }
30
+
31
+ /**
32
+ * Writes the page's schema.org JSON-LD (`app/storefront/structuredData.ts` says which nodes a page
33
+ * type gets) through `@eldrajs/theme-nuxt`'s `useStructuredData`, which applies the theme's
34
+ * opt-out and extender.
35
+ *
36
+ * It reads through the storefront the blocks read through, so a product page's markup carries the
37
+ * very product, price, currency and stock state the buy box renders; the results share the
38
+ * blocks' cache keys, so the build reads each one once. A page the SEO resolver marks `noindex`
39
+ * (a preview build, the not-found shell, an author's own choice) carries none.
40
+ */
41
+ export function usePageStructuredData(input: PageStructuredDataInput): void {
42
+ const storefront = useStorefront();
43
+ const locale = useEldraLocale();
44
+ const money = useMoney();
45
+ const profile = useSiteProfile();
46
+ const { t } = useI18n();
47
+
48
+ // Final at setup, like every source a result is keyed by: a route change remounts the page.
49
+ const kind = input.catalog.value?.kind ?? null;
50
+ const catalogSlug = input.catalog.value?.slug ?? null;
51
+ const categoryPath = input.catalog.value?.path ?? null;
52
+
53
+ const product = storefront.catalog.product(ref(kind === 'product' ? catalogSlug : null)).data;
54
+ const category = storefront.catalog.category(ref(kind === 'category' ? categoryPath : null)).data;
55
+ const items =
56
+ kind === 'collection' && catalogSlug !== null
57
+ ? storefront.catalog.collectionProducts(
58
+ ref({ slug: catalogSlug }),
59
+ ref({ page: 1, pageSize: ITEM_LIST_SIZE })
60
+ ).data
61
+ : kind === 'category' && categoryPath !== null
62
+ ? storefront.catalog.products(ref({ page: 1, pageSize: ITEM_LIST_SIZE, categoryPath })).data
63
+ : ref(null);
64
+
65
+ const origin = siteOrigin(profile.siteUrl);
66
+ // A site path as the URL to write: the page's language kept, absolute when the origin is known.
67
+ const url = (path: string): string => {
68
+ const prefixed = locale.path(path);
69
+ return origin === null ? prefixed : `${origin}${prefixed}`;
70
+ };
71
+
72
+ const pageKind = computed<PageLdKind>(() => {
73
+ if (input.isNotFound.value) return 'notFound';
74
+ if (kind !== null) return kind;
75
+ return input.isHome.value ? 'home' : 'page';
76
+ });
77
+
78
+ useStructuredData(
79
+ () => {
80
+ const trail =
81
+ kind === 'product'
82
+ ? (product.value?.categoryTrail ?? []).map((level) => ({
83
+ label: level.label,
84
+ path: level.href,
85
+ }))
86
+ : kind === 'category'
87
+ ? (category.value?.ancestors ?? []).map((ancestor) => ({
88
+ label: ancestor.title,
89
+ path: categoryHref(ancestor.path),
90
+ }))
91
+ : [];
92
+ return pageStructuredData({
93
+ kind: pageKind.value,
94
+ title: input.title.value,
95
+ currentUrl: input.seo.value.canonical ?? url(input.path.value),
96
+ url,
97
+ absolute: origin !== null,
98
+ homeLabel: t('breadcrumbs.home'),
99
+ trail,
100
+ product: product.value,
101
+ currency: money.currency.value,
102
+ items: (items.value?.items ?? []).map((item) => ({
103
+ title: item.title,
104
+ url: url(item.url),
105
+ })),
106
+ profile,
107
+ searchPath: SEARCH_ACTION_PATH,
108
+ });
109
+ },
110
+ { enabled: () => !input.seo.value.noindex }
111
+ );
112
+ }
@@ -0,0 +1,111 @@
1
+ import { onBeforeUnmount, ref, watch, type Ref } from 'vue';
2
+
3
+ const SCRIPT_SRC = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
4
+
5
+ interface TurnstileApi {
6
+ render(
7
+ container: HTMLElement,
8
+ options: {
9
+ sitekey: string;
10
+ callback: (token: string) => void;
11
+ 'expired-callback': () => void;
12
+ 'error-callback': () => void;
13
+ }
14
+ ): string;
15
+ reset(widgetId: string): void;
16
+ remove(widgetId: string): void;
17
+ }
18
+
19
+ declare global {
20
+ interface Window {
21
+ turnstile?: TurnstileApi;
22
+ }
23
+ }
24
+
25
+ let scriptPromise: Promise<TurnstileApi> | null = null;
26
+
27
+ /** Loads Cloudflare's script once per page; a failed load is forgotten so a later form retries. */
28
+ function loadTurnstile(): Promise<TurnstileApi> {
29
+ if (typeof window === 'undefined') return Promise.reject(new Error('no window'));
30
+ if (window.turnstile) return Promise.resolve(window.turnstile);
31
+ scriptPromise ??= new Promise<TurnstileApi>((resolve, reject) => {
32
+ const script = document.createElement('script');
33
+ script.src = SCRIPT_SRC;
34
+ script.async = true;
35
+ script.onload = () => {
36
+ if (window.turnstile) resolve(window.turnstile);
37
+ else reject(new Error('turnstile missing'));
38
+ };
39
+ script.onerror = () => reject(new Error('turnstile failed to load'));
40
+ document.head.appendChild(script);
41
+ }).catch((error: unknown) => {
42
+ scriptPromise = null;
43
+ throw error;
44
+ });
45
+ return scriptPromise;
46
+ }
47
+
48
+ /**
49
+ * Cloudflare Turnstile for one form: renders the widget into `container` once a `siteKey` is
50
+ * known (the merchant turned it on) and exposes the visitor's `token`. Nothing loads without a
51
+ * site key, so a form on a site that never enabled Turnstile makes no third-party request.
52
+ *
53
+ * `token` is `null` until the visitor passes the check, again after it expires, and after
54
+ * `reset()` — which a form calls after every submit, since a token is single-use. `failed` is true
55
+ * when the script or the check could not run, so the form can say so instead of waiting forever.
56
+ * Browser only: on the server (prerender) it does nothing.
57
+ */
58
+ export function useTurnstile(siteKey: Ref<string | null>, container: Ref<HTMLElement | null>) {
59
+ const token = ref<string | null>(null);
60
+ const failed = ref(false);
61
+ let api: TurnstileApi | null = null;
62
+ let widgetId: string | null = null;
63
+
64
+ async function mount(): Promise<void> {
65
+ if (typeof window === 'undefined' || !siteKey.value || !container.value || widgetId !== null) {
66
+ return;
67
+ }
68
+ const el = container.value;
69
+ const key = siteKey.value;
70
+ try {
71
+ api = await loadTurnstile();
72
+ // The form may have gone away, or changed key, while the script loaded.
73
+ if (container.value !== el || siteKey.value !== key || widgetId !== null) return;
74
+ widgetId = api.render(el, {
75
+ sitekey: key,
76
+ callback: (value) => {
77
+ token.value = value;
78
+ failed.value = false;
79
+ },
80
+ 'expired-callback': () => {
81
+ token.value = null;
82
+ },
83
+ 'error-callback': () => {
84
+ token.value = null;
85
+ failed.value = true;
86
+ },
87
+ });
88
+ } catch {
89
+ failed.value = true;
90
+ }
91
+ }
92
+
93
+ function remove(): void {
94
+ if (api && widgetId !== null) api.remove(widgetId);
95
+ widgetId = null;
96
+ token.value = null;
97
+ }
98
+
99
+ function reset(): void {
100
+ token.value = null;
101
+ if (api && widgetId !== null) api.reset(widgetId);
102
+ }
103
+
104
+ watch([siteKey, container], () => {
105
+ if (widgetId !== null && (!container.value || !siteKey.value)) remove();
106
+ void mount();
107
+ });
108
+ onBeforeUnmount(remove);
109
+
110
+ return { token, failed, reset, mount };
111
+ }
@@ -0,0 +1,93 @@
1
+ import type { DeclaredFormSeed } from '@eldrajs/vite-plugin-theme';
2
+
3
+ /**
4
+ * The forms this theme seeds a site with on its first deploy (`eldra.formSeeds` in
5
+ * `nuxt.config.ts`): the two the starter's own pages use, `contact` and `newsletter`. Core creates
6
+ * a form only when its key is absent and refreshes an unedited seeded form on a theme version bump,
7
+ * so a merchant's edits in Studio's Forms page always win. Every field has a label per locale the
8
+ * starter ships (`en-US`, `is-IS`); a merchant adds the rest in Studio.
9
+ *
10
+ * Also the source of the demo storefront's form definitions (`app/storefront/demo.ts`), so
11
+ * Storybook, the block specs and the deployed site agree on what these two forms are. Nothing here
12
+ * reaches the browser bundle except through that demo module, which is `.storybook`/test-only.
13
+ */
14
+ export function starterFormSeeds(): DeclaredFormSeed[] {
15
+ return [
16
+ {
17
+ key: 'contact',
18
+ name: 'Contact',
19
+ fields: [
20
+ {
21
+ id: 'name',
22
+ type: 'text',
23
+ required: true,
24
+ label: { 'en-US': 'Name', 'is-IS': 'Nafn' },
25
+ },
26
+ {
27
+ id: 'email',
28
+ type: 'email',
29
+ required: true,
30
+ label: { 'en-US': 'Email address', 'is-IS': 'Netfang' },
31
+ placeholder: { 'en-US': 'name@example.com', 'is-IS': 'nafn@example.is' },
32
+ },
33
+ {
34
+ id: 'topic',
35
+ type: 'text',
36
+ required: false,
37
+ label: { 'en-US': 'What is it about?', 'is-IS': 'Um hvað er málið?' },
38
+ validation: { maxLength: 120 },
39
+ },
40
+ {
41
+ id: 'orderNumber',
42
+ type: 'text',
43
+ required: false,
44
+ label: { 'en-US': 'Order number', 'is-IS': 'Pöntunarnúmer' },
45
+ },
46
+ {
47
+ id: 'message',
48
+ type: 'textarea',
49
+ required: true,
50
+ label: { 'en-US': 'Message', 'is-IS': 'Skilaboð' },
51
+ validation: { minLength: 10, maxLength: 4000 },
52
+ },
53
+ ],
54
+ actions: { notify: true, confirm: true },
55
+ success: {
56
+ message: {
57
+ 'en-US': 'Thanks. We reply within one business day, usually sooner.',
58
+ 'is-IS': 'Takk fyrir. Við svörum innan eins virks dags, oftast fyrr.',
59
+ },
60
+ },
61
+ },
62
+ {
63
+ key: 'newsletter',
64
+ name: 'Newsletter',
65
+ fields: [
66
+ {
67
+ id: 'email',
68
+ type: 'email',
69
+ required: true,
70
+ label: { 'en-US': 'Email address', 'is-IS': 'Netfang' },
71
+ placeholder: { 'en-US': 'name@example.com', 'is-IS': 'nafn@example.is' },
72
+ },
73
+ ],
74
+ actions: {
75
+ notify: false,
76
+ confirm: false,
77
+ subscribe: {
78
+ list: 'newsletter',
79
+ consentText: {
80
+ 'en-US': 'I want to receive the newsletter from {shop}. I can unsubscribe at any time.',
81
+ 'is-IS': 'Ég vil fá fréttabréf frá {shop}. Ég get skráð mig úr áskrift hvenær sem er.',
82
+ },
83
+ },
84
+ },
85
+ success: {
86
+ message: {
87
+ 'en-US': 'Check your inbox to confirm your subscription.',
88
+ 'is-IS': 'Kíktu í pósthólfið til að staðfesta áskriftina.',
89
+ },
90
+ },
91
+ },
92
+ ];
93
+ }