@contentstack/studio-client 1.4.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 (97) 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/initializer-sdk.js +1 -9
  12. package/dist/composable-studio/initializer-sdk.js.map +1 -1
  13. package/dist/composable-studio/sdk.js +1551 -195
  14. package/dist/composable-studio/sdk.js.map +1 -1
  15. package/dist/composable-studio/studio-intelligence.manager.js +124 -0
  16. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -0
  17. package/dist/config/config.schema.js +10 -0
  18. package/dist/config/config.schema.js.map +1 -1
  19. package/dist/config/default-config.js +1 -0
  20. package/dist/config/default-config.js.map +1 -1
  21. package/dist/config/process-user-config.js +6 -0
  22. package/dist/config/process-user-config.js.map +1 -1
  23. package/dist/config/stack-sdk-wrapper.js +87 -2
  24. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  25. package/dist/design/handle-active-style-change.js +0 -3
  26. package/dist/design/handle-active-style-change.js.map +1 -1
  27. package/dist/dnd/dnd-manager.js +25 -7
  28. package/dist/dnd/dnd-manager.js.map +1 -1
  29. package/dist/dnd/{utils.js → scroll-utils.js} +2 -27
  30. package/dist/dnd/scroll-utils.js.map +1 -0
  31. package/dist/hidden-element-notification/hidden-element-notification-event.js +7 -0
  32. package/dist/hidden-element-notification/hidden-element-notification-event.js.map +1 -1
  33. package/dist/highlight-node/highlight-node-manager.js +7 -1
  34. package/dist/highlight-node/highlight-node-manager.js.map +1 -1
  35. package/dist/highlight-node/highlight-node.js +38 -18
  36. package/dist/highlight-node/highlight-node.js.map +1 -1
  37. package/dist/index.d.ts +618 -31
  38. package/dist/index.js +16 -5
  39. package/dist/index.js.map +1 -1
  40. package/dist/node_modules/fflate/esm/browser.js +384 -0
  41. package/dist/node_modules/fflate/esm/browser.js.map +1 -0
  42. package/dist/packages/studio-internal/dist/utils/spec-compression.js +43 -0
  43. package/dist/packages/studio-internal/dist/utils/spec-compression.js.map +1 -0
  44. package/dist/query/expression-resolver.js +124 -0
  45. package/dist/query/expression-resolver.js.map +1 -0
  46. package/dist/query/query-executor.js +482 -0
  47. package/dist/query/query-executor.js.map +1 -0
  48. package/dist/shared/dnd-events.js +39 -0
  49. package/dist/shared/dnd-events.js.map +1 -0
  50. package/dist/url-change/url-change.js +65 -0
  51. package/dist/url-change/url-change.js.map +1 -0
  52. package/dist/url-metadata/build-template-query.js +124 -0
  53. package/dist/url-metadata/build-template-query.js.map +1 -0
  54. package/dist/url-metadata/parse-url-metadata.js +75 -0
  55. package/dist/url-metadata/parse-url-metadata.js.map +1 -0
  56. package/dist/url-metadata/rank-url-matches.js +100 -0
  57. package/dist/url-metadata/rank-url-matches.js.map +1 -0
  58. package/dist/url-metadata/select-url-winner.js +45 -0
  59. package/dist/url-metadata/select-url-winner.js.map +1 -0
  60. package/dist/url-metadata/shouldUseUrlMetadataPath.js +22 -0
  61. package/dist/url-metadata/shouldUseUrlMetadataPath.js.map +1 -0
  62. package/dist/url-metadata/types.js +50 -0
  63. package/dist/url-metadata/types.js.map +1 -0
  64. package/dist/url-metadata/url-pattern-matcher.js +311 -0
  65. package/dist/url-metadata/url-pattern-matcher.js.map +1 -0
  66. package/dist/utils/build-composition-fetch-query.js +19 -0
  67. package/dist/utils/build-composition-fetch-query.js.map +1 -0
  68. package/dist/utils/composable-studio-error.js +1 -0
  69. package/dist/utils/composable-studio-error.js.map +1 -1
  70. package/dist/utils/conditionBlock.js +17 -5
  71. package/dist/utils/conditionBlock.js.map +1 -1
  72. package/dist/utils/constants.js +22 -2
  73. package/dist/utils/constants.js.map +1 -1
  74. package/dist/utils/convertCompositionQueryInputToCompositionQuery.js +11 -1
  75. package/dist/utils/convertCompositionQueryInputToCompositionQuery.js.map +1 -1
  76. package/dist/utils/editor-utils.js +9 -0
  77. package/dist/utils/editor-utils.js.map +1 -1
  78. package/dist/utils/error-messages.default.js +1 -1
  79. package/dist/utils/error-messages.default.js.map +1 -1
  80. package/dist/utils/http-error.constants.js +11 -2
  81. package/dist/utils/http-error.constants.js.map +1 -1
  82. package/dist/utils/is-inside-iframe.js +16 -0
  83. package/dist/utils/is-inside-iframe.js.map +1 -0
  84. package/dist/utils/query-param.js +1 -1
  85. package/dist/utils/query-param.js.map +1 -1
  86. package/dist/utils/reference_fetcher.js +125 -14
  87. package/dist/utils/reference_fetcher.js.map +1 -1
  88. package/dist/utils/sdk.js +6 -1
  89. package/dist/utils/sdk.js.map +1 -1
  90. package/dist/utils/spec-analyzer.js +112 -0
  91. package/dist/utils/spec-analyzer.js.map +1 -0
  92. package/package.json +11 -10
  93. package/dist/dnd/utils.js.map +0 -1
  94. package/dist/get-composition-from-slug/get-composition-from-slug.js +0 -59
  95. package/dist/get-composition-from-slug/get-composition-from-slug.js.map +0 -1
  96. package/dist/utils/get-url-patterns.js +0 -40
  97. package/dist/utils/get-url-patterns.js.map +0 -1
@@ -1,21 +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
- import { entriesFromResponse, setTemplateEntryInDS, setStaticEntryInDS } from '../utils/sdk.js';
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';
26
+ import { decompressSpec } from '../packages/studio-internal/dist/utils/spec-compression.js';
17
27
  import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages.default.js';
18
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
+ }
19
220
  function getAuthErrorMessage(err) {
20
221
  const detail = err?.error_message ||
21
222
  err?.errors?.api_key?.[0] ||
@@ -44,18 +245,39 @@ function classifyApiError(err) {
44
245
  message: getAuthErrorMessage(err),
45
246
  };
46
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
+ }
47
265
  // Check for network errors (no response, timeout, connection refused)
48
- // Empty response object often indicates network failure
49
- const isEmptyResponse = err && typeof err === "object" && Object.keys(err).length === 0;
50
- 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
51
275
  return {
52
276
  errorType: ComposableStudioErrors.NETWORK_ERROR,
53
- message: isEmptyResponse
54
- ? getErrorMessage(ErrorMessageKey.NETWORK_ERROR_EMPTY)
55
- : getErrorMessage(ErrorMessageKey.NETWORK_ERROR_GENERIC, {
56
- detail: err?.message ||
57
- getErrorMessage(ErrorMessageKey.NETWORK_ERROR_DETAIL_DEFAULT),
58
- }),
277
+ message: getErrorMessage(ErrorMessageKey.NETWORK_ERROR_GENERIC, {
278
+ detail: err?.message ||
279
+ getErrorMessage(ErrorMessageKey.NETWORK_ERROR_DETAIL_DEFAULT),
280
+ }),
59
281
  };
60
282
  }
61
283
  // Check for 404 - composition not found
@@ -292,15 +514,95 @@ function getParentTagsValue(dataValue, tagsAsObject) {
292
514
  return { "data-cslp-parent-field": dataValue };
293
515
  }
294
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
+ }
295
572
  function generateSdk(userConfig) {
296
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
297
578
  if (clientRendererModeUtil.isInsideStudioFrame()) {
298
- 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) || "";
299
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
+ }
300
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
301
602
  async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}) {
302
603
  const { variantAlias, locale } = options;
303
- const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
604
+ const isInsideEditor = clientRendererModeUtil.isInsideVisualBuilderFrame() ||
605
+ clientRendererModeUtil.isInsideStudioFrame();
304
606
  try {
305
607
  const promises = [];
306
608
  for (const _content_type_uid in staticBindingQueries) {
@@ -308,8 +610,8 @@ function generateSdk(userConfig) {
308
610
  for (const entry_uid in staticBindingQueries[_content_type_uid]) {
309
611
  const references = staticBindingQueries[_content_type_uid][entry_uid];
310
612
  let onlyQuery = [];
311
- // When inside Visual Builder, fetch all fields (don't use onlyQueries)
312
- if (!isInsideVB) {
613
+ // When inside Studio or Visual Builder, fetch all fields (don't use onlyQueries)
614
+ if (!isInsideEditor) {
313
615
  onlyQuery =
314
616
  staticBindingOnlyQueries[_content_type_uid][entry_uid] || [];
315
617
  // We need locale for redirect to the correct locale.
@@ -344,144 +646,1006 @@ function generateSdk(userConfig) {
344
646
  }
345
647
  else {
346
648
  //TODO: Add logger support general to have studio prefix
347
- console.error("Unable to resolve entry", entry.reason);
649
+ if (process.env.NODE_ENV === "development") {
650
+ console.log("Message handling fallback");
651
+ }
348
652
  }
349
653
  }
350
654
  }
351
655
  else {
352
- 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
+ }
353
659
  }
354
660
  }
355
661
  }
356
- catch (err) {
357
- 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
+ }
358
666
  }
359
667
  }
360
668
  /**
361
669
  * When composition is binded to a content type, we need to fetch the entry for that content type. Called template entry.
670
+ * Supports custom fetcher overrides (per-query > global > SDK default).
362
671
  */
363
- async function fetchTemplateEntry(options, data) {
672
+ async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions) {
364
673
  if (!config.stackSdk) {
365
- console.error("Fetching template entry not possible without stackSdk");
366
674
  return;
367
675
  }
368
- const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = options;
676
+ const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = fetchOptions;
369
677
  if (!connected_content_type) {
370
678
  return;
371
679
  }
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;
372
684
  const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
373
- // When inside Visual Builder, fetch all fields (don't use onlyQueries)
374
- const queryOptions = {
375
- references: includeQueries,
376
- variantAlias: options.variantAlias,
377
- locale: options.locale || config.locale, // Use override locale or default
378
- };
379
- if (!isInsideVB) {
380
- queryOptions.only = onlyQueries;
381
- }
382
- let dataQuery = config.stackSdk
383
- .ctQuery(connected_content_type, queryOptions)
384
- .limit(1);
385
- if ("url" in compositionQuery) {
386
- dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
387
- }
388
- // We used the `find` instead of `findOne` because it
389
- // caused issues with the fetch data.
390
- const response = await dataQuery.find().catch((err) => {
391
- const { errorType, message } = classifyApiError(err);
392
- console.error("SDK Error (connected data):", {
393
- errorType,
394
- message,
395
- originalError: err,
396
- });
397
- // For connected data, use specific error or fall back to FETCHING_CONNECTED_DATA_FAILED
398
- const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
399
- ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
400
- : errorType;
401
- throw new ComposableStudioError(finalErrorType, finalErrorType === ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
402
- ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
403
- : message, {
404
- options,
405
- response: err,
406
- statusCode: err?.status || err?.statusCode,
407
- errorCode: err?.error_code,
408
- });
409
- });
410
- const entries = entriesFromResponse(response);
411
- if (!entries?.[0]) {
412
- console.error("Preview/Template entry not found", {
413
- contentType: connected_content_type,
414
- compositionQuery,
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;
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
838
+ const queryOptions = {
839
+ references: allIncludeQueries,
840
+ variantAlias: resolvedOptions.variantAlias,
841
+ // No URL pattern in this branch — pattern locale is N/A.
842
+ locale: resolveLocale(),
843
+ };
844
+ // Smart 'only' parameter handling - only apply in production
845
+ if (!isInsideVB && !isInsideStudio) {
846
+ queryOptions.only = onlyQueries;
847
+ }
848
+ let dataQuery = config.stackSdk
849
+ .ctQuery(connected_content_type, queryOptions)
850
+ .limit(1);
851
+ // Legacy URL matching (note: this is likely incorrect for patterned URLs as mentioned in plan)
852
+ if ("url" in compositionQuery && compositionQuery.url) {
853
+ dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
854
+ }
855
+ const response = await dataQuery.find().catch((err) => {
856
+ const { errorType, message } = classifyApiError(err);
857
+ const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
858
+ ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
859
+ : errorType;
860
+ throw new ComposableStudioError(finalErrorType, finalErrorType ===
861
+ ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
862
+ ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
863
+ : message, {
864
+ options: fetchOptions,
865
+ response: err,
866
+ statusCode: err?.status || err?.statusCode,
867
+ errorCode: err?.error_code,
868
+ });
415
869
  });
416
- throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
417
- contentType: connected_content_type,
418
- }), {
419
- contentType: connected_content_type,
420
- hasStackSdk: !!config.stackSdk,
870
+ const entries = entriesFromResponse(response);
871
+ if (!entries?.[0]) {
872
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
873
+ contentType: connected_content_type,
874
+ }), {
875
+ contentType: connected_content_type,
876
+ hasStackSdk: !!config.stackSdk,
877
+ compositionQuery,
878
+ options: fetchOptions,
879
+ troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
880
+ });
881
+ }
882
+ return entries[0];
883
+ };
884
+ const customFetcher = perQueryFetchTemplateEntry ?? config.fetchTemplateEntry;
885
+ let entry;
886
+ if (customFetcher) {
887
+ entry = await customFetcher({
888
+ compositionEntry,
421
889
  compositionQuery,
422
- options,
423
- troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
890
+ connectedContentType: connected_content_type,
891
+ options: resolvedOptions,
892
+ includeReferences: includeQueries,
893
+ only: isInsideStudio || isInsideVB ? [] : onlyQueries,
894
+ stackSdk: config.stackSdk.sdk,
895
+ defaultFetch: defaultImpl,
424
896
  });
897
+ if (!entry) {
898
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
899
+ contentType: connected_content_type,
900
+ }));
901
+ }
902
+ }
903
+ else {
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
+ }
425
911
  }
426
- const entry = entries[0];
427
912
  if (config.cslp.appendTags) {
428
913
  addEditableTags(entry, connected_content_type, true, entry.locale);
429
914
  }
430
915
  setTemplateEntryInDS(data.dataSources, entry);
431
- if (!isCompositionBeingEdited(options?.composableUid || ""))
916
+ if (!isCompositionBeingEdited(fetchOptions?.composableUid || ""))
432
917
  return;
433
918
  }
434
- async function fetchData(compositionEntry, queryOptions, options) {
919
+ async function fetchData(compositionEntry, queryOptions, options, sectionEntries = []) {
435
920
  const { variantAlias, locale } = options || {};
436
- // This will iterate over ui and collect all data to fetch ( entries and depth of refrerences for both template and static contentstack)
437
- 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);
438
1042
  const data = {
439
1043
  [DATA_SOURCES_PREFIX]: {},
440
1044
  [DATA_SOURCES.STATIC_VALUE]: preProcessStaticValues(compositionEntry.static_value || {}),
1045
+ ...(pageExternalProps ? { component_props: pageExternalProps } : {}),
441
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
+ }
442
1091
  await Promise.all([
443
1092
  fetchTemplateEntry({
444
- connected_content_type: compositionEntry.connected_content_type || "",
1093
+ connected_content_type: templateContentTypeUid,
445
1094
  compositionQuery: queryOptions,
446
1095
  includeQueries: templateReferencesPath,
447
1096
  onlyQueries: templateOnlyKeys,
448
1097
  composableUid: compositionEntry.composable_uid,
1098
+ }, data, compositionEntry, resolvedOptions),
1099
+ resolveStaticData(mergedRefs, mergedOnly, data, {
449
1100
  variantAlias: variantAlias,
450
1101
  locale: locale,
451
- }, data),
452
- resolveStaticData(contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, data, {
453
- variantAlias: variantAlias,
454
- locale: locale,
1102
+ }),
1103
+ resolveQueryData(compositionEntry, data, {
1104
+ variantAlias,
1105
+ locale: locale || config.locale,
1106
+ sectionEntries,
455
1107
  }),
456
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;
457
1238
  return data;
458
1239
  }
459
- async function fetchSpec(queryOptions, options) {
1240
+ async function fetchSpec(queryOptions, options, skipComponentLoading = false) {
460
1241
  if (!config.stackSdk) {
461
1242
  throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
462
1243
  }
463
- const { compositionEntry, symbolEntries } = await fetchComposition(config, queryOptions);
464
- const data = await fetchData(compositionEntry, queryOptions, options);
465
- const page = typeof compositionEntry.ui === "string"
466
- ? JSON.parse(compositionEntry.ui)
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);
1250
+ const ui = typeof compositionEntry.ui === "string"
1251
+ ? decompressSpec(compositionEntry.ui)
467
1252
  : compositionEntry.ui;
468
- const ui = page;
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
+ }
469
1343
  return {
470
1344
  data,
471
1345
  ui,
472
1346
  compositionEntry,
473
- //TODO: Need to fetch symbols from the server
474
- symbols: symbolEntries,
475
- 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
+ },
476
1357
  };
477
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
+ }
1450
+ /**
1451
+ * Reusable helper to fetch data from Contentstack
1452
+ * Now uses QueryExecutor internally to support full QuerySpec with filters, sorting, etc.
1453
+ *
1454
+ * @param querySpec - Full QuerySpec with filters, sorting, pagination, etc.
1455
+ * @param context - RuntimeContext for expression resolution (URL params, etc.)
1456
+ * @returns Promise with data array and count
1457
+ */
1458
+ async function fetchContentstackData(querySpec, context = {}, options) {
1459
+ if (!config.stackSdk) {
1460
+ return { entries: [], count: 0 };
1461
+ }
1462
+ try {
1463
+ // Use QueryExecutor to execute the full QuerySpec
1464
+ // This supports filters, sorting, pagination, includes, only, and expression resolution
1465
+ const { QueryExecutor } = await import('../query/query-executor.js');
1466
+ const executor = new QueryExecutor(config.stackSdk.sdk);
1467
+ // Execute query using QueryExecutor
1468
+ // ExpressionResolver inside QueryExecutor will resolve expressions at execution time
1469
+ const result = await executor.execute(querySpec, 1, context, options);
1470
+ const entries = result.entries || [];
1471
+ const count = result.count || 0;
1472
+ // Add editable tags (CSLP)
1473
+ if (config.cslp.appendTags && Array.isArray(entries)) {
1474
+ entries.forEach((entry) => {
1475
+ addEditableTags(entry, querySpec.contentType, true, entry.locale || "en-us");
1476
+ });
1477
+ }
1478
+ return {
1479
+ entries: entries,
1480
+ count: count,
1481
+ };
1482
+ }
1483
+ catch (error) {
1484
+ if (process.env.NODE_ENV === "development") {
1485
+ console.error("Error resolving query data:", error);
1486
+ }
1487
+ return { entries: [], count: 0 };
1488
+ }
1489
+ }
1490
+ async function resolveQueryData(compositionEntry, data, options) {
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
+ }
1505
+ }
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;
1513
+ }
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
+ }
1560
+ }
1561
+ const dedupedQueries = Array.from(queryDeduper.values());
1562
+ // Nothing to resolve (neither page nor any section declared a query).
1563
+ if (dedupedQueries.length === 0)
1564
+ return;
1565
+ const queryResults = {};
1566
+ // Build RuntimeContext for expression resolution
1567
+ // In SDK, use window.location.href for URL params
1568
+ 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
+ }
1575
+ const context = {
1576
+ url: {
1577
+ params: urlParams,
1578
+ path: {}, // Can be extended if path params are needed
1579
+ hash: typeof window !== "undefined" ? window.location.hash : undefined,
1580
+ },
1581
+ // NO componentProps or user context - expressions only support URL params and time
1582
+ };
1583
+ await Promise.all(dedupedQueries.map(async (queryConfig) => {
1584
+ const { uid, spec } = queryConfig;
1585
+ if (!uid || !spec?.contentType)
1586
+ return;
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
+ }
1636
+ }));
1637
+ if (!data.dataSources[DATA_SOURCES.QUERY]) {
1638
+ data.dataSources[DATA_SOURCES.QUERY] = {};
1639
+ }
1640
+ Object.assign(data.dataSources[DATA_SOURCES.QUERY], queryResults);
1641
+ }
478
1642
  function getLightConfig() {
479
1643
  return pick(config, ["openInStudioButton", "contentTypeUid", "cslp"]);
480
1644
  }
481
1645
  function getSeoMetadata(ui) {
482
1646
  return ui.metadata.seo || null;
483
1647
  }
484
- return {
1648
+ const sdkSingleton = {
485
1649
  internal: {
486
1650
  getConfig() {
487
1651
  return config;
@@ -490,6 +1654,7 @@ function generateSdk(userConfig) {
490
1654
  // Once we fetch the data, we need to perform certain operation to store the UI and data.
491
1655
  // Hence, we moved this to the internal method.
492
1656
  fetchSpec,
1657
+ fetchMultipleSpecs,
493
1658
  fetchData,
494
1659
  fetchTemplateEntry,
495
1660
  getSeoMetadata,
@@ -572,19 +1737,32 @@ function generateSdk(userConfig) {
572
1737
  getConfig: getLightConfig,
573
1738
  },
574
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;
575
1752
  }
576
1753
  const parseUI = (ui) => {
577
1754
  try {
578
- return JSON.parse(ui);
1755
+ return decompressSpec(ui);
579
1756
  }
580
1757
  catch (error) {
581
- console.error("UI parsing error", error);
582
1758
  throw new ComposableStudioError(ComposableStudioErrors.UI_PARSING_ERROR, getErrorMessage(ErrorMessageKey.UI_PARSING_ERROR), { ui, error });
583
1759
  }
584
1760
  };
585
1761
  function getAllSymbols(compositionEntry) {
586
1762
  const res = [];
587
- const Q = [compositionEntry];
1763
+ const Q = [
1764
+ compositionEntry,
1765
+ ];
588
1766
  while (Q.length > 0) {
589
1767
  const curr = Q.shift();
590
1768
  const symbols = (curr?.symbols || []);
@@ -596,116 +1774,294 @@ function getAllSymbols(compositionEntry) {
596
1774
  }
597
1775
  return res;
598
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
+ }
599
1868
  /**
600
1869
  * This function fetches UI Composition from defined options.
1870
+ * Supports custom fetcher overrides (per-query > global > SDK default).
601
1871
  **/
602
- async function fetchComposition(config, options, locale) {
603
- let uiQuery;
604
- if ("composableUid" in options) {
605
- uiQuery = config.stackSdk.where(config.stackSdk.ctQuery(config.contentTypeUid, {
606
- locale: config.locale,
607
- }), "composable_uid", options.composableUid);
608
- const response = await uiQuery
609
- .find()
610
- .then((res) => {
611
- let response;
612
- if (Array.isArray(res)) {
613
- response = res[0][0];
614
- }
615
- else {
616
- response = res.entries[0];
617
- }
618
- if (!response) {
619
- throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
620
- compositionUid: options.composableUid,
1872
+ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
1873
+ const { fetchComposition: perQueryFetchComposition, fetchTemplateEntry: _, ...resolvedOptions } = compositionQueryOptions || {};
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;
1878
+ const defaultImpl = async () => {
1879
+ if ("composableUid" in queryOptions) {
1880
+ const uiQuery = config.stackSdk.where(config.stackSdk.ctQuery(config.contentTypeUid, {
1881
+ locale: locale || config.locale,
1882
+ }), "composable_uid", queryOptions.composableUid);
1883
+ return await uiQuery
1884
+ .find()
1885
+ .then((res) => {
1886
+ let response;
1887
+ if (Array.isArray(res)) {
1888
+ response = res[0][0];
1889
+ }
1890
+ else {
1891
+ response = res.entries[0];
1892
+ }
1893
+ if (!response) {
1894
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
1895
+ compositionUid: queryOptions.composableUid,
1896
+ hasStackSdk: !!config.stackSdk,
1897
+ options: queryOptions,
1898
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
1899
+ });
1900
+ }
1901
+ return response;
1902
+ })
1903
+ .catch((err) => {
1904
+ if (err instanceof ComposableStudioError)
1905
+ throw err;
1906
+ const { errorType, message } = classifyApiError(err);
1907
+ throw new ComposableStudioError(errorType, message, {
1908
+ compositionUid: queryOptions.composableUid,
621
1909
  hasStackSdk: !!config.stackSdk,
622
- options,
623
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
1910
+ statusCode: err?.status || err?.statusCode || "none",
1911
+ errorCode: err?.error_code || "none",
1912
+ errorMessage: err?.error_message || err?.message || "none",
1913
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
624
1914
  });
625
- }
626
- return response;
627
- })
628
- .catch((err) => {
629
- const { errorType, message } = classifyApiError(err);
630
- console.error("SDK Error:", { errorType, message, originalError: err });
631
- throw new ComposableStudioError(errorType, message, {
632
- compositionUid: options.composableUid,
633
- hasStackSdk: !!config.stackSdk,
634
- statusCode: err?.status || err?.statusCode || "none",
635
- errorCode: err?.error_code || "none",
636
- errorMessage: err?.error_message || err?.message || "none",
637
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
638
1915
  });
639
- });
640
- return {
641
- compositionEntry: response,
642
- symbolEntries: getAllSymbols(response),
643
- };
644
- }
645
- else if ("url" in options) {
646
- const possibleEntryUrlPatterns = getUrlPatterns(options.url);
647
- return await config.stackSdk
648
- .ctQuery(config.contentTypeUid, {
649
- includeAll: true,
650
- includeAllDepth: INCLUDE_DEPTH_COUNT,
651
- locale: config.locale,
652
- query: {
653
- url: {
654
- $in: possibleEntryUrlPatterns,
1916
+ }
1917
+ else if ("templateContentTypeUid" in queryOptions) {
1918
+ // Fetch by connected content type - takes priority over url when both are present
1919
+ const placementFilter = getPageLinkedPlacementFilter();
1920
+ return await config.stackSdk
1921
+ .ctQuery(config.contentTypeUid, {
1922
+ includeAll: true,
1923
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
1924
+ locale: locale || config.locale,
1925
+ query: {
1926
+ connected_content_type: queryOptions.templateContentTypeUid,
1927
+ ...placementFilter,
655
1928
  },
656
- $or: [
657
- { place_composition_as: "page" },
658
- { place_composition_as: "" },
659
- { place_composition_as: { $exists: false } },
660
- { connected_content_type: true },
661
- ],
662
- },
663
- })
664
- .find()
665
- .then((res) => {
666
- const entries = entriesFromResponse(res);
667
- const entry = getCompositionFromSlug(options.url, entries);
668
- if (!entry) {
1929
+ })
1930
+ .limit(1) // First match as per plan
1931
+ .find()
1932
+ .then((res) => {
1933
+ const entries = entriesFromResponse(res);
1934
+ const entry = entries[0];
1935
+ if (!entry) {
1936
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
1937
+ templateContentTypeUid: queryOptions.templateContentTypeUid,
1938
+ hasStackSdk: !!config.stackSdk,
1939
+ options: queryOptions,
1940
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
1941
+ });
1942
+ }
1943
+ return entry;
1944
+ })
1945
+ .catch((err) => {
1946
+ if (err instanceof ComposableStudioError)
1947
+ throw err;
1948
+ const { errorType, message } = classifyApiError(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.
669
2002
  throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
670
- url: options.url,
2003
+ url: requestUrl,
671
2004
  }), {
672
- url: options.url,
2005
+ url: requestUrl,
673
2006
  hasStackSdk: !!config.stackSdk,
674
- searchedPatterns: possibleEntryUrlPatterns,
675
- entriesFound: entries.length,
676
- options,
2007
+ options: queryOptions,
677
2008
  troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
678
2009
  });
679
2010
  }
680
- return {
681
- compositionEntry: entry,
682
- symbolEntries: getAllSymbols(entry),
683
- };
684
- })
685
- .catch((err) => {
686
- // This error is different. Here, we have issues while fetching the entries.
687
- const { errorType, message } = classifyApiError(err);
688
- console.error("SDK Error (URL-based fetch):", {
689
- errorType,
690
- message,
691
- originalError: err,
692
- });
693
- throw new ComposableStudioError(errorType, message, {
694
- url: options.url,
695
- hasStackSdk: !!config.stackSdk,
696
- statusCode: err?.status || err?.statusCode || "none",
697
- errorCode: err?.error_code || "none",
698
- errorMessage: err?.error_message || err?.message || "none",
699
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
2011
+ catch (err) {
2012
+ if (err instanceof ComposableStudioError)
2013
+ throw err;
2014
+ const { errorType, message } = classifyApiError(err);
2015
+ throw new ComposableStudioError(errorType, message, {
2016
+ url: requestUrl,
2017
+ hasStackSdk: !!config.stackSdk,
2018
+ statusCode: err?.status || err?.statusCode || "none",
2019
+ errorCode: err?.error_code || "none",
2020
+ errorMessage: err?.error_message || err?.message || "none",
2021
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
2022
+ });
2023
+ }
2024
+ }
2025
+ else {
2026
+ throw new ComposableStudioError(ComposableStudioErrors.MISSING_COMPOSITION_IDENTIFIER, getErrorMessage(ErrorMessageKey.MISSING_COMPOSITION_IDENTIFIER), {
2027
+ options: queryOptions,
700
2028
  });
2029
+ }
2030
+ };
2031
+ const customFetcher = perQueryFetchComposition ?? config.fetchComposition;
2032
+ if (customFetcher) {
2033
+ const entry = await customFetcher({
2034
+ compositionQuery: queryOptions,
2035
+ contentTypeUid: config.contentTypeUid,
2036
+ options: resolvedOptions,
2037
+ stackSdk: config.stackSdk.sdk,
2038
+ defaultFetch: defaultImpl,
701
2039
  });
2040
+ if (!entry) {
2041
+ const isUrlBased = "url" in queryOptions;
2042
+ throw new ComposableStudioError(isUrlBased
2043
+ ? ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL
2044
+ : ComposableStudioErrors.COMPOSITION_NOT_FOUND, isUrlBased
2045
+ ? getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
2046
+ url: queryOptions.url,
2047
+ })
2048
+ : getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404));
2049
+ }
2050
+ return {
2051
+ compositionEntry: entry,
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,
2056
+ };
702
2057
  }
703
- else {
704
- throw new ComposableStudioError(ComposableStudioErrors.MISSING_COMPOSITION_IDENTIFIER, getErrorMessage(ErrorMessageKey.MISSING_COMPOSITION_IDENTIFIER), {
705
- options,
706
- });
707
- }
2058
+ const entry = await defaultImpl();
2059
+ return {
2060
+ compositionEntry: entry,
2061
+ symbolEntries: getAllSymbols(entry),
2062
+ urlResolution,
2063
+ };
708
2064
  }
709
2065
 
710
- export { classifyApiError, generateSdk, parseUI };
2066
+ export { classifyApiError, fetchComposition as fetchCompositionForTest, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, parseUI };
711
2067
  //# sourceMappingURL=sdk.js.map