@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.
@@ -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
+ }