@contentstack/studio-client 1.5.0 → 1.5.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 (81) hide show
  1. package/dist/breakpoints/BreakpointManager.js +17 -5
  2. package/dist/breakpoints/BreakpointManager.js.map +1 -1
  3. package/dist/canvas/canvas.utils.js +1 -1
  4. package/dist/canvas/canvas.utils.js.map +1 -1
  5. package/dist/composable-studio/build-scoped-data.js +101 -0
  6. package/dist/composable-studio/build-scoped-data.js.map +1 -0
  7. package/dist/composable-studio/collect-data-needs.js +226 -0
  8. package/dist/composable-studio/collect-data-needs.js.map +1 -0
  9. package/dist/composable-studio/composition-placement.types.js +7 -0
  10. package/dist/composable-studio/composition-placement.types.js.map +1 -0
  11. package/dist/composable-studio/sdk.js +1316 -113
  12. package/dist/composable-studio/sdk.js.map +1 -1
  13. package/dist/composable-studio/studio-intelligence.manager.js +124 -0
  14. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -0
  15. package/dist/config/default-config.js +1 -0
  16. package/dist/config/default-config.js.map +1 -1
  17. package/dist/config/stack-sdk-wrapper.js +87 -2
  18. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  19. package/dist/design/handle-active-style-change.js +0 -3
  20. package/dist/design/handle-active-style-change.js.map +1 -1
  21. package/dist/dnd/dnd-manager.js +25 -7
  22. package/dist/dnd/dnd-manager.js.map +1 -1
  23. package/dist/dnd/{utils.js → scroll-utils.js} +2 -27
  24. package/dist/dnd/scroll-utils.js.map +1 -0
  25. package/dist/hidden-element-notification/hidden-element-notification-event.js +7 -0
  26. package/dist/hidden-element-notification/hidden-element-notification-event.js.map +1 -1
  27. package/dist/highlight-node/highlight-node-manager.js +7 -1
  28. package/dist/highlight-node/highlight-node-manager.js.map +1 -1
  29. package/dist/highlight-node/highlight-node.js +8 -5
  30. package/dist/highlight-node/highlight-node.js.map +1 -1
  31. package/dist/index.d.ts +432 -22
  32. package/dist/index.js +11 -3
  33. package/dist/index.js.map +1 -1
  34. package/dist/query/query-executor.js +182 -27
  35. package/dist/query/query-executor.js.map +1 -1
  36. package/dist/shared/dnd-events.js +39 -0
  37. package/dist/shared/dnd-events.js.map +1 -0
  38. package/dist/url-metadata/build-template-query.js +124 -0
  39. package/dist/url-metadata/build-template-query.js.map +1 -0
  40. package/dist/url-metadata/parse-url-metadata.js +75 -0
  41. package/dist/url-metadata/parse-url-metadata.js.map +1 -0
  42. package/dist/url-metadata/rank-url-matches.js +100 -0
  43. package/dist/url-metadata/rank-url-matches.js.map +1 -0
  44. package/dist/url-metadata/select-url-winner.js +45 -0
  45. package/dist/url-metadata/select-url-winner.js.map +1 -0
  46. package/dist/url-metadata/shouldUseUrlMetadataPath.js +22 -0
  47. package/dist/url-metadata/shouldUseUrlMetadataPath.js.map +1 -0
  48. package/dist/url-metadata/types.js +50 -0
  49. package/dist/url-metadata/types.js.map +1 -0
  50. package/dist/url-metadata/url-pattern-matcher.js +311 -0
  51. package/dist/url-metadata/url-pattern-matcher.js.map +1 -0
  52. package/dist/utils/build-composition-fetch-query.js +19 -0
  53. package/dist/utils/build-composition-fetch-query.js.map +1 -0
  54. package/dist/utils/composable-studio-error.js +1 -0
  55. package/dist/utils/composable-studio-error.js.map +1 -1
  56. package/dist/utils/conditionBlock.js +1 -1
  57. package/dist/utils/conditionBlock.js.map +1 -1
  58. package/dist/utils/constants.js +22 -2
  59. package/dist/utils/constants.js.map +1 -1
  60. package/dist/utils/convertCompositionQueryInputToCompositionQuery.js +11 -1
  61. package/dist/utils/convertCompositionQueryInputToCompositionQuery.js.map +1 -1
  62. package/dist/utils/editor-utils.js +9 -0
  63. package/dist/utils/editor-utils.js.map +1 -1
  64. package/dist/utils/error-messages.default.js +1 -1
  65. package/dist/utils/error-messages.default.js.map +1 -1
  66. package/dist/utils/http-error.constants.js +11 -2
  67. package/dist/utils/http-error.constants.js.map +1 -1
  68. package/dist/utils/query-param.js +1 -1
  69. package/dist/utils/query-param.js.map +1 -1
  70. package/dist/utils/reference_fetcher.js +37 -22
  71. package/dist/utils/reference_fetcher.js.map +1 -1
  72. package/dist/utils/sdk.js +3 -1
  73. package/dist/utils/sdk.js.map +1 -1
  74. package/dist/utils/spec-analyzer.js +112 -0
  75. package/dist/utils/spec-analyzer.js.map +1 -0
  76. package/package.json +10 -9
  77. package/dist/dnd/utils.js.map +0 -1
  78. package/dist/get-composition-from-slug/get-composition-from-slug.js +0 -59
  79. package/dist/get-composition-from-slug/get-composition-from-slug.js.map +0 -1
  80. package/dist/utils/get-url-patterns.js +0 -40
  81. package/dist/utils/get-url-patterns.js.map +0 -1
@@ -1,22 +1,222 @@
1
- import { COMPOSABLE_STUDIO_QUERY_PARAM } from '@contentstack/studio-messenger';
2
- import { DATA_SOURCES, DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
1
+ import { COMPOSABLE_STUDIO_QUERY_PARAM, composableStudioEventManager, POST_MESSAGE_EVENTS } from '@contentstack/studio-messenger';
2
+ import { INTERNAL_COMPONENTS_NAMES, DATA_SOURCES, getComponentRegistryInstance, DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
3
3
  import { pick } from 'lodash-es';
4
4
  import { processUserConfig } from '../config/process-user-config.js';
5
- import { getCompositionFromSlug } from '../get-composition-from-slug/get-composition-from-slug.js';
6
- import { INCLUDE_DEPTH_COUNT } from '../utils/constants.js';
5
+ import { SCHEMA_VERSION, SDK_VERSION, INCLUDE_DEPTH_COUNT } from '../utils/constants.js';
7
6
  import { isCompositionBeingEdited } from '../utils/is-composition-being-edited.js';
8
7
  import { setTemplateEntryInDS, entriesFromResponse, setStaticEntryInDS } from '../utils/sdk.js';
9
8
  import { ComposableStudioError, ComposableStudioErrors } from '../utils/composable-studio-error.js';
10
9
  import { clientRendererModeUtil, RendererModeUtil } from '../utils/canvas.js';
11
- import { getEntriesQueries } from '../utils/reference_fetcher.js';
12
- import { preProcessStaticValues } from './data/pre-process-static-values.js';
10
+ import { analyzeUsedComponents } from '../utils/spec-analyzer.js';
13
11
  import { convertCompositionQueryInputToCompositionQuery } from '../utils/convertCompositionQueryInputToCompositionQuery.js';
14
- import { getUrlPatterns } from '../utils/get-url-patterns.js';
15
- import { getStatusCode, isContentstackAuthError, hasAuthErrorShape, isAuthError, isNetworkError, HttpStatus, ContentstackErrorCode, isServerError } from '../utils/http-error.constants.js';
16
12
  import { getErrorMessage, getTroubleshootingInfo } from '../utils/error-messages.js';
13
+ import { getPageLinkedPlacementFilter } from '../utils/build-composition-fetch-query.js';
14
+ import { resolveByUrlSource } from '../url-metadata/build-template-query.js';
15
+ import { parseUrlMetadata } from '../url-metadata/parse-url-metadata.js';
16
+ import { rankUrlMatches } from '../url-metadata/rank-url-matches.js';
17
+ import { selectUrlWinner } from '../url-metadata/select-url-winner.js';
18
+ import { COMPOSITION_PREVIEW_URL_SOURCES } from '../url-metadata/types.js';
19
+ import { matchCompositionUrl } from '../url-metadata/url-pattern-matcher.js';
20
+ 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 { parseExternalDataForComponentProps, collectAllDataNeeds, stableHashQuery } from './collect-data-needs.js';
23
+ import { buildScopedDataSources } from './build-scoped-data.js';
24
+ import { preProcessStaticValues } from './data/pre-process-static-values.js';
25
+ import { StudioIntelligenceManager } from './studio-intelligence.manager.js';
17
26
  import { decompressSpec } from '../packages/studio-internal/dist/utils/spec-compression.js';
18
27
  import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages.default.js';
19
28
 
29
+ // ✅ HYBRID APPROACH: List of internal components that should always be available
30
+ // These include both built-in components AND system components (like "page")
31
+ // All are registered synchronously during React initialization via getBasicComponents()
32
+ const INTERNAL_COMPONENT_TYPES = Object.values(INTERNAL_COMPONENTS_NAMES);
33
+ const SECTION_COMPOSITION_NODE_TYPE = "section-composition";
34
+ function findParentRepeaterUidInTree(ui, compositionUID) {
35
+ function traverse(node, nearestRepeaterUID) {
36
+ if (node.type === "section-composition" &&
37
+ node.metadata?.compositionUID === compositionUID) {
38
+ return nearestRepeaterUID;
39
+ }
40
+ const updatedRepeaterUID = node.type === "repeater" ? node.uid : nearestRepeaterUID;
41
+ for (const slotId of Object.keys(node.slots || {})) {
42
+ for (const child of node.slots[slotId] || []) {
43
+ const result = traverse(child, updatedRepeaterUID);
44
+ if (result !== undefined)
45
+ return result;
46
+ }
47
+ }
48
+ return undefined;
49
+ }
50
+ if (!ui)
51
+ return null;
52
+ const result = traverse(ui, null);
53
+ return result !== undefined ? result : null;
54
+ }
55
+ function setSectionCompositionContext(dataSources, sectionUid, selectedField, parentRepeaterUID = null) {
56
+ if (!dataSources["section_compositions"]) {
57
+ dataSources["section_compositions"] = {};
58
+ }
59
+ dataSources["section_compositions"][sectionUid] = {
60
+ selectedField,
61
+ uidRemapping: {},
62
+ parentRepeaterUID,
63
+ };
64
+ }
65
+ function findMatchingSectionSchema(section, templateEntry) {
66
+ const linkedSchemas = section.linked_schemas || [];
67
+ if (!linkedSchemas.length)
68
+ return null;
69
+ if (!templateEntry?._content_type_uid) {
70
+ return linkedSchemas[0] || null;
71
+ }
72
+ return (linkedSchemas.find((schema) => schema.content_type_uid === templateEntry._content_type_uid) || null);
73
+ }
74
+ function resolveSectionContext(section, templateEntry) {
75
+ const matchingSchema = findMatchingSectionSchema(section, templateEntry);
76
+ if (matchingSchema) {
77
+ return { selectedField: matchingSchema.selected_field };
78
+ }
79
+ if (!(section.linked_schemas || []).length) {
80
+ return { selectedField: undefined };
81
+ }
82
+ return null;
83
+ }
84
+ function getTemplateContentTypeForComposition(compositionEntry) {
85
+ if (compositionEntry.connected_content_type) {
86
+ return compositionEntry.connected_content_type;
87
+ }
88
+ if (compositionEntry.place_composition_as === "section" &&
89
+ compositionEntry.linked_schemas?.length) {
90
+ return compositionEntry.linked_schemas[0]?.content_type_uid || "";
91
+ }
92
+ return "";
93
+ }
94
+ function attachSectionCompositionContexts(data, compositionEntry, sectionEntries) {
95
+ const templateEntry = data.dataSources?.[DATA_SOURCES.TEMPLATE];
96
+ if (!templateEntry || Array.isArray(templateEntry))
97
+ return;
98
+ if (compositionEntry.place_composition_as === "section") {
99
+ const ownContext = resolveSectionContext(compositionEntry, templateEntry);
100
+ if (ownContext) {
101
+ setSectionCompositionContext(data.dataSources, compositionEntry.uid, ownContext.selectedField, null);
102
+ }
103
+ }
104
+ const rootUI = compositionEntry.ui ?? null;
105
+ sectionEntries.forEach((sectionEntry) => {
106
+ const sectionContext = resolveSectionContext(sectionEntry, templateEntry);
107
+ if (!sectionContext)
108
+ return;
109
+ const parentRepeaterUID = findParentRepeaterUidInTree(rootUI, sectionEntry.uid);
110
+ setSectionCompositionContext(data.dataSources, sectionEntry.uid, sectionContext.selectedField, parentRepeaterUID);
111
+ });
112
+ }
113
+ /**
114
+ * Walks the UI tree and visits every section-composition node,
115
+ * yielding (instanceUid, compositionUid) pairs for building
116
+ * per-instance scoped data source maps.
117
+ */
118
+ function walkUiForCompositionMapping(ui, visit) {
119
+ if (!ui)
120
+ return;
121
+ const node = ui;
122
+ if (node.type === SECTION_COMPOSITION_NODE_TYPE &&
123
+ node.metadata?.compositionUID &&
124
+ node.uid) {
125
+ visit(node.uid, node.metadata.compositionUID);
126
+ }
127
+ if (node.slots && typeof node.slots === "object") {
128
+ for (const slotNodes of Object.values(node.slots)) {
129
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
130
+ for (const c of arr)
131
+ walkUiForCompositionMapping(c, visit);
132
+ }
133
+ }
134
+ if (Array.isArray(node.children)) {
135
+ for (const c of node.children)
136
+ walkUiForCompositionMapping(c, visit);
137
+ }
138
+ }
139
+ function collectSectionCompositionUIDs(ui, accumulator = new Set()) {
140
+ if (!ui)
141
+ return accumulator;
142
+ if (ui.type === SECTION_COMPOSITION_NODE_TYPE &&
143
+ ui.metadata?.compositionUID) {
144
+ accumulator.add(ui.metadata.compositionUID);
145
+ }
146
+ if (ui.slots && typeof ui.slots === "object") {
147
+ Object.values(ui.slots).forEach((slotNodes) => {
148
+ if (Array.isArray(slotNodes)) {
149
+ slotNodes.forEach((child) => collectSectionCompositionUIDs(child, accumulator));
150
+ }
151
+ else if (slotNodes && typeof slotNodes === "object") {
152
+ collectSectionCompositionUIDs(slotNodes, accumulator);
153
+ }
154
+ });
155
+ }
156
+ if (Array.isArray(ui.children)) {
157
+ ui.children.forEach((child) => collectSectionCompositionUIDs(child, accumulator));
158
+ }
159
+ return accumulator;
160
+ }
161
+ async function fetchSectionCompositionEntries(config, sectionUids, options) {
162
+ if (!config.stackSdk || sectionUids.length === 0) {
163
+ return [];
164
+ }
165
+ const response = await config.stackSdk
166
+ .ctQuery(config.contentTypeUid, {
167
+ includeAll: true,
168
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
169
+ locale: options?.locale || config.locale,
170
+ })
171
+ .containedIn("uid", sectionUids)
172
+ .find();
173
+ return entriesFromResponse(response).map((entry) => ({
174
+ ...entry,
175
+ ui: typeof entry.ui === "string"
176
+ ? decompressSpec(entry.ui)
177
+ : entry.ui,
178
+ }));
179
+ }
180
+ async function getAllSectionCompositions(config, compositionEntry, options) {
181
+ const map = new Map();
182
+ // 1. Pull inline linked_sections from the initial composition response.
183
+ const linked = compositionEntry.linked_sections;
184
+ if (Array.isArray(linked)) {
185
+ for (const candidate of linked) {
186
+ // Skip bare references (uid only — fetch path) — handled by fallback.
187
+ if (candidate && typeof candidate === "object" && "ui" in candidate) {
188
+ const entry = candidate;
189
+ const ui = typeof entry.ui === "string"
190
+ ? decompressSpec(entry.ui)
191
+ : entry.ui;
192
+ map.set(entry.uid, { ...entry, ui });
193
+ }
194
+ }
195
+ }
196
+ // 2. Find any section-composition UIDs referenced in the UI tree that are
197
+ // missing from `map`. These need a fallback fetch.
198
+ const ui = typeof compositionEntry.ui === "string"
199
+ ? decompressSpec(compositionEntry.ui)
200
+ : compositionEntry.ui;
201
+ const referenced = Array.from(collectSectionCompositionUIDs(ui));
202
+ const missing = referenced.filter((uid) => !map.has(uid));
203
+ if (missing.length) {
204
+ if (process.env.NODE_ENV === "development") {
205
+ console.warn("getAllSectionCompositions: falling back to fetch for missing sections", missing);
206
+ }
207
+ try {
208
+ const fetched = await fetchSectionCompositionEntries(config, missing, options);
209
+ for (const s of fetched)
210
+ map.set(s.uid, s);
211
+ }
212
+ catch (err) {
213
+ if (process.env.NODE_ENV === "development") {
214
+ console.error("getAllSectionCompositions: fallback fetch failed", err);
215
+ }
216
+ }
217
+ }
218
+ return map;
219
+ }
20
220
  function getAuthErrorMessage(err) {
21
221
  const detail = err?.error_message ||
22
222
  err?.errors?.api_key?.[0] ||
@@ -45,18 +245,39 @@ function classifyApiError(err) {
45
245
  message: getAuthErrorMessage(err),
46
246
  };
47
247
  }
248
+ // Check for empty entry response (200 OK but no entries found)
249
+ // This happens when API succeeds but returns empty entry list
250
+ // Note: Pure empty objects {} should be treated as network errors, not empty responses
251
+ const isEmptyEntryResponse = statusCode === 200 &&
252
+ err &&
253
+ typeof err === "object" &&
254
+ err.entries &&
255
+ Array.isArray(err.entries) &&
256
+ err.entries.length === 0;
257
+ if (isEmptyEntryResponse) {
258
+ return {
259
+ errorType: ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND,
260
+ message: getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
261
+ contentType: "the composition",
262
+ }),
263
+ };
264
+ }
48
265
  // Check for network errors (no response, timeout, connection refused)
49
- // Empty response object often indicates network failure
50
- const isEmptyResponse = err && typeof err === "object" && Object.keys(err).length === 0;
51
- if ((!statusCode && isNetworkError(err)) || isEmptyResponse) {
266
+ if (!statusCode && isNetworkError(err)) {
267
+ // For empty objects, use the specific empty error message
268
+ if (typeof err === "object" && Object.keys(err).length === 0) {
269
+ return {
270
+ errorType: ComposableStudioErrors.NETWORK_ERROR,
271
+ message: getErrorMessage(ErrorMessageKey.NETWORK_ERROR_EMPTY),
272
+ };
273
+ }
274
+ // For other network errors, use the generic message with detail
52
275
  return {
53
276
  errorType: ComposableStudioErrors.NETWORK_ERROR,
54
- message: isEmptyResponse
55
- ? getErrorMessage(ErrorMessageKey.NETWORK_ERROR_EMPTY)
56
- : getErrorMessage(ErrorMessageKey.NETWORK_ERROR_GENERIC, {
57
- detail: err?.message ||
58
- getErrorMessage(ErrorMessageKey.NETWORK_ERROR_DETAIL_DEFAULT),
59
- }),
277
+ message: getErrorMessage(ErrorMessageKey.NETWORK_ERROR_GENERIC, {
278
+ detail: err?.message ||
279
+ getErrorMessage(ErrorMessageKey.NETWORK_ERROR_DETAIL_DEFAULT),
280
+ }),
60
281
  };
61
282
  }
62
283
  // Check for 404 - composition not found
@@ -293,15 +514,95 @@ function getParentTagsValue(dataValue, tagsAsObject) {
293
514
  return { "data-cslp-parent-field": dataValue };
294
515
  }
295
516
  }
517
+ /**
518
+ * Legacy variable removed - SDK initialization is now handled by INIT_STUDIO system
519
+ * @deprecated - was used for old sdk-initialized handshake, now consolidated to INIT_STUDIO
520
+ */
521
+ /**
522
+ * Dev-only console logs for SDK init. `process.env.NODE_ENV` can be wrong inside Vite’s
523
+ * prebundled `@contentstack/studio-client` graph — use `?csSdkDebug=1` on the canvas URL or
524
+ * `localStorage.setItem('csSdkDebug','1')` + reload to force logs on.
525
+ */
526
+ function isSdkInitDebugEnabled() {
527
+ if (typeof window !== "undefined") {
528
+ try {
529
+ if (new URLSearchParams(window.location.search).get("csSdkDebug") === "1") {
530
+ return true;
531
+ }
532
+ if (window.localStorage?.getItem("csSdkDebug") === "1") {
533
+ return true;
534
+ }
535
+ }
536
+ catch {
537
+ /* ignore */
538
+ }
539
+ }
540
+ return (typeof process !== "undefined" && process.env.NODE_ENV === "development");
541
+ }
542
+ /**
543
+ * 🚀 RESTORED: Send INIT_STUDIO via Advanced Post Message from the right place
544
+ * This fires IMMEDIATELY when SDK is created, ensuring proper timing (like original handshake)
545
+ */
546
+ function sendInitStudioSignal(config) {
547
+ try {
548
+ const initPayload = {
549
+ sdkVersion: SDK_VERSION,
550
+ schemaVersion: SCHEMA_VERSION,
551
+ sdkFramework: "react",
552
+ timestamp: Date.now(),
553
+ globalLocale: config.locale,
554
+ globalVariantAlias: config.variantAlias,
555
+ requestedUrl: window.location.href,
556
+ uid: `sdk-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
557
+ configPassedToTheSdk: {
558
+ contentTypeUid: config.contentTypeUid,
559
+ },
560
+ };
561
+ // Send via Advanced Post Message using static imports
562
+ composableStudioEventManager
563
+ ?.send(POST_MESSAGE_EVENTS.INIT_STUDIO, initPayload)
564
+ .catch((error) => {
565
+ console.warn("⚠️ SDK: INIT_STUDIO failed:", error);
566
+ });
567
+ }
568
+ catch (error) {
569
+ console.warn("⚠️ SDK: Could not send INIT_STUDIO from generateSdk:", error);
570
+ }
571
+ }
296
572
  function generateSdk(userConfig) {
297
573
  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
298
578
  if (clientRendererModeUtil.isInsideStudioFrame()) {
299
- const hash = new URLSearchParams(window.location.search).get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) || "";
579
+ const sp = new URLSearchParams(window.location.search);
580
+ const hash = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) || "";
300
581
  config.stackSdk.livePreviewQuery?.(hash);
582
+ // Studio is the source of truth for locale/variant when the SDK runs
583
+ // inside its iframe. Overriding the user-supplied config values here
584
+ // means every SDK-side fetch (initial spec, linked-entry references,
585
+ // section fetches) automatically uses the right locale/variant, and
586
+ // both INIT_STUDIO.globalLocale/globalVariantAlias and the per-query
587
+ // GET_COMPOSITION_SPEC payload round-trip them back to Studio.
588
+ const urlLocale = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE);
589
+ if (urlLocale) {
590
+ config.locale = urlLocale;
591
+ }
592
+ const urlVariantAlias = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.VARIANT_ALIAS);
593
+ if (urlVariantAlias) {
594
+ config.variantAlias = urlVariantAlias;
595
+ }
301
596
  }
597
+ isSdkInitDebugEnabled();
598
+ // REMOVED: sendSDKInitializedSignal - replaced by INIT_STUDIO via Advanced Post Message
599
+ // The raw postMessage approach has been consolidated into the proven INIT_STUDIO system
600
+ // REMOVED: initiateStudioHandshake - no longer needed with Advanced Post Message
601
+ // The INIT_STUDIO system via composableStudioEventManager handles reliable delivery
302
602
  async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}) {
303
603
  const { variantAlias, locale } = options;
304
- const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
604
+ const isInsideEditor = clientRendererModeUtil.isInsideVisualBuilderFrame() ||
605
+ clientRendererModeUtil.isInsideStudioFrame();
305
606
  try {
306
607
  const promises = [];
307
608
  for (const _content_type_uid in staticBindingQueries) {
@@ -309,8 +610,8 @@ function generateSdk(userConfig) {
309
610
  for (const entry_uid in staticBindingQueries[_content_type_uid]) {
310
611
  const references = staticBindingQueries[_content_type_uid][entry_uid];
311
612
  let onlyQuery = [];
312
- // When inside Visual Builder, fetch all fields (don't use onlyQueries)
313
- if (!isInsideVB) {
613
+ // When inside Studio or Visual Builder, fetch all fields (don't use onlyQueries)
614
+ if (!isInsideEditor) {
314
615
  onlyQuery =
315
616
  staticBindingOnlyQueries[_content_type_uid][entry_uid] || [];
316
617
  // We need locale for redirect to the correct locale.
@@ -345,17 +646,23 @@ function generateSdk(userConfig) {
345
646
  }
346
647
  else {
347
648
  //TODO: Add logger support general to have studio prefix
348
- console.error("Unable to resolve entry", entry.reason);
649
+ if (process.env.NODE_ENV === "development") {
650
+ console.log("Message handling fallback");
651
+ }
349
652
  }
350
653
  }
351
654
  }
352
655
  else {
353
- console.error("Unable to resolve content type", ct_uid, ct_entries.reason);
656
+ if (process.env.NODE_ENV === "development") {
657
+ console.log("Unhandled message case");
658
+ }
354
659
  }
355
660
  }
356
661
  }
357
- catch (err) {
358
- console.error("Error while resolving static data", err);
662
+ catch (error) {
663
+ if (process.env.NODE_ENV === "development") {
664
+ console.error("Error in message listener:", error);
665
+ }
359
666
  }
360
667
  }
361
668
  /**
@@ -364,7 +671,6 @@ function generateSdk(userConfig) {
364
671
  */
365
672
  async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions) {
366
673
  if (!config.stackSdk) {
367
- console.error("Fetching template entry not possible without stackSdk");
368
674
  return;
369
675
  }
370
676
  const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = fetchOptions;
@@ -372,33 +678,182 @@ function generateSdk(userConfig) {
372
678
  return;
373
679
  }
374
680
  const { fetchComposition: _, fetchTemplateEntry: perQueryFetchTemplateEntry, ...resolvedOptions } = compositionQueryOptions || {};
681
+ // Safe access to enhanced options (available only when SDK provides Studio Intelligence)
682
+ const enhancedOptions = compositionQueryOptions; // Type assertion for internal properties
683
+ const _studioIntelligence = enhancedOptions?._studioIntelligence;
375
684
  const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
685
+ const isInsideStudio = clientRendererModeUtil.isInsideStudioFrame();
686
+ // Studio override: when running inside Studio and the iframe URL carries
687
+ // `cs-template-entry-uid`, prefer it over any host-passed `templateEntryUid`.
688
+ // This lets the user pick a preview entry from Studio's navbar that
689
+ // overrides a host-hardcoded UID, while leaving the host's behaviour intact
690
+ // in production (the param is only honored when isInsideStudio).
691
+ //
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
+ }
709
+ }
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;
376
716
  const defaultImpl = async () => {
717
+ // Resolution priority: templateEntryUid > url_metadata path > legacy path
718
+ if (resolvedOptions.templateEntryUid) {
719
+ // Enhanced include queries with Studio Intelligence
720
+ const allIncludeQueries = [
721
+ ...includeQueries,
722
+ ...(_studioIntelligence?.includeReferences || []),
723
+ ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
724
+ const queryOptions = {
725
+ references: allIncludeQueries,
726
+ variantAlias: resolvedOptions.variantAlias,
727
+ // No URL pattern in this branch — pattern locale is N/A.
728
+ locale: resolveLocale(),
729
+ };
730
+ // Smart 'only' parameter handling - only apply in production
731
+ if (!isInsideVB && !isInsideStudio) {
732
+ queryOptions.only = onlyQueries;
733
+ }
734
+ let dataQuery = config.stackSdk
735
+ .ctQuery(connected_content_type, queryOptions)
736
+ .limit(1);
737
+ dataQuery = config.stackSdk.where(dataQuery, "uid", resolvedOptions.templateEntryUid);
738
+ const response = await dataQuery.find().catch((err) => {
739
+ const { errorType, message } = classifyApiError(err);
740
+ const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
741
+ ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
742
+ : errorType;
743
+ throw new ComposableStudioError(finalErrorType, finalErrorType ===
744
+ ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
745
+ ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
746
+ : message, {
747
+ options: fetchOptions,
748
+ response: err,
749
+ statusCode: err?.status || err?.statusCode,
750
+ errorCode: err?.error_code,
751
+ });
752
+ });
753
+ const entries = entriesFromResponse(response);
754
+ if (!entries?.[0]) {
755
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
756
+ contentType: connected_content_type,
757
+ }), {
758
+ contentType: connected_content_type,
759
+ hasStackSdk: !!config.stackSdk,
760
+ compositionQuery,
761
+ options: fetchOptions,
762
+ troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
763
+ });
764
+ }
765
+ return entries[0];
766
+ }
767
+ // Check if we should use url_metadata path
768
+ const parsedMetadata = compositionEntry.url_metadata
769
+ ? parseUrlMetadata(compositionEntry.url_metadata)
770
+ : null;
771
+ if (parsedMetadata && "url" in compositionQuery && compositionQuery.url) {
772
+ // Metadata path: resolve using url_queries + extracted variables
773
+ try {
774
+ // Enhanced include queries with Studio Intelligence
775
+ const allIncludeQueries = [
776
+ ...includeQueries,
777
+ ...(_studioIntelligence?.includeReferences || []),
778
+ ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
779
+ // Smart 'only' parameter handling for onlyQueries
780
+ const finalOnlyQueries = !isInsideVB && !isInsideStudio ? onlyQueries : undefined;
781
+ if (parsedMetadata.url_source ===
782
+ COMPOSITION_PREVIEW_URL_SOURCES.CONTENT_TYPE_URL_PATTERN) {
783
+ // content_type_url_pattern: Direct URL match (no pattern variables).
784
+ let directQuery = config.stackSdk
785
+ .ctQuery(connected_content_type, {
786
+ references: allIncludeQueries,
787
+ variantAlias: resolvedOptions.variantAlias,
788
+ locale: resolveLocale(),
789
+ only: finalOnlyQueries,
790
+ })
791
+ .limit(1);
792
+ directQuery = config.stackSdk.where(directQuery, "url", compositionQuery.url);
793
+ const response = await directQuery.find();
794
+ const entries = entriesFromResponse(response);
795
+ if (entries?.[0]) {
796
+ return entries[0];
797
+ }
798
+ }
799
+ else {
800
+ // Other sources: Use template matching + extracted variables
801
+ if (!compositionEntry.url) {
802
+ throw new Error("Composition entry missing URL pattern for template matching");
803
+ }
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
+ });
809
+ if (matchResult.matched && matchResult.variables) {
810
+ const patternMetadata = matchResult.variables.metadata;
811
+ // Build query using extracted variables and metadata
812
+ const templateQuery = resolveByUrlSource(config.stackSdk, parsedMetadata.url_source, compositionQuery, matchResult.variables, parsedMetadata.url_queries, connected_content_type, {
813
+ references: allIncludeQueries,
814
+ variantAlias: resolvedOptions.variantAlias,
815
+ locale: resolveLocale(patternMetadata.locale),
816
+ branch: patternMetadata.branch,
817
+ environment: patternMetadata.environment,
818
+ only: finalOnlyQueries,
819
+ });
820
+ const response = await templateQuery.find();
821
+ const entries = entriesFromResponse(response);
822
+ if (entries?.[0]) {
823
+ return entries[0];
824
+ }
825
+ }
826
+ }
827
+ }
828
+ catch (metadataError) {
829
+ console.warn("Metadata template resolution failed, falling back to legacy:", metadataError);
830
+ }
831
+ }
832
+ // Legacy path: Original implementation
833
+ // Enhanced include queries with Studio Intelligence
834
+ const allIncludeQueries = [
835
+ ...includeQueries,
836
+ ...(_studioIntelligence?.includeReferences || []),
837
+ ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
377
838
  const queryOptions = {
378
- references: includeQueries,
839
+ references: allIncludeQueries,
379
840
  variantAlias: resolvedOptions.variantAlias,
380
- locale: resolvedOptions.locale || config.locale,
841
+ // No URL pattern in this branch — pattern locale is N/A.
842
+ locale: resolveLocale(),
381
843
  };
382
- if (!isInsideVB) {
844
+ // Smart 'only' parameter handling - only apply in production
845
+ if (!isInsideVB && !isInsideStudio) {
383
846
  queryOptions.only = onlyQueries;
384
847
  }
385
848
  let dataQuery = config.stackSdk
386
849
  .ctQuery(connected_content_type, queryOptions)
387
850
  .limit(1);
388
- // Resolution priority: templateEntryUid > url > first entry
389
- if (resolvedOptions.templateEntryUid) {
390
- dataQuery = config.stackSdk.where(dataQuery, "uid", resolvedOptions.templateEntryUid);
391
- }
392
- else if ("url" in compositionQuery) {
851
+ // Legacy URL matching (note: this is likely incorrect for patterned URLs as mentioned in plan)
852
+ if ("url" in compositionQuery && compositionQuery.url) {
393
853
  dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
394
854
  }
395
855
  const response = await dataQuery.find().catch((err) => {
396
856
  const { errorType, message } = classifyApiError(err);
397
- console.error("SDK Error (connected data):", {
398
- errorType,
399
- message,
400
- originalError: err,
401
- });
402
857
  const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
403
858
  ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
404
859
  : errorType;
@@ -414,10 +869,6 @@ function generateSdk(userConfig) {
414
869
  });
415
870
  const entries = entriesFromResponse(response);
416
871
  if (!entries?.[0]) {
417
- console.error("Preview/Template entry not found", {
418
- contentType: connected_content_type,
419
- compositionQuery,
420
- });
421
872
  throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
422
873
  contentType: connected_content_type,
423
874
  }), {
@@ -439,7 +890,7 @@ function generateSdk(userConfig) {
439
890
  connectedContentType: connected_content_type,
440
891
  options: resolvedOptions,
441
892
  includeReferences: includeQueries,
442
- only: isInsideVB ? [] : onlyQueries,
893
+ only: isInsideStudio || isInsideVB ? [] : onlyQueries,
443
894
  stackSdk: config.stackSdk.sdk,
444
895
  defaultFetch: defaultImpl,
445
896
  });
@@ -451,6 +902,12 @@ function generateSdk(userConfig) {
451
902
  }
452
903
  else {
453
904
  entry = await defaultImpl();
905
+ // Check if defaultImpl returned empty/null entry (e.g., empty entry list from API)
906
+ if (!entry) {
907
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
908
+ contentType: connected_content_type,
909
+ }));
910
+ }
454
911
  }
455
912
  if (config.cslp.appendTags) {
456
913
  addEditableTags(entry, connected_content_type, true, entry.locale);
@@ -459,49 +916,537 @@ function generateSdk(userConfig) {
459
916
  if (!isCompositionBeingEdited(fetchOptions?.composableUid || ""))
460
917
  return;
461
918
  }
462
- async function fetchData(compositionEntry, queryOptions, options) {
919
+ async function fetchData(compositionEntry, queryOptions, options, sectionEntries = []) {
463
920
  const { variantAlias, locale } = options || {};
464
- const { templateReferencesPath, templateOnlyKeys, contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, } = getEntriesQueries(compositionEntry, compositionEntry.connected_content_type || "", options);
921
+ // Read all saved reference include paths from compositionEntry.data_sources.resolvedReferences.
922
+ // Covers toggle ON paths, directly-bound field paths, and condition block binding paths.
923
+ // Works in both embedded and standalone modes — compositionEntry is always present.
924
+ // Restores what the April 9 refactor removed (generateQueryDetails referencePaths) but safely:
925
+ // resolvedReferences contains only validated reference paths, never inferred tree paths.
926
+ const rawDataSources = (() => {
927
+ try {
928
+ const raw = compositionEntry.data_sources;
929
+ return Array.isArray(raw)
930
+ ? raw
931
+ : Object.values(typeof raw === "string" ? JSON.parse(raw) : (raw ?? {}));
932
+ }
933
+ catch {
934
+ return [];
935
+ }
936
+ })();
937
+ const extendQuery = {
938
+ ...(options?.extendQuery ?? {}),
939
+ };
940
+ // Sanitize resolvedReferences paths before injecting into CDA include[].
941
+ // Filters: pure numeric segments (picker-tree array indexes like "entries.0.cross_links")
942
+ // and modular-block numeric prefixes ("2_block_1" → "block_1").
943
+ // Applied uniformly to contentstack, template, and query DS paths.
944
+ const sanitizeResolvedPaths = (paths) => [
945
+ ...new Set(paths
946
+ .filter((p) => typeof p === "string" && p.trim().length > 0)
947
+ .map((p) => {
948
+ const segments = p.split(".").filter(Boolean);
949
+ const result = [];
950
+ for (let i = 0; i < segments.length; i++) {
951
+ const stripped = segments[i].replace(/^\d+_/, ""); // strip modular-block prefix
952
+ // Skip pure numeric array indexes and "entries" array-wrapper segments —
953
+ // neither is a valid Contentstack include[] field name.
954
+ if (/^\d+$/.test(stripped) || stripped === "entries") {
955
+ continue;
956
+ }
957
+ result.push(stripped);
958
+ }
959
+ return result.join(".");
960
+ })
961
+ .filter((p) => p.length > 0)),
962
+ ];
963
+ // Static entries (contentstack DS) → extendQuery[ctUid].includeReferences
964
+ const csDS = rawDataSources.find((ds) => ds.uid === DATA_SOURCES.CONTENTSTACK);
965
+ if (csDS?.resolvedReferences && Array.isArray(csDS.data)) {
966
+ for (const entry of csDS.data) {
967
+ const raw = csDS.resolvedReferences[entry.uid] ?? [];
968
+ const paths = sanitizeResolvedPaths(raw);
969
+ if (!paths.length)
970
+ continue;
971
+ const ct = entry._content_type_uid;
972
+ if (!extendQuery[ct])
973
+ extendQuery[ct] = { includeReferences: [] };
974
+ extendQuery[ct].includeReferences = [
975
+ ...new Set([...(extendQuery[ct].includeReferences ?? []), ...paths]),
976
+ ];
977
+ }
978
+ }
979
+ // Template entry (contentstackPreview DS) → extendQuery[connectedContentTypeUid].includeReferences
980
+ // Now safe to inject because sanitizeResolvedPaths filters out picker-tree
981
+ // tracking paths (pure numeric indexes) before they reach the CDA query.
982
+ const connectedContentTypeUid = compositionEntry.connected_content_type || "";
983
+ const previewDS = rawDataSources.find((ds) => ds.uid === DATA_SOURCES.TEMPLATE);
984
+ if (previewDS?.resolvedReferences && connectedContentTypeUid) {
985
+ const previewPaths = sanitizeResolvedPaths(Object.values(previewDS.resolvedReferences).flat());
986
+ if (previewPaths.length) {
987
+ if (!extendQuery[connectedContentTypeUid])
988
+ extendQuery[connectedContentTypeUid] = { includeReferences: [] };
989
+ extendQuery[connectedContentTypeUid].includeReferences = [
990
+ ...new Set([
991
+ ...(extendQuery[connectedContentTypeUid].includeReferences ?? []),
992
+ ...previewPaths,
993
+ ]),
994
+ ];
995
+ }
996
+ }
997
+ const resolvedOptions = { ...options, extendQuery };
998
+ const { templateReferencesPath, templateOnlyKeys, contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, } = getEntriesQueries(compositionEntry, connectedContentTypeUid, resolvedOptions);
999
+ // When inside Studio, ensure ALL configured contentstack DS entries are in
1000
+ // contentstackEntriesReferencesPath — not just those with active bindings.
1001
+ // Entries without bindings are still shown in Studio's data picker and must
1002
+ // be fetched with their saved resolvedReferences include paths so that
1003
+ // isResolutionFresh() returns true and Studio skips its own CMA call.
1004
+ if (clientRendererModeUtil.isInsideStudioFrame() &&
1005
+ csDS?.data &&
1006
+ Array.isArray(csDS.data)) {
1007
+ for (const entry of csDS.data) {
1008
+ const { uid, _content_type_uid } = entry;
1009
+ if (!uid || !_content_type_uid)
1010
+ continue;
1011
+ if (contentstackEntriesReferencesPath[_content_type_uid]?.[uid] !==
1012
+ undefined)
1013
+ continue;
1014
+ const paths = sanitizeResolvedPaths(csDS.resolvedReferences?.[uid] ?? []);
1015
+ if (!contentstackEntriesReferencesPath[_content_type_uid]) {
1016
+ contentstackEntriesReferencesPath[_content_type_uid] = {};
1017
+ }
1018
+ contentstackEntriesReferencesPath[_content_type_uid][uid] = paths;
1019
+ // Also ensure the onlyKeys slot exists (empty = fetch all fields, correct for Studio)
1020
+ if (!contentstackEntriesOnlyKeys[_content_type_uid]) {
1021
+ contentstackEntriesOnlyKeys[_content_type_uid] = {};
1022
+ }
1023
+ if (!contentstackEntriesOnlyKeys[_content_type_uid][uid]) {
1024
+ contentstackEntriesOnlyKeys[_content_type_uid][uid] = [];
1025
+ }
1026
+ }
1027
+ }
1028
+ // The page composition's `static_value` lives at the top level; each
1029
+ // section composition's own `static_value` is carried per-instance via
1030
+ // `section_scoped_data[instanceUid].static_value` (built below) and
1031
+ // overlaid by SectionCompositionProvider inside the section subtree. This
1032
+ // keeps section keys scoped to their own subtree — siblings and the page
1033
+ // can't read each other's keys through `data.static_value`.
1034
+ // Surface the page composition's own `external_data` JSON as
1035
+ // `spec.data.component_props`. useDataWithSpec uses this as the fallback
1036
+ // when the consumer's `<StudioComponent componentProps={...} />`
1037
+ // doesn't supply state — and SectionCompositionProvider merges it under
1038
+ // each section's `componentPropsFallback` (page wins per top-level
1039
+ // key). The Studio editor's `useFetchCurrentUI` does the same injection
1040
+ // for the editor canvas; this branch keeps the SDK runtime in sync.
1041
+ const pageExternalProps = parseExternalDataForComponentProps(compositionEntry.data_sources);
465
1042
  const data = {
466
1043
  [DATA_SOURCES_PREFIX]: {},
467
1044
  [DATA_SOURCES.STATIC_VALUE]: preProcessStaticValues(compositionEntry.static_value || {}),
1045
+ ...(pageExternalProps ? { component_props: pageExternalProps } : {}),
468
1046
  };
1047
+ const templateContentTypeUid = getTemplateContentTypeForComposition(compositionEntry);
1048
+ // Build merged entry-reference paths covering page + all section data
1049
+ // sources, with unioned include[] per (ct_uid, entry_uid).
1050
+ const mergedRefs = JSON.parse(JSON.stringify(contentstackEntriesReferencesPath));
1051
+ const mergedOnly = JSON.parse(JSON.stringify(contentstackEntriesOnlyKeys));
1052
+ for (const section of sectionEntries) {
1053
+ // SectionCompositionEntry has ui: Node (already parsed). getEntriesQueries
1054
+ // expects ui as a string so decompressSpec can parse it — re-serialize here.
1055
+ const sectionAsCompositionEntry = {
1056
+ ...section,
1057
+ ui: typeof section.ui === "string"
1058
+ ? section.ui
1059
+ : JSON.stringify(section.ui),
1060
+ };
1061
+ const sectionRefs = getEntriesQueries(sectionAsCompositionEntry, config.contentTypeUid, resolvedOptions);
1062
+ // Union refs per ct_uid:entry_uid
1063
+ for (const ctUid of Object.keys(sectionRefs.contentstackEntriesReferencesPath)) {
1064
+ if (!mergedRefs[ctUid])
1065
+ mergedRefs[ctUid] = {};
1066
+ for (const entryUid of Object.keys(sectionRefs.contentstackEntriesReferencesPath[ctUid])) {
1067
+ const existing = mergedRefs[ctUid][entryUid] ?? [];
1068
+ const incoming = sectionRefs.contentstackEntriesReferencesPath[ctUid][entryUid];
1069
+ mergedRefs[ctUid][entryUid] = Array.from(new Set([...existing, ...incoming]));
1070
+ }
1071
+ }
1072
+ // Union onlyKeys
1073
+ for (const ctUid of Object.keys(sectionRefs.contentstackEntriesOnlyKeys)) {
1074
+ if (!mergedOnly[ctUid])
1075
+ mergedOnly[ctUid] = {};
1076
+ for (const entryUid of Object.keys(sectionRefs.contentstackEntriesOnlyKeys[ctUid])) {
1077
+ const existing = mergedOnly[ctUid][entryUid] ?? [];
1078
+ const incoming = sectionRefs.contentstackEntriesOnlyKeys[ctUid][entryUid];
1079
+ const seen = new Set(existing.map((p) => p.join("|")));
1080
+ for (const p of incoming) {
1081
+ const sig = p.join("|");
1082
+ if (!seen.has(sig)) {
1083
+ existing.push(p);
1084
+ seen.add(sig);
1085
+ }
1086
+ }
1087
+ mergedOnly[ctUid][entryUid] = existing;
1088
+ }
1089
+ }
1090
+ }
469
1091
  await Promise.all([
470
1092
  fetchTemplateEntry({
471
- connected_content_type: compositionEntry.connected_content_type || "",
1093
+ connected_content_type: templateContentTypeUid,
472
1094
  compositionQuery: queryOptions,
473
1095
  includeQueries: templateReferencesPath,
474
1096
  onlyQueries: templateOnlyKeys,
475
1097
  composableUid: compositionEntry.composable_uid,
476
- }, data, compositionEntry, options),
477
- resolveStaticData(contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, data, {
1098
+ }, data, compositionEntry, resolvedOptions),
1099
+ resolveStaticData(mergedRefs, mergedOnly, data, {
478
1100
  variantAlias: variantAlias,
479
1101
  locale: locale,
480
1102
  }),
481
1103
  resolveQueryData(compositionEntry, data, {
482
1104
  variantAlias,
483
1105
  locale: locale || config.locale,
1106
+ sectionEntries,
484
1107
  }),
485
1108
  ]);
1109
+ attachSectionCompositionContexts(data, compositionEntry, sectionEntries);
1110
+ // NEW: build per-instance scoped data sources and attach to spec.
1111
+ // Convert the sectionEntries array to a Map<compositionUid, entry> for collectAllDataNeeds.
1112
+ const sectionEntriesMap = new Map(sectionEntries.map((sec) => [sec.uid, sec]));
1113
+ const pageUi = typeof compositionEntry.ui === "string"
1114
+ ? decompressSpec(compositionEntry.ui)
1115
+ : compositionEntry.ui;
1116
+ const { needsBySection } = collectAllDataNeeds(compositionEntry, pageUi, sectionEntriesMap);
1117
+ // Build per-section-composition maps of (entryUid -> poolKey) and
1118
+ // (queryUid -> stableHash) by re-parsing each section's data_sources.
1119
+ // Pool key format matches what setStaticEntryInDS uses: `${ct_uid}:${entry_uid}`.
1120
+ const compEntryDsToPoolKey = new Map();
1121
+ const compQueryDsToPoolKey = new Map();
1122
+ for (const sec of sectionEntries) {
1123
+ const entryMap = new Map();
1124
+ const queryMap = new Map();
1125
+ try {
1126
+ const parsed = JSON.parse(sec.data_sources ?? "[]");
1127
+ const list = Array.isArray(parsed)
1128
+ ? parsed
1129
+ : Object.values(parsed);
1130
+ for (const ds of list) {
1131
+ if (ds?.uid === "contentstack") {
1132
+ // Support both { data: { entries: [...] } } and legacy { data: [...] } formats.
1133
+ const rawEntries = Array.isArray(ds.data?.entries)
1134
+ ? ds.data.entries
1135
+ : Array.isArray(ds.data)
1136
+ ? ds.data
1137
+ : [];
1138
+ for (const e of rawEntries) {
1139
+ const ct = e.content_type_uid ?? e._content_type_uid;
1140
+ if (ct && e.uid)
1141
+ entryMap.set(e.uid, `${ct}:${e.uid}`);
1142
+ }
1143
+ }
1144
+ if (ds?.uid === "queries" ||
1145
+ ds?.uid === DATA_SOURCES.QUERY ||
1146
+ ds?.id === DATA_SOURCES.QUERY) {
1147
+ const items = Array.isArray(ds.data)
1148
+ ? ds.data
1149
+ : (ds.data?.queries ?? []);
1150
+ for (const q of items) {
1151
+ if (q?.uid && q?.spec)
1152
+ queryMap.set(q.uid, stableHashQuery(q.spec));
1153
+ }
1154
+ }
1155
+ }
1156
+ }
1157
+ catch {
1158
+ // malformed JSON — skip; already logged in collectAllDataNeeds
1159
+ }
1160
+ compEntryDsToPoolKey.set(sec.uid, entryMap);
1161
+ compQueryDsToPoolKey.set(sec.uid, queryMap);
1162
+ }
1163
+ // Per-section-composition map of preprocessed `static_value` (key -> value),
1164
+ // mirroring the page-level path at lines ~1503. Without this, static_value
1165
+ // bindings inside a section subtree fall through at runtime to component
1166
+ // defaults — the editor renders them only because it loads the entire
1167
+ // section composition (including its static_value) into scope.
1168
+ const compStaticValue = new Map();
1169
+ for (const sec of sectionEntries) {
1170
+ compStaticValue.set(sec.uid, preProcessStaticValues(sec.static_value || {}));
1171
+ }
1172
+ // Build per-instance pool-key maps from per-section-composition maps.
1173
+ const instanceEntryDs = new Map();
1174
+ const instanceQueryDs = new Map();
1175
+ const instanceStaticValue = new Map();
1176
+ walkUiForCompositionMapping(pageUi, (instanceUid, compositionUid) => {
1177
+ const e = compEntryDsToPoolKey.get(compositionUid);
1178
+ const q = compQueryDsToPoolKey.get(compositionUid);
1179
+ const sv = compStaticValue.get(compositionUid);
1180
+ if (e)
1181
+ instanceEntryDs.set(instanceUid, e);
1182
+ if (q)
1183
+ instanceQueryDs.set(instanceUid, q);
1184
+ if (sv)
1185
+ instanceStaticValue.set(instanceUid, sv);
1186
+ });
1187
+ // data.dataSources.contentstack is already keyed by pool key (`${ct_uid}:${uid}`).
1188
+ // Entries by pool key map is the contentstack data source itself.
1189
+ const csEntries = data.dataSources?.contentstack ?? {};
1190
+ const entriesByKey = new Map(Object.entries(csEntries));
1191
+ // Build queriesByKey (hash -> result) by combining page + section query uid->hash maps.
1192
+ const queriesByKey = new Map();
1193
+ const csQueries = data.dataSources?.contentstack_queries ?? {};
1194
+ // Helper: walk a dsUid->hash map, look up result in contentstack_queries by dsUid,
1195
+ // then store in queriesByKey keyed by hash.
1196
+ const recordQueryFromDsMap = (dsMap) => {
1197
+ for (const [dsUid, poolKey] of dsMap.entries()) {
1198
+ const q = csQueries[dsUid];
1199
+ if (q !== undefined)
1200
+ queriesByKey.set(poolKey, q);
1201
+ }
1202
+ };
1203
+ // Page's own queries:
1204
+ try {
1205
+ const parsed = JSON.parse(compositionEntry.data_sources ?? "[]");
1206
+ const list = Array.isArray(parsed)
1207
+ ? parsed
1208
+ : Object.values(parsed);
1209
+ const pageQueryMap = new Map();
1210
+ for (const ds of list) {
1211
+ if (ds?.uid === "queries" ||
1212
+ ds?.uid === DATA_SOURCES.QUERY ||
1213
+ ds?.id === DATA_SOURCES.QUERY) {
1214
+ const items = Array.isArray(ds.data)
1215
+ ? ds.data
1216
+ : (ds.data?.queries ?? []);
1217
+ for (const q of items) {
1218
+ if (q?.uid && q?.spec)
1219
+ pageQueryMap.set(q.uid, stableHashQuery(q.spec));
1220
+ }
1221
+ }
1222
+ }
1223
+ recordQueryFromDsMap(pageQueryMap);
1224
+ }
1225
+ catch {
1226
+ // ignore — page data_sources already parsed earlier
1227
+ }
1228
+ for (const [, dsMap] of instanceQueryDs.entries())
1229
+ recordQueryFromDsMap(dsMap);
1230
+ const scoped = buildScopedDataSources({
1231
+ entriesByKey,
1232
+ queriesByKey,
1233
+ sectionEntryDsToPoolKey: instanceEntryDs,
1234
+ sectionQueryDsToPoolKey: instanceQueryDs,
1235
+ sectionStaticValueByInstance: instanceStaticValue,
1236
+ }, needsBySection, data.dataSources);
1237
+ data.section_scoped_data = scoped;
486
1238
  return data;
487
1239
  }
488
- async function fetchSpec(queryOptions, options) {
1240
+ async function fetchSpec(queryOptions, options, skipComponentLoading = false) {
489
1241
  if (!config.stackSdk) {
490
1242
  throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
491
1243
  }
492
- const { compositionEntry, symbolEntries } = await fetchComposition(config, queryOptions, options);
493
- const data = await fetchData(compositionEntry, queryOptions, options);
1244
+ // Phase 1: Get Studio Intelligence if available (graceful fallback)
1245
+ const studioIntelligence = await StudioIntelligenceManager.getStudioIntelligence(options, config);
1246
+ // Phase 2: Enhance options with Studio Intelligence (preserves user preferences)
1247
+ const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
1248
+ // Phase 3: Fetch with enhanced context (preserves custom fetchers)
1249
+ const { compositionEntry, symbolEntries, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions);
494
1250
  const ui = typeof compositionEntry.ui === "string"
495
1251
  ? decompressSpec(compositionEntry.ui)
496
1252
  : compositionEntry.ui;
1253
+ const sectionEntries = await getAllSectionCompositions(config, compositionEntry, enhancedOptions);
1254
+ const allSymbolEntries = [...symbolEntries];
1255
+ const seenSymbolUids = new Set(symbolEntries.map((symbol) => symbol.uid));
1256
+ for (const sectionEntry of sectionEntries.values()) {
1257
+ getAllSymbols(sectionEntry).forEach((symbol) => {
1258
+ if (seenSymbolUids.has(symbol.uid))
1259
+ return;
1260
+ seenSymbolUids.add(symbol.uid);
1261
+ allSymbolEntries.push(symbol);
1262
+ });
1263
+ }
1264
+ const data = await fetchData(compositionEntry, queryOptions, enhancedOptions, Array.from(sectionEntries.values()));
1265
+ // Lazy loading and SSR validation for production mode
1266
+ // Skip if called from fetchMultipleSpecs (which handles loading in batch)
1267
+ const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
1268
+ // 1.3.0 rendering contract: server returns the spec as data only. The
1269
+ // renderer is `"use client"` and runs entirely on the client — that's
1270
+ // where registry-vs-spec validation belongs. Running it server-side
1271
+ // forces consumers to make their registration module server-evaluable,
1272
+ // which means dragging `"use client"` components into the server module
1273
+ // graph — exactly the failure mode the RFC asks us to avoid.
1274
+ const isServer = typeof window === "undefined";
1275
+ if (!isServer && isProductionMode && ui && !skipComponentLoading) {
1276
+ const componentRegistry = getComponentRegistryInstance();
1277
+ // SSR VALIDATION: Check if all required components are registered
1278
+ // Built-in components should be registered automatically when @contentstack/studio-react is imported
1279
+ const usedComponents = analyzeUsedComponents(ui);
1280
+ const sectionComponentTypes = new Set(sectionEntries.keys());
1281
+ const missingBuiltInComponents = [];
1282
+ const missingCustomComponents = [];
1283
+ usedComponents.forEach((type) => {
1284
+ if (sectionComponentTypes.has(type)) {
1285
+ return;
1286
+ }
1287
+ if (!componentRegistry.hasComponentLoader(type)) {
1288
+ if (INTERNAL_COMPONENT_TYPES.includes(type)) {
1289
+ missingBuiltInComponents.push(type);
1290
+ }
1291
+ else {
1292
+ missingCustomComponents.push(type);
1293
+ }
1294
+ }
1295
+ });
1296
+ // Handle missing internal components (SDK import issue)
1297
+ if (missingBuiltInComponents.length > 0) {
1298
+ const errorMessage = [
1299
+ `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
1300
+ "",
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.",
1309
+ "",
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);",
1316
+ ].join("\n");
1317
+ throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
1318
+ }
1319
+ // Handle missing custom components (normal - user needs to register)
1320
+ if (missingCustomComponents.length > 0) {
1321
+ const errorMessage = [
1322
+ `[Composable Studio SDK] Custom components not registered: ${missingCustomComponents.join(", ")}`,
1323
+ "",
1324
+ "This error occurs when fetchSpec() is called before custom components are registered.",
1325
+ "In SSR environments, ensure all registerComponent() calls complete before fetchSpec().",
1326
+ "",
1327
+ "Fix: Import your component registry module at the top of your server file:",
1328
+ ' import "./components/registry"; // Register custom components',
1329
+ " const spec = await fetchSpec({ ... }); // Now safe to use",
1330
+ "",
1331
+ ].join("\n");
1332
+ throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
1333
+ }
1334
+ // Load the components
1335
+ try {
1336
+ await componentRegistry.loadComponents(Array.from(usedComponents));
1337
+ }
1338
+ catch (error) {
1339
+ console.error("Error loading components lazily:", error);
1340
+ throw error; // Re-throw to surface the actual loading error
1341
+ }
1342
+ }
497
1343
  return {
498
1344
  data,
499
1345
  ui,
500
1346
  compositionEntry,
501
- symbols: symbolEntries,
502
- config: getLightConfig(),
1347
+ symbols: allSymbolEntries,
1348
+ sectionCompositions: Array.from(sectionEntries.values()),
1349
+ // Studio-only resolution diagnostics (URL metadata path); undefined otherwise.
1350
+ urlResolution,
1351
+ config: {
1352
+ ...getLightConfig(),
1353
+ // Debug information for compatibility checking (type assertion for internal properties)
1354
+ _studioEnhanced: enhancedOptions._enhancementMode === "studio-aware",
1355
+ _enhancementMode: enhancedOptions._enhancementMode,
1356
+ },
503
1357
  };
504
1358
  }
1359
+ async function fetchMultipleSpecs(queries, options) {
1360
+ if (!config.stackSdk) {
1361
+ throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
1362
+ }
1363
+ // Fetch all specs in parallel (skip individual component loading)
1364
+ const specs = await Promise.all(queries.map((query) => fetchSpec(query, options, true)));
1365
+ // In production mode, perform union analysis and load components once.
1366
+ // Gated to client-only — see the equivalent block in `fetchSpec` for the
1367
+ // 1.3.0-contract reasoning (server returns spec as data; validation belongs
1368
+ // on the client where the renderer actually runs).
1369
+ const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
1370
+ const isServer = typeof window === "undefined";
1371
+ if (!isServer && isProductionMode) {
1372
+ const componentRegistry = getComponentRegistryInstance();
1373
+ // Collect all unique component types from all specs
1374
+ // Built-in components should be registered automatically when @contentstack/studio-react is imported
1375
+ const allComponents = new Set();
1376
+ const allSectionComponents = new Set();
1377
+ specs.forEach((spec) => {
1378
+ if (spec.ui) {
1379
+ const components = analyzeUsedComponents(spec.ui);
1380
+ components.forEach((c) => allComponents.add(c));
1381
+ }
1382
+ spec.sectionCompositions?.forEach((section) => allSectionComponents.add(section.uid));
1383
+ });
1384
+ // SSR VALIDATION: Check if all required components are registered
1385
+ const missingBuiltInComponents = [];
1386
+ const missingCustomComponents = [];
1387
+ allComponents.forEach((type) => {
1388
+ if (allSectionComponents.has(type)) {
1389
+ return;
1390
+ }
1391
+ if (!componentRegistry.hasComponentLoader(type)) {
1392
+ if (INTERNAL_COMPONENT_TYPES.includes(type)) {
1393
+ missingBuiltInComponents.push(type);
1394
+ }
1395
+ else {
1396
+ missingCustomComponents.push(type);
1397
+ }
1398
+ }
1399
+ });
1400
+ // Handle missing internal components (SDK import issue)
1401
+ if (missingBuiltInComponents.length > 0) {
1402
+ const errorMessage = [
1403
+ `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
1404
+ "",
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";',
1417
+ "",
1418
+ " const components = getBasicComponents({ csDesignTokens: getDefaultDesignTokens() });",
1419
+ " registerComponents(components);",
1420
+ ].join("\n");
1421
+ throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
1422
+ }
1423
+ // Handle missing custom components (normal - user needs to register)
1424
+ if (missingCustomComponents.length > 0) {
1425
+ const errorMessage = [
1426
+ `[Composable Studio SDK] Custom components not registered: ${missingCustomComponents.join(", ")}`,
1427
+ "",
1428
+ "This error occurs when fetchMultipleSpecs() is called before custom components are registered.",
1429
+ "In SSR environments, ensure all registerComponent() calls complete before fetchMultipleSpecs().",
1430
+ "",
1431
+ "Fix: Import your component registry module at the top of your server file:",
1432
+ ' import "./components/registry"; // Register custom components',
1433
+ " const specs = await fetchMultipleSpecs([...]); // Now safe to use",
1434
+ "",
1435
+ `Missing components: ${missingCustomComponents.join(", ")}`,
1436
+ ].join("\n");
1437
+ throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
1438
+ }
1439
+ // Load all unique components in parallel (deduplication happens automatically)
1440
+ try {
1441
+ await componentRegistry.loadComponents(Array.from(allComponents));
1442
+ }
1443
+ catch (error) {
1444
+ console.error("Error loading components for multiple specs:", error);
1445
+ throw error; // Re-throw to surface the actual loading error
1446
+ }
1447
+ }
1448
+ return specs;
1449
+ }
505
1450
  /**
506
1451
  * Reusable helper to fetch data from Contentstack
507
1452
  * Now uses QueryExecutor internally to support full QuerySpec with filters, sorting, etc.
@@ -512,7 +1457,6 @@ function generateSdk(userConfig) {
512
1457
  */
513
1458
  async function fetchContentstackData(querySpec, context = {}, options) {
514
1459
  if (!config.stackSdk) {
515
- console.warn("Stack SDK not available for fetchContentstackData");
516
1460
  return { entries: [], count: 0 };
517
1461
  }
518
1462
  try {
@@ -536,30 +1480,87 @@ function generateSdk(userConfig) {
536
1480
  count: count,
537
1481
  };
538
1482
  }
539
- catch (err) {
540
- console.error(`[SDK] Failed to fetch data for ${querySpec.contentType}`, err);
1483
+ catch (error) {
1484
+ if (process.env.NODE_ENV === "development") {
1485
+ console.error("Error resolving query data:", error);
1486
+ }
541
1487
  return { entries: [], count: 0 };
542
1488
  }
543
1489
  }
544
1490
  async function resolveQueryData(compositionEntry, data, options) {
545
- if (!compositionEntry.data_sources) {
546
- return;
547
- }
548
- let dataSources = [];
549
- try {
550
- const parsed = JSON.parse(compositionEntry.data_sources);
551
- dataSources = Array.isArray(parsed) ? parsed : Object.values(parsed);
1491
+ // Parse page data_sources (may be absent — sections may still declare queries).
1492
+ let pageDataSources = [];
1493
+ if (compositionEntry.data_sources) {
1494
+ try {
1495
+ const parsed = JSON.parse(compositionEntry.data_sources);
1496
+ pageDataSources = Array.isArray(parsed)
1497
+ ? parsed
1498
+ : Object.values(parsed);
1499
+ }
1500
+ catch (error) {
1501
+ if (process.env.NODE_ENV === "development") {
1502
+ console.error("Error parsing data sources JSON:", error);
1503
+ }
1504
+ }
552
1505
  }
553
- catch (e) {
554
- console.warn("[SDK] Failed to parse data_sources from composition", e);
555
- return;
1506
+ const queriesDS = pageDataSources.find((ds) => ds.uid === DATA_SOURCES.QUERY || ds.id === DATA_SOURCES.QUERY);
1507
+ // Page-side queries (may be empty if page declares no queries).
1508
+ let queries = [];
1509
+ if (queriesDS) {
1510
+ const raw = queriesDS.data || queriesDS.queries || [];
1511
+ if (Array.isArray(raw))
1512
+ queries = raw;
556
1513
  }
557
- const queriesDS = dataSources.find((ds) => ds.uid === "contentstack_queries" || ds.id === "contentstack_queries");
558
- if (!queriesDS || !queriesDS.data) {
559
- return;
1514
+ // Stable-hash dedup across page queries + section queries.
1515
+ // We also track every uid (alias) that maps to a given hash so the
1516
+ // single resolved result can be fanned out to all of them — section
1517
+ // instances bind by their own data_source uid, which differs from
1518
+ // the page's, and section_scoped_data lookups go via uid.
1519
+ const queryDeduper = new Map();
1520
+ const aliasesByHash = new Map();
1521
+ const seedFromQueries = (items) => {
1522
+ for (const item of items) {
1523
+ if (!item?.spec || !item?.uid)
1524
+ continue;
1525
+ const hash = stableHashQuery(item.spec);
1526
+ if (!queryDeduper.has(hash))
1527
+ queryDeduper.set(hash, item);
1528
+ const aliases = aliasesByHash.get(hash) ?? [];
1529
+ if (!aliases.includes(item.uid))
1530
+ aliases.push(item.uid);
1531
+ aliasesByHash.set(hash, aliases);
1532
+ }
1533
+ };
1534
+ seedFromQueries(queries);
1535
+ // Aggregate resolvedReferences across page + section query data sources.
1536
+ const queriesResolvedRefs = {
1537
+ ...((queriesDS && queriesDS.resolvedReferences) || {}),
1538
+ };
1539
+ for (const sec of options?.sectionEntries ?? []) {
1540
+ try {
1541
+ const parsed = JSON.parse(sec.data_sources);
1542
+ const list = Array.isArray(parsed) ? parsed : Object.values(parsed);
1543
+ const qDs = list.find((d) => d?.uid === DATA_SOURCES.QUERY ||
1544
+ d?.uid === "queries" ||
1545
+ d?.id === DATA_SOURCES.QUERY);
1546
+ if (qDs) {
1547
+ const items = Array.isArray(qDs.data)
1548
+ ? qDs.data
1549
+ : (qDs.data?.queries ?? []);
1550
+ seedFromQueries(items);
1551
+ // Merge section's per-query resolvedReferences as well.
1552
+ if (qDs.resolvedReferences) {
1553
+ Object.assign(queriesResolvedRefs, qDs.resolvedReferences);
1554
+ }
1555
+ }
1556
+ }
1557
+ catch {
1558
+ /* per-section JSON failure already logged in collect-data-needs */
1559
+ }
560
1560
  }
561
- const queries = queriesDS.data || queriesDS.queries || [];
562
- if (!Array.isArray(queries))
1561
+ const dedupedQueries = Array.from(queryDeduper.values());
1562
+ // Nothing to resolve (neither page nor any section declared a query).
1563
+ if (dedupedQueries.length === 0)
563
1564
  return;
564
1565
  const queryResults = {};
565
1566
  // Build RuntimeContext for expression resolution
@@ -579,14 +1580,59 @@ function generateSdk(userConfig) {
579
1580
  },
580
1581
  // NO componentProps or user context - expressions only support URL params and time
581
1582
  };
582
- await Promise.all(queries.map(async (queryConfig) => {
1583
+ await Promise.all(dedupedQueries.map(async (queryConfig) => {
583
1584
  const { uid, spec } = queryConfig;
584
1585
  if (!uid || !spec?.contentType)
585
1586
  return;
586
- // Use fetchContentstackData with full QuerySpec
587
- // This now uses QueryExecutor internally to support filters, sorting, etc.
588
- const result = await fetchContentstackData(spec, context, options);
589
- queryResults[uid] = result;
1587
+ // Merge toggle/binding-driven include paths from resolvedReferences into the query spec.
1588
+ // QueryExecutor reads spec.params.include via normalizeReferenceIncludeParam → includeReference().
1589
+ const togglePaths = (queriesResolvedRefs[uid] ?? [])
1590
+ .map((p) => p
1591
+ .split(".")
1592
+ .filter((s) => !/^\d+$/.test(s) && s !== "entries")
1593
+ .join("."))
1594
+ .filter(Boolean);
1595
+ // When inside Studio, add editor params so the delivery SDK (preview API)
1596
+ // returns unpublished entries and full field metadata — matching CMA richness.
1597
+ // Studio's isResolutionFresh then sees non-empty entries and skips its CMA call.
1598
+ const isInsideStudio = clientRendererModeUtil.isInsideStudioFrame();
1599
+ const studioParams = isInsideStudio
1600
+ ? {
1601
+ include_publish_details: true,
1602
+ include_unpublished: true,
1603
+ include_fields: true,
1604
+ }
1605
+ : {};
1606
+ const needsMerge = togglePaths.length > 0 || Object.keys(studioParams).length > 0;
1607
+ const mergedSpec = needsMerge
1608
+ ? {
1609
+ ...spec,
1610
+ params: {
1611
+ ...studioParams,
1612
+ ...(spec.params ?? {}),
1613
+ ...(togglePaths.length
1614
+ ? {
1615
+ include: [
1616
+ ...new Set([
1617
+ ...(Array.isArray(spec.params?.include)
1618
+ ? spec.params.include
1619
+ : []),
1620
+ ...togglePaths,
1621
+ ]),
1622
+ ],
1623
+ }
1624
+ : {}),
1625
+ },
1626
+ }
1627
+ : spec;
1628
+ const result = await fetchContentstackData(mergedSpec, context, options);
1629
+ // Fan out result to every uid that resolved to this query spec
1630
+ // (page's data_source uid + each section instance's data_source uid).
1631
+ const hash = stableHashQuery(spec);
1632
+ const aliases = aliasesByHash.get(hash) ?? [uid];
1633
+ for (const alias of aliases) {
1634
+ queryResults[alias] = result;
1635
+ }
590
1636
  }));
591
1637
  if (!data.dataSources[DATA_SOURCES.QUERY]) {
592
1638
  data.dataSources[DATA_SOURCES.QUERY] = {};
@@ -599,7 +1645,7 @@ function generateSdk(userConfig) {
599
1645
  function getSeoMetadata(ui) {
600
1646
  return ui.metadata.seo || null;
601
1647
  }
602
- return {
1648
+ const sdkSingleton = {
603
1649
  internal: {
604
1650
  getConfig() {
605
1651
  return config;
@@ -608,6 +1654,7 @@ function generateSdk(userConfig) {
608
1654
  // Once we fetch the data, we need to perform certain operation to store the UI and data.
609
1655
  // Hence, we moved this to the internal method.
610
1656
  fetchSpec,
1657
+ fetchMultipleSpecs,
611
1658
  fetchData,
612
1659
  fetchTemplateEntry,
613
1660
  getSeoMetadata,
@@ -690,19 +1737,32 @@ function generateSdk(userConfig) {
690
1737
  getConfig: getLightConfig,
691
1738
  },
692
1739
  };
1740
+ // 🚀 RESTORED: Send INIT_STUDIO immediately like the original handshake (synchronous)
1741
+ if (typeof window !== "undefined") {
1742
+ if (clientRendererModeUtil.isInsideStudioFrame()) {
1743
+ // Inside Studio iframe - send INIT_STUDIO
1744
+ sendInitStudioSignal(config);
1745
+ }
1746
+ else if (clientRendererModeUtil.isInsideIframe()) {
1747
+ // Inside preview iframe - send INIT_STUDIO
1748
+ sendInitStudioSignal(config);
1749
+ }
1750
+ }
1751
+ return sdkSingleton;
693
1752
  }
694
1753
  const parseUI = (ui) => {
695
1754
  try {
696
1755
  return decompressSpec(ui);
697
1756
  }
698
1757
  catch (error) {
699
- console.error("UI parsing error", error);
700
1758
  throw new ComposableStudioError(ComposableStudioErrors.UI_PARSING_ERROR, getErrorMessage(ErrorMessageKey.UI_PARSING_ERROR), { ui, error });
701
1759
  }
702
1760
  };
703
1761
  function getAllSymbols(compositionEntry) {
704
1762
  const res = [];
705
- const Q = [compositionEntry];
1763
+ const Q = [
1764
+ compositionEntry,
1765
+ ];
706
1766
  while (Q.length > 0) {
707
1767
  const curr = Q.shift();
708
1768
  const symbols = (curr?.symbols || []);
@@ -714,6 +1774,97 @@ function getAllSymbols(compositionEntry) {
714
1774
  }
715
1775
  return res;
716
1776
  }
1777
+ /** CDA entries page size for the lightweight candidate fetch. */
1778
+ const CANDIDATE_PAGE_SIZE = 100;
1779
+ /** Safety cap on candidate pages (server-side resolution will own this later). */
1780
+ const MAX_CANDIDATE_PAGES = 20;
1781
+ /**
1782
+ * Fetch every page-linked composition (lightweight: url + url_metadata +
1783
+ * composable_uid + connected_content_type) for URL resolution — legacy and
1784
+ * variable, linked and freeform. Section compositions are excluded by the page
1785
+ * placement filter. Paginates with skip/limit; `truncated` is true if the safety
1786
+ * cap is hit.
1787
+ */
1788
+ async function fetchAllPageCompositions(config, locale) {
1789
+ const all = [];
1790
+ for (let page = 0; page < MAX_CANDIDATE_PAGES; page++) {
1791
+ const res = await config.stackSdk
1792
+ .ctQuery(config.contentTypeUid, {
1793
+ locale: locale || config.locale,
1794
+ query: { ...getPageLinkedPlacementFilter() },
1795
+ only: [
1796
+ ["BASE", "url"],
1797
+ ["BASE", "url_metadata"],
1798
+ ["BASE", "composable_uid"],
1799
+ ["BASE", "connected_content_type"],
1800
+ ],
1801
+ })
1802
+ .limit(CANDIDATE_PAGE_SIZE)
1803
+ .skip(page * CANDIDATE_PAGE_SIZE)
1804
+ .find();
1805
+ const batch = entriesFromResponse(res);
1806
+ all.push(...batch);
1807
+ if (batch.length < CANDIDATE_PAGE_SIZE) {
1808
+ return { entries: all, truncated: false };
1809
+ }
1810
+ }
1811
+ return { entries: all, truncated: true };
1812
+ }
1813
+ /**
1814
+ * Decide which composition wins among the ranking's top-tier candidates.
1815
+ *
1816
+ * - Single top-tier candidate → it wins, no probe.
1817
+ * - Multiple → probe each tied *linked* candidate's connected content type (in
1818
+ * parallel) for an entry matching the URL. A freeform candidate (no content
1819
+ * type) is unconditionally valid. The first valid candidate in fetch order
1820
+ * wins; a residual multi-owner case is a content mistake surfaced by Studio
1821
+ * diagnostics, never an error.
1822
+ *
1823
+ * Returns the winner's composable_uid (or undefined if nothing owns the URL) and
1824
+ * the per-candidate ownership outcome for diagnostics.
1825
+ */
1826
+ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale) {
1827
+ const topTier = ranking.matches;
1828
+ // Happy path — a single (or no) top-tier candidate needs no probe.
1829
+ if (topTier.length <= 1) {
1830
+ return selectUrlWinner(topTier, new Map());
1831
+ }
1832
+ // Tie — probe each tied linked candidate's content type in parallel.
1833
+ const linkedMatches = topTier.filter((m) => m.connected_content_type);
1834
+ const probeOutcomes = await Promise.all(linkedMatches.map(async (m) => {
1835
+ const lightweight = candidatesByUid.get(m.composable_uid);
1836
+ // Legacy compositions persist no `url_metadata`. parseUrlMetadata maps an
1837
+ // absent/unknown source to the canonical LEGACY_URL metadata (url-non-empty
1838
+ // / url-equals query), so a tie of metadata-less legacy compositions still
1839
+ // gets probed by URL instead of bailing to "no winner" → COMPOSITION_NOT_
1840
+ // FOUND_BY_URL. Only an unmatched candidate (no captured variables / no
1841
+ // content type) is unprobeable.
1842
+ const meta = parseUrlMetadata(lightweight?.url_metadata);
1843
+ if (!m.variables || !m.connected_content_type) {
1844
+ return { uid: m.composable_uid, owns: false };
1845
+ }
1846
+ try {
1847
+ const probeQuery = resolveByUrlSource(config.stackSdk, meta.url_source, { url: requestUrl }, m.variables, meta.url_queries, m.connected_content_type, {
1848
+ references: [],
1849
+ only: [["BASE", "uid"]],
1850
+ locale: m.variables.metadata.locale || locale || config.locale,
1851
+ branch: m.variables.metadata.branch,
1852
+ environment: m.variables.metadata.environment,
1853
+ });
1854
+ const res = await probeQuery.find();
1855
+ return {
1856
+ uid: m.composable_uid,
1857
+ owns: entriesFromResponse(res).length > 0,
1858
+ };
1859
+ }
1860
+ catch {
1861
+ // A failed probe counts as non-owning; another candidate may still own it.
1862
+ return { uid: m.composable_uid, owns: false };
1863
+ }
1864
+ }));
1865
+ const ownsByUid = new Map(probeOutcomes.map((r) => [r.uid, r.owns]));
1866
+ return selectUrlWinner(topTier, ownsByUid);
1867
+ }
717
1868
  /**
718
1869
  * This function fetches UI Composition from defined options.
719
1870
  * Supports custom fetcher overrides (per-query > global > SDK default).
@@ -721,6 +1872,9 @@ function getAllSymbols(compositionEntry) {
721
1872
  async function fetchComposition(config, queryOptions, compositionQueryOptions) {
722
1873
  const { fetchComposition: perQueryFetchComposition, fetchTemplateEntry: _, ...resolvedOptions } = compositionQueryOptions || {};
723
1874
  const locale = resolvedOptions.locale;
1875
+ // Captured by the URL metadata (Phase A) path for Studio resolution
1876
+ // diagnostics — every candidate considered, with specificity.
1877
+ let urlResolution;
724
1878
  const defaultImpl = async () => {
725
1879
  if ("composableUid" in queryOptions) {
726
1880
  const uiQuery = config.stackSdk.where(config.stackSdk.ctQuery(config.contentTypeUid, {
@@ -750,11 +1904,6 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
750
1904
  if (err instanceof ComposableStudioError)
751
1905
  throw err;
752
1906
  const { errorType, message } = classifyApiError(err);
753
- console.error("SDK Error:", {
754
- errorType,
755
- message,
756
- originalError: err,
757
- });
758
1907
  throw new ComposableStudioError(errorType, message, {
759
1908
  compositionUid: queryOptions.composableUid,
760
1909
  hasStackSdk: !!config.stackSdk,
@@ -765,41 +1914,30 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
765
1914
  });
766
1915
  });
767
1916
  }
768
- else if ("url" in queryOptions) {
769
- const possibleEntryUrlPatterns = getUrlPatterns(queryOptions.url);
1917
+ else if ("templateContentTypeUid" in queryOptions) {
1918
+ // Fetch by connected content type - takes priority over url when both are present
1919
+ const placementFilter = getPageLinkedPlacementFilter();
770
1920
  return await config.stackSdk
771
1921
  .ctQuery(config.contentTypeUid, {
772
1922
  includeAll: true,
773
1923
  includeAllDepth: INCLUDE_DEPTH_COUNT,
774
1924
  locale: locale || config.locale,
775
1925
  query: {
776
- url: {
777
- $in: possibleEntryUrlPatterns,
778
- },
779
- $or: [
780
- { place_composition_as: "page" },
781
- { place_composition_as: "" },
782
- { place_composition_as: null },
783
- { place_composition_as: undefined },
784
- { place_composition_as: { $exists: false } },
785
- { connected_content_type: { $exists: true } },
786
- ],
1926
+ connected_content_type: queryOptions.templateContentTypeUid,
1927
+ ...placementFilter,
787
1928
  },
788
1929
  })
1930
+ .limit(1) // First match as per plan
789
1931
  .find()
790
1932
  .then((res) => {
791
1933
  const entries = entriesFromResponse(res);
792
- const entry = getCompositionFromSlug(queryOptions.url, entries);
1934
+ const entry = entries[0];
793
1935
  if (!entry) {
794
- throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
795
- url: queryOptions.url,
796
- }), {
797
- url: queryOptions.url,
1936
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
1937
+ templateContentTypeUid: queryOptions.templateContentTypeUid,
798
1938
  hasStackSdk: !!config.stackSdk,
799
- searchedPatterns: possibleEntryUrlPatterns,
800
- entriesFound: entries.length,
801
1939
  options: queryOptions,
802
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
1940
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
803
1941
  });
804
1942
  }
805
1943
  return entry;
@@ -808,20 +1946,81 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
808
1946
  if (err instanceof ComposableStudioError)
809
1947
  throw err;
810
1948
  const { errorType, message } = classifyApiError(err);
811
- console.error("SDK Error (URL-based fetch):", {
812
- errorType,
813
- message,
814
- originalError: err,
1949
+ throw new ComposableStudioError(errorType, message, {
1950
+ templateContentTypeUid: queryOptions.templateContentTypeUid,
1951
+ hasStackSdk: !!config.stackSdk,
1952
+ statusCode: err?.status || err?.statusCode || "none",
1953
+ errorCode: err?.error_code || "none",
1954
+ errorMessage: err?.error_message || err?.message || "none",
1955
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
1956
+ });
1957
+ });
1958
+ }
1959
+ else if ("url" in queryOptions) {
1960
+ // Unified resolution: rank ALL page-linked compositions (legacy +
1961
+ // variable, linked + freeform) in one pool, then disambiguate any
1962
+ // top-tier tie by probing each tied linked candidate's content type for an
1963
+ // entry matching the URL. The most-specific match is authoritative — no
1964
+ // descent to lower tiers, no legacy fallback.
1965
+ const requestUrl = queryOptions.url;
1966
+ try {
1967
+ // 1. Fetch every page-linked candidate (lightweight, paginated).
1968
+ const { entries: candidates, truncated } = await fetchAllPageCompositions(config, locale);
1969
+ if (truncated) {
1970
+ console.warn(`[Composable Studio SDK] Composition candidate list hit the pagination cap while resolving "${requestUrl}"; some compositions may not have been considered.`);
1971
+ }
1972
+ // 2. Rank the whole pool by literal-character specificity.
1973
+ const ranking = rankUrlMatches(requestUrl, candidates);
1974
+ if (ranking.composableUids.length > 0) {
1975
+ const candidatesByUid = new Map(candidates.map((c) => [c.composable_uid, c]));
1976
+ // 3. Disambiguate top-tier ties by entry existence.
1977
+ const { winnerUid, ownershipByUid } = await resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale);
1978
+ // 4. Record every considered candidate (all tiers) + ownership for
1979
+ // Studio diagnostics, before committing to a winner.
1980
+ urlResolution = {
1981
+ shortlisted: ranking.allMatches.map((d) => ({
1982
+ ...d,
1983
+ connectedEntryResult: ownershipByUid.get(d.composable_uid) ?? "not-checked",
1984
+ })),
1985
+ };
1986
+ if (winnerUid) {
1987
+ // 5. Full-fetch the winning composition only.
1988
+ const fullQuery = config.stackSdk.ctQuery(config.contentTypeUid, {
1989
+ includeAll: true,
1990
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
1991
+ locale: locale || config.locale,
1992
+ query: { composable_uid: winnerUid },
1993
+ });
1994
+ const fullRes = await fullQuery.find();
1995
+ const fullEntries = entriesFromResponse(fullRes);
1996
+ if (fullEntries[0]) {
1997
+ return fullEntries[0];
1998
+ }
1999
+ }
2000
+ }
2001
+ // Nothing matched, or no tied candidate owns the URL.
2002
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
2003
+ url: requestUrl,
2004
+ }), {
2005
+ url: requestUrl,
2006
+ hasStackSdk: !!config.stackSdk,
2007
+ options: queryOptions,
2008
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
815
2009
  });
2010
+ }
2011
+ catch (err) {
2012
+ if (err instanceof ComposableStudioError)
2013
+ throw err;
2014
+ const { errorType, message } = classifyApiError(err);
816
2015
  throw new ComposableStudioError(errorType, message, {
817
- url: queryOptions.url,
2016
+ url: requestUrl,
818
2017
  hasStackSdk: !!config.stackSdk,
819
2018
  statusCode: err?.status || err?.statusCode || "none",
820
2019
  errorCode: err?.error_code || "none",
821
2020
  errorMessage: err?.error_message || err?.message || "none",
822
2021
  troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
823
2022
  });
824
- });
2023
+ }
825
2024
  }
826
2025
  else {
827
2026
  throw new ComposableStudioError(ComposableStudioErrors.MISSING_COMPOSITION_IDENTIFIER, getErrorMessage(ErrorMessageKey.MISSING_COMPOSITION_IDENTIFIER), {
@@ -851,14 +2050,18 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
851
2050
  return {
852
2051
  compositionEntry: entry,
853
2052
  symbolEntries: getAllSymbols(entry),
2053
+ // Populated if the custom fetcher delegated to `defaultFetch` and it
2054
+ // resolved via the URL metadata path; otherwise undefined.
2055
+ urlResolution,
854
2056
  };
855
2057
  }
856
2058
  const entry = await defaultImpl();
857
2059
  return {
858
2060
  compositionEntry: entry,
859
2061
  symbolEntries: getAllSymbols(entry),
2062
+ urlResolution,
860
2063
  };
861
2064
  }
862
2065
 
863
- export { classifyApiError, generateSdk, parseUI };
2066
+ export { classifyApiError, fetchComposition as fetchCompositionForTest, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, parseUI };
864
2067
  //# sourceMappingURL=sdk.js.map