@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
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Resolve the active language for CMS delivery reads. The value is returned AS-IS (no
3
+ * normalization — the server/Java layer interprets it; see config/env.ts).
4
+ *
5
+ * Resolution order (first hit wins):
6
+ * 1. `options.language` — explicit caller override. Always wins.
7
+ * 2. `SFDC_ENV.language` — EXTERNAL apps. Experience sites inject it, so its presence
8
+ * is the signal that we're on a site; checked BEFORE the internal path so a site
9
+ * never pays for a wasted i18n GraphQL round-trip. Read fresh (sync), never cached.
10
+ * 3. platform-sdk i18n `fetchI18nContext().lang` — INTERNAL apps (authenticated uiapi).
11
+ * Async; the resolved value is cached module-side so it can be read SYNCHRONOUSLY
12
+ * afterwards (see {@link getResolvedCmsLanguage}) — this is what lets the synchronous
13
+ * {@link resolveCmsImageUrl} localize internal-app media once the language is warmed.
14
+ * 4. `undefined` — nothing resolved; the API applies the channel/site default.
15
+ *
16
+ * Two entry points:
17
+ * - {@link resolveCmsLanguage} — ASYNC. Runs the full chain and WARMS the cache with
18
+ * the resolved internal-app language. Concurrent internal-app calls share ONE in-flight
19
+ * i18n request (memoized), so a burst of media resolutions never fans out into N
20
+ * I18nDetect GraphQL round-trips.
21
+ * - {@link getResolvedCmsLanguage} — SYNC. Reads explicit → `SFDC_ENV.language` → the
22
+ * i18n language warmed by a prior `resolveCmsLanguage()`. Returns `undefined` when the
23
+ * internal-app language has not been warmed yet.
24
+ *
25
+ * Typical use: `await resolveCmsLanguage()` ONCE up front (e.g. in a page loader, before
26
+ * rendering a grid of images), then call the synchronous `resolveCmsImageUrl` per image —
27
+ * each reads the warmed language from cache with no further async work or duplicate fetch.
28
+ *
29
+ * Staleness / in-session locale change: both this module's cache AND platform-sdk's
30
+ * `fetchI18nContext` memoize for the life of the page, so a locale change takes effect on a
31
+ * full reload (the natural flow — `SFDC_ENV.language` is re-injected / the platform locale
32
+ * is re-queried). If the app changes locale WITHOUT reloading, pass the new value explicitly
33
+ * as `options.language` (which bypasses the cache) rather than relying on auto-resolution.
34
+ *
35
+ * Fail-open: the internal i18n path is wrapped so any error (no GraphQL surface, guest
36
+ * context, network failure) resolves to `undefined` instead of throwing — a content read
37
+ * must never fail purely because the locale could not be detected.
38
+ */
39
+ import { createDataSDK } from "@salesforce/platform-sdk";
40
+ import { fetchI18nContext } from "@salesforce/platform-sdk/i18n";
41
+ import { readEnvLanguage } from "../config/env";
42
+
43
+ /** Options controlling language resolution. Shared by every localizing read. */
44
+ export interface ResolveLocaleOptions {
45
+ /**
46
+ * Explicit language (BCP-47 tag like `en-US`, or a Salesforce key like `en_US`).
47
+ * Short-circuits detection — pass this to force a specific language.
48
+ */
49
+ language?: string;
50
+ }
51
+
52
+ /**
53
+ * Cached internal-app i18n language. Populated once by {@link resolveCmsLanguage} so
54
+ * {@link getResolvedCmsLanguage} can serve it synchronously. Only the i18n result is
55
+ * cached — `SFDC_ENV.language` is read fresh each call (sync and cheap), and an explicit
56
+ * `options.language` never touches this cache.
57
+ */
58
+ let cachedI18nLanguage: string | undefined;
59
+ /**
60
+ * Shared in-flight i18n lookup. Concurrent internal-app resolutions await the SAME promise
61
+ * instead of each firing its own I18nDetect GraphQL request. Cleared on settle so a failed
62
+ * (or empty) lookup can be retried later.
63
+ */
64
+ let inflightI18nLanguage: Promise<string | undefined> | null = null;
65
+ /**
66
+ * Whether the internal-app i18n path has EVER been attempted (i.e. `resolveCmsLanguage()`
67
+ * reached the i18n branch at least once). Lets callers distinguish a genuinely cold cache
68
+ * ("warm-up never ran") from a warmed-but-empty one ("ran, but i18n has no language") —
69
+ * used by the dev-mode unwarmed-cache warning in {@link getResolvedCmsLanguage}'s consumers.
70
+ */
71
+ let i18nAttempted = false;
72
+
73
+ /**
74
+ * Fetch the internal-app language via platform-sdk i18n. Fail-open: returns `undefined`
75
+ * on any error (missing GraphQL surface, guest context, network). The underlying
76
+ * `fetchI18nContext` is memoized by platform-sdk, so repeat calls are cheap.
77
+ */
78
+ async function readI18nLanguage(): Promise<string | undefined> {
79
+ try {
80
+ const sdk = await createDataSDK();
81
+ const context = await fetchI18nContext(sdk);
82
+ return context.lang;
83
+ } catch {
84
+ return undefined;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Resolve the internal-app i18n language ONCE: serve a previously-cached value, share a
90
+ * single in-flight request across concurrent callers, and cache a resolved (defined) value
91
+ * for later synchronous reads. A `undefined` result is NOT cached, so a lookup that failed
92
+ * (e.g. a transient network error) can be retried on the next call.
93
+ */
94
+ function resolveI18nLanguageOnce(): Promise<string | undefined> {
95
+ // Mark the i18n path as attempted the moment we enter it — even a call that returns a
96
+ // cached/undefined value counts, so the unwarmed-cache warning fires only before warm-up.
97
+ i18nAttempted = true;
98
+ if (cachedI18nLanguage !== undefined) return Promise.resolve(cachedI18nLanguage);
99
+ if (inflightI18nLanguage) return inflightI18nLanguage;
100
+
101
+ inflightI18nLanguage = readI18nLanguage()
102
+ .then((language) => {
103
+ if (language) cachedI18nLanguage = language;
104
+ return language;
105
+ })
106
+ .finally(() => {
107
+ inflightI18nLanguage = null;
108
+ });
109
+ return inflightI18nLanguage;
110
+ }
111
+
112
+ /**
113
+ * Resolve the CMS `language` value for the current app, or `undefined` when none can be
114
+ * determined (the API then falls back to the channel/site default). ASYNC — runs the full
115
+ * chain (explicit → `SFDC_ENV.language` → platform-sdk i18n) and WARMS the module cache
116
+ * with the resolved internal-app language, so a later {@link getResolvedCmsLanguage} (and
117
+ * therefore the synchronous {@link resolveCmsImageUrl}) can serve it without any await.
118
+ *
119
+ * @param options - Optional explicit `language` override.
120
+ */
121
+ export async function resolveCmsLanguage(
122
+ options?: ResolveLocaleOptions,
123
+ ): Promise<string | undefined> {
124
+ if (options?.language) return options.language;
125
+
126
+ const envLanguage = readEnvLanguage();
127
+ if (envLanguage) return envLanguage;
128
+
129
+ return resolveI18nLanguageOnce();
130
+ }
131
+
132
+ /**
133
+ * SYNCHRONOUS read of the active CMS language: explicit `options.language` →
134
+ * `SFDC_ENV.language` → the internal-app i18n language cached by a prior
135
+ * {@link resolveCmsLanguage} call. Returns `undefined` when an internal-app language has
136
+ * not been warmed yet — callers that need it should `await resolveCmsLanguage()` once up
137
+ * front (e.g. before rendering images) so this can serve the value synchronously.
138
+ *
139
+ * @param options - Optional explicit `language` override.
140
+ */
141
+ export function getResolvedCmsLanguage(options?: ResolveLocaleOptions): string | undefined {
142
+ if (options?.language) return options.language;
143
+
144
+ const envLanguage = readEnvLanguage();
145
+ if (envLanguage) return envLanguage;
146
+
147
+ return cachedI18nLanguage;
148
+ }
149
+
150
+ /**
151
+ * Whether the internal-app i18n language has been WARMED (or at least attempted) via
152
+ * {@link resolveCmsLanguage}. `false` means the cache is genuinely cold — no warm-up has
153
+ * run — so a synchronous read on an internal app would fall through to `undefined`.
154
+ * Internal helper for the dev-mode "did you forget to warm the cache?" warning; not part of
155
+ * the public barrel. Not meaningful on Experience sites (there `SFDC_ENV.language` answers
156
+ * synchronously and the i18n path is never reached).
157
+ */
158
+ export function hasAttemptedCmsLanguage(): boolean {
159
+ return i18nAttempted;
160
+ }
@@ -1 +1 @@
1
- {"root":["./src/app.tsx","./src/appLayout.tsx","./src/index.ts","./src/navigationMenu.tsx","./src/router-utils.tsx","./src/routes.tsx","./src/api/graphqlClient.ts","./src/components/alerts/status-alert.tsx","./src/components/layouts/card-layout.tsx","./src/components/ui/alert.tsx","./src/components/ui/avatar.tsx","./src/components/ui/badge.tsx","./src/components/ui/breadcrumb.tsx","./src/components/ui/button.tsx","./src/components/ui/calendar.tsx","./src/components/ui/card.tsx","./src/components/ui/checkbox.tsx","./src/components/ui/collapsible.tsx","./src/components/ui/datePicker.tsx","./src/components/ui/dialog.tsx","./src/components/ui/dropdown-menu.tsx","./src/components/ui/field.tsx","./src/components/ui/index.ts","./src/components/ui/input.tsx","./src/components/ui/label.tsx","./src/components/ui/pagination.tsx","./src/components/ui/popover.tsx","./src/components/ui/select.tsx","./src/components/ui/separator.tsx","./src/components/ui/skeleton.tsx","./src/components/ui/sonner.tsx","./src/components/ui/spinner.tsx","./src/components/ui/table.tsx","./src/components/ui/tabs.tsx","./src/features/cmsToolkit/index.ts","./src/features/cmsToolkit/api/catalog.ts","./src/features/cmsToolkit/api/cmsContent.ts","./src/features/cmsToolkit/api/cmsPaths.ts","./src/features/cmsToolkit/api/envelope.ts","./src/features/cmsToolkit/api/errors.ts","./src/features/cmsToolkit/api/httpClient.ts","./src/features/cmsToolkit/config/env.ts","./src/features/cmsToolkit/types/cms.ts","./src/features/cmsToolkit/utils/htmlEntities.ts","./src/features/cmsToolkit/utils/imageUrl.ts","./src/hooks/useAsyncData.ts","./src/lib/utils.ts","./src/pages/Home.tsx","./src/pages/NotFound.tsx","./e2e/app.spec.ts","./vite-env.d.ts","./vitest-env.d.ts","./vitest.setup.ts","../../../../../../../../../sdk/platform-sdk/types/env.d.ts"],"version":"5.9.3"}
1
+ {"root":["./src/app.tsx","./src/appLayout.tsx","./src/index.ts","./src/navigationMenu.tsx","./src/router-utils.tsx","./src/routes.tsx","./src/__tests__/cmsContent.test.ts","./src/__tests__/imageUrl.test.ts","./src/__tests__/localiseUrl.test.ts","./src/__tests__/resolveLocale.test.ts","./src/api/graphqlClient.ts","./src/components/alerts/status-alert.tsx","./src/components/layouts/card-layout.tsx","./src/components/ui/alert.tsx","./src/components/ui/avatar.tsx","./src/components/ui/badge.tsx","./src/components/ui/breadcrumb.tsx","./src/components/ui/button.tsx","./src/components/ui/calendar.tsx","./src/components/ui/card.tsx","./src/components/ui/checkbox.tsx","./src/components/ui/collapsible.tsx","./src/components/ui/datePicker.tsx","./src/components/ui/dialog.tsx","./src/components/ui/dropdown-menu.tsx","./src/components/ui/field.tsx","./src/components/ui/index.ts","./src/components/ui/input.tsx","./src/components/ui/label.tsx","./src/components/ui/pagination.tsx","./src/components/ui/popover.tsx","./src/components/ui/select.tsx","./src/components/ui/separator.tsx","./src/components/ui/skeleton.tsx","./src/components/ui/sonner.tsx","./src/components/ui/spinner.tsx","./src/components/ui/table.tsx","./src/components/ui/tabs.tsx","./src/features/cmsToolkit/index.ts","./src/features/cmsToolkit/api/catalog.ts","./src/features/cmsToolkit/api/cmsContent.ts","./src/features/cmsToolkit/api/cmsPaths.ts","./src/features/cmsToolkit/api/envelope.ts","./src/features/cmsToolkit/api/errors.ts","./src/features/cmsToolkit/api/httpClient.ts","./src/features/cmsToolkit/config/env.ts","./src/features/cmsToolkit/types/cms.ts","./src/features/cmsToolkit/utils/htmlEntities.ts","./src/features/cmsToolkit/utils/imageUrl.ts","./src/features/cmsToolkit/utils/localiseUrl.ts","./src/features/cmsToolkit/utils/resolveLocale.ts","./src/hooks/useAsyncData.ts","./src/lib/utils.ts","./src/pages/Home.tsx","./src/pages/NotFound.tsx","./e2e/app.spec.ts","./vite-env.d.ts","./vitest-env.d.ts","./vitest.setup.ts","../../../../../../../../../sdk/platform-sdk/types/env.d.ts"],"version":"5.9.3"}
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@salesforce/ui-bundle-template-base-sfdx-project",
3
- "version": "11.64.0",
3
+ "version": "11.66.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@salesforce/ui-bundle-template-base-sfdx-project",
9
- "version": "11.64.0",
9
+ "version": "11.66.1",
10
10
  "license": "SEE LICENSE IN LICENSE.txt",
11
11
  "dependencies": {
12
12
  "fast-xml-parser": "^5.9.3",
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salesforce/ui-bundle-template-base-sfdx-project",
3
- "version": "11.64.0",
3
+ "version": "11.66.1",
4
4
  "description": "Base SFDX project template",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "publishConfig": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salesforce/ui-bundle-template-feature-cms-toolkit",
3
- "version": "11.64.0",
3
+ "version": "11.66.1",
4
4
  "description": "CMS toolkit — framework-agnostic APIs for reading Salesforce CMS delivery content (by public URL or contentKey, single or bulk) and decoding RichText and other utility functions",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "author": "",
@@ -22,14 +22,19 @@
22
22
  "access": "public"
23
23
  },
24
24
  "scripts": {
25
- "clean": "rm -rf dist"
25
+ "clean": "rm -rf dist",
26
+ "test": "vitest run",
27
+ "test:watch": "vitest",
28
+ "test:coverage": "vitest run --coverage"
26
29
  },
27
30
  "dependencies": {
28
- "@salesforce/platform-sdk": "^11.64.0"
31
+ "@salesforce/platform-sdk": "^11.66.1"
29
32
  },
30
33
  "devDependencies": {
31
- "@salesforce/ui-bundle": "^11.64.0",
32
- "vite": "^7.3.5"
34
+ "@salesforce/ui-bundle": "^11.66.1",
35
+ "@vitest/coverage-v8": "^4.1.0",
36
+ "vite": "^7.3.5",
37
+ "vitest": "^4.1.0"
33
38
  },
34
39
  "nx": {
35
40
  "targets": {
@@ -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
  }