@revenexx/cover 0.16.0 → 0.18.0
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/app/app.config.ts +4 -0
- package/app/plugins/storefront-messages.ts +96 -0
- package/nuxt.config.ts +9 -0
- package/package.json +1 -1
- package/server/api/i18n/[locale].get.ts +34 -0
- package/server/middleware/storefront-preview.ts +38 -0
- package/server/services/ApiCartService.ts +75 -6
- package/server/utils/i18n.ts +39 -10
- package/server/utils/storefrontMessages.ts +480 -0
- package/server/utils/storefrontPreview.ts +63 -0
- package/server/utils/storefrontSource.ts +155 -0
package/app/app.config.ts
CHANGED
|
@@ -46,6 +46,10 @@ export default defineAppConfig({
|
|
|
46
46
|
// nothing, and every surface then falls back to the default the owning app
|
|
47
47
|
// itself declares, so the demo and an untouched live tenant behave alike.
|
|
48
48
|
settingsService: "mock",
|
|
49
|
+
// The tenant's own storefront texts, published from the Experience Studio
|
|
50
|
+
// through transpose and merged over the theme's locale files. Mock reads
|
|
51
|
+
// nothing, so the demo shows the theme's texts; a theme switches it to "api".
|
|
52
|
+
translationsService: "mock",
|
|
49
53
|
// How an ordered quote is paid. A quote is a negotiated B2B price, so the
|
|
50
54
|
// order it becomes goes on account; a storefront that takes quotes on
|
|
51
55
|
// another method names its code here.
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tenant's storefront texts over the theme's (PE-1073, transpose
|
|
3
|
+
* sprachtags §3.2).
|
|
4
|
+
*
|
|
5
|
+
* The theme's locale files are bundled once for every tenant; what a tenant
|
|
6
|
+
* changed in the Experience Studio arrives per request as an overlay from
|
|
7
|
+
* /api/i18n/{locale} (the BFF holds it per tenant). This plugin merges it into
|
|
8
|
+
* the request's vue-i18n messages — on the server before the page renders, and
|
|
9
|
+
* again in the browser from the payload, so the client hydrates with exactly
|
|
10
|
+
* the texts the server rendered.
|
|
11
|
+
*
|
|
12
|
+
* It runs after @nuxtjs/i18n has loaded the initial locale (a merge before
|
|
13
|
+
* that would be overwritten by the theme's messages), and wraps the module's
|
|
14
|
+
* message loader so a later language switch gets its overlay right after the
|
|
15
|
+
* theme's messages for that locale, before the locale changes.
|
|
16
|
+
*
|
|
17
|
+
* Not an @nuxtjs/i18n locale loader on purpose: loader results are cached per
|
|
18
|
+
* locale for the whole process, and one build serves many tenants.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
type MessageTree = Record<string, unknown>;
|
|
22
|
+
|
|
23
|
+
interface I18nTarget {
|
|
24
|
+
mergeLocaleMessage: (locale: string, messages: MessageTree) => void;
|
|
25
|
+
locale: { value: string } | string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The slice of @nuxtjs/i18n's internal context this plugin wraps. */
|
|
29
|
+
interface NuxtI18nContext {
|
|
30
|
+
loadMessages: (locale: string) => Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const STATE_KEY = "cover:storefront-messages";
|
|
34
|
+
|
|
35
|
+
export default defineNuxtPlugin({
|
|
36
|
+
name: "cover:storefront-messages",
|
|
37
|
+
dependsOn: ["i18n:plugin:route-locale-detect"],
|
|
38
|
+
async setup(nuxtApp) {
|
|
39
|
+
// Per request on the server, shipped in the payload to the client.
|
|
40
|
+
const overlays = useState<Record<string, MessageTree>>(STATE_KEY, () => ({}));
|
|
41
|
+
const i18n = nuxtApp.$i18n as unknown as I18nTarget;
|
|
42
|
+
const requestFetch = useRequestFetch();
|
|
43
|
+
|
|
44
|
+
// On the first page of a preview the cookie is only being set, so the
|
|
45
|
+
// server-side read names the token itself (server/middleware/
|
|
46
|
+
// storefront-preview.ts left it on the request).
|
|
47
|
+
const preview = import.meta.server
|
|
48
|
+
? String((useRequestEvent()?.context as Record<string, unknown> | undefined)?.coverStorefrontPreview ?? "")
|
|
49
|
+
: "";
|
|
50
|
+
|
|
51
|
+
async function overlayFor(locale: string): Promise<MessageTree> {
|
|
52
|
+
const held = overlays.value[locale];
|
|
53
|
+
if (held) {
|
|
54
|
+
return held;
|
|
55
|
+
}
|
|
56
|
+
let messages: MessageTree = {};
|
|
57
|
+
try {
|
|
58
|
+
const res = await requestFetch<{ messages?: MessageTree }>(`/api/i18n/${encodeURIComponent(locale)}`, {
|
|
59
|
+
query: preview ? { preview } : undefined,
|
|
60
|
+
});
|
|
61
|
+
messages = res?.messages && typeof res.messages === "object" ? res.messages : {};
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
// Fails open: the theme's own texts stand.
|
|
65
|
+
}
|
|
66
|
+
overlays.value = { ...overlays.value, [locale]: messages };
|
|
67
|
+
return messages;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function apply(locale: string): Promise<void> {
|
|
71
|
+
if (!locale) {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const messages = await overlayFor(locale);
|
|
75
|
+
if (Object.keys(messages).length > 0) {
|
|
76
|
+
i18n.mergeLocaleMessage(locale, messages);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const ctx = (nuxtApp as unknown as { _nuxtI18n?: NuxtI18nContext })._nuxtI18n;
|
|
81
|
+
if (ctx && typeof ctx.loadMessages === "function") {
|
|
82
|
+
const loadThemeMessages = ctx.loadMessages;
|
|
83
|
+
ctx.loadMessages = async (locale: string) => {
|
|
84
|
+
await loadThemeMessages(locale);
|
|
85
|
+
await apply(locale);
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
// The module's internals moved: still correct, one render later.
|
|
90
|
+
nuxtApp.hook("i18n:localeSwitched", ({ newLocale }) => apply(newLocale));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const current = typeof i18n.locale === "string" ? i18n.locale : i18n.locale.value;
|
|
94
|
+
await apply(current);
|
|
95
|
+
},
|
|
96
|
+
});
|
package/nuxt.config.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { defineNuxtConfig } from "nuxt/config";
|
|
|
8
8
|
|
|
9
9
|
const currentDir = dirname(fileURLToPath(import.meta.url));
|
|
10
10
|
const require_ = createRequire(import.meta.url);
|
|
11
|
+
const coverVersion = String((require_("./package.json") as { version?: string }).version ?? "");
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* Auto-discovers the layer's locale files under i18n/locales/{code}/.
|
|
@@ -121,6 +122,14 @@ export default defineNuxtConfig({
|
|
|
121
122
|
// HMAC secret for the stateless checkout session tokens — override
|
|
122
123
|
// via NUXT_CHECKOUT_SESSION_SECRET in multi-tenant deployments.
|
|
123
124
|
checkoutSessionSecret: "",
|
|
125
|
+
// The transpose catalog this build's storefront texts are published
|
|
126
|
+
// under, `theme:<vendor>/<name>` (PE-1073). Each theme sets its own;
|
|
127
|
+
// empty reads nothing. Override via NUXT_TRANSPOSE_CATALOG.
|
|
128
|
+
transposeCatalog: "",
|
|
129
|
+
// What the shop hands over its texts as (PE-1072): a name for the
|
|
130
|
+
// Studio, and the layer's version so a theme update shows as one.
|
|
131
|
+
transposeCatalogName: "",
|
|
132
|
+
transposeCatalogVersion: coverVersion,
|
|
124
133
|
public: {
|
|
125
134
|
// Cart state keys the layer's stores read — apps may override, but
|
|
126
135
|
// the layer must ship working defaults (an undefined TTL turns the
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@revenexx/cover",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "Cover — revenexx design system for Nuxt. Distributed as a Nuxt layer: generic UI components, theming tokens and stores shared by the demo shop, custom storefronts and the Blokkli theme.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./nuxt.config.ts",
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { createError, getQuery, getRouterParam, setResponseHeader } from "h3";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The tenant's storefront texts for one UI locale — the overlay transpose
|
|
5
|
+
* published, only what differs from the theme (PE-1073).
|
|
6
|
+
*
|
|
7
|
+
* Read by the storefront-messages plugin: on the server for the page being
|
|
8
|
+
* rendered, in the browser when the buyer switches language. Both go through
|
|
9
|
+
* the same per-tenant cache, so a page and a later switch can never disagree.
|
|
10
|
+
*
|
|
11
|
+
* `?preview=<token>` reads the Studio's draft, like `?rx-preview=` on a page;
|
|
12
|
+
* the server-side render passes it explicitly because on the first page of a
|
|
13
|
+
* preview the cookie is set, not yet sent.
|
|
14
|
+
*/
|
|
15
|
+
export default defineEventHandler(async (event) => {
|
|
16
|
+
const locale = getRouterParam(event, "locale") ?? "";
|
|
17
|
+
if (!isStorefrontLocale(locale)) {
|
|
18
|
+
throw createError({ statusCode: 400, statusMessage: "Unknown locale" });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const preview = getQuery(event).preview;
|
|
22
|
+
if (isStorefrontPreviewToken(preview)) {
|
|
23
|
+
setStorefrontPreview(event, preview);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const messages = await readStorefrontMessages(event, locale);
|
|
27
|
+
|
|
28
|
+
setResponseHeader(
|
|
29
|
+
event,
|
|
30
|
+
"Cache-Control",
|
|
31
|
+
resolveStorefrontPreview(event) ? "no-store" : "private, max-age=30",
|
|
32
|
+
);
|
|
33
|
+
return { locale, messages };
|
|
34
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { deleteCookie, getQuery, getRequestProtocol, setCookie, setResponseHeader } from "h3";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Keep the Studio's preview for the visit (PE-1073, transpose sprachtags §3.3).
|
|
5
|
+
*
|
|
6
|
+
* The Experience Studio opens the shop with `?rx-preview=<token>`. Only that
|
|
7
|
+
* first URL carries it, so it goes into a short-lived cookie and every later
|
|
8
|
+
* page — and every client-side language switch through /api/i18n — reads the
|
|
9
|
+
* draft too. An empty `?rx-preview=` ends the preview.
|
|
10
|
+
*
|
|
11
|
+
* A request that reads the draft is never cached: `Cache-Control: no-store`
|
|
12
|
+
* on whatever it answers, so no edge or browser cache hands a draft to a
|
|
13
|
+
* buyer.
|
|
14
|
+
*/
|
|
15
|
+
export default defineEventHandler((event) => {
|
|
16
|
+
const fromQuery = getQuery(event)[STOREFRONT_PREVIEW_QUERY];
|
|
17
|
+
|
|
18
|
+
if (fromQuery === "") {
|
|
19
|
+
deleteCookie(event, STOREFRONT_PREVIEW_COOKIE, { path: "/" });
|
|
20
|
+
setStorefrontPreview(event, "");
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (isStorefrontPreviewToken(fromQuery)) {
|
|
25
|
+
setCookie(event, STOREFRONT_PREVIEW_COOKIE, fromQuery, {
|
|
26
|
+
path: "/",
|
|
27
|
+
httpOnly: true,
|
|
28
|
+
sameSite: "lax",
|
|
29
|
+
secure: getRequestProtocol(event, { xForwardedProto: true }) === "https",
|
|
30
|
+
maxAge: STOREFRONT_PREVIEW_MAX_AGE_S,
|
|
31
|
+
});
|
|
32
|
+
setStorefrontPreview(event, fromQuery);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (resolveStorefrontPreview(event)) {
|
|
36
|
+
setResponseHeader(event, "Cache-Control", "no-store");
|
|
37
|
+
}
|
|
38
|
+
});
|
|
@@ -68,6 +68,29 @@ function visitCartId(event: H3Event): string | null {
|
|
|
68
68
|
return visit && !visit.handedBack ? visit.cartId : null;
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
/**
|
|
72
|
+
* The query a call on `cartId` has to carry: the visit's pSid as
|
|
73
|
+
* `?session_key=` when the cart is the open visit's own, else null.
|
|
74
|
+
*
|
|
75
|
+
* The visit's cart is owned by its pSid, not by the contact, and every call
|
|
76
|
+
* this BFF makes for a signed-in buyer carries their principal. From carts
|
|
77
|
+
* 3.0.0 on such a call reaches a cart no contact owns only with that cart's
|
|
78
|
+
* key, so every call on the visit's cart presents it (RAD-167). carts accepts
|
|
79
|
+
* it from 2.5.0 on (RAD-252). The typed SDK takes no such parameter yet, so
|
|
80
|
+
* these calls go through the transport's escape hatch.
|
|
81
|
+
*/
|
|
82
|
+
function visitCartKey(event: H3Event, cartId: string): { session_key: string } | null {
|
|
83
|
+
const visit = readPunchoutVisit(event);
|
|
84
|
+
return visit && !visit.handedBack && visit.cartId === cartId && visit.psid
|
|
85
|
+
? { session_key: visit.psid }
|
|
86
|
+
: null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A cart's address in the gateway, with an optional sub-path. */
|
|
90
|
+
function cartPath(cartId: string, suffix = ""): string {
|
|
91
|
+
return `/v1/carts/${encodeURIComponent(cartId)}${suffix}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
71
94
|
/** Storefront CartItem → carts-app line. The snapshot is the loose product copy. */
|
|
72
95
|
function toApiLine(item: CartItem, position: number): Record<string, unknown> {
|
|
73
96
|
return {
|
|
@@ -175,8 +198,11 @@ export class ApiCartService implements ICartService, ICartManager {
|
|
|
175
198
|
}) as unknown as ApiCart;
|
|
176
199
|
}
|
|
177
200
|
|
|
178
|
-
private async listItems(cartId: string): Promise<CartItem[]> {
|
|
179
|
-
const
|
|
201
|
+
private async listItems(event: H3Event, cartId: string): Promise<CartItem[]> {
|
|
202
|
+
const query = visitCartKey(event, cartId);
|
|
203
|
+
const { items } = (query
|
|
204
|
+
? await useRevenexxSdk().call("GET", cartPath(cartId, "/items"), { query })
|
|
205
|
+
: await useRevenexxSdk().cartsItems.cartsItemsList({ cartId })) as unknown as { items: ApiCartLine[] };
|
|
180
206
|
return items.map(toCartItem);
|
|
181
207
|
}
|
|
182
208
|
|
|
@@ -194,14 +220,20 @@ export class ApiCartService implements ICartService, ICartManager {
|
|
|
194
220
|
|
|
195
221
|
async getItems(event: H3Event): Promise<CartItem[]> {
|
|
196
222
|
const cartId = await this.activeCartId(event);
|
|
197
|
-
return cartId ? await this.listItems(cartId) : [];
|
|
223
|
+
return cartId ? await this.listItems(event, cartId) : [];
|
|
198
224
|
}
|
|
199
225
|
|
|
200
226
|
async saveItems(event: H3Event, items: CartItem[]): Promise<void> {
|
|
201
227
|
const cartId = visitCartId(event) ?? (await this.ensureActiveCart(resolveOwner(event))).id;
|
|
228
|
+
const lines = items.map((item, index) => toApiLine(item, index));
|
|
229
|
+
const query = visitCartKey(event, cartId);
|
|
230
|
+
if (query) {
|
|
231
|
+
await useRevenexxSdk().call("PUT", cartPath(cartId, "/items"), { query, body: { items: lines } });
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
202
234
|
await useRevenexxSdk().cartsItems.cartsItemsReplace({
|
|
203
235
|
cartId,
|
|
204
|
-
items:
|
|
236
|
+
items: lines as unknown as Models.CartItemCreateRequest[],
|
|
205
237
|
});
|
|
206
238
|
}
|
|
207
239
|
|
|
@@ -217,7 +249,7 @@ export class ApiCartService implements ICartService, ICartManager {
|
|
|
217
249
|
// sends that cart and no other. The visit sees exactly its own cart.
|
|
218
250
|
const visitCart = visitCartId(event);
|
|
219
251
|
if (visitCart) {
|
|
220
|
-
const cart = await useRevenexxSdk().call<ApiCart>("GET",
|
|
252
|
+
const cart = await useRevenexxSdk().call<ApiCart>("GET", cartPath(visitCart), { query: visitCartKey(event, visitCart) ?? {} });
|
|
221
253
|
return { carts: [{ ...toSummary(cart), active: true }], activeCartId: visitCart };
|
|
222
254
|
}
|
|
223
255
|
const carts = await this.listActive(resolveOwner(event));
|
|
@@ -244,10 +276,22 @@ export class ApiCartService implements ICartService, ICartManager {
|
|
|
244
276
|
}
|
|
245
277
|
|
|
246
278
|
async renameCart(event: H3Event, id: string, name: string): Promise<void> {
|
|
279
|
+
const query = visitCartKey(event, id);
|
|
280
|
+
if (query) {
|
|
281
|
+
await useRevenexxSdk().call("PUT", cartPath(id), { query, body: { name: name.trim() } });
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
247
284
|
await useRevenexxSdk().carts.cartsUpdate({ id, name: name.trim() });
|
|
248
285
|
}
|
|
249
286
|
|
|
250
287
|
async deleteCart(event: H3Event, id: string): Promise<void> {
|
|
288
|
+
// The visit's own cart never gets here (assertPunchoutCartKept), but a
|
|
289
|
+
// call on it would need its key all the same.
|
|
290
|
+
const query = visitCartKey(event, id);
|
|
291
|
+
if (query) {
|
|
292
|
+
await useRevenexxSdk().call("DELETE", cartPath(id), { query });
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
251
295
|
await useRevenexxSdk().carts.cartsDelete({ id });
|
|
252
296
|
}
|
|
253
297
|
|
|
@@ -262,11 +306,31 @@ export class ApiCartService implements ICartService, ICartManager {
|
|
|
262
306
|
if (!visitCart) {
|
|
263
307
|
await useRevenexxSdk().carts.cartsActivate({ id });
|
|
264
308
|
}
|
|
265
|
-
return await this.listItems(id);
|
|
309
|
+
return await this.listItems(event, id);
|
|
266
310
|
}
|
|
267
311
|
|
|
268
312
|
async addItemToCart(event: H3Event, id: string, item: CartItem): Promise<void> {
|
|
269
313
|
const line = toApiLine(item, 0);
|
|
314
|
+
const query = visitCartKey(event, id);
|
|
315
|
+
if (query) {
|
|
316
|
+
// The wire form of exactly what the typed call below sends.
|
|
317
|
+
await useRevenexxSdk().call("POST", cartPath(id, "/items"), {
|
|
318
|
+
query,
|
|
319
|
+
body: {
|
|
320
|
+
...(line.product_id ? { product_id: String(line.product_id) } : {}),
|
|
321
|
+
...(line.sku ? { sku: String(line.sku) } : {}),
|
|
322
|
+
name: String(line.name),
|
|
323
|
+
quantity: Number(line.quantity),
|
|
324
|
+
...(line.unit ? { unit: String(line.unit) } : {}),
|
|
325
|
+
unit_price: Number(line.unit_price),
|
|
326
|
+
tax_rate: Number(line.tax_rate),
|
|
327
|
+
position: Number(line.position),
|
|
328
|
+
snapshot: line.snapshot,
|
|
329
|
+
metadata: line.metadata,
|
|
330
|
+
},
|
|
331
|
+
});
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
270
334
|
await useRevenexxSdk().cartsItems.cartsItemsCreate({
|
|
271
335
|
cartId: id,
|
|
272
336
|
...(line.product_id ? { productId: String(line.product_id) } : {}),
|
|
@@ -287,6 +351,11 @@ export class ApiCartService implements ICartService, ICartManager {
|
|
|
287
351
|
if (!cartId) {
|
|
288
352
|
return null;
|
|
289
353
|
}
|
|
354
|
+
const query = visitCartKey(event, cartId);
|
|
355
|
+
if (query) {
|
|
356
|
+
await useRevenexxSdk().call("POST", cartPath(cartId, "/order"), { query, body: { order_ref: orderRef } });
|
|
357
|
+
return cartId;
|
|
358
|
+
}
|
|
290
359
|
await useRevenexxSdk().carts.cartsOrder({ id: cartId, orderRef });
|
|
291
360
|
return cartId;
|
|
292
361
|
}
|
package/server/utils/i18n.ts
CHANGED
|
@@ -1,23 +1,49 @@
|
|
|
1
|
+
import type { H3Event } from "h3";
|
|
2
|
+
|
|
1
3
|
type TranslationRecord = Record<string, unknown>;
|
|
2
4
|
|
|
3
5
|
const cache = new Map<string, TranslationRecord>();
|
|
4
6
|
|
|
7
|
+
/** The request being served, when there is one (Nitro's async context). */
|
|
8
|
+
function currentEvent(): H3Event | undefined {
|
|
9
|
+
try {
|
|
10
|
+
return useEvent();
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
5
17
|
/**
|
|
6
18
|
* Loads locale namespaces from the layer's i18n server assets into the cache.
|
|
7
19
|
* Call this once per request before using the synchronous serverT() — e.g.
|
|
8
20
|
* at the top of an event handler or service method.
|
|
21
|
+
*
|
|
22
|
+
* Also reads the tenant's published texts for the locale (and its fallback)
|
|
23
|
+
* into the request, so serverT() answers what the page shows: a text the
|
|
24
|
+
* tenant changed in the Experience Studio reads changed here too.
|
|
9
25
|
*/
|
|
10
26
|
export async function preloadLocaleNamespaces(locale: string, namespaces: string[]): Promise<void> {
|
|
11
27
|
const fallbackLocale = String(useRuntimeConfig().public.defaultLocale);
|
|
12
28
|
const wanted = locale === fallbackLocale ? [locale] : [locale, fallbackLocale];
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
29
|
+
const event = currentEvent();
|
|
30
|
+
await Promise.all([
|
|
31
|
+
...wanted.flatMap(loc => namespaces.map(async (ns) => {
|
|
32
|
+
const key = `${loc}/${ns}`;
|
|
33
|
+
if (cache.has(key)) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const data = await readCoverLocaleJson<TranslationRecord>(loc, ns);
|
|
37
|
+
cache.set(key, data ?? {});
|
|
38
|
+
})),
|
|
39
|
+
...wanted.map(loc => readStorefrontMessages(event, loc)),
|
|
40
|
+
]);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The tenant's text for a key, when its overlay was read for this request. */
|
|
44
|
+
function overlayValue(locale: string, keyPath: string): string | undefined {
|
|
45
|
+
const overlay = storefrontMessagesRead(currentEvent(), locale);
|
|
46
|
+
return overlay ? getNestedValue(overlay, keyPath) : undefined;
|
|
21
47
|
}
|
|
22
48
|
|
|
23
49
|
function getNamespace(locale: string, namespace: string): TranslationRecord {
|
|
@@ -60,14 +86,17 @@ export function serverT(
|
|
|
60
86
|
);
|
|
61
87
|
};
|
|
62
88
|
|
|
63
|
-
|
|
89
|
+
// The tenant's text first: vue-i18n merges all namespace files into one
|
|
90
|
+
// tree, and the overlay is keyed the same way, so `key` addresses it as is.
|
|
91
|
+
const value = overlayValue(locale, key) ?? getNestedValue(getNamespace(locale, namespace), key);
|
|
64
92
|
if (value !== undefined) {
|
|
65
93
|
return interpolate(value);
|
|
66
94
|
}
|
|
67
95
|
|
|
68
96
|
const fallbackLocale = String(useRuntimeConfig().public.defaultLocale);
|
|
69
97
|
if (locale !== fallbackLocale) {
|
|
70
|
-
const fallbackValue =
|
|
98
|
+
const fallbackValue = overlayValue(fallbackLocale, key)
|
|
99
|
+
?? getNestedValue(getNamespace(fallbackLocale, namespace), key);
|
|
71
100
|
if (fallbackValue !== undefined) {
|
|
72
101
|
return interpolate(fallbackValue);
|
|
73
102
|
}
|
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
import type { H3Event } from "h3";
|
|
2
|
+
|
|
3
|
+
// Imported explicitly rather than left to Nitro's auto-imports, so the cache
|
|
4
|
+
// and the transport can be unit-tested outside a Nitro build.
|
|
5
|
+
import { resolveRevenexxCredentials } from "./revenexxCredentials";
|
|
6
|
+
import { resolveStorefrontPreview } from "./storefrontPreview";
|
|
7
|
+
import { storefrontSource } from "./storefrontSource";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The tenant's own storefront texts, published from the Experience Studio
|
|
11
|
+
* through transpose (PE-1073, transpose sprachtags §3).
|
|
12
|
+
*
|
|
13
|
+
* A theme ships its texts in its locale files; a tenant changes some of them
|
|
14
|
+
* and adds languages the theme does not ship. transpose publishes those
|
|
15
|
+
* changes as an OVERLAY per catalog and locale — only what differs from the
|
|
16
|
+
* theme, nested by key the way vue-i18n addresses it — and the shop merges it
|
|
17
|
+
* over the theme's messages per request:
|
|
18
|
+
*
|
|
19
|
+
* GET {revenexxApiUrl}/v1/translations/messages?catalog=<key>&locale=<ui locale>
|
|
20
|
+
* Authorization: Bearer <brokered tenant JWT> X-Revenexx-Tenant: <slug>
|
|
21
|
+
* If-None-Match: "<hash of the overlay held>"
|
|
22
|
+
* → 200 { data: { release, hash, locale, fallback, messages, draft, source } } | 304
|
|
23
|
+
*
|
|
24
|
+
* The answer's `source.fingerprint` is what this tenant's shop handed over
|
|
25
|
+
* last. When it is not this build's own, the shop hands its theme's texts over
|
|
26
|
+
* once (PUT /v1/translations/sources, same credentials) — so a new theme
|
|
27
|
+
* version reaches the tenant's catalog with the first page it serves, for this
|
|
28
|
+
* tenant only. It never waits for that push.
|
|
29
|
+
*
|
|
30
|
+
* Per tenant, because ONE build serves many tenants: an @nuxtjs/i18n locale
|
|
31
|
+
* loader is cached per locale, which would hand the first tenant's texts to
|
|
32
|
+
* every other one. That is why this is not a loader.
|
|
33
|
+
*
|
|
34
|
+
* The read never decides whether the shop renders. It is bounded by a 300 ms
|
|
35
|
+
* timeout, asked at most every 30 s per tenant + catalog + locale with the
|
|
36
|
+
* held ETag, and fails OPEN: the last overlay stays, and without one the
|
|
37
|
+
* theme's own texts show. Same stance as ./appSettings.ts.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
export type MessageTree = Record<string, unknown>;
|
|
41
|
+
|
|
42
|
+
/** How long one overlay is served before transpose is asked again. */
|
|
43
|
+
export const STOREFRONT_MESSAGES_TTL_MS = 30_000;
|
|
44
|
+
|
|
45
|
+
/** A text read that has not answered by then is not waited for. */
|
|
46
|
+
export const STOREFRONT_MESSAGES_TIMEOUT_MS = 300;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Upper bound on held overlays. The tenant comes from the platform and the
|
|
50
|
+
* catalog from configuration, but the locale arrives in a client URL, so the
|
|
51
|
+
* map must not grow with whatever a caller types.
|
|
52
|
+
*/
|
|
53
|
+
const MAX_ENTRIES = 1_000;
|
|
54
|
+
|
|
55
|
+
/** A UI locale as transpose and vue-i18n spell it: `de`, `fr-CH`, `zh-Hant-TW`. */
|
|
56
|
+
export function isStorefrontLocale(value: unknown): value is string {
|
|
57
|
+
return typeof value === "string" && /^[a-z]{2,3}(?:-[a-z\d]{2,8}){0,3}$/i.test(value);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isMessageTree(value: unknown): value is MessageTree {
|
|
61
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/* ------------------------------------------------------------------ */
|
|
65
|
+
/* Transport */
|
|
66
|
+
/* ------------------------------------------------------------------ */
|
|
67
|
+
|
|
68
|
+
export interface StorefrontOverlayRequest {
|
|
69
|
+
/** Gateway base URL, e.g. https://api.revenexx.com */
|
|
70
|
+
readonly endpoint: string;
|
|
71
|
+
/** Tenant + auth headers, as the SDK would send them. */
|
|
72
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
73
|
+
readonly catalog: string;
|
|
74
|
+
readonly locale: string;
|
|
75
|
+
/** Studio preview token — reads the draft. */
|
|
76
|
+
readonly preview?: string;
|
|
77
|
+
/** ETag of the overlay already held. */
|
|
78
|
+
readonly etag?: string;
|
|
79
|
+
readonly timeoutMs?: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
interface FreshOverlay {
|
|
83
|
+
readonly status: "fresh";
|
|
84
|
+
readonly messages: MessageTree;
|
|
85
|
+
readonly etag: string;
|
|
86
|
+
/** What the tenant's shop handed over last; null when nothing yet. */
|
|
87
|
+
readonly sourceFingerprint?: string | null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export type StorefrontOverlayAnswer = FreshOverlay | { readonly status: "unchanged" };
|
|
91
|
+
|
|
92
|
+
type AuthHeaders = Readonly<Record<string, string>>;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* One read of one overlay. Throws on anything but 200/304 — the caller decides
|
|
96
|
+
* what failing open means for it.
|
|
97
|
+
*/
|
|
98
|
+
export async function fetchStorefrontOverlay(
|
|
99
|
+
request: StorefrontOverlayRequest,
|
|
100
|
+
): Promise<StorefrontOverlayAnswer> {
|
|
101
|
+
const url = new URL(`${request.endpoint.replace(/\/+$/, "")}/v1/translations/messages`);
|
|
102
|
+
url.searchParams.set("catalog", request.catalog);
|
|
103
|
+
url.searchParams.set("locale", request.locale);
|
|
104
|
+
if (request.preview) {
|
|
105
|
+
url.searchParams.set("preview", request.preview);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const headers: Record<string, string> = { Accept: "application/json", ...request.headers };
|
|
109
|
+
if (request.etag && !request.preview) {
|
|
110
|
+
headers["If-None-Match"] = request.etag;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const response = await fetch(url, {
|
|
114
|
+
headers,
|
|
115
|
+
signal: AbortSignal.timeout(request.timeoutMs ?? STOREFRONT_MESSAGES_TIMEOUT_MS),
|
|
116
|
+
...(request.preview ? { cache: "no-store" as const } : {}),
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
if (response.status === 304) {
|
|
120
|
+
return { status: "unchanged" };
|
|
121
|
+
}
|
|
122
|
+
if (!response.ok) {
|
|
123
|
+
throw new Error(`translations/messages answered ${response.status}`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const body = await response.json() as { data?: { messages?: unknown; hash?: unknown; source?: { fingerprint?: unknown } | null } } | null;
|
|
127
|
+
const data = body?.data;
|
|
128
|
+
const messages = isMessageTree(data?.messages) ? data.messages : {};
|
|
129
|
+
const etag = response.headers.get("etag")
|
|
130
|
+
?? (typeof data?.hash === "string" && data.hash ? `"${data.hash}"` : "");
|
|
131
|
+
const fingerprint = data?.source?.fingerprint;
|
|
132
|
+
return { status: "fresh", messages, etag, sourceFingerprint: typeof fingerprint === "string" ? fingerprint : null };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/* ------------------------------------------------------------------ */
|
|
136
|
+
/* Cache */
|
|
137
|
+
/* ------------------------------------------------------------------ */
|
|
138
|
+
|
|
139
|
+
export interface StorefrontMessageKey {
|
|
140
|
+
readonly tenant: string;
|
|
141
|
+
readonly catalog: string;
|
|
142
|
+
readonly locale: string;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export interface StorefrontMessageCacheOptions {
|
|
146
|
+
/**
|
|
147
|
+
* Reads one overlay; `etag` is what is held, if anything, and `auth` the
|
|
148
|
+
* headers of the request that asked — the brokered JWT rotates per
|
|
149
|
+
* invocation, so a read always carries the token of the request it serves.
|
|
150
|
+
*/
|
|
151
|
+
readonly load: (
|
|
152
|
+
key: StorefrontMessageKey,
|
|
153
|
+
etag: string,
|
|
154
|
+
auth: AuthHeaders,
|
|
155
|
+
) => Promise<StorefrontOverlayAnswer>;
|
|
156
|
+
readonly ttlMs?: number;
|
|
157
|
+
readonly maxEntries?: number;
|
|
158
|
+
readonly now?: () => number;
|
|
159
|
+
readonly onError?: (err: unknown, key: StorefrontMessageKey) => void;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
interface Entry {
|
|
163
|
+
messages: MessageTree;
|
|
164
|
+
etag: string;
|
|
165
|
+
checkedAt: number;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface StorefrontMessageCache {
|
|
169
|
+
read: (key: StorefrontMessageKey, auth?: AuthHeaders) => Promise<MessageTree>;
|
|
170
|
+
clear: () => void;
|
|
171
|
+
readonly size: number;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Overlays held in this process, partitioned by tenant + catalog + locale.
|
|
176
|
+
* Pure — the loader and the clock are injected — so the refresh and fail-open
|
|
177
|
+
* rules are tested without a server.
|
|
178
|
+
*/
|
|
179
|
+
export function createStorefrontMessageCache(
|
|
180
|
+
options: StorefrontMessageCacheOptions,
|
|
181
|
+
): StorefrontMessageCache {
|
|
182
|
+
const ttl = options.ttlMs ?? STOREFRONT_MESSAGES_TTL_MS;
|
|
183
|
+
const maxEntries = options.maxEntries ?? MAX_ENTRIES;
|
|
184
|
+
const now = options.now ?? Date.now;
|
|
185
|
+
const entries = new Map<string, Entry>();
|
|
186
|
+
/** A burst of requests for one key makes one read, not one each. */
|
|
187
|
+
const inFlight = new Map<string, Promise<MessageTree>>();
|
|
188
|
+
|
|
189
|
+
function remember(id: string, entry: Entry): void {
|
|
190
|
+
entries.delete(id);
|
|
191
|
+
entries.set(id, entry);
|
|
192
|
+
while (entries.size > maxEntries) {
|
|
193
|
+
const oldest = entries.keys().next().value;
|
|
194
|
+
if (oldest === undefined) {
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
entries.delete(oldest);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function refresh(
|
|
202
|
+
id: string,
|
|
203
|
+
key: StorefrontMessageKey,
|
|
204
|
+
auth: AuthHeaders,
|
|
205
|
+
held: Entry | undefined,
|
|
206
|
+
): Promise<MessageTree> {
|
|
207
|
+
try {
|
|
208
|
+
const answer = await options.load(key, held?.etag ?? "", auth);
|
|
209
|
+
if (answer.status === "unchanged") {
|
|
210
|
+
const messages = held?.messages ?? {};
|
|
211
|
+
remember(id, { messages, etag: held?.etag ?? "", checkedAt: now() });
|
|
212
|
+
return messages;
|
|
213
|
+
}
|
|
214
|
+
remember(id, { messages: answer.messages, etag: answer.etag, checkedAt: now() });
|
|
215
|
+
return answer.messages;
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
options.onError?.(err, key);
|
|
219
|
+
// Fail open: keep what was held — or nothing, i.e. the theme's own
|
|
220
|
+
// texts — and wait out the window before asking again, so an
|
|
221
|
+
// unreachable transpose is not asked on every page view.
|
|
222
|
+
const messages = held?.messages ?? {};
|
|
223
|
+
remember(id, { messages, etag: held?.etag ?? "", checkedAt: now() });
|
|
224
|
+
return messages;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return {
|
|
229
|
+
async read(key, auth = {}) {
|
|
230
|
+
const id = `${key.tenant}\u0000${key.catalog}\u0000${key.locale}`;
|
|
231
|
+
const held = entries.get(id);
|
|
232
|
+
if (held && now() - held.checkedAt < ttl) {
|
|
233
|
+
return held.messages;
|
|
234
|
+
}
|
|
235
|
+
let pending = inFlight.get(id);
|
|
236
|
+
if (!pending) {
|
|
237
|
+
pending = refresh(id, key, auth, held).finally(() => inFlight.delete(id));
|
|
238
|
+
inFlight.set(id, pending);
|
|
239
|
+
}
|
|
240
|
+
return await pending;
|
|
241
|
+
},
|
|
242
|
+
clear() {
|
|
243
|
+
entries.clear();
|
|
244
|
+
inFlight.clear();
|
|
245
|
+
},
|
|
246
|
+
get size() {
|
|
247
|
+
return entries.size;
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/* ------------------------------------------------------------------ */
|
|
253
|
+
/* The request's overlay */
|
|
254
|
+
/* ------------------------------------------------------------------ */
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Registry key, like every other BFF domain: "mock" (the layer default — the
|
|
258
|
+
* demo shop reads nothing and shows the theme's texts) or "api" (transpose
|
|
259
|
+
* through the gateway). The dev panel's cookie overrides it per browser.
|
|
260
|
+
*/
|
|
261
|
+
export function isStorefrontMessagesLive(event?: H3Event): boolean {
|
|
262
|
+
return resolveServiceKey(event, {
|
|
263
|
+
domain: "translationsService",
|
|
264
|
+
mockKey: "mock",
|
|
265
|
+
liveKey: "api",
|
|
266
|
+
}) === "api";
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The catalog this build's texts are published under — `theme:<vendor>/<name>`
|
|
271
|
+
* from the theme's runtime config (`transposeCatalog`, NUXT_TRANSPOSE_CATALOG).
|
|
272
|
+
* Empty means the build has none and nothing is read.
|
|
273
|
+
*/
|
|
274
|
+
export function storefrontCatalog(): string {
|
|
275
|
+
return String(useRuntimeConfig().transposeCatalog ?? "").trim();
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** The SDK's tenant + auth headers, without the buyer, market or channel. */
|
|
279
|
+
function gatewayHeaders(event: H3Event | undefined): Record<string, string> | null {
|
|
280
|
+
const { tenant, jwt, apiKey } = resolveRevenexxCredentials(event);
|
|
281
|
+
if (!tenant || (!jwt && !apiKey)) {
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
return jwt
|
|
285
|
+
? { "X-Revenexx-Tenant": tenant, "Authorization": `Bearer ${jwt}` }
|
|
286
|
+
: { "X-Revenexx-Tenant": tenant, "X-Revenexx-Api-Key": apiKey };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function endpoint(): string {
|
|
290
|
+
return String(useRuntimeConfig().revenexxApiUrl || "https://api.revenexx.com");
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Hands this build's theme texts to the tenant's catalog when transpose does
|
|
295
|
+
* not hold them — at most once at a time per tenant and catalog, and after a
|
|
296
|
+
* failure not again for ten minutes.
|
|
297
|
+
*/
|
|
298
|
+
export function createSourcePusher(options: {
|
|
299
|
+
readonly push: (catalog: string, auth: AuthHeaders) => Promise<string | null>;
|
|
300
|
+
readonly own: () => Promise<string | null>;
|
|
301
|
+
readonly now?: () => number;
|
|
302
|
+
readonly retryMs?: number;
|
|
303
|
+
readonly onError?: (err: unknown, catalog: string) => void;
|
|
304
|
+
}) {
|
|
305
|
+
const now = options.now ?? Date.now;
|
|
306
|
+
const retry = options.retryMs ?? 600_000;
|
|
307
|
+
const known = new Map<string, string>();
|
|
308
|
+
const failedAt = new Map<string, number>();
|
|
309
|
+
const inFlight = new Map<string, Promise<void>>();
|
|
310
|
+
|
|
311
|
+
return {
|
|
312
|
+
/** Called with what transpose answered; returns the push, if one started. */
|
|
313
|
+
check(key: { tenant: string; catalog: string }, heldFingerprint: string | null, auth: AuthHeaders): Promise<void> | undefined {
|
|
314
|
+
const id = `${key.tenant}\u0000${key.catalog}`;
|
|
315
|
+
if (inFlight.has(id) || (failedAt.has(id) && now() - (failedAt.get(id) ?? 0) < retry)) {
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
318
|
+
const pending = (async () => {
|
|
319
|
+
const own = await options.own();
|
|
320
|
+
if (!own || own === heldFingerprint || known.get(id) === own) {
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
try {
|
|
324
|
+
const pushed = await options.push(key.catalog, auth);
|
|
325
|
+
known.set(id, pushed ?? own);
|
|
326
|
+
failedAt.delete(id);
|
|
327
|
+
}
|
|
328
|
+
catch (err) {
|
|
329
|
+
failedAt.set(id, now());
|
|
330
|
+
options.onError?.(err, key.catalog);
|
|
331
|
+
}
|
|
332
|
+
})().finally(() => inFlight.delete(id));
|
|
333
|
+
inFlight.set(id, pending);
|
|
334
|
+
return pending;
|
|
335
|
+
},
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const pusher = createSourcePusher({
|
|
340
|
+
own: async () => (await storefrontSource())?.fingerprint ?? null,
|
|
341
|
+
push: async (catalog, auth) => {
|
|
342
|
+
const body = await storefrontSource();
|
|
343
|
+
if (!body || body.key !== catalog) {
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
const response = await fetch(`${endpoint().replace(/\/+$/, "")}/v1/translations/sources`, {
|
|
347
|
+
method: "PUT",
|
|
348
|
+
headers: { "Accept": "application/json", "Content-Type": "application/json", ...auth },
|
|
349
|
+
body: JSON.stringify(body),
|
|
350
|
+
signal: AbortSignal.timeout(10_000),
|
|
351
|
+
});
|
|
352
|
+
if (!response.ok) {
|
|
353
|
+
throw new Error(`translations/sources answered ${response.status}`);
|
|
354
|
+
}
|
|
355
|
+
const answer = await response.json() as { data?: { fingerprint?: unknown } } | null;
|
|
356
|
+
return typeof answer?.data?.fingerprint === "string" ? answer.data.fingerprint : body.fingerprint;
|
|
357
|
+
},
|
|
358
|
+
onError: (err, catalog) => {
|
|
359
|
+
getLogService().error("Storefront texts not handed to transpose", { catalog, ...toErrorContext(err) });
|
|
360
|
+
},
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
const cache = createStorefrontMessageCache({
|
|
364
|
+
load: async (key, etag, auth) => {
|
|
365
|
+
const answer = await fetchStorefrontOverlay({
|
|
366
|
+
endpoint: endpoint(),
|
|
367
|
+
headers: auth,
|
|
368
|
+
catalog: key.catalog,
|
|
369
|
+
locale: key.locale,
|
|
370
|
+
etag,
|
|
371
|
+
});
|
|
372
|
+
if (answer.status === "fresh") {
|
|
373
|
+
// Never awaited: the page renders with what is there.
|
|
374
|
+
void pusher.check(key, answer.sourceFingerprint ?? null, auth);
|
|
375
|
+
}
|
|
376
|
+
return answer;
|
|
377
|
+
},
|
|
378
|
+
onError: (err, key) => {
|
|
379
|
+
getLogService().error("Storefront texts unavailable", {
|
|
380
|
+
catalog: key.catalog,
|
|
381
|
+
locale: key.locale,
|
|
382
|
+
...toErrorContext(err),
|
|
383
|
+
});
|
|
384
|
+
},
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
/** Test hook: forget every held overlay. */
|
|
388
|
+
export function resetStorefrontMessages(): void {
|
|
389
|
+
cache.clear();
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Per-request memo, so serverT() can read the overlay synchronously. */
|
|
393
|
+
const REQUEST_CACHE = "coverStorefrontMessages";
|
|
394
|
+
|
|
395
|
+
function requestMemo(event: H3Event | undefined): Map<string, MessageTree> | undefined {
|
|
396
|
+
if (!event) {
|
|
397
|
+
return undefined;
|
|
398
|
+
}
|
|
399
|
+
const ctx = event.context as Record<string, unknown>;
|
|
400
|
+
const existing = ctx[REQUEST_CACHE];
|
|
401
|
+
if (existing instanceof Map) {
|
|
402
|
+
return existing as Map<string, MessageTree>;
|
|
403
|
+
}
|
|
404
|
+
const fresh = new Map<string, MessageTree>();
|
|
405
|
+
ctx[REQUEST_CACHE] = fresh;
|
|
406
|
+
return fresh;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* The tenant's overlay for one UI locale on this request — `{}` when there is
|
|
411
|
+
* none, when the build has no catalog, in mock mode, and whenever the read
|
|
412
|
+
* fails without anything held.
|
|
413
|
+
*
|
|
414
|
+
* A preview request reads the draft, uncached; if that read fails it falls
|
|
415
|
+
* back to the published overlay rather than to nothing.
|
|
416
|
+
*/
|
|
417
|
+
export async function readStorefrontMessages(
|
|
418
|
+
event: H3Event | undefined,
|
|
419
|
+
locale: string,
|
|
420
|
+
): Promise<MessageTree> {
|
|
421
|
+
if (!isStorefrontLocale(locale)) {
|
|
422
|
+
return {};
|
|
423
|
+
}
|
|
424
|
+
const memo = requestMemo(event);
|
|
425
|
+
const known = memo?.get(locale);
|
|
426
|
+
if (known) {
|
|
427
|
+
return known;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const messages = await readUncached(event, locale);
|
|
431
|
+
memo?.set(locale, messages);
|
|
432
|
+
return messages;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async function readUncached(event: H3Event | undefined, locale: string): Promise<MessageTree> {
|
|
436
|
+
if (!isStorefrontMessagesLive(event)) {
|
|
437
|
+
return {};
|
|
438
|
+
}
|
|
439
|
+
const catalog = storefrontCatalog();
|
|
440
|
+
if (!catalog) {
|
|
441
|
+
return {};
|
|
442
|
+
}
|
|
443
|
+
const headers = gatewayHeaders(event);
|
|
444
|
+
if (!headers) {
|
|
445
|
+
return {};
|
|
446
|
+
}
|
|
447
|
+
const { tenant } = resolveRevenexxCredentials(event);
|
|
448
|
+
|
|
449
|
+
const preview = resolveStorefrontPreview(event);
|
|
450
|
+
if (preview) {
|
|
451
|
+
try {
|
|
452
|
+
const answer = await fetchStorefrontOverlay({
|
|
453
|
+
endpoint: endpoint(),
|
|
454
|
+
headers,
|
|
455
|
+
catalog,
|
|
456
|
+
locale,
|
|
457
|
+
preview,
|
|
458
|
+
});
|
|
459
|
+
if (answer.status === "fresh") {
|
|
460
|
+
return answer.messages;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
catch (err) {
|
|
464
|
+
getLogService().error("Storefront preview texts unavailable", { catalog, locale, ...toErrorContext(err) });
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
return await cache.read({ tenant, catalog, locale }, headers);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* The overlay this request already read for `locale`, if any — for the
|
|
473
|
+
* synchronous serverT(), after an await of readStorefrontMessages().
|
|
474
|
+
*/
|
|
475
|
+
export function storefrontMessagesRead(
|
|
476
|
+
event: H3Event | undefined,
|
|
477
|
+
locale: string,
|
|
478
|
+
): MessageTree | undefined {
|
|
479
|
+
return requestMemo(event)?.get(locale);
|
|
480
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { H3Event } from "h3";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* "Vorschau im Shop": the Experience Studio opens the storefront with
|
|
5
|
+
* `?rx-preview=<token>` so an editor sees the DRAFT texts of their tenant
|
|
6
|
+
* before publishing them (transpose sprachtags §3.3).
|
|
7
|
+
*
|
|
8
|
+
* The token is signed by transpose, names one tenant and one catalog and lives
|
|
9
|
+
* for 15 minutes. The shop never inspects it — it forwards it as `preview=`
|
|
10
|
+
* and transpose decides whether it is valid. What the shop does own is keeping
|
|
11
|
+
* it for the visit: the first page carries it in the query, every later page
|
|
12
|
+
* and every client-side language switch must still read the draft, so it is
|
|
13
|
+
* kept in a short-lived cookie (server/middleware/storefront-preview.ts).
|
|
14
|
+
*
|
|
15
|
+
* A request reading the draft is never cached anywhere: the overlay read skips
|
|
16
|
+
* the in-memory cache and the response says `Cache-Control: no-store`.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Query parameter the Studio opens the shop with. */
|
|
20
|
+
export const STOREFRONT_PREVIEW_QUERY = "rx-preview";
|
|
21
|
+
|
|
22
|
+
/** Cookie the token is kept in for the rest of the visit. */
|
|
23
|
+
export const STOREFRONT_PREVIEW_COOKIE = "rx-preview";
|
|
24
|
+
|
|
25
|
+
/** Matches the token's own lifetime; a stale cookie only reads as "not a draft". */
|
|
26
|
+
export const STOREFRONT_PREVIEW_MAX_AGE_S = 15 * 60;
|
|
27
|
+
|
|
28
|
+
/** Where the middleware leaves the token for the rest of the request. */
|
|
29
|
+
const CONTEXT_KEY = "coverStorefrontPreview";
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Opaque, but bounded: it travels into an upstream query string and a cookie,
|
|
33
|
+
* so anything that is not a plausible token is dropped rather than forwarded.
|
|
34
|
+
*/
|
|
35
|
+
export function isStorefrontPreviewToken(value: unknown): value is string {
|
|
36
|
+
return typeof value === "string" && /^[\w.~+/=-]{8,2048}$/.test(value);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Pin the token for this request (the middleware, or a `preview=` on the BFF route). */
|
|
40
|
+
export function setStorefrontPreview(event: H3Event, token: string): void {
|
|
41
|
+
(event.context as Record<string, unknown>)[CONTEXT_KEY] = token;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The preview token this request reads texts with, or "" for the published
|
|
46
|
+
* release. Pinned value first, then the query (a request the middleware did
|
|
47
|
+
* not see), then the visit's cookie.
|
|
48
|
+
*/
|
|
49
|
+
export function resolveStorefrontPreview(event: H3Event | undefined): string {
|
|
50
|
+
if (!event) {
|
|
51
|
+
return "";
|
|
52
|
+
}
|
|
53
|
+
const pinned = (event.context as Record<string, unknown>)[CONTEXT_KEY];
|
|
54
|
+
if (typeof pinned === "string") {
|
|
55
|
+
return isStorefrontPreviewToken(pinned) ? pinned : "";
|
|
56
|
+
}
|
|
57
|
+
const fromQuery = getQuery(event)[STOREFRONT_PREVIEW_QUERY];
|
|
58
|
+
if (isStorefrontPreviewToken(fromQuery)) {
|
|
59
|
+
return fromQuery;
|
|
60
|
+
}
|
|
61
|
+
const fromCookie = getCookie(event, STOREFRONT_PREVIEW_COOKIE);
|
|
62
|
+
return isStorefrontPreviewToken(fromCookie) ? fromCookie : "";
|
|
63
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The theme's own texts, as the shop hands them to transpose (PE-1072,
|
|
5
|
+
* transpose sprachtags §2): for its own tenant, through the gateway, with the
|
|
6
|
+
* tenant's key — so two tenants on one theme hold two copies and no release
|
|
7
|
+
* workflow or machine user is involved.
|
|
8
|
+
*
|
|
9
|
+
* The source is what this build ships: the layer's locale files
|
|
10
|
+
* (`assets:cover-locales`) and, where a theme registers them, its own
|
|
11
|
+
* (`assets:theme-locales`), merged per locale, nested keys flattened with dots
|
|
12
|
+
* the way vue-i18n addresses them. The source language's folder is the
|
|
13
|
+
* source; every other folder is the theme's own translations.
|
|
14
|
+
*
|
|
15
|
+
* The fingerprint is computed the way transpose's CLI computes it, so a push
|
|
16
|
+
* by hand and a push by the shop agree on what "the same texts" are.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export type FlatTexts = Record<string, string>;
|
|
20
|
+
|
|
21
|
+
export interface StorefrontSourceBody {
|
|
22
|
+
readonly key: string;
|
|
23
|
+
readonly name: string;
|
|
24
|
+
readonly kind: "theme";
|
|
25
|
+
readonly locale: string;
|
|
26
|
+
readonly version: string | null;
|
|
27
|
+
readonly fingerprint: string;
|
|
28
|
+
readonly keys: Record<string, { text: string }>;
|
|
29
|
+
readonly defaults: Record<string, FlatTexts>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** `{ cart: { page: { title: "Warenkorb" } } }` → `{ "cart.page.title": "Warenkorb" }` */
|
|
33
|
+
export function flattenTexts(tree: unknown, prefix = "", out: FlatTexts = {}): FlatTexts {
|
|
34
|
+
if (typeof tree !== "object" || tree === null || Array.isArray(tree)) {
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
for (const [key, value] of Object.entries(tree as Record<string, unknown>)) {
|
|
38
|
+
const name = prefix === "" ? key : `${prefix}.${key}`;
|
|
39
|
+
if (typeof value === "string") {
|
|
40
|
+
if (value !== "") {
|
|
41
|
+
out[name] = value;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
flattenTexts(value, name, out);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function sorted<T>(record: Record<string, T>): Record<string, T> {
|
|
52
|
+
return Object.fromEntries(Object.keys(record).sort().map(k => [k, record[k] as T]));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** What a push is, as one value — transpose's CLI computes it the same way. */
|
|
56
|
+
export function sourceFingerprint(locale: string, keys: Record<string, { text: string }>, defaults: Record<string, FlatTexts>): string {
|
|
57
|
+
const texts = sorted(Object.fromEntries(Object.entries(keys).map(([k, v]) => [k, v.text])));
|
|
58
|
+
const other = sorted(Object.fromEntries(Object.entries(defaults).map(([l, t]) => [l, sorted(t)])));
|
|
59
|
+
return createHash("sha256").update(JSON.stringify([locale, texts, other])).digest("hex");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The body of `PUT /v1/translations/sources`. Pure: the locale files arrive
|
|
64
|
+
* as locale → list of parsed files, so it is tested without a Nitro build.
|
|
65
|
+
*/
|
|
66
|
+
export function buildSourceBody(options: {
|
|
67
|
+
catalog: string;
|
|
68
|
+
name: string;
|
|
69
|
+
version: string | null;
|
|
70
|
+
source: string;
|
|
71
|
+
locales: Record<string, unknown[]>;
|
|
72
|
+
}): StorefrontSourceBody | null {
|
|
73
|
+
const merged: Record<string, FlatTexts> = {};
|
|
74
|
+
for (const [locale, files] of Object.entries(options.locales)) {
|
|
75
|
+
const texts: FlatTexts = {};
|
|
76
|
+
for (const file of files) {
|
|
77
|
+
Object.assign(texts, flattenTexts(file));
|
|
78
|
+
}
|
|
79
|
+
merged[locale] = texts;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const sourceTexts = merged[options.source];
|
|
83
|
+
if (!sourceTexts || Object.keys(sourceTexts).length === 0) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const defaults: Record<string, FlatTexts> = {};
|
|
88
|
+
for (const [locale, texts] of Object.entries(merged)) {
|
|
89
|
+
if (locale !== options.source) {
|
|
90
|
+
defaults[locale] = Object.fromEntries(Object.entries(texts).filter(([k]) => k in sourceTexts));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const keys = Object.fromEntries(Object.entries(sourceTexts).map(([k, text]) => [k, { text }]));
|
|
95
|
+
return {
|
|
96
|
+
key: options.catalog,
|
|
97
|
+
name: options.name,
|
|
98
|
+
kind: "theme",
|
|
99
|
+
locale: options.source,
|
|
100
|
+
version: options.version,
|
|
101
|
+
fingerprint: sourceFingerprint(options.source, keys, defaults),
|
|
102
|
+
keys,
|
|
103
|
+
defaults,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Every `<locale>/<file>.json` under one server-asset mount, parsed. */
|
|
108
|
+
async function readMount(base: string): Promise<Record<string, unknown[]>> {
|
|
109
|
+
const storage = useStorage(base);
|
|
110
|
+
const out: Record<string, unknown[]> = {};
|
|
111
|
+
const files = (await storage.getKeys()).filter(k => k.endsWith(".json")).sort();
|
|
112
|
+
for (const file of files) {
|
|
113
|
+
const [locale] = file.split(":");
|
|
114
|
+
if (!locale) {
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const parsed = await storage.getItem(file);
|
|
118
|
+
if (parsed && typeof parsed === "object") {
|
|
119
|
+
(out[locale] ??= []).push(parsed);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
let built: Promise<StorefrontSourceBody | null> | undefined;
|
|
126
|
+
|
|
127
|
+
/** This build's source, built once per process — the files do not change while it runs. */
|
|
128
|
+
export function storefrontSource(): Promise<StorefrontSourceBody | null> {
|
|
129
|
+
built ??= (async () => {
|
|
130
|
+
const config = useRuntimeConfig();
|
|
131
|
+
const catalog = String(config.transposeCatalog ?? "").trim();
|
|
132
|
+
if (!catalog) {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
const layer = await readMount("assets:cover-locales");
|
|
136
|
+
const theme = await readMount("assets:theme-locales").catch(() => ({}));
|
|
137
|
+
const locales: Record<string, unknown[]> = {};
|
|
138
|
+
for (const [locale, files] of [...Object.entries(layer), ...Object.entries(theme)]) {
|
|
139
|
+
(locales[locale] ??= []).push(...files);
|
|
140
|
+
}
|
|
141
|
+
return buildSourceBody({
|
|
142
|
+
catalog,
|
|
143
|
+
name: String(config.transposeCatalogName || catalog),
|
|
144
|
+
version: String(config.transposeCatalogVersion || "") || null,
|
|
145
|
+
source: String(config.public?.defaultLocale || "de"),
|
|
146
|
+
locales,
|
|
147
|
+
});
|
|
148
|
+
})();
|
|
149
|
+
return built;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Test hook. */
|
|
153
|
+
export function resetStorefrontSource(): void {
|
|
154
|
+
built = undefined;
|
|
155
|
+
}
|