@eldrajs/theme-nuxt 0.4.8 → 0.5.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.
package/CHANGELOG.md CHANGED
@@ -5,8 +5,106 @@ Release-please writes the generated notes from commit messages and does not repl
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ - **A theme can keep a draft preview session's veil up for its own reads (WS-1277).** New
9
+ auto-import `holdPreviewSession(work)`: work started while a session is covered (a read outside
10
+ Nuxt's async data that the draft's own render started, such as a block whose draft names a
11
+ collection the pinned build never read) keeps the veil up until it settles, and the session
12
+ renders once more before the draft is shown, within the same 15 s bound. A no-op outside a
13
+ covered session. A focus the session replays now lands on the settled page.
14
+ - **Link targets carry a card's picture and price (WS-1326).** `collectLinkTargets` fills
15
+ `LinkTargetInfo.image` from a product's `thumbnail` or a collection's `image` and
16
+ `LinkTargetInfo.price` from a product's `minPrice`, out of the reads it already makes.
8
17
  - **A store's own currency can be off (WS-1399).** `commerce` on `runtimeConfig.public.eldra` carries `defaultCurrency` when it is not the store's own `currency`, and `currencies` is cleaned with the default first. A store selling in its own currency gets the same config as before.
9
18
  - **Selling in more than one currency (WS-1391).** `commerce` on `runtimeConfig.public.eldra` carries `currencies`, the currencies the store offers with its own first, when it offers more than one (a one-currency store's config is unchanged). New server route `GET /_eldra/visitor` answers `{ country }` from Cloudflare's `CF-IPCountry` header, `private, no-store`, so a prerendered page can start a first-time visitor in their country's currency; it answers `null` off Cloudflare.
19
+ - **Draft preview sessions (WS-1303).** On the preview router's session host (its
20
+ `<meta name="eldra-preview" content="session">`, or a `p-<session>.previews-{env}.eldra.dev` host)
21
+ the theme renders drafts read through the router's same-origin proxy: no route is answered from
22
+ the build, a draft-only page renders, the published prerender is veiled until the draft is on
23
+ screen, an exit banner links to `/__eldra/preview/exit`, and a refused session shows an
24
+ expired or unavailable notice in Icelandic or English, never the published page. Commerce reads
25
+ stay published. Outside a session nothing changes. See `docs/themes.md`, "Draft preview sessions".
26
+ - **A draft preview session renders exactly what Publish puts live (WS-1358).** A page or route
27
+ template placing shared components is rendered in the public read's shape (no authored node ids,
28
+ no `data-eldra-reusable-placement`, the component not rebuilt); `useEldraPage().pending` stays
29
+ `false` while the session re-reads the route it has just hydrated, so the page is patched in place
30
+ rather than rebuilt; and a `focus()` asked for under the veil is given once the draft is shown.
31
+ Outside a session nothing changes. The starter's parity spec is the release gate; see
32
+ `docs/themes.md`, "Parity with the published page".
33
+ - **A draft preview session shows the saved design tokens and theme texts (WS-1394).** After
34
+ hydration, before the veil comes down and inside the same bound, a session reads
35
+ `/site/v1/design-tokens` and `/site/v1/theme-messages` through the router (`@eldrajs/theme-core`'s
36
+ new `getSiteSetting`) and puts them where the build put its own: `context.designTokens` (so
37
+ `EldraLayout`'s token style re-renders) and `context.messages`, resolved as the build resolves
38
+ them. One 10 s bound covers the chunk (loaded from the session's start) and the reads; a failure
39
+ keeps the build's values and never ends the session, except a 401, which is the router refusing
40
+ the session itself. In its own chunk, loaded only in a session; outside a session nothing
41
+ changes.
42
+ - **A draft preview session shows the saved design tokens and theme texts (WS-1394).** From its
43
+ start, a session reads `/site/v1/design-tokens` and `/site/v1/theme-messages` through the router
44
+ (`@eldrajs/theme-core`'s new `getSiteSetting`) and, once the page is hydrated and before the veil
45
+ comes down, puts them where the build put its own: `context.designTokens` (so `EldraLayout`'s
46
+ token style re-renders) and `context.messages`, resolved as the build resolves them. One 10 s
47
+ bound covers the chunk and the reads, counted from the session's start like its 15 s deadline,
48
+ so it always ends first; a failure keeps the build's values and never ends the session, except a
49
+ 401, which is the router refusing the session itself. In its own chunk, loaded only in a
50
+ session; outside a session nothing changes.
51
+
52
+ - **A session lifts the preview router's early hide (WS-1376).** The router hides a session
53
+ document's body (for at most 12 s) until `data-eldra-preview-ready` is on `<html>`, so the
54
+ published prerender shows only blurred, under the veil, never as the page itself. The kit sets it as soon as its veil (or the built-in fallback
55
+ notice) is mounted and covering the page, and on every way the session leaves the veil in case
56
+ it never mounted: the draft shown, a refusal, the 15 s bound, a render that failed (now the
57
+ unavailable notice rather than a veil left up), or a client that cannot read drafts. A UI that
58
+ throws while mounting falls back to the built-in notice, as a chunk that cannot load does. The
59
+ first refusal is the one a session shows: an expired or revoked one is never replaced by the
60
+ invalid ones the reads after it get once the router has cleared the session's cookies. The veil,
61
+ the banner and the fallback notice set `visibility: visible`, so they show under the hide.
62
+ Outside a session nothing changes.
63
+
64
+ - **Needs Nuxt 4.7.0 or later (WS-1358).** Nuxt shares `useAsyncData` answers between the
65
+ routes of one `nuxi generate`; before 4.7.0 a read that failed left every route rendered after it
66
+ an empty answer (`null`) where the routes rendered before or alongside it baked the error, so the
67
+ same content built different pages depending on route order (nuxt/nuxt#37241). Nuxt 4.7.0 reads
68
+ a failed key again on each later route. **Breaking:** the module declares `nuxt: '>=4.7.0'` and
69
+ Nuxt does not run it on an older Nuxt (the build logs "Module `@eldrajs/theme-nuxt` is disabled
70
+ due to incompatibility issues", and fails with `experimental.enforceModuleCompatibility`), so
71
+ upgrade Nuxt with the kit; `nuxt >=4.7.0` is also a peer dependency, so the package manager warns
72
+ at install.
73
+
74
+ - **A draft preview session renders exactly what Publish puts live (WS-1358).** Shared components
75
+ render in the public read's shape (`@eldrajs/theme-core`'s session client reshapes every answer);
76
+ `useEldraPage().pending` stays `false` while the session re-reads the route it has just hydrated,
77
+ so the page is patched in place rather than rebuilt; the veil drops only once the head manager
78
+ has written the draft's head (never on the pinned title); a `focus()` asked for under the veil is given
79
+ once the draft is shown; and a page that exists only as a draft, opened directly, resolves the
80
+ address bar's path rather than the not-found document's (only a document rendered for `/404`,
81
+ compared without the app's `baseURL`; its route read, still at its `default`, is read through the
82
+ session, and no other entry is run). A session's page always keeps the router's
83
+ `noindex, nofollow` robots tag, whatever a page writes. Outside a session nothing changes. The
84
+ starter's parity spec is the release gate; see `docs/themes.md`, "Parity with the published
85
+ page", for what it proves and the known differences it pins.
86
+
87
+ - **Draft preview sessions (WS-1303).** On the preview router's session host
88
+ (`p-<session>.previews-{env}.eldra.dev`; its `<meta name="eldra-preview" content="session">` in the
89
+ head counts only there or on a local development host) the theme renders drafts read through the
90
+ router's same-origin proxy: no route is answered from the build, every async data entry the
91
+ server filled is re-run once through the session after hydration (the theme's own `useAsyncData`
92
+ CMS reads included; never an entry that did not run on load, such as an `immediate: false` submit),
93
+ bounded at 15 s from the session's start (whether or not the app finishes hydrating) before the
94
+ unavailable notice, a
95
+ draft-only page renders, the published prerender is veiled (once the kit's JavaScript has loaded)
96
+ until the drafts are on screen, an exit banner links to `/__eldra/preview/exit`, and a refused
97
+ session clears what it read and shows an expired or unavailable notice in Icelandic or English,
98
+ never the published page. Commerce reads stay published. Outside a session nothing changes, and
99
+ the session UI is a chunk a storefront never loads. A CMS read the router refuses as
100
+ `404 PREVIEW_GATEWAY_PATH_NOT_ALLOWED` (a typed address with `%` or `/` in a route value) is a
101
+ not-found read, not the end of the session. See `docs/themes.md`, "Draft preview sessions", for
102
+ which reads are covered. **Not usable yet from this release:** Core refuses a session for a theme
103
+ whose manifest does not declare `draftPreview`, and this release does not declare it
104
+ (`DECLARE_MANIFEST_CAPABILITIES` is off). Preview works from the kit release that turns it on
105
+ (WS-1375), once site-service accepts the key everywhere; themes must then rebuild and deploy
106
+ again.
107
+
10
108
  - **Campaign landings are captured (WS-546).** A client plugin calls `@eldrajs/sdk`'s
11
109
  `captureCampaignAttribution` on the first page and after every navigation, so a theme's cart adds
12
110
  carry the campaign a visitor came from (`utm_*` tags only, one `localStorage` key, 30 days). New
package/dist/module.json CHANGED
@@ -2,9 +2,9 @@
2
2
  "name": "@eldrajs/theme-nuxt",
3
3
  "configKey": "eldra",
4
4
  "compatibility": {
5
- "nuxt": ">=3.13.0"
5
+ "nuxt": ">=4.7.0"
6
6
  },
7
- "version": "0.4.8",
7
+ "version": "0.5.1",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "0.8.4",
10
10
  "unbuild": "unknown"
package/dist/module.mjs CHANGED
@@ -39,7 +39,7 @@ const eldraModule = defineNuxtModule({
39
39
  meta: {
40
40
  name: "@eldrajs/theme-nuxt",
41
41
  configKey: "eldra",
42
- compatibility: { nuxt: ">=3.13.0" }
42
+ compatibility: { nuxt: ">=4.7.0" }
43
43
  },
44
44
  defaults: {
45
45
  gatewayUrl: process.env.ELDRA_GATEWAY_URL ?? "",
@@ -59,6 +59,7 @@ const eldraModule = defineNuxtModule({
59
59
  const buildTarget = options.buildTarget ?? resolveBuildTarget(process.env.ELDRA_BUILD_TARGET);
60
60
  const themeOptions = {
61
61
  framework: "nuxt",
62
+ capabilities: void 0,
62
63
  routes: options.routes,
63
64
  customPages: options.customPages,
64
65
  templates: options.templates,
@@ -126,6 +127,7 @@ const eldraModule = defineNuxtModule({
126
127
  isPreview: nuxt.options.dev || buildTarget !== "production"
127
128
  };
128
129
  const buildToken = (process.env.ELDRA_BUILD_TOKEN ?? "").trim();
130
+ addPlugin({ src: resolver.resolve("./runtime/previewSessionRoute"), mode: "client" });
129
131
  addPlugin(resolver.resolve("./runtime/plugin"));
130
132
  addServerHandler({
131
133
  route: VISITOR_COUNTRY_PATH,
@@ -163,7 +165,10 @@ const eldraModule = defineNuxtModule({
163
165
  // module is what fills it from the route.
164
166
  { name: "useEldraLocale", from: "@eldrajs/theme-vue" },
165
167
  { name: "useEldraEntry", from: "@eldrajs/theme-vue" },
166
- { name: "useEldraPreview", from: "@eldrajs/theme-vue" }
168
+ { name: "useEldraPreview", from: "@eldrajs/theme-vue" },
169
+ // A read a theme makes outside Nuxt's async data, started while a draft preview session is
170
+ // covered, keeps the veil up until it has answered (`./runtime/previewSession.ts`).
171
+ { name: "holdPreviewSession", from: resolver.resolve("./runtime/previewSession") }
167
172
  ]);
168
173
  let localeRouting = resolveLocaleRouting(null, options.locale);
169
174
  const crawlRoutes = [];
@@ -20,16 +20,22 @@ import {
20
20
  stripLocalePrefix
21
21
  } from "../locales.js";
22
22
  import { isStudioPreviewFrame } from "../origins.js";
23
+ import { isPreviewSessionRefused, usePreviewSession } from "../previewSession.js";
24
+ import { PAGE_KEY_PREFIX } from "../previewSessionReads.js";
23
25
  import { EMPTY_ELDRA_ROUTE, resolveEldraRoute } from "../resolveRoute.js";
24
26
  import { canonicalRoutePath } from "../routePath.js";
25
27
  import { knownPrerenderedRoutes, prerenderedRoutes } from "../staticRoutes.js";
26
- const PAGE_KEY_PREFIX = "eldra-page:";
27
28
  const routeDataKey = (path) => `${PAGE_KEY_PREFIX}${path}`;
29
+ const SESSION_REFUSED_ROUTE = {
30
+ ...EMPTY_ELDRA_ROUTE,
31
+ error: "[eldra] the draft preview session was refused"
32
+ };
28
33
  export function useEldraPage() {
29
34
  const route = useRoute();
30
35
  const activePath = createActivePath(route, useRouter());
31
36
  const requestEvent = useRequestEvent();
32
37
  const ctx = useEldra();
38
+ const session = usePreviewSession();
33
39
  const cfg = useRuntimeConfig().public.eldra;
34
40
  const routing = resolveLocaleRouting(resolveStoreLocales(cfg.locales), cfg.locale);
35
41
  const routeTarget = (path) => ({
@@ -37,8 +43,12 @@ export function useEldraPage() {
37
43
  locale: localeForPath(path, routing)
38
44
  });
39
45
  const runtimeLocale = (path) => normalizeLocale(ctx.preview.active ? ctx.preview.locale : null) ?? routeTarget(path).locale;
40
- const buildAnswersRoutes = () => !ctx.preview.active && !isStudioPreviewFrame(cfg.studioOrigins);
46
+ const buildAnswersRoutes = () => !session.active && !ctx.preview.active && !isStudioPreviewFrame(cfg.studioOrigins);
41
47
  const cachedRoute = (key, nuxtApp, context) => {
48
+ if (session.active) {
49
+ if (!nuxtApp.isHydrating) return void 0;
50
+ return nuxtApp.payload.data[key];
51
+ }
42
52
  if (context.cause !== "refresh:manual" && context.cause !== "refresh:hook") {
43
53
  const fromBuild = nuxtApp.isHydrating ? nuxtApp.payload.data[key] : nuxtApp.static.data[key];
44
54
  if (fromBuild !== void 0) return fromBuild;
@@ -143,9 +153,13 @@ export function useEldraPage() {
143
153
  previewResolvedRoute.value = void 0;
144
154
  }
145
155
  );
146
- const active = computed(
147
- () => previewResolvedRoute.value ?? resolvedRoute.value ?? EMPTY_ELDRA_ROUTE
148
- );
156
+ const active = computed(() => {
157
+ if (session.active) {
158
+ if (session.hydrated && isPreviewSessionRefused(session.status)) return SESSION_REFUSED_ROUTE;
159
+ return resolvedRoute.value ?? EMPTY_ELDRA_ROUTE;
160
+ }
161
+ return previewResolvedRoute.value ?? resolvedRoute.value ?? EMPTY_ELDRA_ROUTE;
162
+ });
149
163
  const error = computed(() => active.value.error ?? null);
150
164
  const page = computed(() => {
151
165
  void ctx.preview.revision;
@@ -182,6 +196,9 @@ export function useEldraPage() {
182
196
  const reusableComponentProjection = computed(
183
197
  () => page.value?.reusableComponentProjection ?? template.value?.reusableComponentProjection
184
198
  );
199
+ const reading = computed(
200
+ () => session.active && session.status === "pending" ? false : pending.value
201
+ );
185
202
  return {
186
203
  page,
187
204
  template,
@@ -191,7 +208,7 @@ export function useEldraPage() {
191
208
  blocks,
192
209
  reusableComponentProjection,
193
210
  links: linkState,
194
- pending,
211
+ pending: reading,
195
212
  error
196
213
  };
197
214
  }
@@ -43,6 +43,15 @@ export declare const READ_TIMEOUT_MS = 10000;
43
43
  * deploying while serving its own tokens.
44
44
  */
45
45
  export declare function readDesignTokens(reader: DesignTokensReader | null, warn?: (message: string) => void): Promise<ThemeDesignTokens | null>;
46
+ /**
47
+ * Accepts only a whole answer: the contract shape `{ revision, resolved }`, `resolved` normalized
48
+ * through `normalizeThemeDesignTokens` the same way a theme's own `tokens.json` is. A partial or
49
+ * malformed response — a missing `revision`, a `resolved` that fails the theme's own validation —
50
+ * is treated as no answer at all, exactly like `toThemeMessages`/`toStoreCommerce`: half of an
51
+ * untrusted network response must never reach the generated CSS or the runtime context as if it
52
+ * were real theme content.
53
+ */
54
+ export declare function toResolvedDesignTokens(value: unknown): ThemeDesignTokens | null;
46
55
  /**
47
56
  * The platform's design-token catalog as it reaches the running site on
48
57
  * `runtimeConfig.public.eldra.designTokens` — already `normalizeThemeDesignTokens`'d at build time
@@ -31,7 +31,7 @@ async function readOrNull(reader) {
31
31
  clearTimeout(timer);
32
32
  }
33
33
  }
34
- function toResolvedDesignTokens(value) {
34
+ export function toResolvedDesignTokens(value) {
35
35
  if (typeof value !== "object" || value === null) return null;
36
36
  const record = value;
37
37
  if (typeof record.revision !== "number" || !Number.isFinite(record.revision)) return null;
@@ -74,7 +74,7 @@ export async function collectLinkTargets(client, keys, locale, sources = {}) {
74
74
  for (const doc of result.data) {
75
75
  const id = text(doc.id);
76
76
  if (id === "" || !ids.has(id) || into.has(`${type}:${id}`)) continue;
77
- into.set(`${type}:${id}`, toTargetInfo(doc));
77
+ into.set(`${type}:${id}`, toTargetInfo(doc, type));
78
78
  }
79
79
  if (!result.hasNext || result.data.length === 0) return;
80
80
  }
@@ -130,7 +130,7 @@ async function readCategoriesInto(into, wanted, listCategories, locale, memoScop
130
130
  into.set(`category:${node.id}`, { ...toTargetInfo(node.raw), path: node.path });
131
131
  }
132
132
  }
133
- function toTargetInfo(doc) {
133
+ function toTargetInfo(doc, type) {
134
134
  const info = {};
135
135
  const slug = text(doc.slug);
136
136
  if (slug !== "") info.slug = slug;
@@ -138,6 +138,14 @@ function toTargetInfo(doc) {
138
138
  if (title !== "") info.title = title;
139
139
  const schemaApiId = text(doc.schemaApiId);
140
140
  if (schemaApiId !== "") info.schemaApiId = schemaApiId;
141
+ if (type === "product" || type === "collection") {
142
+ const picture = type === "product" ? doc.thumbnail : doc.image;
143
+ const image = text(picture?.url);
144
+ if (image !== "") info.image = image;
145
+ }
146
+ if (type === "product" && typeof doc.minPrice === "number" && Number.isFinite(doc.minPrice)) {
147
+ info.price = doc.minPrice;
148
+ }
141
149
  return info;
142
150
  }
143
151
  function text(value) {
@@ -48,6 +48,15 @@ export declare const READ_TIMEOUT_MS = 10000;
48
48
  * keeps deploying while serving its own default texts.
49
49
  */
50
50
  export declare function readThemeMessages(reader: ThemeMessagesReader | null, warn?: (message: string) => void): Promise<ThemeMessages | null>;
51
+ /**
52
+ * Accepts only a whole answer: a non-empty `defaultLocale` string and a `locales` record of
53
+ * records of strings, none of them keyed by a forbidden locale tag (`isForbiddenLocaleTag` —
54
+ * `__proto__`/`prototype`/`constructor`, which a plain `locales[tag] = …` write would turn into a
55
+ * prototype reassignment instead of an own property). A partial or malformed response is treated
56
+ * as no answer at all, exactly like `toStoreCommerce`/`toStoreLocales` — half of an untrusted
57
+ * network response must never reach the merge as if it were real theme content.
58
+ */
59
+ export declare function toThemeMessages(value: unknown): ThemeMessages | null;
51
60
  /**
52
61
  * Calls `@eldrajs/theme-core/i18n`'s `resolveMessageCatalogue` with the build-time inputs this
53
62
  * module's `resolveMessages` option needs: the theme's own manifest messages, the platform's
@@ -36,7 +36,7 @@ async function readOrNull(reader) {
36
36
  clearTimeout(timer);
37
37
  }
38
38
  }
39
- function toThemeMessages(value) {
39
+ export function toThemeMessages(value) {
40
40
  if (typeof value !== "object" || value === null) return null;
41
41
  const record = value;
42
42
  if (typeof record.defaultLocale !== "string" || record.defaultLocale === "") return null;
@@ -9,8 +9,16 @@ import {
9
9
  registerBlockFields,
10
10
  startEldraPreview
11
11
  } from "@eldrajs/theme-vue";
12
- import { defineNuxtPlugin, useHead, useRuntimeConfig, useState } from "nuxt/app";
13
- import { reactive } from "vue";
12
+ import {
13
+ clearNuxtData,
14
+ defineNuxtPlugin,
15
+ injectHead,
16
+ refreshNuxtData,
17
+ useHead,
18
+ useRuntimeConfig,
19
+ useState
20
+ } from "nuxt/app";
21
+ import { nextTick, reactive, watch } from "vue";
14
22
  import blockFields from "virtual:eldra/block-fields";
15
23
  import manifest from "virtual:eldra/manifest";
16
24
  import messages from "virtual:eldra/messages";
@@ -20,8 +28,19 @@ import { resolveSiteDesignTokens } from "./designTokens.js";
20
28
  import { createNuxtEldraLocaleState, localeAlternates } from "./localeState.js";
21
29
  import { localeDisplayName, resolveLocaleRouting, resolveStoreLocales } from "./locales.js";
22
30
  import { resolveBridgeOrigins } from "./origins.js";
31
+ import {
32
+ isPreviewSessionRefused,
33
+ reportPreviewSessionSiteSettingError,
34
+ settlePreviewSessionDrafts,
35
+ settlePreviewSessionSiteSettings,
36
+ startPreviewSession,
37
+ usePreviewSession
38
+ } from "./previewSession.js";
39
+ import { afterHeadRendered } from "./previewSessionHead.js";
40
+ import { sessionReads } from "./previewSessionReads.js";
23
41
  import { canonicalRoutePath } from "./routePath.js";
24
42
  import { primePrerenderedRoutes } from "./staticRoutes.js";
43
+ const PREVIEW_SESSION_ROBOTS = "noindex, nofollow";
25
44
  export default defineNuxtPlugin({
26
45
  name: "eldra-theme",
27
46
  setup(nuxtApp) {
@@ -39,6 +58,65 @@ export default defineNuxtPlugin({
39
58
  defaultLocale: storeLocales?.default ?? routing.default ?? null
40
59
  });
41
60
  const preview = createEldraPreviewState();
61
+ const hydratedKeys = import.meta.client ? Object.keys(nuxtApp.payload.data ?? {}).filter(
62
+ (key) => nuxtApp.payload.data[key] !== void 0
63
+ ) : [];
64
+ const readDrafts = async () => {
65
+ const { reread, inFlight } = sessionReads({
66
+ hydratedKeys,
67
+ asyncData: nuxtApp._asyncData ?? {},
68
+ promises: nuxtApp._asyncDataPromises ?? {}
69
+ });
70
+ await Promise.allSettled([
71
+ reread.length > 0 ? refreshNuxtData(reread) : void 0,
72
+ ...inFlight
73
+ ]);
74
+ };
75
+ let markSessionHydrated = () => void 0;
76
+ const sessionHydrated = new Promise((resolve) => {
77
+ markSessionHydrated = resolve;
78
+ });
79
+ let siteSettings = Promise.resolve();
80
+ let sessionHead;
81
+ try {
82
+ sessionHead = injectHead(nuxtApp);
83
+ } catch {
84
+ }
85
+ const previewSession = import.meta.client && startPreviewSession(client, {
86
+ onHydrated: (hydrated) => nuxtApp.hooks.hookOnce("app:suspense:resolve", async () => {
87
+ hydrated();
88
+ markSessionHydrated();
89
+ await settlePreviewSessionDrafts(
90
+ () => Promise.allSettled([readDrafts(), siteSettings]),
91
+ () => afterHeadRendered(sessionHead, () => nextTick())
92
+ );
93
+ })
94
+ });
95
+ if (previewSession) {
96
+ siteSettings = settlePreviewSessionSiteSettings(
97
+ (isOpen) => import("./previewSessionSite.js").then(
98
+ ({ readSessionSiteSettings }) => readSessionSiteSettings(client, context, {
99
+ themeMessages: manifest.messages,
100
+ locales: storeLocales,
101
+ isOpen,
102
+ applyAfter: sessionHydrated,
103
+ onError: reportPreviewSessionSiteSettingError
104
+ })
105
+ )
106
+ );
107
+ useHead({
108
+ meta: [{ name: "robots", content: PREVIEW_SESSION_ROBOTS, tagPriority: "critical" }]
109
+ });
110
+ const session = usePreviewSession();
111
+ const stop = watch(
112
+ () => session.hydrated && isPreviewSessionRefused(session.status),
113
+ (refused) => {
114
+ if (!refused) return;
115
+ stop();
116
+ clearNuxtData();
117
+ }
118
+ );
119
+ }
42
120
  const router = () => nuxtApp.$router;
43
121
  const localeNames = useState(
44
122
  "eldra-locale-names",
@@ -70,8 +148,8 @@ export default defineNuxtPlugin({
70
148
  seoSiteUrl
71
149
  )
72
150
  }));
73
- if (import.meta.client) primePrerenderedRoutes();
74
- if (import.meta.client && window.parent !== window) {
151
+ if (import.meta.client && !previewSession) primePrerenderedRoutes();
152
+ if (import.meta.client && !previewSession && window.parent !== window) {
75
153
  const allowedOrigins = resolveBridgeOrigins(cfg.studioOrigins, document.referrer);
76
154
  if (allowedOrigins.length === 0) {
77
155
  console.warn("[eldra] preview disabled: parent origin is not an allowed Studio origin");
@@ -0,0 +1,155 @@
1
+ import { type EldraClient } from '@eldrajs/theme-core';
2
+ /**
3
+ * Draft preview sessions (WS-1293, WS-1303): the page is the theme's own deployment, served by
4
+ * Eldra's preview router on a host of its own (`p-<session id>.previews-{env}.eldra.dev`), and it
5
+ * renders the organisation's **drafts**, read client-side through the router.
6
+ *
7
+ * The router is the only holder of the credential: it keeps the session in an HttpOnly cookie, so
8
+ * the page never sees one and never sends one. Draft reads go same-origin to `/__eldra/gateway/*`,
9
+ * and the router adds `X-Org-Id` and `X-Preview-Session` itself (`@eldrajs/theme-core`'s
10
+ * `enableSessionPreview`). What the browser paints first is the published prerender — the
11
+ * deployment is the ordinary build — so it is covered by a veil until the first draft is on screen,
12
+ * and a session the router refuses is a notice, never the published page.
13
+ *
14
+ * Nothing here runs outside a session: a storefront, a build and Studio's canvas preview (the
15
+ * bridge's `X-Preview-Token`) are exactly what they were.
16
+ */
17
+ /** The `<meta name>` the preview router puts in every page it serves for a session. */
18
+ export declare const PREVIEW_SESSION_META_NAME = "eldra-preview";
19
+ export declare const PREVIEW_SESSION_META_CONTENT = "session";
20
+ /** Where the router serves the draft read proxy on a session host. */
21
+ export declare const PREVIEW_SESSION_PROXY_PATH = "/__eldra/gateway";
22
+ /** The router's exit: clears the session's cookies and says so. */
23
+ export declare const PREVIEW_SESSION_EXIT_PATH = "/__eldra/preview/exit";
24
+ /**
25
+ * The attribute the page sets on `<html>` once the session no longer needs the router's early hide
26
+ * (WS-1376). The router puts `html:not([data-eldra-preview-ready]) body { visibility: hidden }` at
27
+ * the top of every document it serves for a session, so the published prerender is never painted
28
+ * before the kit's own veil covers it. The page sets this as soon as its veil (or the built-in
29
+ * fallback notice) is mounted and covering the page, and on every way the session leaves the veil
30
+ * (the draft shown, a refusal, the timeout, a failure) in case it never mounted. The router's rule
31
+ * reveals the body after 12 s on its own, which is shorter than the 15 s the drafts may take: that
32
+ * is why it is the mounted veil, not the dropped one, that lifts it.
33
+ */
34
+ export declare const PREVIEW_SESSION_READY_ATTRIBUTE = "data-eldra-preview-ready";
35
+ export declare function isPreviewSessionHost(hostname: string): boolean;
36
+ /**
37
+ * A local development host: where a theme developer (or a test) runs a stand-in for the router.
38
+ * Only there is the router's marker trusted on its own — see `detectPreviewSession`.
39
+ */
40
+ export declare function isLocalDevelopmentHost(hostname: string): boolean;
41
+ /**
42
+ * Whether the document's **head** carries the router's session marker
43
+ * (`<meta name="eldra-preview" content="session">`). A marker anywhere else — in the body, where
44
+ * merchant-authored content can end up — is not the router's.
45
+ */
46
+ export declare function hasPreviewSessionMarker(doc: Pick<Document, 'head'>): boolean;
47
+ /**
48
+ * Whether this page is a draft preview session. Browser only; a server render is never one.
49
+ *
50
+ * The session host's shape decides on its own (only the router answers those names). The router's
51
+ * marker in the head is honoured only together with that shape, or on a local development host
52
+ * (`isLocalDevelopmentHost`), so a marker that reaches a storefront's own page never turns it into
53
+ * a session.
54
+ */
55
+ export declare function detectPreviewSession(win: {
56
+ location: {
57
+ hostname: string;
58
+ };
59
+ document: Pick<Document, 'head'>;
60
+ } | undefined): boolean;
61
+ /**
62
+ * Where a session is.
63
+ * * `off`: not a session (every storefront, every build, Studio's canvas).
64
+ * * `pending`: a session whose first draft is not on screen yet — the veil is up.
65
+ * * `ready`: the draft is on screen.
66
+ * * `expired`: the router refused the session (401: invalid, revoked or expired). Final.
67
+ * * `unavailable`: the router could not check it or read the draft (403, 502, 503).
68
+ */
69
+ export type PreviewSessionStatus = 'off' | 'pending' | 'ready' | 'expired' | 'unavailable';
70
+ export interface PreviewSessionState {
71
+ active: boolean;
72
+ status: PreviewSessionStatus;
73
+ /** The refusal's `errorId`, when it named one. */
74
+ errorId: string | null;
75
+ /** The published prerender has been hydrated, so the page may now be replaced. */
76
+ hydrated: boolean;
77
+ }
78
+ export declare function usePreviewSession(): Readonly<PreviewSessionState>;
79
+ export declare function isPreviewSessionRefused(status: PreviewSessionStatus): boolean;
80
+ /** The draft is on screen: the veil comes down. A refusal stays. */
81
+ export declare function markPreviewSessionDraftShown(): void;
82
+ /** The page has been hydrated with the published prerender. */
83
+ export declare function markPreviewSessionHydrated(): void;
84
+ /**
85
+ * What a failed read says about the session, or `null` when it says nothing about it (a page the
86
+ * drafts do not have is a `404` from Core, which is the theme's own not-found, not a refusal).
87
+ * Only a session read through the proxy counts: a commerce read failing is the storefront's own
88
+ * business. A `404 PREVIEW_GATEWAY_PATH_NOT_ALLOWED` is a not-found too: the router refuses a path
89
+ * it will not forward, which a typed address can make (a route value with `%` or `/` is sent
90
+ * encoded), and the published site would show its not-found page for it, not end anything.
91
+ */
92
+ export declare function previewSessionRefusal(error: unknown): {
93
+ status: 'expired' | 'unavailable';
94
+ errorId: string | null;
95
+ } | null;
96
+ /**
97
+ * A site setting read (`getSiteSetting`) that failed. Its failure is never reported to the client's
98
+ * refusal listeners, and must not end the session by itself — except when the router refused the
99
+ * session (401): the router clears the session's cookies then, so the CMS reads after it can only
100
+ * say `SITE_PREVIEW_SESSION_INVALID`, and this refusal is the one that says why (expired, revoked).
101
+ */
102
+ export declare function reportPreviewSessionSiteSettingError(error: unknown): void;
103
+ /**
104
+ * When the UI chunk cannot be loaded (a deployment pruned under an open page, a network that
105
+ * dropped it): a plain line of text over the page, so a veiled or refused session is never an empty,
106
+ * inert page with nothing said. Deliberately bare — no styling beyond what keeps it readable.
107
+ */
108
+ export declare function mountFallbackNotice(doc: Document): HTMLElement;
109
+ /**
110
+ * How long the drafts may take to arrive before the session says it is unavailable, counted from
111
+ * the session's start (`startPreviewSession`), so it runs even when the app never finishes
112
+ * hydrating (a theme awaiting a read that hangs, so suspense never resolves).
113
+ */
114
+ export declare const PREVIEW_SESSION_DRAFT_TIMEOUT_MS = 15000;
115
+ /**
116
+ * Wait for the session's re-reads to settle, then bring the veil down — or, when they have not
117
+ * settled within `timeoutMs`, end in the unavailable notice. Never the published page either way.
118
+ */
119
+ export declare function settlePreviewSessionDrafts(reads: () => Promise<unknown>, afterRender: () => Promise<unknown>, timeoutMs?: number): Promise<void>;
120
+ /**
121
+ * Keep the veil up until `work` has settled, when it was started while the session is covered —
122
+ * a no-op otherwise (outside a session, or once the draft is shown).
123
+ *
124
+ * For the reads a theme makes outside Nuxt's async data, which the session cannot see: a block
125
+ * whose draft names a collection the pinned build never read starts that read in the draft's own
126
+ * render, and without this the veil drops on its skeleton and the page changes under the merchant
127
+ * a moment later — and a focus the session replays (`replayCoveredFocus`) scrolls against a layout
128
+ * that is about to change, landing where the live page, which never had the skeleton, does not.
129
+ * Resolve `work` once its answer has been written where the page renders it from; the session
130
+ * renders once more after it.
131
+ */
132
+ export declare function holdPreviewSession(work: PromiseLike<unknown>): void;
133
+ /** How long a session waits for the site's saved settings before it keeps the build's. */
134
+ export declare const PREVIEW_SESSION_SITE_SETTINGS_TIMEOUT_MS = 10000;
135
+ /**
136
+ * The bound around a session's site settings read (WS-1394): the chunk that reads them and the
137
+ * reads themselves together, so neither a stalled chunk nor a stalled read reaches the drafts'
138
+ * own 15 s bound — a settings failure never ends the session. `read` is handed `isOpen`; once the
139
+ * bound has passed (or the read settled) it answers `false`, and an answer that arrives later must
140
+ * not be applied, so nothing changes after the veil. Never rejects.
141
+ */
142
+ export declare function settlePreviewSessionSiteSettings(read: (isOpen: () => boolean) => Promise<unknown>, timeoutMs?: number): Promise<void>;
143
+ /**
144
+ * Turn the page into a draft preview session when it is one: the client's CMS reads go to the
145
+ * router's proxy, a refusal on any of them ends the session on screen, and the veil, the exit
146
+ * banner and the notices are mounted. Returns whether it did. Browser only.
147
+ *
148
+ * `onHydrated` is handed what to run once the published prerender is hydrated: it marks the state,
149
+ * then the caller re-reads every async data entry through the session and calls
150
+ * `markPreviewSessionDraftShown` when they have settled.
151
+ */
152
+ export declare function startPreviewSession(client: EldraClient, options: {
153
+ win?: Window;
154
+ onHydrated: (done: () => void) => void;
155
+ }): boolean;