@contentstack/studio-client 1.5.1 → 1.7.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.
@@ -1,10 +1,11 @@
1
1
  import { COMPOSABLE_STUDIO_QUERY_PARAM, composableStudioEventManager, POST_MESSAGE_EVENTS } from '@contentstack/studio-messenger';
2
2
  import { INTERNAL_COMPONENTS_NAMES, DATA_SOURCES, getComponentRegistryInstance, DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
3
- import { pick } from 'lodash-es';
3
+ import { pick, get } from 'lodash-es';
4
4
  import { processUserConfig } from '../config/process-user-config.js';
5
+ import { setStackSdkInstance } from '../json-rte-registry/stack-sdk-store.js';
5
6
  import { SCHEMA_VERSION, SDK_VERSION, INCLUDE_DEPTH_COUNT } from '../utils/constants.js';
6
7
  import { isCompositionBeingEdited } from '../utils/is-composition-being-edited.js';
7
- import { setTemplateEntryInDS, entriesFromResponse, setStaticEntryInDS } from '../utils/sdk.js';
8
+ import { setTemplateEntryInDS, entriesFromResponse, setStaticEntryInDS, getBindingStringForCS } from '../utils/sdk.js';
8
9
  import { ComposableStudioError, ComposableStudioErrors } from '../utils/composable-studio-error.js';
9
10
  import { clientRendererModeUtil, RendererModeUtil } from '../utils/canvas.js';
10
11
  import { analyzeUsedComponents } from '../utils/spec-analyzer.js';
@@ -18,7 +19,7 @@ import { selectUrlWinner } from '../url-metadata/select-url-winner.js';
18
19
  import { COMPOSITION_PREVIEW_URL_SOURCES } from '../url-metadata/types.js';
19
20
  import { matchCompositionUrl } from '../url-metadata/url-pattern-matcher.js';
20
21
  import { getStatusCode, isContentstackAuthError, hasAuthErrorShape, isAuthError, isNetworkError, HttpStatus, ContentstackErrorCode, isServerError } from '../utils/http-error.constants.js';
21
- import { getEntriesQueries } from '../utils/reference_fetcher.js';
22
+ import { getEntriesQueries, projectIncludePathsOntoOnlyKeys, getSchemaPath } from '../utils/reference_fetcher.js';
22
23
  import { parseExternalDataForComponentProps, collectAllDataNeeds, stableHashQuery } from './collect-data-needs.js';
23
24
  import { buildScopedDataSources } from './build-scoped-data.js';
24
25
  import { preProcessStaticValues } from './data/pre-process-static-values.js';
@@ -158,6 +159,184 @@ function collectSectionCompositionUIDs(ui, accumulator = new Set()) {
158
159
  }
159
160
  return accumulator;
160
161
  }
162
+ /**
163
+ * Strip a field path down to CDA include[]/only[]-safe segments: drop array
164
+ * indices (`x[0]` → `x`), modular-block numeric prefixes (`2_block` → `block`),
165
+ * pure-numeric segments, and the `entries` array wrapper. Shared by the
166
+ * instance walk (ancestor prefix composition) and the template-ref merge.
167
+ */
168
+ function sanitizeFieldPath(path) {
169
+ return path
170
+ .split(".")
171
+ .map((seg) => seg.replace(/\[\d+\]$/, "").replace(/^\d+_/, ""))
172
+ .filter((seg) => seg.length > 0 && !/^\d+$/.test(seg) && seg !== "entries");
173
+ }
174
+ /**
175
+ * Compose the page-template projection root for a placed section's reference
176
+ * field paths.
177
+ *
178
+ * Normally a section's references are rooted at its page-rooted prefix:
179
+ * `[...ancestorPrefix, ...selectedField]`. But when the section sits inside a
180
+ * page `Repeater(reference)+reference-ConditionBlock`, the enclosing reference
181
+ * is ALREADY in `ancestorPrefix`, and the section's own `selectedField`
182
+ * re-expresses that SAME reference with the target-CT uid tacked on as a
183
+ * discriminator (e.g. `reference.test_purpose`). That ctUid is NOT a data key,
184
+ * and re-appending the reference double-counts it — yielding an invalid CDA
185
+ * only[] key like `reference.reference.test_purpose.title` that the API
186
+ * silently ignores, so the referenced entry's fields (e.g. `title`) never come
187
+ * back and the section renders its component default on the deployed site.
188
+ *
189
+ * When `referenceCtUids` is non-empty (an enclosing reference ConditionBlock
190
+ * was seen), drop those ctUid segments and collapse the leading overlap with
191
+ * `ancestorPrefix`, so the section's fields root at the reference exactly like a
192
+ * page-DIRECT binding does (`only[reference][]=title`). When it is empty, every
193
+ * other shape (wrapper chains, cross-CT ref-target binds) keeps the original
194
+ * `[...ancestorPrefix, ...selectedField]` behavior unchanged.
195
+ */
196
+ function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCtUids) {
197
+ if (referenceCtUids.length === 0) {
198
+ return [...ancestorPrefix, ...sanitizeFieldPath(selectedField)];
199
+ }
200
+ const dropCtUids = new Set(referenceCtUids);
201
+ const sf = sanitizeFieldPath(selectedField).filter((seg) => !dropCtUids.has(seg));
202
+ const remainder = ancestorPrefix.length > 0 &&
203
+ sf.length >= ancestorPrefix.length &&
204
+ ancestorPrefix.every((seg, i) => seg === sf[i])
205
+ ? sf.slice(ancestorPrefix.length)
206
+ : sf;
207
+ return [...ancestorPrefix, ...remainder];
208
+ }
209
+ /**
210
+ * Resolve a section-composition node's effective `selectedField`. Resolution
211
+ * order MUST match the render side (`collect-data-needs`'s declaredField) so
212
+ * the fetch scopes the section against the SAME field the renderer reads:
213
+ * 1. per-instance override on `metadata.sectionBindingOverride`,
214
+ * 2. legacy `metadata.selectedField`,
215
+ * 3. linked_schemas default — the field declared for the page CT, else the
216
+ * first schema's `selected_field`.
217
+ *
218
+ * A repeater-nested section is NOT forced to scope-root: its declared
219
+ * `selected_field` still applies and scopes each iteration item further (e.g. a
220
+ * reference-chain section bound to ct2's `reference_to_ct3` iterates that
221
+ * referenced array per ct2 item). The render side never forced "" here, so
222
+ * forcing it on the fetch side starved exactly those sections of their nested
223
+ * reference data (the internal Repeater then received the bare iteration object
224
+ * instead of the array → "items.map is not a function").
225
+ */
226
+ function resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid) {
227
+ const override = node.metadata?.sectionBindingOverride;
228
+ let selectedField = typeof override?.selectedField === "string"
229
+ ? override.selectedField
230
+ : node.metadata?.selectedField;
231
+ if (selectedField == null) {
232
+ const linked = (sectionsByUid.get(node.metadata?.compositionUID)
233
+ ?.linked_schemas || []);
234
+ selectedField =
235
+ linked.find((s) => s.content_type_uid === pageContentTypeUid)
236
+ ?.selected_field ??
237
+ linked[0]?.selected_field ??
238
+ "";
239
+ }
240
+ return selectedField || "";
241
+ }
242
+ /**
243
+ * Walks the page UI tree and resolves every section-composition instance's
244
+ * effective binding (selectedField + uidRemapping) AND its page-rooted
245
+ * `ancestorPrefix` — the composed reference path of the wrapper sections it is
246
+ * nested inside. The template fetch roots each section's references at
247
+ * `[...ancestorPrefix, ...selectedField]` so nested wrapper chains fetch the
248
+ * full reference depth (W1.selectedField → W2.selectedField → …).
249
+ */
250
+ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
251
+ const out = [];
252
+ const walk = (node, parentRepeaterUID, ancestorPrefix,
253
+ // Binding field path of the nearest enclosing TEMPLATE-bound Repeater that
254
+ // hasn't yet been confirmed as a reference. A Repeater's template binding
255
+ // alone can't be told apart from a plain array; the reference condition-
256
+ // block dropped inside it is the signal (mirrors `reference_fetcher`, which
257
+ // only records a repeater ref path at the reference condition-block). When
258
+ // we reach that block we commit this path into the prefix so a section
259
+ // nested in the repeater roots its references under the reference field.
260
+ enclosingRepeaterRefField,
261
+ // Target-CT uids from the enclosing reference ConditionBlock(s) on the path
262
+ // to this node (see SectionInstanceBinding.referenceCtUids).
263
+ refCtUids) => {
264
+ if (!node || typeof node !== "object")
265
+ return;
266
+ const nextRepeater = node.type === "repeater" && node.uid ? node.uid : parentRepeaterUID;
267
+ // Children that descend into THIS node's slots inherit `ancestorPrefix`,
268
+ // extended by this node's reference path when it is a wrapper section.
269
+ let childPrefix = ancestorPrefix;
270
+ let childRepeaterRefField = enclosingRepeaterRefField;
271
+ let childRefCtUids = refCtUids;
272
+ // Remember a Repeater's template binding path; it becomes a reference hop
273
+ // only once a reference condition-block downstream confirms the field is a
274
+ // reference (committed below). A CONTENTSTACK/REPEATER-typed binding is not
275
+ // a page-template reference path, so it never extends the prefix.
276
+ if (node.type === "repeater") {
277
+ const itemsBinding = node.props?.items?.binding;
278
+ childRepeaterRefField =
279
+ itemsBinding?.type === DATA_SOURCES.TEMPLATE
280
+ ? getBindingStringForCS(itemsBinding) || null
281
+ : null;
282
+ }
283
+ // A reference condition-block confirms the enclosing repeater iterates a
284
+ // reference field. Commit that field into the prefix so slotted sections
285
+ // (selectedField "") fetch/project their fields under e.g.
286
+ // `reference_to_ct2`, not the page root. Clear it afterwards so a deeper
287
+ // structure doesn't double-count the same hop.
288
+ if (node.type === "condition-block" &&
289
+ node.metadata?.condition?.type === "reference" &&
290
+ enclosingRepeaterRefField) {
291
+ childPrefix = [
292
+ ...ancestorPrefix,
293
+ ...getSchemaPath(enclosingRepeaterRefField),
294
+ ];
295
+ childRepeaterRefField = null;
296
+ // Record the narrowed target CT so a slotted section can drop this uid
297
+ // from its own selectedField when rooting field projections.
298
+ const cbCtUid = node.metadata?.condition?.value;
299
+ if (typeof cbCtUid === "string" && cbCtUid) {
300
+ childRefCtUids = [...refCtUids, cbCtUid];
301
+ }
302
+ }
303
+ if (node.type === SECTION_COMPOSITION_NODE_TYPE &&
304
+ node.metadata?.compositionUID &&
305
+ node.uid) {
306
+ const compositionUid = node.metadata.compositionUID;
307
+ const selectedField = resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid);
308
+ const override = node.metadata?.sectionBindingOverride;
309
+ const uidRemapping = override?.uidRemapping ?? node.metadata.uidRemapping ?? {};
310
+ out.push({
311
+ instanceUid: node.uid,
312
+ compositionUid,
313
+ selectedField,
314
+ uidRemapping,
315
+ parentRepeaterUID,
316
+ ancestorPrefix,
317
+ referenceCtUids: refCtUids,
318
+ });
319
+ // A whole-CT wrapper (selectedField "") adds no segment — correct, it
320
+ // creates no reference hop. A reference-bound wrapper extends the prefix
321
+ // so its slot children's references resolve from that reference.
322
+ childPrefix = [...ancestorPrefix, ...sanitizeFieldPath(selectedField)];
323
+ }
324
+ if (node.slots && typeof node.slots === "object") {
325
+ for (const slotNodes of Object.values(node.slots)) {
326
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
327
+ for (const c of arr)
328
+ walk(c, nextRepeater, childPrefix, childRepeaterRefField, childRefCtUids);
329
+ }
330
+ }
331
+ if (Array.isArray(node.children)) {
332
+ // children (non-slot) stay in the same scope as this node.
333
+ for (const c of node.children)
334
+ walk(c, nextRepeater, ancestorPrefix, childRepeaterRefField, refCtUids);
335
+ }
336
+ };
337
+ walk(ui, null, [], null, []);
338
+ return out;
339
+ }
161
340
  async function fetchSectionCompositionEntries(config, sectionUids, options) {
162
341
  if (!config.stackSdk || sectionUids.length === 0) {
163
342
  return [];
@@ -225,6 +404,106 @@ function getAuthErrorMessage(err) {
225
404
  getErrorMessage(ErrorMessageKey.INVALID_CREDENTIALS_DEFAULT);
226
405
  return getErrorMessage(ErrorMessageKey.AUTHENTICATION_ERROR, { detail });
227
406
  }
407
+ /**
408
+ * SEO bindings are stored in the UI metadata with the same nested `value.path`
409
+ * shape used by the normal data-binding system:
410
+ *
411
+ * { type: "template", value: { path: { title: {} } } }
412
+ *
413
+ * For SEO we only need the final property path as a dot-separated string
414
+ * (`title`, `seo.title`, etc.), so this helper converts the nested path object
415
+ * into a plain path string that can be used with `lodash/get`.
416
+ */
417
+ /**
418
+ * SEO bindings are stored in UI metadata with the nested `value.path` shape
419
+ * used by the rest of the data-binding system:
420
+ *
421
+ * { type: "template", value: { path: { title: {} } } }
422
+ * { type: "template", value: { path: { seo: { title: {} } } } }
423
+ *
424
+ * The path is always a SINGLE-KEY chain at each level — bindings target one
425
+ * leaf field, not multiple siblings. If a multi-key object is encountered
426
+ * (shouldn't happen given how Studio writes these), we warn in dev and pick
427
+ * the first key so SEO doesn't silently break, but the upstream caller should
428
+ * be fixed.
429
+ *
430
+ * Returns a dot-separated path (`"title"`, `"seo.title"`) usable with
431
+ * `lodash/get`, or `""` when the binding has no path.
432
+ */
433
+ function flattenBindingPathFromValue(binding) {
434
+ const path = binding.value
435
+ ?.path;
436
+ if (!path || typeof path !== "object")
437
+ return "";
438
+ const flattenPath = (value) => {
439
+ if (!value)
440
+ return "";
441
+ const keys = Object.keys(value);
442
+ if (keys.length === 0)
443
+ return "";
444
+ if (keys.length > 1 && process.env.NODE_ENV === "development") {
445
+ console.warn(`[studio-sdk] SEO binding path has multiple keys at one level (${keys.join(", ")}); using "${keys[0]}". Studio is expected to write single-key chains.`);
446
+ }
447
+ const key = keys[0];
448
+ const next = value[key];
449
+ const suffix = next && typeof next === "object"
450
+ ? flattenPath(next)
451
+ : "";
452
+ return suffix ? `${key}.${suffix}` : key;
453
+ };
454
+ return flattenPath(path);
455
+ }
456
+ function isTemplateBinding(binding) {
457
+ return binding.type === DATA_SOURCES.TEMPLATE || binding.type === "template";
458
+ }
459
+ /**
460
+ * Resolve a single SEO field value (`pageTitle`, `pageDescription`,
461
+ * `openGraphImage`, `metaProps[].value`) from either:
462
+ *
463
+ * 1. the static value saved on the composition, or
464
+ * 2. the currently resolved template entry data in `spec.data`
465
+ *
466
+ * Branches:
467
+ * - No binding → keep saved static value.
468
+ * - `static_value` binding → use binding literal (fall back to static).
469
+ * - `template` binding → read template entry at the flattened path.
470
+ * - Otherwise → fall back to static.
471
+ *
472
+ * Returns the resolved primitive as a string. Non-primitive resolved values
473
+ * (which shouldn't happen for SEO fields) fall back to the static value
474
+ * rather than coercing an object to "[object Object]".
475
+ */
476
+ function resolveSeoBindingValue(staticValue, binding, specData) {
477
+ const fallback = (staticValue ?? "").trim();
478
+ if (!binding || typeof binding !== "object" || binding.type == null) {
479
+ return fallback;
480
+ }
481
+ if (binding.type === "static_value" ||
482
+ binding.type === DATA_SOURCES.STATIC_VALUE) {
483
+ return typeof binding.value === "string" && binding.value.trim()
484
+ ? binding.value.trim()
485
+ : fallback;
486
+ }
487
+ if (!specData || !isTemplateBinding(binding)) {
488
+ return fallback;
489
+ }
490
+ const templateEntry = specData.dataSources?.[DATA_SOURCES.TEMPLATE];
491
+ const subPath = flattenBindingPathFromValue(binding);
492
+ if (!templateEntry || !subPath) {
493
+ return fallback;
494
+ }
495
+ const resolved = get(templateEntry, subPath);
496
+ // SEO fields are expected to resolve to a primitive. Anything else (an
497
+ // object, a missing path, an empty string) falls back to the static value
498
+ // so consumers always see a string.
499
+ if (resolved === undefined ||
500
+ resolved === null ||
501
+ resolved === "" ||
502
+ typeof resolved === "object") {
503
+ return fallback;
504
+ }
505
+ return String(resolved);
506
+ }
228
507
  /**
229
508
  * Helper function to detect and classify API errors
230
509
  * @internal - Exported for testing purposes
@@ -571,10 +850,6 @@ function sendInitStudioSignal(config) {
571
850
  }
572
851
  function generateSdk(userConfig) {
573
852
  const config = processUserConfig(userConfig);
574
- // ✅ HYBRID APPROACH: Register internal components immediately during SDK init
575
- // This ensures all internal components (page, section, text, etc.) are available
576
- // ✅ HYBRID APPROACH: Component registration moved to React layer (useStudioInit)
577
- // This avoids cyclic dependencies while ensuring components are available before fetchSpec
578
853
  if (clientRendererModeUtil.isInsideStudioFrame()) {
579
854
  const sp = new URLSearchParams(window.location.search);
580
855
  const hash = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) || "";
@@ -594,15 +869,149 @@ function generateSdk(userConfig) {
594
869
  config.variantAlias = urlVariantAlias;
595
870
  }
596
871
  }
872
+ if (config.stackSdk)
873
+ setStackSdkInstance(config.stackSdk);
874
+ /**
875
+ * The variant alias every SDK-side data fetch should use, in priority order:
876
+ * 1. The `cs-variant-alias` URL param when running inside Studio — Studio
877
+ * (and the Visual Builder navbar behind it) is the source of truth for the
878
+ * variant being previewed.
879
+ * 2. The per-fetch `options.variantAlias` (host-supplied, e.g. a Personalize
880
+ * alias passed to `fetchSpec`).
881
+ * 3. `config.variantAlias` — the SDK-level default. Inside Studio the init
882
+ * block above already copies `cs-variant-alias` into it, so this also acts
883
+ * as the no-search-param fallback.
884
+ *
885
+ * Centralized because the stack-sdk-wrapper applies a variant ONLY from the
886
+ * per-query option — unlike locale, it has no `config.variantAlias` fallback.
887
+ * So the resolved value must be handed to every fetch explicitly (template
888
+ * entry, bound contentstack entries, and dynamic queries); otherwise a
889
+ * Studio-selected variant renders on the page entry but silently skips all
890
+ * secondary data. Mirrors `resolveLocale`'s studio-search-param-first order.
891
+ */
892
+ /**
893
+ * The search params for the CURRENT fetch. In CSR the SDK fetches in the browser, so
894
+ * they come from `window.location.search`; in SSR the fetch runs server-side where
895
+ * `window` is blind, so the caller threads the forwarded request query string as
896
+ * `searchParams`. Request-scoped — never reads shared mutable state, so concurrent SSR
897
+ * requests cannot clobber one another.
898
+ */
899
+ const getRequestSearchParams = (searchParams) => searchParams ??
900
+ (typeof window !== "undefined"
901
+ ? new URLSearchParams(window.location.search)
902
+ : undefined);
903
+ /**
904
+ * Whether this fetch is rendering the Studio editor preview — the `cs-composable-studio`
905
+ * flag is on the iframe URL. Replaces the `window`-only `isInsideStudioFrame()` in the
906
+ * fetch path so SSR (server-side, `window`-blind) is detected via the forwarded params.
907
+ */
908
+ const isInStudio = (searchParams) => getRequestSearchParams(searchParams)?.has(COMPOSABLE_STUDIO_QUERY_PARAM.ENABLED) ?? false;
909
+ /**
910
+ * Whether this fetch renders inside an editor (Studio OR Visual Builder). Editor fetches
911
+ * widen the query (all fields, no `only` projection). VB is browser-only so it still
912
+ * comes from the global mode util; Studio is searchParams-aware (so it works in SSR).
913
+ */
914
+ const isEditorFetch = (searchParams) => isInStudio(searchParams) ||
915
+ clientRendererModeUtil.isInsideVisualBuilderFrame();
916
+ /**
917
+ * Read a Studio iframe-URL param (locale, variant, template-entry) for the current
918
+ * fetch — the author's live editor choices. Returns undefined outside the editor.
919
+ */
920
+ const readStudioParam = (param, searchParams) => {
921
+ const params = getRequestSearchParams(searchParams);
922
+ if (!params?.has(COMPOSABLE_STUDIO_QUERY_PARAM.ENABLED))
923
+ return undefined;
924
+ return params.get(param) || undefined;
925
+ };
926
+ const resolveEffectiveVariantAlias = (optionVariantAlias, searchParams) => {
927
+ const studioVariant = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.VARIANT_ALIAS, searchParams);
928
+ return studioVariant || optionVariantAlias || config.variantAlias;
929
+ };
930
+ /**
931
+ * The locale every SDK-side data fetch should use, in priority order:
932
+ * 1. The `cs-locale` URL param when running inside Studio — Studio is the
933
+ * source of truth for the previewed locale.
934
+ * 2. A URL-pattern `{{locale}}` capture (only known after URL matching, so
935
+ * callers pass it in as `patternLocale`).
936
+ * 3. The per-fetch `options.locale` (`optionLocale`).
937
+ * 4. `config.locale` — the SDK-level default (also overridden with `cs-locale`
938
+ * inside Studio by the init block above).
939
+ * 5. `config.stackSdk.locale` — the underlying delivery stack's own configured
940
+ * locale (its `_locale`/`Stack({ locale })`). Makes the stack-locale floor
941
+ * *explicit* rather than relying on the delivery SDK's implicit auto-apply
942
+ * (the TS SDK auto-applies it; the legacy JS SDK applies none) — so behavior
943
+ * is deterministic across SDK flavors. When all tiers are empty the locale is
944
+ * omitted and the CMS returns its master copy (with `include_fallback`).
945
+ *
946
+ * Mirrors resolveEffectiveVariantAlias. Centralized so the template entry, bound
947
+ * contentstack entries, and dynamic queries all resolve locale identically —
948
+ * previously only the template entry saw the URL-pattern locale; the secondary
949
+ * fetches dropped it.
950
+ */
951
+ const resolveLocale = (patternLocale, optionLocale, searchParams) => {
952
+ const studioLocale = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE, searchParams);
953
+ return (studioLocale ||
954
+ patternLocale ||
955
+ optionLocale ||
956
+ config.locale ||
957
+ config.stackSdk?.locale);
958
+ };
959
+ /**
960
+ * Resolve the URL-pattern locale for a composition ONCE per fetch, and return
961
+ * the `matchResult` so fetchTemplateEntry can reuse it instead of re-matching.
962
+ *
963
+ * The locale is captured by matching the requested URL against the
964
+ * composition's `url_metadata` pattern (a `{{locale}}` placeholder). Hoisting
965
+ * it here lets fetchData hand the captured locale to the bound-entry and
966
+ * dynamic-query fetches too — previously only the template entry saw it. Locale
967
+ * is safe to vary per URL because Contentstack fallback always terminates at
968
+ * master, so an unpublished locale yields the master copy (never empty/stale).
969
+ *
970
+ * Environment is deliberately NOT resolved here. Unlike locale it has no
971
+ * fallback, so a per-URL environment that diverges from where the composition
972
+ * is published would serve a split/stale snapshot. Environment is the
973
+ * connection (SDK-init) environment, applied uniformly to composition AND data
974
+ * — see ADR-0002 §Environment.
975
+ *
976
+ * Returns no locale for the templateEntryUid path, the direct
977
+ * content_type_url_pattern source, and legacy compositions (no `{{...}}`
978
+ * captures there).
979
+ */
980
+ const resolveUrlPatternContext = (compositionEntry, compositionQuery, connectedContentType) => {
981
+ const empty = {
982
+ matchResult: undefined,
983
+ patternLocale: undefined,
984
+ };
985
+ const parsedMetadata = compositionEntry.url_metadata
986
+ ? parseUrlMetadata(compositionEntry.url_metadata)
987
+ : null;
988
+ const url = "url" in compositionQuery ? compositionQuery.url : undefined;
989
+ if (!parsedMetadata ||
990
+ !url ||
991
+ !compositionEntry.url ||
992
+ parsedMetadata.url_source ===
993
+ COMPOSITION_PREVIEW_URL_SOURCES.CONTENT_TYPE_URL_PATTERN) {
994
+ return empty;
995
+ }
996
+ const matchResult = matchCompositionUrl(url, compositionEntry.url, compositionEntry.composable_uid, {
997
+ includeReferences: parsedMetadata.url_queries?.include,
998
+ connected_content_type: connectedContentType,
999
+ });
1000
+ return {
1001
+ matchResult,
1002
+ patternLocale: matchResult.matched
1003
+ ? matchResult.variables?.metadata?.locale
1004
+ : undefined,
1005
+ };
1006
+ };
597
1007
  isSdkInitDebugEnabled();
598
1008
  // REMOVED: sendSDKInitializedSignal - replaced by INIT_STUDIO via Advanced Post Message
599
1009
  // The raw postMessage approach has been consolidated into the proven INIT_STUDIO system
600
1010
  // REMOVED: initiateStudioHandshake - no longer needed with Advanced Post Message
601
1011
  // The INIT_STUDIO system via composableStudioEventManager handles reliable delivery
602
- async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}) {
1012
+ async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}, searchParams) {
603
1013
  const { variantAlias, locale } = options;
604
- const isInsideEditor = clientRendererModeUtil.isInsideVisualBuilderFrame() ||
605
- clientRendererModeUtil.isInsideStudioFrame();
1014
+ const isInsideEditor = isEditorFetch(searchParams);
606
1015
  try {
607
1016
  const promises = [];
608
1017
  for (const _content_type_uid in staticBindingQueries) {
@@ -669,7 +1078,7 @@ function generateSdk(userConfig) {
669
1078
  * When composition is binded to a content type, we need to fetch the entry for that content type. Called template entry.
670
1079
  * Supports custom fetcher overrides (per-query > global > SDK default).
671
1080
  */
672
- async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions) {
1081
+ async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions, urlPatternContext, searchParams) {
673
1082
  if (!config.stackSdk) {
674
1083
  return;
675
1084
  }
@@ -682,37 +1091,22 @@ function generateSdk(userConfig) {
682
1091
  const enhancedOptions = compositionQueryOptions; // Type assertion for internal properties
683
1092
  const _studioIntelligence = enhancedOptions?._studioIntelligence;
684
1093
  const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
685
- const isInsideStudio = clientRendererModeUtil.isInsideStudioFrame();
1094
+ // searchParams-aware so the all-fields projection (the `only`-suppression gates below)
1095
+ // fires for an SSR editor fetch, where the window-based util would report false.
1096
+ const isInsideStudio = isInStudio(searchParams);
686
1097
  // Studio override: when running inside Studio and the iframe URL carries
687
1098
  // `cs-template-entry-uid`, prefer it over any host-passed `templateEntryUid`.
688
1099
  // This lets the user pick a preview entry from Studio's navbar that
689
1100
  // overrides a host-hardcoded UID, while leaving the host's behaviour intact
690
1101
  // in production (the param is only honored when isInsideStudio).
691
1102
  //
692
- // Studio also passes the active locale via `cs-locale`. When present, it
693
- // reflects explicit user intent and outranks any URL-pattern {{locale}} or
694
- // host-supplied option (see resolveLocale below).
695
- let studioSearchParamLocale;
696
- if (isInsideStudio && typeof window !== "undefined") {
697
- try {
698
- const urlSearchParam = new URLSearchParams(window.location.search);
699
- const studioOverride = urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.TEMPLATE_ENTRY_UID);
700
- if (studioOverride) {
701
- resolvedOptions.templateEntryUid = studioOverride;
702
- }
703
- studioSearchParamLocale =
704
- urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE) || undefined;
705
- }
706
- catch {
707
- // Ignore — fall through to normal resolution.
708
- }
1103
+ const studioOverride = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.TEMPLATE_ENTRY_UID, searchParams);
1104
+ if (studioOverride) {
1105
+ resolvedOptions.templateEntryUid = studioOverride;
709
1106
  }
710
- // Locale priority: studio search-param > URL-pattern {{locale}} > host option > config.
711
- // Pattern locale is only known after URL pattern matching, so callers pass it in.
712
- const resolveLocale = (patternLocale) => studioSearchParamLocale ||
713
- patternLocale ||
714
- resolvedOptions.locale ||
715
- config.locale;
1107
+ // Locale/variant resolution is shared across all SDK fetches — see
1108
+ // resolveEffectiveVariantAlias (studio `cs-variant-alias` > per-fetch option > config).
1109
+ const resolveVariant = () => resolveEffectiveVariantAlias(resolvedOptions.variantAlias, searchParams);
716
1110
  const defaultImpl = async () => {
717
1111
  // Resolution priority: templateEntryUid > url_metadata path > legacy path
718
1112
  if (resolvedOptions.templateEntryUid) {
@@ -723,9 +1117,9 @@ function generateSdk(userConfig) {
723
1117
  ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
724
1118
  const queryOptions = {
725
1119
  references: allIncludeQueries,
726
- variantAlias: resolvedOptions.variantAlias,
1120
+ variantAlias: resolveVariant(),
727
1121
  // No URL pattern in this branch — pattern locale is N/A.
728
- locale: resolveLocale(),
1122
+ locale: resolveLocale(undefined, resolvedOptions.locale, searchParams),
729
1123
  };
730
1124
  // Smart 'only' parameter handling - only apply in production
731
1125
  if (!isInsideVB && !isInsideStudio) {
@@ -784,8 +1178,8 @@ function generateSdk(userConfig) {
784
1178
  let directQuery = config.stackSdk
785
1179
  .ctQuery(connected_content_type, {
786
1180
  references: allIncludeQueries,
787
- variantAlias: resolvedOptions.variantAlias,
788
- locale: resolveLocale(),
1181
+ variantAlias: resolveVariant(),
1182
+ locale: resolveLocale(undefined, resolvedOptions.locale, searchParams),
789
1183
  only: finalOnlyQueries,
790
1184
  })
791
1185
  .limit(1);
@@ -801,20 +1195,27 @@ function generateSdk(userConfig) {
801
1195
  if (!compositionEntry.url) {
802
1196
  throw new Error("Composition entry missing URL pattern for template matching");
803
1197
  }
804
- // Match the composition URL pattern to extract variables
805
- const matchResult = matchCompositionUrl(compositionQuery.url, compositionEntry.url, compositionEntry.composable_uid, {
806
- includeReferences: parsedMetadata.url_queries?.include,
807
- connected_content_type,
808
- });
1198
+ // Match the composition URL pattern to extract variables. Reuse the
1199
+ // match fetchData already computed for the whole page
1200
+ // (resolveUrlPatternContext) when provided — same inputs, so this is
1201
+ // a true resolve-once rather than a second identical match.
1202
+ const matchResult = urlPatternContext?.matchResult ??
1203
+ matchCompositionUrl(compositionQuery.url, compositionEntry.url, compositionEntry.composable_uid, {
1204
+ includeReferences: parsedMetadata.url_queries?.include,
1205
+ connected_content_type,
1206
+ });
809
1207
  if (matchResult.matched && matchResult.variables) {
810
1208
  const patternMetadata = matchResult.variables.metadata;
811
1209
  // Build query using extracted variables and metadata
812
1210
  const templateQuery = resolveByUrlSource(config.stackSdk, parsedMetadata.url_source, compositionQuery, matchResult.variables, parsedMetadata.url_queries, connected_content_type, {
813
1211
  references: allIncludeQueries,
814
- variantAlias: resolvedOptions.variantAlias,
815
- locale: resolveLocale(patternMetadata.locale),
1212
+ variantAlias: resolveVariant(),
1213
+ locale: resolveLocale(patternMetadata.locale, resolvedOptions.locale, searchParams),
816
1214
  branch: patternMetadata.branch,
817
- environment: patternMetadata.environment,
1215
+ // environment intentionally omitted: it is the connection
1216
+ // (SDK-init) env, uniform across composition + data. Per-URL
1217
+ // {{environment}} has no fallback and would split the snapshot
1218
+ // (see ADR-0002 §Environment).
818
1219
  only: finalOnlyQueries,
819
1220
  });
820
1221
  const response = await templateQuery.find();
@@ -837,9 +1238,11 @@ function generateSdk(userConfig) {
837
1238
  ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
838
1239
  const queryOptions = {
839
1240
  references: allIncludeQueries,
840
- variantAlias: resolvedOptions.variantAlias,
841
- // No URL pattern in this branch — pattern locale is N/A.
842
- locale: resolveLocale(),
1241
+ variantAlias: resolveVariant(),
1242
+ // No URL pattern in this branch — pattern locale is N/A. Forward
1243
+ // searchParams so the SSR editor's cs-locale is honored here too
1244
+ // (window is blind on the server); matches every sibling branch.
1245
+ locale: resolveLocale(undefined, resolvedOptions.locale, searchParams),
843
1246
  };
844
1247
  // Smart 'only' parameter handling - only apply in production
845
1248
  if (!isInsideVB && !isInsideStudio) {
@@ -916,7 +1319,7 @@ function generateSdk(userConfig) {
916
1319
  if (!isCompositionBeingEdited(fetchOptions?.composableUid || ""))
917
1320
  return;
918
1321
  }
919
- async function fetchData(compositionEntry, queryOptions, options, sectionEntries = []) {
1322
+ async function fetchData(compositionEntry, queryOptions, options, sectionEntries = [], searchParams) {
920
1323
  const { variantAlias, locale } = options || {};
921
1324
  // Read all saved reference include paths from compositionEntry.data_sources.resolvedReferences.
922
1325
  // Covers toggle ON paths, directly-bound field paths, and condition block binding paths.
@@ -1045,6 +1448,15 @@ function generateSdk(userConfig) {
1045
1448
  ...(pageExternalProps ? { component_props: pageExternalProps } : {}),
1046
1449
  };
1047
1450
  const templateContentTypeUid = getTemplateContentTypeForComposition(compositionEntry);
1451
+ // Resolve the URL-pattern locale ONCE for the whole page, so the bound-entry
1452
+ // and dynamic-query fetches honor a captured {{locale}} — not just the
1453
+ // template entry. (Environment is the connection env, not threaded per-URL —
1454
+ // see resolveUrlPatternContext / ADR-0002 §Environment.)
1455
+ const urlPatternContext = resolveUrlPatternContext(compositionEntry, queryOptions, templateContentTypeUid);
1456
+ const pageLocale = resolveLocale(urlPatternContext.patternLocale, locale, searchParams);
1457
+ // Resolve the effective variant once for the whole page (mirrors pageLocale); the
1458
+ // bound-entry and dynamic-query fetches below share it.
1459
+ const pageVariantAlias = resolveEffectiveVariantAlias(variantAlias, searchParams);
1048
1460
  // Build merged entry-reference paths covering page + all section data
1049
1461
  // sources, with unioned include[] per (ct_uid, entry_uid).
1050
1462
  const mergedRefs = JSON.parse(JSON.stringify(contentstackEntriesReferencesPath));
@@ -1088,23 +1500,135 @@ function generateSdk(userConfig) {
1088
1500
  }
1089
1501
  }
1090
1502
  }
1503
+ // ---- Section template references → page template include/only ----
1504
+ // Each section renders against a scoped slice of the PAGE template entry
1505
+ // (data.dataSources.template, narrowed by selectedField). For a section's
1506
+ // reference fields to resolve at render, the CDA template fetch must pull
1507
+ // them in — remapped from the section's own schema namespace into the page
1508
+ // template namespace via the instance's selectedField (path prefix) and
1509
+ // uidRemapping (per-segment rename). getEntriesQueries(section) above only
1510
+ // contributed the section's *contentstack-entry* refs; its template refs
1511
+ // and field projections were dropped, so section-bound references came back
1512
+ // as bare stubs (or were never requested) and rendered blank standalone.
1513
+ // For nested wrapper chains, each section's references are rooted at its
1514
+ // page-rooted `ancestorPrefix` + its own `selectedField`, so a multi-level
1515
+ // reference chain (W1 → W2 → …) fetches the full nested include depth.
1516
+ const sectionsByUid = new Map(sectionEntries.map((s) => [s.uid, s]));
1517
+ const instanceBindings = collectSectionInstanceBindings(typeof compositionEntry.ui === "string"
1518
+ ? decompressSpec(compositionEntry.ui)
1519
+ : compositionEntry.ui, sectionsByUid, connectedContentTypeUid);
1520
+ const mergedTemplateRefs = [...templateReferencesPath];
1521
+ const mergedTemplateOnly = [...templateOnlyKeys];
1522
+ for (const binding of instanceBindings) {
1523
+ const section = sectionsByUid.get(binding.compositionUid);
1524
+ if (!section)
1525
+ continue;
1526
+ // Page-rooted prefix: enclosing wrapper reference path (ancestorPrefix)
1527
+ // composed with this instance's own selectedField. ancestorPrefix is
1528
+ // already sanitized + page-namespaced (ancestor selectedFields are real
1529
+ // field names), so only the instance's own selectedField is sanitized here.
1530
+ // Reference-ancestor placement: when the section sits inside a page
1531
+ // Repeater(reference)+reference-ConditionBlock (see
1532
+ // composeSectionTemplatePrefix).
1533
+ const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids);
1534
+ const remapSeg = (seg) => binding.uidRemapping?.[seg] ?? seg;
1535
+ const sectionAsCompositionEntry = {
1536
+ ...section,
1537
+ ui: typeof section.ui === "string"
1538
+ ? section.ui
1539
+ : JSON.stringify(section.ui),
1540
+ };
1541
+ const sectionRefs = getEntriesQueries(sectionAsCompositionEntry, config.contentTypeUid, resolvedOptions);
1542
+ // Section reference include paths: UI-derived (reference conditions) plus
1543
+ // saved toggle paths from the SECTION's own data_sources[template].
1544
+ const sectionTemplateRefPaths = new Set(sectionRefs.templateReferencesPath);
1545
+ try {
1546
+ const sds = Array.isArray(section.data_sources)
1547
+ ? section.data_sources
1548
+ : typeof section.data_sources === "string"
1549
+ ? JSON.parse(section.data_sources)
1550
+ : [];
1551
+ const tmplDS = sds.find((ds) => ds?.uid === DATA_SOURCES.TEMPLATE);
1552
+ if (tmplDS?.resolvedReferences) {
1553
+ for (const p of Object.values(tmplDS.resolvedReferences).flat()) {
1554
+ if (typeof p === "string" && p.trim())
1555
+ sectionTemplateRefPaths.add(p);
1556
+ }
1557
+ }
1558
+ }
1559
+ catch {
1560
+ // malformed section data_sources — fall back to UI-derived refs only
1561
+ }
1562
+ for (const p of sectionTemplateRefPaths) {
1563
+ const full = [...prefix, ...sanitizeFieldPath(p).map(remapSeg)].join(".");
1564
+ if (full)
1565
+ mergedTemplateRefs.push(full);
1566
+ }
1567
+ // Include + project EVERY cumulative hop of the composed prefix so each
1568
+ // reference in the chain is fetched and the next hop is reachable, e.g.
1569
+ // include[]=related_articles, include[]=related_articles.author
1570
+ // only[BASE][]=related_articles, only[related_articles][]=author
1571
+ {
1572
+ let parent = "BASE";
1573
+ const acc = [];
1574
+ for (const seg of prefix) {
1575
+ acc.push(seg);
1576
+ mergedTemplateRefs.push(acc.join("."));
1577
+ mergedTemplateOnly.push([parent, seg]);
1578
+ parent = acc.join(".");
1579
+ }
1580
+ }
1581
+ // Re-parent the section's field projections under the selectedField
1582
+ // subtree so the right fields come back on the referenced entries.
1583
+ for (const [parentKey, child] of sectionRefs.templateOnlyKeys) {
1584
+ const remappedChild = child.split(".").map(remapSeg).join(".");
1585
+ let newParent;
1586
+ if (parentKey === "BASE") {
1587
+ newParent = prefix.length ? prefix.join(".") : "BASE";
1588
+ }
1589
+ else {
1590
+ const remappedParent = parentKey.split(".").map(remapSeg).join(".");
1591
+ newParent = prefix.length
1592
+ ? `${prefix.join(".")}.${remappedParent}`
1593
+ : remappedParent;
1594
+ }
1595
+ mergedTemplateOnly.push([newParent, remappedChild]);
1596
+ }
1597
+ }
1598
+ const dedupedTemplateRefs = [...new Set(mergedTemplateRefs)];
1599
+ // A deep reference that lives inside a section slot only assembles its full
1600
+ // include[] path in this merged set (the page sees the slot child at the
1601
+ // wrong depth; the section sees its own reference repeater but not the
1602
+ // page-authored slot binding). Reconcile here so every merged include[]
1603
+ // segment is projected in only[] at its parent — otherwise the section's
1604
+ // restrictive projection (e.g. only[a.b][]=_content_type_uid) silently
1605
+ // strips the leaf reference and it renders blank.
1606
+ mergedTemplateOnly.push(...projectIncludePathsOntoOnlyKeys(dedupedTemplateRefs, mergedTemplateOnly));
1607
+ const seenOnly = new Set();
1608
+ const dedupedTemplateOnly = mergedTemplateOnly.filter(([p, c]) => {
1609
+ const sig = `${p}|${c}`;
1610
+ if (seenOnly.has(sig))
1611
+ return false;
1612
+ seenOnly.add(sig);
1613
+ return true;
1614
+ });
1091
1615
  await Promise.all([
1092
1616
  fetchTemplateEntry({
1093
1617
  connected_content_type: templateContentTypeUid,
1094
1618
  compositionQuery: queryOptions,
1095
- includeQueries: templateReferencesPath,
1096
- onlyQueries: templateOnlyKeys,
1619
+ includeQueries: dedupedTemplateRefs,
1620
+ onlyQueries: dedupedTemplateOnly,
1097
1621
  composableUid: compositionEntry.composable_uid,
1098
- }, data, compositionEntry, resolvedOptions),
1622
+ }, data, compositionEntry, resolvedOptions, urlPatternContext, searchParams),
1099
1623
  resolveStaticData(mergedRefs, mergedOnly, data, {
1100
- variantAlias: variantAlias,
1101
- locale: locale,
1102
- }),
1624
+ variantAlias: pageVariantAlias,
1625
+ locale: pageLocale,
1626
+ }, searchParams),
1103
1627
  resolveQueryData(compositionEntry, data, {
1104
- variantAlias,
1105
- locale: locale || config.locale,
1628
+ variantAlias: pageVariantAlias,
1629
+ locale: pageLocale,
1106
1630
  sectionEntries,
1107
- }),
1631
+ }, searchParams),
1108
1632
  ]);
1109
1633
  attachSectionCompositionContexts(data, compositionEntry, sectionEntries);
1110
1634
  // NEW: build per-instance scoped data sources and attach to spec.
@@ -1237,7 +1761,7 @@ function generateSdk(userConfig) {
1237
1761
  data.section_scoped_data = scoped;
1238
1762
  return data;
1239
1763
  }
1240
- async function fetchSpec(queryOptions, options, skipComponentLoading = false) {
1764
+ async function fetchSpec(queryOptions, options, skipComponentLoading = false, searchParams) {
1241
1765
  if (!config.stackSdk) {
1242
1766
  throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
1243
1767
  }
@@ -1261,7 +1785,7 @@ function generateSdk(userConfig) {
1261
1785
  allSymbolEntries.push(symbol);
1262
1786
  });
1263
1787
  }
1264
- const data = await fetchData(compositionEntry, queryOptions, enhancedOptions, Array.from(sectionEntries.values()));
1788
+ const data = await fetchData(compositionEntry, queryOptions, enhancedOptions, Array.from(sectionEntries.values()), searchParams);
1265
1789
  // Lazy loading and SSR validation for production mode
1266
1790
  // Skip if called from fetchMultipleSpecs (which handles loading in batch)
1267
1791
  const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
@@ -1298,21 +1822,12 @@ function generateSdk(userConfig) {
1298
1822
  const errorMessage = [
1299
1823
  `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
1300
1824
  "",
1301
- "❌ Built-in components should be automatically available when importing the SDK.",
1302
- "This indicates a build, import, or packaging issue.",
1303
- "",
1304
- "Ensure you're importing from @contentstack/studio-react:",
1305
- ' import { useCompositionData } from "@contentstack/studio-react";',
1306
- "",
1307
- "If using a bundler, verify the package is properly resolved and built.",
1308
- "Check for console errors during module import.",
1825
+ "Built-in components are auto-registered on first import of @contentstack/studio-react.",
1826
+ "If you're seeing this, the package root was either not imported on this code path",
1827
+ "(e.g. a server-only bundle that pulls a subpath but not the root) or was tree-shaken away.",
1309
1828
  "",
1310
- "Manual registration workaround:",
1311
- ' import { registerComponents, getDefaultDesignTokens } from "@contentstack/studio-react";',
1312
- ' import { getBasicComponents } from "@contentstack/studio-react-components";',
1313
- "",
1314
- " const components = getBasicComponents({ csDesignTokens: getDefaultDesignTokens() });",
1315
- " registerComponents(components);",
1829
+ "Fix: make sure the package root is imported at least once before fetchSpec runs:",
1830
+ ' import "@contentstack/studio-react";',
1316
1831
  ].join("\n");
1317
1832
  throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
1318
1833
  }
@@ -1402,21 +1917,12 @@ function generateSdk(userConfig) {
1402
1917
  const errorMessage = [
1403
1918
  `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
1404
1919
  "",
1405
- "❌ Built-in components should be automatically available when importing the SDK.",
1406
- "This indicates a build, import, or packaging issue.",
1407
- "",
1408
- "Ensure you're importing from @contentstack/studio-react:",
1409
- ' import { useCompositionData } from "@contentstack/studio-react";',
1410
- "",
1411
- "If using a bundler, verify the package is properly resolved and built.",
1412
- "Check for console errors during module import.",
1413
- "",
1414
- "Manual registration workaround:",
1415
- ' import { registerComponents, getDefaultDesignTokens } from "@contentstack/studio-react";',
1416
- ' import { getBasicComponents } from "@contentstack/studio-react-components";',
1920
+ "Built-in components are auto-registered on first import of @contentstack/studio-react.",
1921
+ "If you're seeing this, the package root was either not imported on this code path",
1922
+ "(e.g. a server-only bundle that pulls a subpath but not the root) or was tree-shaken away.",
1417
1923
  "",
1418
- " const components = getBasicComponents({ csDesignTokens: getDefaultDesignTokens() });",
1419
- " registerComponents(components);",
1924
+ "Fix: make sure the package root is imported at least once before fetchSpec runs:",
1925
+ ' import "@contentstack/studio-react";',
1420
1926
  ].join("\n");
1421
1927
  throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
1422
1928
  }
@@ -1487,7 +1993,7 @@ function generateSdk(userConfig) {
1487
1993
  return { entries: [], count: 0 };
1488
1994
  }
1489
1995
  }
1490
- async function resolveQueryData(compositionEntry, data, options) {
1996
+ async function resolveQueryData(compositionEntry, data, options, searchParams) {
1491
1997
  // Parse page data_sources (may be absent — sections may still declare queries).
1492
1998
  let pageDataSources = [];
1493
1999
  if (compositionEntry.data_sources) {
@@ -1563,15 +2069,17 @@ function generateSdk(userConfig) {
1563
2069
  if (dedupedQueries.length === 0)
1564
2070
  return;
1565
2071
  const queryResults = {};
1566
- // Build RuntimeContext for expression resolution
1567
- // In SDK, use window.location.href for URL params
2072
+ // The request's search params (forwarded `searchParams` in SSR, `window.location.search`
2073
+ // in CSR), resolved once and reused for url.params and the in-Studio check below.
2074
+ const requestParams = getRequestSearchParams(searchParams);
2075
+ const isInsideStudio = requestParams?.has(COMPOSABLE_STUDIO_QUERY_PARAM.ENABLED) ?? false;
2076
+ // Build RuntimeContext for expression resolution. URL params come from the request.
2077
+ // `url.hash` stays window-only — the fragment is never sent to a server, so SSR
2078
+ // (preview and production alike) cannot see it.
1568
2079
  const urlParams = {};
1569
- if (typeof window !== "undefined" && window.location) {
1570
- const searchParams = new URLSearchParams(window.location.search);
1571
- searchParams.forEach((value, key) => {
1572
- urlParams[key] = value;
1573
- });
1574
- }
2080
+ requestParams?.forEach((value, key) => {
2081
+ urlParams[key] = value;
2082
+ });
1575
2083
  const context = {
1576
2084
  url: {
1577
2085
  params: urlParams,
@@ -1595,7 +2103,7 @@ function generateSdk(userConfig) {
1595
2103
  // When inside Studio, add editor params so the delivery SDK (preview API)
1596
2104
  // returns unpublished entries and full field metadata — matching CMA richness.
1597
2105
  // Studio's isResolutionFresh then sees non-empty entries and skips its CMA call.
1598
- const isInsideStudio = clientRendererModeUtil.isInsideStudioFrame();
2106
+ // (isInsideStudio is resolved once for the whole resolveQueryData call above.)
1599
2107
  const studioParams = isInsideStudio
1600
2108
  ? {
1601
2109
  include_publish_details: true,
@@ -1642,8 +2150,34 @@ function generateSdk(userConfig) {
1642
2150
  function getLightConfig() {
1643
2151
  return pick(config, ["openInStudioButton", "contentTypeUid", "cslp"]);
1644
2152
  }
1645
- function getSeoMetadata(ui) {
1646
- return ui.metadata.seo || null;
2153
+ function getSeoMetadata(ui, specData) {
2154
+ const seo = ui.metadata.seo;
2155
+ if (!seo)
2156
+ return null;
2157
+ /**
2158
+ * Flow:
2159
+ * 1. Studio stores SEO in `ui.metadata.seo`.
2160
+ * 2. Template entry data is fetched separately into `spec.data`.
2161
+ * 3. We merge both here so callers of `specOptions.seo` receive resolved
2162
+ * values instead of raw binding-only metadata.
2163
+ *
2164
+ * Each bindable field (pageTitle, pageDescription, openGraphImage, and
2165
+ * every metaProp.value) is run through `resolveSeoBindingValue` so a
2166
+ * bound field returns the template entry value, while an unbound field
2167
+ * keeps its saved static value.
2168
+ */
2169
+ return {
2170
+ ...seo,
2171
+ pageTitle: resolveSeoBindingValue(seo.pageTitle, seo.pageTitleBinding, specData),
2172
+ pageDescription: resolveSeoBindingValue(seo.pageDescription, seo.pageDescriptionBinding, specData),
2173
+ openGraphImage: resolveSeoBindingValue(seo.openGraphImage, seo.openGraphImageBinding, specData),
2174
+ metaProps: (seo.metaProps || []).map((prop) => {
2175
+ const resolved = resolveSeoBindingValue(prop.value, prop.binding, specData);
2176
+ // Both `value` and `previewValue` reflect the resolved value when the
2177
+ // meta prop is bound, so canvas/SSR consumers stay in sync.
2178
+ return { ...prop, value: resolved, previewValue: resolved };
2179
+ }),
2180
+ };
1647
2181
  }
1648
2182
  const sdkSingleton = {
1649
2183
  internal: {
@@ -1662,11 +2196,36 @@ function generateSdk(userConfig) {
1662
2196
  public: {
1663
2197
  // Exposing this method for the user to fetch the data.
1664
2198
  /**
1665
- * This method is used to fetch the composition data for the SSR.
2199
+ * Server-side composition fetcher. Resolves a composition + its bound
2200
+ * data into a `StudioComponentSpecOptions` object you can hand to
2201
+ * `<StudioComponent specOptions={...} />`.
2202
+ *
2203
+ * Pair with `useCompositionData` for CSR; the two cover the same use
2204
+ * cases on different render paths.
2205
+ *
2206
+ * IMPORTANT — this returns the spec options object **directly**, NOT
2207
+ * wrapped in `{ specOptions }`. Destructure accordingly:
2208
+ *
2209
+ * ```ts
2210
+ * // ✅ Correct
2211
+ * const specOptions = await sdk.fetchCompositionData({ url: "/about", searchQuery: "" });
1666
2212
  *
1667
- * @param queryOptions - The query options for the composition.
1668
- * @param options - The options for the composition.
1669
- * @returns The composition data for the SSR.
2213
+ * // ❌ Wrong — `specOptions` will be undefined
2214
+ * const { specOptions } = await sdk.fetchCompositionData(...);
2215
+ * ```
2216
+ *
2217
+ * There is **no `.public` namespace** on the SDK returned from
2218
+ * `studioSdk.init(...)` — call `sdk.fetchCompositionData(...)`,
2219
+ * not `sdk.public.fetchCompositionData(...)`.
2220
+ *
2221
+ * @param queryOptions - Identifies the composition (`compositionUid`,
2222
+ * `url`, `templateContentTypeUid`, or a combination) PLUS the
2223
+ * server-only `searchQuery` string for forwarding Studio iframe
2224
+ * overrides (locale, variant, preview entry, edit mode).
2225
+ * @param options - Optional modifiers: `variantAlias`, `locale`,
2226
+ * `templateEntryUid`, `extendQuery`, custom fetchers.
2227
+ * @returns `Promise<StudioComponentSpecOptions>` — the resolved spec
2228
+ * options object.
1670
2229
  */
1671
2230
  fetchCompositionData: async (queryOptions, options) => {
1672
2231
  if (!config.stackSdk) {
@@ -1677,43 +2236,46 @@ function generateSdk(userConfig) {
1677
2236
  const urlSearchParam = new URLSearchParams(searchQuery);
1678
2237
  // NOTE: Always keep this before fetching the spec. In SSR, we use the urlSearchParams
1679
2238
  // to get the hash and then use it to fetch the composition.
1680
- config.stackSdk.livePreviewQuery(urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
1681
- urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH) ||
1682
- "");
1683
- const rendererModeUtil = new RendererModeUtil(urlSearchParam);
1684
- // If queryOptions has composableUid and we are editing the current composition, we don't need to fetch the spec.
1685
- if ("compositionUid" in queryOptions &&
1686
- rendererModeUtil.isEditingCurrentComposition(queryOptions.compositionUid || "")) {
1687
- return {
1688
- spec: null,
1689
- fetchOptions: {
1690
- searchQuery: urlSearchParam.toString(),
1691
- compositionQuery,
1692
- config: getLightConfig(),
1693
- options,
1694
- mode: rendererModeUtil.getMode(queryOptions.compositionUid || ""),
1695
- },
1696
- hasSpec: true,
1697
- hasTemplate: true,
1698
- seo: null,
1699
- };
1700
- }
1701
- const spec = await fetchSpec(compositionQuery, options);
1702
- if (rendererModeUtil.isEditingCurrentComposition(spec.compositionEntry.composable_uid || "")) {
1703
- return {
1704
- spec: null,
1705
- fetchOptions: {
1706
- searchQuery: urlSearchParam.toString(),
1707
- compositionQuery,
1708
- config: getLightConfig(),
1709
- options,
1710
- mode: rendererModeUtil.getMode(spec.compositionEntry.composable_uid),
1711
- },
1712
- hasSpec: true,
1713
- hasTemplate: true,
1714
- seo: null,
1715
- };
2239
+ //
2240
+ // Only invoke `livePreviewQuery` when the request URL actually carries
2241
+ // a preview hash. Passing an empty string explicitly disables live
2242
+ // preview on the delivery SDK for subsequent requests, which forces
2243
+ // SSR's `fetchSpec` to hit the delivery API even when the stack was
2244
+ // initialised with `live_preview.enable=true`. Skipping the reset
2245
+ // when there's no hash preserves the stack's initialised live-preview
2246
+ // state and matches CSR's `useCompositionData` behaviour, which never
2247
+ // resets the hash between fetches.
2248
+ const previewHash = urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
2249
+ urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH);
2250
+ if (previewHash) {
2251
+ config.stackSdk.livePreviewQuery(previewHash);
1716
2252
  }
2253
+ const rendererModeUtil = new RendererModeUtil(urlSearchParam);
2254
+ // P4.2 (ADR-0005): always fetch and return the spec — uniformly for the
2255
+ // composition-uid and URL cases, whether or not it is being edited. The two
2256
+ // being-edited `null` returns are removed: returning `null` is what put SSR on
2257
+ // the served path (the iframe falls back to `getSpecFromParent` and asks Studio).
2258
+ // With the spec returned, SSR-being-edited now renders through the spec-provided
2259
+ // boundary and hands the spec to Studio via the push path (SDK_SPEC_RESOLVED,
2260
+ // emitted from EditableRendererHelper) — the same way CSR and production fetch.
2261
+ // The credential-less playground is unaffected: it never calls fetchCompositionData
2262
+ // (it uses `getSpecFromParent` directly) and stays on the served path.
2263
+ // Thread the forwarded request query (`searchQuery`) into the fetch so the
2264
+ // server-side resolvers see the author's live editor context (cs-locale,
2265
+ // cs-variant-alias, cs-template-entry-uid) — SSR resolves identically to CSR.
2266
+ // On the client this is the same window-derived context, so CSR is unchanged.
2267
+ const spec = await fetchSpec(compositionQuery, options, false, urlSearchParam);
2268
+ // Echo the resolved editor locale/variant back to Studio so the pushed
2269
+ // `sdkContext` reports the copy the SSR data was actually fetched in (e.g.
2270
+ // fr-fr) rather than the host's empty default — otherwise Studio's
2271
+ // diagnostics warn "rendered en-us" and Stage-2 entry/query adds would use
2272
+ // the wrong copy. Same precedence as the fetch (cs-locale > option >
2273
+ // config), read from the request query.
2274
+ const echoedOptions = {
2275
+ ...options,
2276
+ locale: resolveLocale(undefined, options?.locale, urlSearchParam),
2277
+ variantAlias: resolveEffectiveVariantAlias(options?.variantAlias, urlSearchParam),
2278
+ };
1717
2279
  return {
1718
2280
  spec,
1719
2281
  hasSpec: !!spec.compositionEntry,
@@ -1722,11 +2284,11 @@ function generateSdk(userConfig) {
1722
2284
  // TODO: @Nilesh - see if we can remove this as this config is already available in the spec.
1723
2285
  config: getLightConfig(),
1724
2286
  compositionQuery,
1725
- options,
2287
+ options: echoedOptions,
1726
2288
  searchQuery: urlSearchParam.toString(),
1727
2289
  mode: rendererModeUtil.getMode(spec.compositionEntry.composable_uid),
1728
2290
  },
1729
- seo: getSeoMetadata(spec.ui),
2291
+ seo: getSeoMetadata(spec.ui, spec.data),
1730
2292
  };
1731
2293
  },
1732
2294
  /**
@@ -1849,7 +2411,9 @@ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, lo
1849
2411
  only: [["BASE", "uid"]],
1850
2412
  locale: m.variables.metadata.locale || locale || config.locale,
1851
2413
  branch: m.variables.metadata.branch,
1852
- environment: m.variables.metadata.environment,
2414
+ // environment intentionally omitted — the ownership probe uses the
2415
+ // connection (SDK-init) env, consistent with how the page is served
2416
+ // (see ADR-0002 §Environment).
1853
2417
  });
1854
2418
  const res = await probeQuery.find();
1855
2419
  return {
@@ -2063,5 +2627,5 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
2063
2627
  };
2064
2628
  }
2065
2629
 
2066
- export { classifyApiError, fetchComposition as fetchCompositionForTest, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, parseUI };
2630
+ export { classifyApiError, collectSectionInstanceBindings as collectSectionInstanceBindingsForTest, composeSectionTemplatePrefix, fetchComposition as fetchCompositionForTest, flattenBindingPathFromValue, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, isTemplateBinding, parseUI, resolveSeoBindingValue };
2067
2631
  //# sourceMappingURL=sdk.js.map