@revenexx/cover 0.17.0 → 0.19.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/components/product/detail/ProductDetailImageGallery.vue +39 -13
- package/app/components/product/detail/ProductDetailView.vue +3 -1
- package/app/composables/useProduct.ts +6 -1
- package/app/interfaces/product-detail.ts +11 -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/ApiProductService.ts +20 -1
- package/server/services/LocalFileProductService.ts +9 -1
- package/server/utils/i18n.ts +39 -10
- package/server/utils/liveCatalog.ts +178 -2
- package/server/utils/storefrontMessages.ts +480 -0
- package/server/utils/storefrontPreview.ts +63 -0
- package/server/utils/storefrontSource.ts +155 -0
|
@@ -134,6 +134,108 @@ export function liveImageSrc(raw: string): string {
|
|
|
134
134
|
return `${CDN_PREFIX}${tenant && key.startsWith(`${tenant}/`) ? key.slice(tenant.length + 1) : key}`;
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
/** A product asset row (products app): the catalogue's record of one file. */
|
|
138
|
+
interface LiveProductAssetRow {
|
|
139
|
+
code: string;
|
|
140
|
+
source?: string | null;
|
|
141
|
+
storage_asset_id?: string | null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The storage service's view of an uploaded file. */
|
|
145
|
+
interface LiveStorageAsset {
|
|
146
|
+
kind?: string | null;
|
|
147
|
+
model_url?: string | null;
|
|
148
|
+
preview_url?: string | null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* A storage delivery URL as a key for the `/cdn/` path: the URL's own host is
|
|
153
|
+
* the storage service's (unreachable from the shop's domain), the path is
|
|
154
|
+
* `<tenant>/<folder>/<file>`, and the query (`?d=model`, `?d=preview`) selects
|
|
155
|
+
* the rendition, so it is kept. The path stays percent-encoded: decoded, a
|
|
156
|
+
* `#` or `?` in a file name would end the URL early.
|
|
157
|
+
*/
|
|
158
|
+
function storageUrlToCdnSrc(url: string): string {
|
|
159
|
+
const parsed = new URL(url);
|
|
160
|
+
return `${liveImageSrc(parsed.pathname.replace(/^\/+/, ""))}${parsed.search}`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
type LiveProductModel = { url: string; poster: string | null };
|
|
164
|
+
|
|
165
|
+
const MODEL_TTL_MS = 5 * 60 * 1000;
|
|
166
|
+
const modelCache = new Map<string, { model: LiveProductModel | null; loadedAt: number }>();
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* One media code's 3D model, or `null`: not a product asset, not in storage,
|
|
170
|
+
* or not a model. `undefined` when the lookup failed — a deleted file must not
|
|
171
|
+
* cost the product's other media, and a failure must not be cached as "none".
|
|
172
|
+
*/
|
|
173
|
+
async function liveAssetModel(code: string): Promise<LiveProductModel | null | undefined> {
|
|
174
|
+
const sdk = useRevenexxSdk();
|
|
175
|
+
try {
|
|
176
|
+
const assets = await sdk.call<{ items?: LiveProductAssetRow[] }>(
|
|
177
|
+
"GET", "/v1/products/assets", { query: { code, limit: 1 } },
|
|
178
|
+
);
|
|
179
|
+
const asset = assets.items?.[0];
|
|
180
|
+
if (!asset?.storage_asset_id) {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
const file = await sdk.call<LiveStorageAsset | { data?: LiveStorageAsset }>(
|
|
184
|
+
"GET", `/v1/storage/assets/${encodeURIComponent(asset.storage_asset_id)}`,
|
|
185
|
+
);
|
|
186
|
+
const stored: LiveStorageAsset = "data" in file && file.data ? file.data : file as LiveStorageAsset;
|
|
187
|
+
if (stored.kind !== "model3d" || !stored.model_url) {
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
url: storageUrlToCdnSrc(stored.model_url),
|
|
192
|
+
poster: stored.preview_url ? storageUrlToCdnSrc(stored.preview_url) : null,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
catch (err) {
|
|
196
|
+
getLogService().warn("Live 3D lookup failed for one asset", { code, ...toErrorContext(err) });
|
|
197
|
+
return undefined;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The product's 3D model, from its own media: the codes in its
|
|
203
|
+
* `asset_collection` attributes name product assets, a product asset names
|
|
204
|
+
* its file in storage, and storage renders a CAD file (STEP) as a glTF mesh
|
|
205
|
+
* plus a preview still. The first file storage reports as `model3d` wins, in
|
|
206
|
+
* the order the attributes are declared. `null` when there is none.
|
|
207
|
+
*
|
|
208
|
+
* Runs on every product page, so the codes are looked up side by side, not
|
|
209
|
+
* one after another, and the answer (a missing model too) is kept for a few
|
|
210
|
+
* minutes per tenant and set of codes.
|
|
211
|
+
*/
|
|
212
|
+
export async function resolveLiveProductModel(
|
|
213
|
+
attrs: Record<string, unknown>,
|
|
214
|
+
): Promise<LiveProductModel | null> {
|
|
215
|
+
const meta = await loadLiveAttributeMeta();
|
|
216
|
+
const codes = Object.entries(attrs)
|
|
217
|
+
.filter(([key, value]) => meta[key]?.type === "asset_collection" && Array.isArray(value))
|
|
218
|
+
.sort(([a], [b]) => (meta[a]?.position ?? 999) - (meta[b]?.position ?? 999))
|
|
219
|
+
.flatMap(([, value]) => (value as unknown[]).filter((code): code is string => typeof code === "string" && code !== ""));
|
|
220
|
+
if (!codes.length) {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const key = `${revenexxTenantKey()}:${codes.join("|")}`;
|
|
225
|
+
const cached = modelCache.get(key);
|
|
226
|
+
if (cached && Date.now() - cached.loadedAt < MODEL_TTL_MS) {
|
|
227
|
+
return cached.model;
|
|
228
|
+
}
|
|
229
|
+
const found = await Promise.all(codes.map(code => liveAssetModel(code)));
|
|
230
|
+
const model = found.find(candidate => candidate !== null && candidate !== undefined) ?? null;
|
|
231
|
+
// A model found is kept; "none" only when every lookup answered, so a
|
|
232
|
+
// passing outage does not hide the 3D view for the whole TTL.
|
|
233
|
+
if (model || !found.includes(undefined)) {
|
|
234
|
+
modelCache.set(key, { model, loadedAt: Date.now() });
|
|
235
|
+
}
|
|
236
|
+
return model;
|
|
237
|
+
}
|
|
238
|
+
|
|
137
239
|
/** Fallback attribute code holding a manufacturer's logo on the product doc. */
|
|
138
240
|
const DEFAULT_LOGO_ATTRIBUTE = "manufacturer_logo";
|
|
139
241
|
|
|
@@ -874,12 +976,68 @@ export function renderLiveAttributeValue(
|
|
|
874
976
|
value: unknown,
|
|
875
977
|
locale: Locale,
|
|
876
978
|
): string {
|
|
979
|
+
if (isMeasureValue(value)) {
|
|
980
|
+
return renderMeasureValue(value, meta?.unit);
|
|
981
|
+
}
|
|
982
|
+
// Any other object (no amount to read) has no text of its own; empty drops
|
|
983
|
+
// the row instead of printing "[object Object]" or throwing.
|
|
984
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
985
|
+
return "";
|
|
986
|
+
}
|
|
877
987
|
const raw = String(value);
|
|
878
988
|
const option = meta?.options?.[raw];
|
|
879
989
|
const label = option ? pickLiveLabel(option, locale, raw) : raw;
|
|
880
990
|
return meta?.unit && !raw.includes(meta.unit) ? `${label} ${meta.unit}` : label;
|
|
881
991
|
}
|
|
882
992
|
|
|
993
|
+
/**
|
|
994
|
+
* A metric attribute as the products app stores it: `{ amount, unit }`, the
|
|
995
|
+
* unit a code such as `MILLIMETER`. Cockpit edits and shows it in this shape;
|
|
996
|
+
* `String()` on it throws for the prototype-less objects the API client
|
|
997
|
+
* parses ("Cannot convert object to primitive value"), and took the whole
|
|
998
|
+
* product page down with it.
|
|
999
|
+
*/
|
|
1000
|
+
function isMeasureValue(value: unknown): value is { amount: unknown; unit?: unknown; currency?: unknown } {
|
|
1001
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) && "amount" in value;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/** Symbols for the common unit codes; any other code is shown as it is. */
|
|
1005
|
+
const UNIT_SYMBOLS: Record<string, string> = {
|
|
1006
|
+
AMPERE_HOUR: "Ah",
|
|
1007
|
+
CENTIMETER: "cm",
|
|
1008
|
+
DECIBEL: "dB",
|
|
1009
|
+
DEGREE: "°",
|
|
1010
|
+
GRAM: "g",
|
|
1011
|
+
GRAM_PER_SQUARE_METER: "g/m²",
|
|
1012
|
+
KELVIN: "K",
|
|
1013
|
+
KILOGRAM: "kg",
|
|
1014
|
+
LITER: "l",
|
|
1015
|
+
LUMEN: "lm",
|
|
1016
|
+
METER: "m",
|
|
1017
|
+
MICROLITER: "µl",
|
|
1018
|
+
MILLILITER: "ml",
|
|
1019
|
+
MILLIMETER: "mm",
|
|
1020
|
+
REVOLUTIONS_PER_MINUTE: "rpm",
|
|
1021
|
+
VOLT: "V",
|
|
1022
|
+
WATT: "W",
|
|
1023
|
+
};
|
|
1024
|
+
|
|
1025
|
+
function renderMeasureValue(value: { amount: unknown; unit?: unknown; currency?: unknown }, fallbackUnit?: string): string {
|
|
1026
|
+
const amount = value.amount === null || value.amount === undefined ? "" : String(value.amount);
|
|
1027
|
+
if (!amount) {
|
|
1028
|
+
return "";
|
|
1029
|
+
}
|
|
1030
|
+
// A price-shaped value carries its currency where a metric carries its unit.
|
|
1031
|
+
const own = typeof value.unit === "string" && value.unit
|
|
1032
|
+
? value.unit
|
|
1033
|
+
: typeof value.currency === "string" && value.currency ? value.currency : "";
|
|
1034
|
+
const unit = own || fallbackUnit;
|
|
1035
|
+
if (!unit) {
|
|
1036
|
+
return amount;
|
|
1037
|
+
}
|
|
1038
|
+
return `${amount} ${UNIT_SYMBOLS[unit] ?? unit}`;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
883
1041
|
/**
|
|
884
1042
|
* Build the product detail specification rows from the doc's `attrs`:
|
|
885
1043
|
* localized label, option/unit-aware value, internal keys hidden. Degrades to
|
|
@@ -980,6 +1138,8 @@ async function buildSpecRows(
|
|
|
980
1138
|
const rank = m?.groupCode && SPEC_GROUP_RANK[m.groupCode] !== undefined ? SPEC_GROUP_RANK[m.groupCode] : 5;
|
|
981
1139
|
return { label: pickLiveLabel(m?.labels, locale, prettifyAttrKey(key)), value: display, sort: rank * 1000 + (m?.position ?? 999) };
|
|
982
1140
|
})
|
|
1141
|
+
// A value with nothing to read (an object without an amount) is no row.
|
|
1142
|
+
.filter(row => row.value !== "")
|
|
983
1143
|
.sort((a, b) => a.sort - b.sort || a.label.localeCompare(b.label));
|
|
984
1144
|
|
|
985
1145
|
return rows.map((r, i) => ({ id: i + 1, name: r.label, value: r.value }));
|
|
@@ -1066,6 +1226,22 @@ function livePimName(product: LivePimProduct, locale: Locale): string {
|
|
|
1066
1226
|
return pickLiveLabel(names, locale, product.sku);
|
|
1067
1227
|
}
|
|
1068
1228
|
|
|
1229
|
+
/**
|
|
1230
|
+
* An attribute value as a comparable string, for telling siblings apart. A
|
|
1231
|
+
* metric compares by what it reads ("40 W"); `String()` would make every
|
|
1232
|
+
* metric "[object Object]", or throw on the prototype-less objects the API
|
|
1233
|
+
* client parses.
|
|
1234
|
+
*/
|
|
1235
|
+
function attributeValueKey(value: unknown): string {
|
|
1236
|
+
if (value === null || value === undefined) {
|
|
1237
|
+
return "";
|
|
1238
|
+
}
|
|
1239
|
+
if (isMeasureValue(value)) {
|
|
1240
|
+
return renderMeasureValue(value);
|
|
1241
|
+
}
|
|
1242
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1069
1245
|
/**
|
|
1070
1246
|
* Which attributes actually distinguish these siblings.
|
|
1071
1247
|
*
|
|
@@ -1091,7 +1267,7 @@ function deriveVariantAxisCodes(
|
|
|
1091
1267
|
}
|
|
1092
1268
|
|
|
1093
1269
|
const distinctCount = (code: string): number =>
|
|
1094
|
-
new Set(commons.map(common =>
|
|
1270
|
+
new Set(commons.map(common => attributeValueKey(common[code]))).size;
|
|
1095
1271
|
|
|
1096
1272
|
const candidates = [...codes]
|
|
1097
1273
|
.filter((code) => {
|
|
@@ -1115,7 +1291,7 @@ function deriveVariantAxisCodes(
|
|
|
1115
1291
|
}
|
|
1116
1292
|
chosen.push(candidate.code);
|
|
1117
1293
|
const tuples = new Set(
|
|
1118
|
-
commons.map(common => chosen.map(code =>
|
|
1294
|
+
commons.map(common => chosen.map(code => attributeValueKey(common[code])).join("")),
|
|
1119
1295
|
);
|
|
1120
1296
|
// Every sibling now has its own combination — further attributes would
|
|
1121
1297
|
// add columns without adding information.
|
|
@@ -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
|
+
}
|