@salesforce/ui-bundle-template-feature-cms-toolkit 11.64.0 → 11.66.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. package/dist/CHANGELOG.md +48 -0
  2. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/package.json +3 -3
  3. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/api/cmsContent.ts +35 -8
  4. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/api/cmsPaths.ts +13 -5
  5. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/config/env.ts +21 -0
  6. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/index.ts +13 -1
  7. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/types/cms.ts +2 -1
  8. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/imageUrl.ts +63 -1
  9. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/localiseUrl.ts +128 -0
  10. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/resolveLocale.ts +160 -0
  11. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/tsconfig.tsbuildinfo +1 -1
  12. package/dist/package-lock.json +2 -2
  13. package/dist/package.json +1 -1
  14. package/package.json +10 -5
  15. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/api/cmsContent.ts +35 -8
  16. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/api/cmsPaths.ts +13 -5
  17. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/config/env.ts +21 -0
  18. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/index.ts +13 -1
  19. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/types/cms.ts +2 -1
  20. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/imageUrl.ts +63 -1
  21. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/localiseUrl.ts +128 -0
  22. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/resolveLocale.ts +160 -0
package/dist/CHANGELOG.md CHANGED
@@ -3,6 +3,54 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [11.66.1](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.66.0...v11.66.1) (2026-08-20)
7
+
8
+ **Note:** Version bump only for package @salesforce/ui-bundle-template-base-sfdx-project
9
+
10
+
11
+
12
+
13
+
14
+ ## [11.66.0](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.65.3...v11.66.0) (2026-08-19)
15
+
16
+ **Note:** Version bump only for package @salesforce/ui-bundle-template-base-sfdx-project
17
+
18
+
19
+
20
+
21
+
22
+ ## [11.65.3](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.65.2...v11.65.3) (2026-08-19)
23
+
24
+ **Note:** Version bump only for package @salesforce/ui-bundle-template-base-sfdx-project
25
+
26
+
27
+
28
+
29
+
30
+ ## [11.65.2](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.65.1...v11.65.2) (2026-08-19)
31
+
32
+ **Note:** Version bump only for package @salesforce/ui-bundle-template-base-sfdx-project
33
+
34
+
35
+
36
+
37
+
38
+ ## [11.65.1](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.65.0...v11.65.1) (2026-08-19)
39
+
40
+ **Note:** Version bump only for package @salesforce/ui-bundle-template-base-sfdx-project
41
+
42
+
43
+
44
+
45
+
46
+ ## [11.65.0](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.64.0...v11.65.0) (2026-08-19)
47
+
48
+ **Note:** Version bump only for package @salesforce/ui-bundle-template-base-sfdx-project
49
+
50
+
51
+
52
+
53
+
6
54
  ## [11.64.0](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.63.0...v11.64.0) (2026-08-18)
7
55
 
8
56
  **Note:** Version bump only for package @salesforce/ui-bundle-template-base-sfdx-project
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@salesforce/platform-sdk": "^11.51.0",
22
- "@salesforce/ui-bundle": "^11.64.0",
22
+ "@salesforce/ui-bundle": "^11.66.1",
23
23
  "@tailwindcss/vite": "^4.1.17",
24
24
  "class-variance-authority": "^0.7.1",
25
25
  "clsx": "^2.1.1",
@@ -44,8 +44,8 @@
44
44
  "@graphql-eslint/eslint-plugin": "^4.1.0",
45
45
  "@graphql-tools/utils": "^11.0.0",
46
46
  "@playwright/test": "^1.49.0",
47
- "@salesforce/graphiti": "^11.64.0",
48
- "@salesforce/vite-plugin-ui-bundle": "^11.64.0",
47
+ "@salesforce/graphiti": "^11.66.1",
48
+ "@salesforce/vite-plugin-ui-bundle": "^11.66.1",
49
49
  "@testing-library/jest-dom": "^6.6.3",
50
50
  "@testing-library/react": "^16.1.0",
51
51
  "@testing-library/user-event": "^14.5.2",
@@ -12,6 +12,8 @@ import { buildBulkPath, buildDetailPath } from "./cmsPaths";
12
12
  import { resolveChannelId, resolveEffectiveContentKey } from "./catalog";
13
13
  import { unwrapContent } from "./envelope";
14
14
  import { CmsNotFoundError } from "./errors";
15
+ import { resolveCmsLanguage } from "../utils/resolveLocale";
16
+ import { localiseCmsUrl } from "../utils/localiseUrl";
15
17
  import type {
16
18
  CmsBulkResult,
17
19
  CmsContentBody,
@@ -20,9 +22,17 @@ import type {
20
22
  } from "../types/cms";
21
23
 
22
24
  /**
23
- * Fetch a single CMS item from a public delivery URL (a pasted CDN link or
25
+ * Fetch a single CMS item from a public delivery URL (a pasted CDN link or the envelope's
24
26
  * `unauthenticatedUrl`). Unauthenticated. Throws on failure.
25
27
  *
28
+ * CONTRACT: `url` MUST be a Salesforce CMS delivery content URL. Those are Salesforce-origin
29
+ * and path-based (NOT query-string-signed), so appending the `language` param is safe AND
30
+ * intended — `language` is the delivery API's server-honored localisation param, so localising
31
+ * here is how the localized content item is fetched. Do NOT pass a signed/opaque third-party
32
+ * URL (e.g. one carrying an `X-Amz-Signature`): adding a query param would break its signature.
33
+ * (This is why the media path in `imageUrl.ts` gates to root-relative CMS media — it can receive
34
+ * a foreign CDN url; this content path cannot, by contract.)
35
+ *
26
36
  * @example
27
37
  * ```ts
28
38
  * const article = await getCmsContentByUrl<NewsBody>(url, { signal });
@@ -32,7 +42,20 @@ export async function getCmsContentByUrl<TBody = CmsContentBody>(
32
42
  url: string,
33
43
  options?: CmsReadOptions,
34
44
  ): Promise<TBody> {
35
- const envelope = await cmsDeliveryGet<CmsDeliveryEnvelope<TBody>>(url, options?.signal);
45
+ // Localize the directly-passed URL (set/override the `language` param). Safe because the
46
+ // contract restricts `url` to Salesforce CMS delivery URLs (Salesforce-origin, unsigned) —
47
+ // see the docblock. Skip an empty URL so we never turn it into a bare `?language=…`.
48
+ // Fail-open: if localisation throws for any reason, fall back to the original URL so a
49
+ // language concern can never block the content read.
50
+ let targetUrl = url;
51
+ if (url) {
52
+ try {
53
+ targetUrl = await localiseCmsUrl(url, { language: options?.language });
54
+ } catch {
55
+ targetUrl = url;
56
+ }
57
+ }
58
+ const envelope = await cmsDeliveryGet<CmsDeliveryEnvelope<TBody>>(targetUrl, options?.signal);
36
59
  return unwrapContent<TBody>(envelope);
37
60
  }
38
61
 
@@ -50,12 +73,15 @@ export async function getCmsContentByKey<TBody = CmsContentBody>(
50
73
  contentKey: string,
51
74
  options?: CmsReadOptions,
52
75
  ): Promise<TBody> {
53
- const [channel, effectiveKey] = await Promise.all([
76
+ // resolveCmsLanguage fail-opens internally (see utils/resolveLocale.ts), so language
77
+ // detection never fails the read — it resolves to undefined and the API applies the default.
78
+ const [channel, effectiveKey, language] = await Promise.all([
54
79
  resolveChannelId(options?.channelId),
55
80
  resolveEffectiveContentKey(contentKey),
81
+ resolveCmsLanguage({ language: options?.language }),
56
82
  ]);
57
83
  const envelope = await connectGet<CmsDeliveryEnvelope<TBody>>(
58
- buildDetailPath(channel, effectiveKey),
84
+ buildDetailPath(channel, effectiveKey, language),
59
85
  options?.signal,
60
86
  );
61
87
  return unwrapContent<TBody>(envelope);
@@ -85,15 +111,16 @@ export async function getCmsContentByKeys<TBody = CmsContentBody>(
85
111
  }
86
112
 
87
113
  try {
88
- // Resolve channel + keys INSIDE the try: `resolveChannelId` throws when the
89
- // catalog is absent and no `channelId` was passed (the normal local-dev state)
90
- const [channel, effectiveKeys] = await Promise.all([
114
+ // Resolve channel + keys + language INSIDE the try: `resolveChannelId` throws when
115
+ // the catalog is absent and no `channelId` was passed (the normal local-dev state)
116
+ const [channel, effectiveKeys, language] = await Promise.all([
91
117
  resolveChannelId(options?.channelId),
92
118
  Promise.all(contentKeys.map((key) => resolveEffectiveContentKey(key))),
119
+ resolveCmsLanguage({ language: options?.language }),
93
120
  ]);
94
121
 
95
122
  const response = await connectGet<{ contents?: CmsDeliveryEnvelope<TBody>[] }>(
96
- buildBulkPath(channel, effectiveKeys),
123
+ buildBulkPath(channel, effectiveKeys, language),
97
124
  options?.signal,
98
125
  );
99
126
  const contents = Array.isArray(response.contents) ? response.contents : [];
@@ -5,7 +5,7 @@
5
5
  * `connectGet`. Public delivery URLs never come through here — they are complete
6
6
  * URLs fetched as-is via `cmsDeliveryGet`.
7
7
  */
8
- import { API_VERSION } from "../config/env";
8
+ import { API_VERSION, CMS_LANGUAGE_PARAM } from "../config/env";
9
9
 
10
10
  /**
11
11
  * Build the authenticated Connect delivery path for a single uiBundle-space item.
@@ -14,12 +14,17 @@ import { API_VERSION } from "../config/env";
14
14
  * `channelId` and `contentKey` are `encodeURIComponent`-wrapped so a value containing
15
15
  * `?`/`#`/`/` can't corrupt the path. An empty `contentKey` fast-fails, since it would
16
16
  * otherwise collapse to the collection form (`.../contents/`) and silently mis-read.
17
+ *
18
+ * When `language` is provided it is appended as the (only) query param — the CMS
19
+ * delivery API localizes by `language` (e.g. `en_US`) and falls back to the channel
20
+ * default when the translation is unavailable.
17
21
  */
18
- export function buildDetailPath(channelId: string, contentKey: string): string {
22
+ export function buildDetailPath(channelId: string, contentKey: string, language?: string): string {
19
23
  if (!contentKey) {
20
24
  throw new Error("buildDetailPath: contentKey must be a non-empty string.");
21
25
  }
22
- return `/services/data/v${API_VERSION}/connect/cms/delivery/channels/${encodeURIComponent(channelId)}/contents/${encodeURIComponent(contentKey)}`;
26
+ const path = `/services/data/v${API_VERSION}/connect/cms/delivery/channels/${encodeURIComponent(channelId)}/contents/${encodeURIComponent(contentKey)}`;
27
+ return language ? `${path}?${CMS_LANGUAGE_PARAM}=${encodeURIComponent(language)}` : path;
23
28
  }
24
29
 
25
30
  /**
@@ -30,8 +35,11 @@ export function buildDetailPath(channelId: string, contentKey: string): string {
30
35
  * Each key is `encodeURIComponent`-wrapped BEFORE the `,` join, so a key containing
31
36
  * `&`/`=`/`,` can't inject query params (e.g. flip off the required `includeContentBody`)
32
37
  * or split into extra server-side lookups. `channelId` is encoded for the same reason.
38
+ *
39
+ * When `language` is provided it is appended (`&language=…`) to localize the whole batch.
33
40
  */
34
- export function buildBulkPath(channelId: string, contentKeys: string[]): string {
41
+ export function buildBulkPath(channelId: string, contentKeys: string[], language?: string): string {
35
42
  const joinedKeys = contentKeys.map((key) => encodeURIComponent(key)).join(",");
36
- return `/services/data/v${API_VERSION}/connect/cms/delivery/channels/${encodeURIComponent(channelId)}/contents/?includeContentBody=true&contentKeys=${joinedKeys}`;
43
+ const path = `/services/data/v${API_VERSION}/connect/cms/delivery/channels/${encodeURIComponent(channelId)}/contents/?includeContentBody=true&contentKeys=${joinedKeys}`;
44
+ return language ? `${path}&${CMS_LANGUAGE_PARAM}=${encodeURIComponent(language)}` : path;
37
45
  }
@@ -2,11 +2,20 @@
2
2
  * Environment values for the CMS toolkit runtime:
3
3
  * - API_VERSION — Salesforce Connect REST API version (Vite define).
4
4
  * - CONTENT_CATALOG_URL — where to fetch content-metadata.json.
5
+ * - CMS_LANGUAGE_PARAM — query-param name for the delivery language.
5
6
  * - getCmsInstanceOrigin() — Salesforce instance origin for prefixing media URLs.
7
+ * - readEnvLanguage() — external-site language from `SFDC_ENV.language`.
6
8
  *
7
9
  * The CMS `channelId` is not here — it ships in the catalog (see api/catalog.ts).
8
10
  */
9
11
 
12
+ /**
13
+ * Query-param name the CMS Delivery API reads the language from (content AND media).
14
+ * The resolved value is passed AS-IS — the server normalizes it (e.g. `en-US` → `en_US`)
15
+ * and falls back to the channel default when the requested translation is unavailable.
16
+ */
17
+ export const CMS_LANGUAGE_PARAM = "language";
18
+
10
19
  /** Salesforce Connect REST API version, injected by @salesforce/vite-plugin-ui-bundle. */
11
20
  declare const __SF_API_VERSION__: string;
12
21
  export const API_VERSION: string =
@@ -25,6 +34,8 @@ export const CONTENT_CATALOG_URL: string =
25
34
  interface SfdcEnvLike {
26
35
  /** Salesforce org force.com URL, e.g. `https://myorg.lightning.force.com`. */
27
36
  orgUrl?: string;
37
+ /** Active language on Experience (external) sites, e.g. `en-US`. */
38
+ language?: string;
28
39
  }
29
40
 
30
41
  /**
@@ -44,3 +55,13 @@ export function getCmsInstanceOrigin(): string | undefined {
44
55
  const env = (globalThis as { SFDC_ENV?: SfdcEnvLike }).SFDC_ENV;
45
56
  return env?.orgUrl;
46
57
  }
58
+
59
+ /**
60
+ * Read `globalThis.SFDC_ENV.language` — the active language injected on Experience
61
+ * (external) sites. Returns `undefined` when the global is absent (internal apps),
62
+ * where language is instead resolved via platform-sdk i18n (see utils/resolveLocale.ts).
63
+ */
64
+ export function readEnvLanguage(): string | undefined {
65
+ const env = (globalThis as { SFDC_ENV?: SfdcEnvLike }).SFDC_ENV;
66
+ return env?.language;
67
+ }
@@ -7,12 +7,19 @@
7
7
  * - getCmsContentByUrl(url, options?) — public URL (unauthenticated CDN)
8
8
  * - getCmsContentByKey(key, options?) — one item by contentKey (throws)
9
9
  * - getCmsContentByKeys(keys, options?) — many by contentKey (best-effort)
10
- * - resolveCmsImageUrl(field, options?) — image field → loadable URL
10
+ * - resolveCmsImageUrl(field, options?) — image field → loadable URL (sync)
11
+ * - localiseMediaUrl(url, language?) — add the active `language` to a URL (sync)
12
+ * - localiseCmsUrl(url, options?) — add the active `language` to a URL (async)
13
+ * - resolveCmsLanguage(options?) — active language, async (SFDC_ENV / i18n); warms cache
14
+ * - getResolvedCmsLanguage(options?) — active language, sync (SFDC_ENV / warmed i18n)
11
15
  * - getCmsInstanceOrigin() — instance origin for media prefixing
12
16
  * - resolveEffectiveContentKey(key, catalogUrl?) — catalog source→target key remap
13
17
  * - getCmsDefaultChannelId(catalogUrl?) — catalog default channelId (fail-open)
14
18
  * - decodeRichHtmlEntities(encoded) — decode RichText before injection
15
19
  *
20
+ * Localization: reads/media auto-resolve language — `SFDC_ENV.language` on external
21
+ * sites, else platform-sdk i18n on internal apps — or take an explicit `options.language`.
22
+ *
16
23
  * This is the public entry point. When the feature is copied into a consuming app,
17
24
  * `src/features/cmsToolkit/index.ts` is the single import target — consumers import
18
25
  * from `.../features/cmsToolkit`.
@@ -27,6 +34,10 @@ export { resolveCmsImageUrl } from "./utils/imageUrl";
27
34
  export { getCmsInstanceOrigin } from "./config/env";
28
35
  export { resolveEffectiveContentKey, getCmsDefaultChannelId } from "./api/catalog";
29
36
 
37
+ // ── localization ────────────────────────────────────────────────────────────
38
+ export { localiseCmsUrl, localiseMediaUrl, appendLanguageParam } from "./utils/localiseUrl";
39
+ export { resolveCmsLanguage, getResolvedCmsLanguage } from "./utils/resolveLocale";
40
+
30
41
  // ── errors (stable for instanceof) ──────────────────────────────────────────
31
42
  export {
32
43
  CmsDeliveryError,
@@ -44,3 +55,4 @@ export type {
44
55
  CmsImageField,
45
56
  } from "./types/cms";
46
57
  export type { CmsImageOptions } from "./utils/imageUrl";
58
+ export type { ResolveLocaleOptions } from "./utils/resolveLocale";
@@ -50,7 +50,8 @@ export interface CmsImageField {
50
50
  export interface CmsReadOptions {
51
51
  signal?: AbortSignal;
52
52
  channelId?: string;
53
- // ← future options (locale, apiVersion, fields…) are ADDED here. Additive only.
53
+ /** Language (BCP-47 `en-US` or Salesforce `en_US`); omit to auto-resolve. See utils/resolveLocale.ts. */
54
+ language?: string;
54
55
  }
55
56
 
56
57
  /**
@@ -5,6 +5,8 @@
5
5
  * - CMS image (`source.type === 'imageReference'`) → a root-relative `url`, prefixed
6
6
  * with `options.instanceOrigin` when supplied (else returned unchanged).
7
7
  */
8
+ import { appendLanguageParam } from "./localiseUrl";
9
+ import { getResolvedCmsLanguage, hasAttemptedCmsLanguage } from "./resolveLocale";
8
10
  import type { CmsImageField } from "../types/cms";
9
11
 
10
12
  /** Options for {@link resolveCmsImageUrl}. */
@@ -21,6 +23,40 @@ export interface CmsImageOptions {
21
23
  * its own `url`), or undefined if unknown.
22
24
  */
23
25
  resolveRef?: (contentKey: string) => CmsImageField | undefined;
26
+ /**
27
+ * Explicit language (BCP-47 tag or Salesforce key) appended to Salesforce-served CMS
28
+ * media as the `language` param so the localized variant loads. Highest-priority
29
+ * override — when omitted, Experience (external) sites fall back to `SFDC_ENV.language`
30
+ * automatically so localized media loads without the caller threading a value.
31
+ *
32
+ * Only applied to root-relative CMS media — foreign/absolute CDN URLs are left
33
+ * untouched. Resolution here is SYNCHRONOUS (explicit option → `SFDC_ENV.language` →
34
+ * the internal-app i18n language cached by a prior `resolveCmsLanguage()`). On internal
35
+ * apps, `await resolveCmsLanguage()` once up front (e.g. in a loader) to warm the cache
36
+ * so this resolves the i18n language without the caller threading a value.
37
+ */
38
+ language?: string;
39
+ }
40
+
41
+ /**
42
+ * Dev-only guard so a consumer who forgets the one-time `resolveCmsLanguage()` warm-up on an
43
+ * internal app isn't left debugging silently-untranslated images. Fires ONCE, only in dev,
44
+ * and only when the cache is genuinely cold: a CMS media path resolved with no language AND
45
+ * the i18n warm-up has never run. Experience sites answer via `SFDC_ENV.language` (so
46
+ * `language` is set → no warning), and a warmed-but-empty i18n result flips `hasAttempted…`
47
+ * to true (so we don't nag when there's simply no translation to apply).
48
+ */
49
+ let warnedUnwarmedLanguage = false;
50
+ function warnUnwarmedLanguageOnce(): void {
51
+ if (warnedUnwarmedLanguage) return;
52
+ warnedUnwarmedLanguage = true;
53
+ // eslint-disable-next-line no-console
54
+ console.warn(
55
+ "[cms] resolveCmsImageUrl resolved CMS media without a language and the i18n cache " +
56
+ "is not warmed. On internal apps, `await resolveCmsLanguage()` once up front (e.g. " +
57
+ "in a loader) before rendering images, or pass `options.language`, so localized media " +
58
+ "loads. This warning is dev-only and shown once.",
59
+ );
24
60
  }
25
61
 
26
62
  /** Prefix a root-relative url with `origin`; leave absolute and protocol-relative urls untouched. */
@@ -69,6 +105,19 @@ function extractRawUrl(
69
105
  * imageReference (root-relative, prefixed with `options.instanceOrigin`). Returns
70
106
  * undefined when the field has no resolvable url.
71
107
  *
108
+ * SYNCHRONOUS — safe to call directly in JSX (`<img src={resolveCmsImageUrl(field)} />`).
109
+ * Localizing CMS media reads the active language synchronously (explicit `options.language`
110
+ * → `SFDC_ENV.language` on Experience sites → the internal-app i18n language cached by a
111
+ * prior `resolveCmsLanguage()`). To pick up the internal-app i18n language, warm it ONCE
112
+ * up front — the per-image calls then stay synchronous and share that single lookup:
113
+ * ```ts
114
+ * await resolveCmsLanguage(); // once, in a loader/effect — warms the cache
115
+ * const src = resolveCmsImageUrl(field, { instanceOrigin }); // sync; reads warmed language
116
+ * ```
117
+ * In dev, resolving CMS media before the cache is warmed (no explicit `options.language` and
118
+ * no `SFDC_ENV.language`) logs a one-time console warning so a forgotten warm-up doesn't turn
119
+ * into silently-untranslated images; it is a no-op in production.
120
+ *
72
121
  * @example
73
122
  * ```ts
74
123
  * // Foreign/CDN image — absolute url, origin not needed:
@@ -84,5 +133,18 @@ export function resolveCmsImageUrl(
84
133
  if (!field || typeof field !== "object") return undefined;
85
134
  const rawUrl = extractRawUrl(field, options?.resolveRef);
86
135
  if (!rawUrl) return undefined;
87
- return prefixOrigin(rawUrl, options?.instanceOrigin);
136
+ // Only Salesforce-served CMS media (root-relative, not protocol-relative) is
137
+ // localizable — a foreign absolute CDN url doesn't understand the `language` param.
138
+ const isCmsMedia = rawUrl.startsWith("/") && !rawUrl.startsWith("//");
139
+ // Synchronous resolution: explicit option → SFDC_ENV.language → cached i18n language
140
+ // (warmed by a prior resolveCmsLanguage()). Localise BEFORE prefixing the origin so the
141
+ // param lands on the raw media path.
142
+ const language = getResolvedCmsLanguage(options);
143
+ // Dev-only nudge: CMS media with no language AND a cold (never-warmed) i18n cache is the
144
+ // "forgot to warm up" footgun on internal apps — warn once so it's not silently untranslated.
145
+ if (import.meta.env.DEV && isCmsMedia && !language && !hasAttemptedCmsLanguage()) {
146
+ warnUnwarmedLanguageOnce();
147
+ }
148
+ const localisedUrl = isCmsMedia ? appendLanguageParam(rawUrl, language) : rawUrl;
149
+ return prefixOrigin(localisedUrl, options?.instanceOrigin);
88
150
  }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * URL localization for CMS delivery — add/override the `language` query param on a URL.
3
+ *
4
+ * Three entry points, low to high level:
5
+ * - appendLanguageParam(url, language) — PURE + synchronous. Sets `language` on any
6
+ * URL (absolute or root-relative), overriding an existing value. No-op when
7
+ * `language` is falsy. Used by the read/image paths that already know the language.
8
+ * - localiseMediaUrl(url, language?) — SYNCHRONOUS. Reads the active language via
9
+ * {@link getResolvedCmsLanguage} (explicit arg → `SFDC_ENV.language` → warmed i18n
10
+ * cache), then appends it. The render-time sibling of {@link appendLanguageParam} for
11
+ * `<img src>`: it returns a string, not a Promise. On internal apps the i18n language
12
+ * is served only after a one-time `await resolveCmsLanguage()` warms the cache.
13
+ * - localiseCmsUrl(url, options?) — ASYNC convenience for when a content or media
14
+ * URL is passed DIRECTLY: resolves the current language (options → SFDC_ENV → i18n,
15
+ * performing the i18n fetch if needed) and appends it. Used by the async content-read
16
+ * path, where awaiting guarantees resolution without a separate warm-up.
17
+ */
18
+ import { CMS_LANGUAGE_PARAM } from "../config/env";
19
+ import {
20
+ getResolvedCmsLanguage,
21
+ resolveCmsLanguage,
22
+ type ResolveLocaleOptions,
23
+ } from "./resolveLocale";
24
+
25
+ /**
26
+ * Set the `language` query param on `url`, overriding any existing one(s). Preserves the
27
+ * rest of the query and any `#fragment`. Works on absolute URLs and root-relative paths
28
+ * alike (no base needed), so both public CDN links and relative dev paths are handled.
29
+ * Returns `url` unchanged when `language` is falsy.
30
+ *
31
+ * Every segment whose key is EXACTLY `language` is removed — not just the first — so a
32
+ * duplicated key (`?language=de&language=es`) can never leave a stale value for a
33
+ * first-value query parser to pick. The requested value replaces the FIRST such segment in
34
+ * place (keeping its position) and is appended when none existed.
35
+ *
36
+ * The key match is LITERAL and case-sensitive: it is compared byte-for-byte against the
37
+ * canonical `language`, NOT case-folded or percent-decoded. So `Language=`, `LANGUAGE=`, or
38
+ * a percent-encoded `%6canguage=` are treated as DIFFERENT params and left untouched. This
39
+ * is intentional and safe: we only ever emit the canonical lowercase `language` (which the
40
+ * CMS reads), and we always write it here — a variant-cased key is not one the delivery API
41
+ * honours, and case-folding/percent-decoding keys would contradict the byte-for-byte
42
+ * guarantee below (and could clobber a genuinely distinct caller param).
43
+ *
44
+ * The query is spliced BYTE-FOR-BYTE: every other segment is preserved verbatim — it is NOT
45
+ * round-tripped through `URLSearchParams`, which would re-encode other params (e.g.
46
+ * `%20`→`+`) and could invalidate a signed URL.
47
+ */
48
+ export function appendLanguageParam(url: string, language?: string): string {
49
+ if (!language) return url;
50
+
51
+ // Split off a trailing #fragment so it survives at the end untouched.
52
+ const hashIndex = url.indexOf("#");
53
+ const hash = hashIndex === -1 ? "" : url.slice(hashIndex);
54
+ const withoutHash = hashIndex === -1 ? url : url.slice(0, hashIndex);
55
+
56
+ // Split the query from the base without a URL base (keeps relative paths relative).
57
+ const queryIndex = withoutHash.indexOf("?");
58
+ const base = queryIndex === -1 ? withoutHash : withoutHash.slice(0, queryIndex);
59
+ const query = queryIndex === -1 ? "" : withoutHash.slice(queryIndex + 1);
60
+
61
+ const encoded = `${CMS_LANGUAGE_PARAM}=${encodeURIComponent(language)}`;
62
+
63
+ // Walk the existing segments: drop every one whose key is EXACTLY `language` (literal,
64
+ // case-sensitive, not percent-decoded — see docblock), but keep each other segment's
65
+ // bytes untouched. The new value replaces the FIRST `language` occurrence in place;
66
+ // duplicates are discarded; if none existed we append at the end.
67
+ const segments = query ? query.split("&") : [];
68
+ const nextSegments: string[] = [];
69
+ let inserted = false;
70
+ for (const segment of segments) {
71
+ const eq = segment.indexOf("=");
72
+ const key = eq === -1 ? segment : segment.slice(0, eq);
73
+ if (key === CMS_LANGUAGE_PARAM) {
74
+ if (!inserted) {
75
+ nextSegments.push(encoded);
76
+ inserted = true;
77
+ }
78
+ continue;
79
+ }
80
+ nextSegments.push(segment);
81
+ }
82
+ if (!inserted) nextSegments.push(encoded);
83
+
84
+ return `${base}?${nextSegments.join("&")}${hash}`;
85
+ }
86
+
87
+ /**
88
+ * Localize a directly-passed media URL — read the active language via
89
+ * {@link getResolvedCmsLanguage} (explicit `language` arg → `SFDC_ENV.language` on
90
+ * Experience sites → the warmed platform-sdk i18n language on internal apps), then append
91
+ * it as the `language` query param. Returns `url` unchanged when nothing resolves (the API
92
+ * applies its default).
93
+ *
94
+ * SYNCHRONOUS: it returns a ready-to-use string for `<img src>` without an await. Because
95
+ * it only READS the resolved language (it never performs the i18n fetch itself), an
96
+ * internal app must warm the cache once up front so the i18n language is available:
97
+ * ```tsx
98
+ * await resolveCmsLanguage(); // once at init (e.g. in a loader/effect)
99
+ * // ...later, in render:
100
+ * <img src={localiseMediaUrl(mediaUrl)} />
101
+ * ```
102
+ * On Experience sites (`SFDC_ENV.language`) or when you pass an explicit `language`, no
103
+ * warm-up is needed. When you already hold a resolved language, {@link appendLanguageParam}
104
+ * is the pure, dependency-free alternative.
105
+ */
106
+ export function localiseMediaUrl(url: string, language?: string): string {
107
+ return appendLanguageParam(url, getResolvedCmsLanguage({ language }));
108
+ }
109
+
110
+ /**
111
+ * Localize a directly-passed CMS content or media URL: resolve the active language
112
+ * (see {@link resolveCmsLanguage}) and append it as the `language` query param. When no
113
+ * language can be resolved the URL is returned unchanged (the API applies its default).
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * // Fetch language automatically for a pasted delivery URL:
118
+ * const localized = await localiseCmsUrl(deliveryUrl);
119
+ * const article = await getCmsContentByUrl(localized);
120
+ *
121
+ * // Or force a language:
122
+ * const fr = await localiseCmsUrl(mediaUrl, { language: "fr" });
123
+ * ```
124
+ */
125
+ export async function localiseCmsUrl(url: string, options?: ResolveLocaleOptions): Promise<string> {
126
+ const language = await resolveCmsLanguage(options);
127
+ return appendLanguageParam(url, language);
128
+ }