@contentstack/studio-client 3.1.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +21 -0
  2. package/dist/breakpoints/BreakpointManager.js +7 -5
  3. package/dist/breakpoints/BreakpointManager.js.map +1 -1
  4. package/dist/breakpoints/breakpoint.js +3 -2
  5. package/dist/breakpoints/breakpoint.js.map +1 -1
  6. package/dist/canvas/canvas.utils.js +13 -1
  7. package/dist/canvas/canvas.utils.js.map +1 -1
  8. package/dist/composable-studio/build-scoped-data.js +53 -31
  9. package/dist/composable-studio/build-scoped-data.js.map +1 -1
  10. package/dist/composable-studio/collect-data-needs.js +22 -4
  11. package/dist/composable-studio/collect-data-needs.js.map +1 -1
  12. package/dist/composable-studio/sdk.js +1288 -453
  13. package/dist/composable-studio/sdk.js.map +1 -1
  14. package/dist/composable-studio/section-data.js +316 -0
  15. package/dist/composable-studio/section-data.js.map +1 -0
  16. package/dist/composable-studio/studio-intelligence.manager.js +5 -2
  17. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -1
  18. package/dist/config/config.schema.js +45 -8
  19. package/dist/config/config.schema.js.map +1 -1
  20. package/dist/config/default-config.js +10 -3
  21. package/dist/config/default-config.js.map +1 -1
  22. package/dist/config/process-user-config.js +37 -1
  23. package/dist/config/process-user-config.js.map +1 -1
  24. package/dist/config/stack-sdk-wrapper.js +71 -2
  25. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  26. package/dist/context-menu/context-menu.js +5 -2
  27. package/dist/context-menu/context-menu.js.map +1 -1
  28. package/dist/design/handle-active-style-change.js +3 -2
  29. package/dist/design/handle-active-style-change.js.map +1 -1
  30. package/dist/dnd/dnd-event.js +2 -1
  31. package/dist/dnd/dnd-event.js.map +1 -1
  32. package/dist/dnd/dnd-manager.js +3 -1
  33. package/dist/dnd/dnd-manager.js.map +1 -1
  34. package/dist/editor.d.ts +250 -0
  35. package/dist/editor.js +11 -0
  36. package/dist/editor.js.map +1 -0
  37. package/dist/get-active-node-screenshot/get-node-screenshot-event.js +2 -1
  38. package/dist/get-active-node-screenshot/get-node-screenshot-event.js.map +1 -1
  39. package/dist/hidden-element-notification/hidden-element-notification-event.js +2 -1
  40. package/dist/hidden-element-notification/hidden-element-notification-event.js.map +1 -1
  41. package/dist/highlight-node/highlight-node-manager.js +225 -15
  42. package/dist/highlight-node/highlight-node-manager.js.map +1 -1
  43. package/dist/highlight-node/highlight-node.js +42 -6
  44. package/dist/highlight-node/highlight-node.js.map +1 -1
  45. package/dist/highlight-spacing/highlight-spacing-events.js +2 -1
  46. package/dist/highlight-spacing/highlight-spacing-events.js.map +1 -1
  47. package/dist/index.d.ts +1334 -467
  48. package/dist/index.js +14 -14
  49. package/dist/index.js.map +1 -1
  50. package/dist/url-change/url-change.js +4 -3
  51. package/dist/url-change/url-change.js.map +1 -1
  52. package/dist/url-metadata/build-template-query.js +27 -6
  53. package/dist/url-metadata/build-template-query.js.map +1 -1
  54. package/dist/utils/canvas.js +2 -1
  55. package/dist/utils/canvas.js.map +1 -1
  56. package/dist/utils/check-bindings.js +233 -0
  57. package/dist/utils/check-bindings.js.map +1 -0
  58. package/dist/utils/classify-response-error.js +288 -0
  59. package/dist/utils/classify-response-error.js.map +1 -0
  60. package/dist/utils/composable-studio-error.js +36 -20
  61. package/dist/utils/composable-studio-error.js.map +1 -1
  62. package/dist/utils/composition-not-found.js +52 -0
  63. package/dist/utils/composition-not-found.js.map +1 -0
  64. package/dist/utils/conditionBlock.js +80 -3
  65. package/dist/utils/conditionBlock.js.map +1 -1
  66. package/dist/utils/constants.js +21 -2
  67. package/dist/utils/constants.js.map +1 -1
  68. package/dist/utils/degraded-finding.js +166 -0
  69. package/dist/utils/degraded-finding.js.map +1 -0
  70. package/dist/utils/editor-mode.js +1 -1
  71. package/dist/utils/http-error.constants.js +12 -46
  72. package/dist/utils/http-error.constants.js.map +1 -1
  73. package/dist/utils/include-path-rules.js +141 -0
  74. package/dist/utils/include-path-rules.js.map +1 -0
  75. package/dist/utils/is-composition-being-edited.js +1 -1
  76. package/dist/utils/is-inside-iframe.js +1 -1
  77. package/dist/utils/is-inside-visual-builder-frame.js +1 -1
  78. package/dist/utils/parse-ui.js +60 -0
  79. package/dist/utils/parse-ui.js.map +1 -0
  80. package/dist/utils/query-param.js +1 -1
  81. package/dist/utils/query-param.js.map +1 -1
  82. package/dist/utils/query-url-budget.js +79 -0
  83. package/dist/utils/query-url-budget.js.map +1 -0
  84. package/dist/utils/reference-stub.js +75 -0
  85. package/dist/utils/reference-stub.js.map +1 -0
  86. package/dist/utils/reference_fetcher.js +59 -4
  87. package/dist/utils/reference_fetcher.js.map +1 -1
  88. package/dist/utils/require-stack.js +141 -0
  89. package/dist/utils/require-stack.js.map +1 -0
  90. package/dist/utils/served-by.js +33 -0
  91. package/dist/utils/served-by.js.map +1 -0
  92. package/dist/utils/spec-analyzer.js +2 -2
  93. package/dist/utils/spec-analyzer.js.map +1 -1
  94. package/dist/utils/studio-error-codes.js +253 -0
  95. package/dist/utils/studio-error-codes.js.map +1 -0
  96. package/dist/utils/studio-error.js +122 -0
  97. package/dist/utils/studio-error.js.map +1 -0
  98. package/dist/utils/studio-messaging.js +25 -0
  99. package/dist/utils/studio-messaging.js.map +1 -0
  100. package/dist/visual-builder/composition-save-event.js +2 -1
  101. package/dist/visual-builder/composition-save-event.js.map +1 -1
  102. package/package.json +19 -7
  103. package/LICENSE +0 -21
  104. package/dist/utils/error-messages.default.js +0 -141
  105. package/dist/utils/error-messages.default.js.map +0 -1
  106. package/dist/utils/error-messages.js +0 -47
  107. package/dist/utils/error-messages.js.map +0 -1
@@ -1,18 +1,28 @@
1
- import { COMPOSABLE_STUDIO_QUERY_PARAM, composableStudioEventManager, POST_MESSAGE_EVENTS } from '@contentstack/studio-messenger';
1
+ import { COMPOSABLE_STUDIO_QUERY_PARAM, POST_MESSAGE_EVENTS } from '@contentstack/studio-messenger/constants';
2
+ import { sendStudioEvent } from '../utils/studio-messaging.js';
2
3
  import { INTERNAL_COMPONENTS_NAMES, DATA_SOURCES, getStateStoreInstance, getComponentRegistryInstance, DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
3
4
  import { get, pick, uniq, uniqBy, chunk, range } from 'lodash-es';
4
5
  import { processUserConfig } from '../config/process-user-config.js';
5
6
  import { setStackSdkInstance } from '../json-rte-registry/stack-sdk-store.js';
7
+ import { requireStack } from '../utils/require-stack.js';
8
+ import { parseUI } from '../utils/parse-ui.js';
6
9
  import { SCHEMA_VERSION, SDK_VERSION, INCLUDE_DEPTH_COUNT } from '../utils/constants.js';
7
10
  import { isCompositionBeingEdited } from '../utils/is-composition-being-edited.js';
8
- import { setTemplateEntryInDS, setStaticEntryInDS, entriesFromResponse, getBindingStringForCS } from '../utils/sdk.js';
11
+ import { setTemplateEntryInDS, setStaticEntryInDS, getBindingStringForCS, entriesFromResponse } from '../utils/sdk.js';
9
12
  import '../utils/editor-mode.js';
10
- import { ComposableStudioError, ComposableStudioErrors } from '../utils/composable-studio-error.js';
13
+ import { ComposableStudioError } from '../utils/composable-studio-error.js';
14
+ import '../utils/composition-not-found.js';
15
+ import { createStudioError, buildStudioErrorContext, isSetupFault } from '../utils/studio-error.js';
16
+ import { StudioErrorCode } from '../utils/studio-error-codes.js';
11
17
  import '../utils/conditionBlock.js';
12
18
  import { clientRendererModeUtil, RendererModeUtil } from '../utils/canvas.js';
13
19
  import { analyzeUsedComponents } from '../utils/spec-analyzer.js';
14
20
  import { convertCompositionQueryInputToCompositionQuery } from '../utils/convertCompositionQueryInputToCompositionQuery.js';
15
- import { getErrorMessage, getTroubleshootingInfo } from '../utils/error-messages.js';
21
+ import { classifyResponseError, diagnoseUnreadableResponse } from '../utils/classify-response-error.js';
22
+ import { reportDegraded, degradedReportingIsOn, DegradedCode } from '../utils/degraded-finding.js';
23
+ import { countUnresolvedReferences } from '../utils/reference-stub.js';
24
+ import { findBindingDefects } from '../utils/check-bindings.js';
25
+ import { resolveServedBy } from '../utils/served-by.js';
16
26
  import { getPageLinkedPlacementFilter } from '../utils/build-composition-fetch-query.js';
17
27
  import { resolveByUrlSource } from '../url-metadata/build-template-query.js';
18
28
  import { parseUrlMetadata } from '../url-metadata/parse-url-metadata.js';
@@ -20,14 +30,15 @@ import { rankUrlMatches } from '../url-metadata/rank-url-matches.js';
20
30
  import { selectUrlWinner } from '../url-metadata/select-url-winner.js';
21
31
  import { COMPOSITION_PREVIEW_URL_SOURCES } from '../url-metadata/types.js';
22
32
  import { matchCompositionUrl } from '../url-metadata/url-pattern-matcher.js';
23
- import { getStatusCode, isContentstackAuthError, hasAuthErrorShape, isAuthError, isNetworkError, HttpStatus, ContentstackErrorCode, isServerError } from '../utils/http-error.constants.js';
33
+ import { indexModularBlocks, isModularBlockPath, compositionCarriesCompleteIncludes, dropImpliedParents } from '../utils/include-path-rules.js';
24
34
  import { getEntriesQueries, projectIncludePathsOntoOnlyKeys, getSchemaPath } from '../utils/reference_fetcher.js';
35
+ import { applyUrlBudget, referencesExceedBudget } from '../utils/query-url-budget.js';
25
36
  import { collectAllDataNeeds, stableHashQuery, parseExternalDataForComponentProps } from './collect-data-needs.js';
26
37
  import { buildScopedDataSources } from './build-scoped-data.js';
27
38
  import { preProcessStaticValues } from './data/pre-process-static-values.js';
28
39
  import { StudioIntelligenceManager } from './studio-intelligence.manager.js';
40
+ import { TEMPLATE_FETCH_ROOT_KEY, parseEntryFetchRootKey, resolveInstanceRootBinding, fetchRootFromBinding, resolveLegacySelectedFieldWithProvenance, isTemplateRootBinding, getRootBindingPath, resolveLegacySelectedField, isPageAbsoluteField, templateFetchRoot } from './section-data.js';
29
41
  import { decompressSpec } from '../studio-internal/dist/utils/spec-compression.js';
30
- import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages.default.js';
31
42
 
32
43
  // ✅ HYBRID APPROACH: List of internal components that should always be available
33
44
  // These include both built-in components AND system components (like "page")
@@ -145,7 +156,7 @@ function walkUiForCompositionMapping(ui, visit) {
145
156
  visit(node.uid, node.metadata.compositionUID);
146
157
  }
147
158
  if (node.slots && typeof node.slots === "object") {
148
- for (const slotNodes of Object.values(node.slots)) {
159
+ for (const slotNodes of Object.values(node.slots ?? {})) {
149
160
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
150
161
  for (const c of arr)
151
162
  walkUiForCompositionMapping(c, visit);
@@ -242,9 +253,18 @@ function sanitizeFieldPath(path) {
242
253
  * other shape (wrapper chains, cross-CT ref-target binds) keeps the original
243
254
  * `[...ancestorPrefix, ...selectedField]` behavior unchanged.
244
255
  */
245
- function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCtUids) {
256
+ function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCtUids, options) {
246
257
  const dropCtUids = new Set(referenceCtUids);
247
258
  const sf = sanitizeFieldPath(selectedField).filter((seg) => !dropCtUids.has(seg));
259
+ // A page-absolute field REPLACES the inherited prefix. The leading-overlap
260
+ // collapse below only catches an absolute path that happens to share a
261
+ // leading segment with its ancestor; one that does not overlap was blindly
262
+ // concatenated, producing e.g. `author.related_block` — a path the referenced
263
+ // content type does not have, which CDA silently drops so the section renders
264
+ // component defaults. Provenance answers this directly instead of guessing
265
+ // from the string. See `isPageAbsoluteField`.
266
+ if (options?.pageAbsolute && sf.length > 0)
267
+ return sf;
248
268
  // Collapse the leading overlap with `ancestorPrefix`. A section whose
249
269
  // `selected_field` is rooted at the PAGE content type re-declares the
250
270
  // ancestor's path FROM THE PAGE ROOT — e.g. nested passthrough sections each
@@ -310,7 +330,7 @@ function mapSectionRepeaterPaths(node, runningPath, map) {
310
330
  }
311
331
  }
312
332
  if (node.slots && typeof node.slots === "object") {
313
- for (const slotNodes of Object.values(node.slots)) {
333
+ for (const slotNodes of Object.values(node.slots ?? {})) {
314
334
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
315
335
  for (const c of arr)
316
336
  mapSectionRepeaterPaths(c, childPath, map);
@@ -358,7 +378,7 @@ function mapSectionSlotSegments(node, runningPath, map) {
358
378
  map.set(node.uid, childPath);
359
379
  }
360
380
  if (node.slots && typeof node.slots === "object") {
361
- for (const slotNodes of Object.values(node.slots)) {
381
+ for (const slotNodes of Object.values(node.slots ?? {})) {
362
382
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
363
383
  for (const c of arr)
364
384
  mapSectionSlotSegments(c, childPath, map);
@@ -417,7 +437,7 @@ function projectCrossBoundaryRepeaterBindings(node, map, onlyOut) {
417
437
  }
418
438
  }
419
439
  if (node.slots && typeof node.slots === "object") {
420
- for (const slotNodes of Object.values(node.slots)) {
440
+ for (const slotNodes of Object.values(node.slots ?? {})) {
421
441
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
422
442
  for (const c of arr)
423
443
  projectCrossBoundaryRepeaterBindings(c, map, onlyOut);
@@ -446,20 +466,23 @@ function projectCrossBoundaryRepeaterBindings(node, map, onlyOut) {
446
466
  * instead of the array → "items.map is not a function").
447
467
  */
448
468
  function resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid) {
469
+ const linkedSchemasFor = (compositionUid) => (sectionsByUid.get(compositionUid)?.linked_schemas ||
470
+ []);
471
+ // A Section data that names ANOTHER document (pinned entry / query / repeater)
472
+ // has no page-template path to project, and a cleared root (`null`) has none
473
+ // by definition — both yield "". Otherwise fall through to the legacy ladder,
474
+ // which both this and `resolveInstanceRootBinding` share, so the page-template
475
+ // projection and the Section data can never drift apart.
449
476
  const override = node.metadata?.sectionBindingOverride;
450
- let selectedField = typeof override?.selectedField === "string"
451
- ? override.selectedField
452
- : node.metadata?.selectedField;
453
- if (selectedField == null) {
454
- const linked = (sectionsByUid.get(node.metadata?.compositionUID)
455
- ?.linked_schemas || []);
456
- selectedField =
457
- linked.find((s) => s.content_type_uid === pageContentTypeUid)
458
- ?.selected_field ??
459
- linked[0]?.selected_field ??
460
- "";
461
- }
462
- return selectedField || "";
477
+ if (override && "rootBinding" in override) {
478
+ const root = resolveInstanceRootBinding(node, linkedSchemasFor, pageContentTypeUid);
479
+ if (!isTemplateRootBinding(root))
480
+ return "";
481
+ return getRootBindingPath(root).join(".");
482
+ }
483
+ // Unsanitised on purpose — callers sanitise at the point of use, and an
484
+ // indexed path (`navigation_menu_3[0].menu_subitems`) must survive to them.
485
+ return resolveLegacySelectedField(node, linkedSchemasFor, pageContentTypeUid);
463
486
  }
464
487
  /**
465
488
  * Walks the page UI tree and resolves every section-composition instance's
@@ -471,7 +494,10 @@ function resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid) {
471
494
  */
472
495
  function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
473
496
  const out = [];
474
- const walk = (node, parentRepeaterUID, ancestorPrefix,
497
+ const walk = (node, parentRepeaterUID,
498
+ // The document `ancestorPrefix` counts from, threaded together with it so a
499
+ // prefix can never travel without its fetch root (ADR 0017).
500
+ inheritedFetchRoot, ancestorPrefix,
475
501
  // Binding field path of the nearest enclosing TEMPLATE-bound Repeater that
476
502
  // hasn't yet been confirmed as a reference. A Repeater's template binding
477
503
  // alone can't be told apart from a plain array; the reference condition-
@@ -493,6 +519,9 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
493
519
  // Children that descend into THIS node's slots inherit `ancestorPrefix`,
494
520
  // extended by this node's reference path when it is a wrapper section.
495
521
  let childPrefix = ancestorPrefix;
522
+ // Always assigned together with `childPrefix` — a prefix is meaningless
523
+ // without the document it counts from (ADR 0017).
524
+ let childFetchRoot = inheritedFetchRoot;
496
525
  let childRepeaterRefField = enclosingRepeaterRefField;
497
526
  let childRefCtUids = refCtUids;
498
527
  // For a wrapper section, the per-section-slot internal Repeater/CB segments
@@ -535,17 +564,53 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
535
564
  node.metadata?.compositionUID &&
536
565
  node.uid) {
537
566
  const compositionUid = node.metadata.compositionUID;
567
+ const linkedSchemasFor = (uid) => (sectionsByUid.get(uid)?.linked_schemas ||
568
+ []);
538
569
  const selectedField = resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid);
539
570
  const override = node.metadata?.sectionBindingOverride;
540
571
  const uidRemapping = override?.uidRemapping ?? node.metadata.uidRemapping ?? {};
572
+ // Resolve the Section data, then decide which document this instance's paths
573
+ // belong to. A root naming ANOTHER document (pinned entry / query)
574
+ // rebases the fetch root for this instance and for everything in its
575
+ // slots — inside such a wrapper, paths really are relative to that
576
+ // document, not to the page entry.
577
+ // Only an EXPLICIT Section data can rebase the document. A section with no
578
+ // stored `rootBinding` derives a template-typed one from its
579
+ // `linked_schemas` — that means "no opinion", so it must inherit the
580
+ // enclosing document rather than reset it to the page template entry.
581
+ // Getting this wrong sends a slot child's include paths to a template
582
+ // entry a freeform page does not have.
583
+ const hasExplicitRoot = !!override &&
584
+ Object.prototype.hasOwnProperty.call(override, "rootBinding");
585
+ const sectionData = hasExplicitRoot
586
+ ? resolveInstanceRootBinding(node, linkedSchemasFor, pageContentTypeUid)
587
+ : undefined;
588
+ const ownFetchRoot = hasExplicitRoot
589
+ ? fetchRootFromBinding(sectionData, {
590
+ key: inheritedFetchRoot.key,
591
+ prefix: ancestorPrefix,
592
+ })
593
+ : { key: inheritedFetchRoot.key, prefix: ancestorPrefix };
594
+ const rebasedDocument = ownFetchRoot.key !== inheritedFetchRoot.key;
595
+ const { provenance } = resolveLegacySelectedFieldWithProvenance(node, linkedSchemasFor, pageContentTypeUid);
596
+ // A rebased document makes the inherited prefix meaningless, so the field
597
+ // is absolute within the new document by construction.
598
+ const fieldIsPageAbsolute = rebasedDocument || isPageAbsoluteField(selectedField, provenance);
599
+ // Paths for a rebased instance count from the new document's own prefix,
600
+ // not from the page-rooted chain we walked in on.
601
+ const effectiveAncestorPrefix = rebasedDocument
602
+ ? ownFetchRoot.prefix
603
+ : ancestorPrefix;
541
604
  out.push({
542
605
  instanceUid: node.uid,
543
606
  compositionUid,
544
607
  selectedField,
545
608
  uidRemapping,
546
609
  parentRepeaterUID,
547
- ancestorPrefix,
610
+ ancestorPrefix: effectiveAncestorPrefix,
548
611
  referenceCtUids: refCtUids,
612
+ fetchRootKey: ownFetchRoot.key,
613
+ fieldIsPageAbsolute,
549
614
  });
550
615
  // A whole-CT wrapper (selectedField "") adds no segment — correct, it
551
616
  // creates no reference hop. A reference-bound wrapper extends the prefix
@@ -554,13 +619,21 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
554
619
  // re-declare an overlapping page-root-absolute selected_field (e.g.
555
620
  // `modular_blocks` → `modular_blocks.ref_block` → `modular_blocks.ref_block`)
556
621
  // does not double-count segments into an invalid include[] path.
557
- childPrefix = extendAncestorPrefix(ancestorPrefix, selectedField);
622
+ // Slot children inherit this wrapper's document. When the wrapper rebased,
623
+ // they inherit the NEW one and the page-rooted chain is dropped; when the
624
+ // wrapper's own field is page-absolute, it replaces rather than extends.
625
+ childFetchRoot = rebasedDocument ? ownFetchRoot : inheritedFetchRoot;
626
+ childPrefix = rebasedDocument
627
+ ? extendAncestorPrefix(ownFetchRoot.prefix, "")
628
+ : fieldIsPageAbsolute
629
+ ? sanitizeFieldPath(selectedField)
630
+ : extendAncestorPrefix(ancestorPrefix, selectedField);
558
631
  // Compute this wrapper's slot-internal context so a section dropped into
559
632
  // a slot buried inside the wrapper's OWN Repeater/CB chain roots at the
560
633
  // full slot path (mirrors the editor's `indexSectionSlotsContext`).
561
634
  const wrapperUi = sectionsByUid.get(compositionUid)?.ui;
562
635
  if (wrapperUi) {
563
- const wrapperUiNode = typeof wrapperUi === "string" ? decompressSpec(wrapperUi) : wrapperUi;
636
+ const wrapperUiNode = typeof wrapperUi === "string" ? parseUI(wrapperUi) : wrapperUi;
564
637
  slotSegments = new Map();
565
638
  mapSectionSlotSegments(wrapperUiNode, [], slotSegments);
566
639
  }
@@ -592,35 +665,35 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
592
665
  metadata: { compositionUID: defaultUid },
593
666
  slots: {},
594
667
  };
595
- walk(synth, nextRepeater, slotSegments
668
+ walk(synth, nextRepeater, childFetchRoot, slotSegments
596
669
  ? [...childPrefix, ...(slotSegments.get(slotUid) || [])]
597
670
  : childPrefix, childRepeaterRefField, childRefCtUids, chain);
598
671
  }
599
672
  }
600
673
  if (node.slots && typeof node.slots === "object") {
601
- for (const [slotUid, slotNodes] of Object.entries(node.slots)) {
674
+ for (const [slotUid, slotNodes] of Object.entries(node.slots ?? {})) {
602
675
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
603
676
  const slotPrefix = slotSegments
604
677
  ? [...childPrefix, ...(slotSegments.get(slotUid) || [])]
605
678
  : childPrefix;
606
679
  for (const c of arr)
607
- walk(c, nextRepeater, slotPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
680
+ walk(c, nextRepeater, childFetchRoot, slotPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
608
681
  }
609
682
  }
610
683
  if (Array.isArray(node.children)) {
611
684
  // children (non-slot) stay in the same scope as this node.
612
685
  for (const c of node.children)
613
- walk(c, nextRepeater, ancestorPrefix, childRepeaterRefField, refCtUids, defaultAncestors);
686
+ walk(c, nextRepeater, inheritedFetchRoot, ancestorPrefix, childRepeaterRefField, refCtUids, defaultAncestors);
614
687
  }
615
688
  };
616
- walk(ui, null, [], null, []);
689
+ walk(ui, null, templateFetchRoot(), [], null, []);
617
690
  return out;
618
691
  }
619
692
  async function fetchSectionCompositionEntries(config, sectionUids, options) {
620
- if (!config.stackSdk || sectionUids.length === 0) {
693
+ if (sectionUids.length === 0) {
621
694
  return [];
622
695
  }
623
- const response = await config.stackSdk
696
+ const response = await requireStack(config)
624
697
  .ctQuery(config.contentTypeUid, {
625
698
  includeAll: true,
626
699
  includeAllDepth: INCLUDE_DEPTH_COUNT,
@@ -631,7 +704,7 @@ async function fetchSectionCompositionEntries(config, sectionUids, options) {
631
704
  return entriesFromResponse(response).map((entry) => ({
632
705
  ...entry,
633
706
  ui: typeof entry.ui === "string"
634
- ? decompressSpec(entry.ui)
707
+ ? parseUI(entry.ui, entry.composable_uid)
635
708
  : entry.ui,
636
709
  }));
637
710
  }
@@ -641,6 +714,46 @@ async function fetchSectionCompositionEntries(config, sectionUids, options) {
641
714
  * section) unioned with any `section-composition` nodes embedded in its `ui`.
642
715
  * One depth level of the nested-section graph.
643
716
  */
717
+ /**
718
+ * A component the stored layout uses that the registry does not have.
719
+ *
720
+ * Setup rather than content: the composition is fine, and the application did
721
+ * not tell the SDK about a component it refers to. The two kinds take opposite
722
+ * advice — ours register themselves on first import of the React package, so a
723
+ * missing built-in means the package root was never imported, while a missing
724
+ * custom one means a `registerComponent()` call had not run yet.
725
+ */
726
+ function componentsNotRegistered(componentTypes, areBuiltIn, config) {
727
+ return createStudioError({
728
+ code: StudioErrorCode.COMPONENT_NOT_REGISTERED,
729
+ headline: areBuiltIn
730
+ ? `Studio's own components are not registered: ${componentTypes.join(", ")}.`
731
+ : `These components are used by this composition and not registered: ${componentTypes.join(", ")}.`,
732
+ causes: areBuiltIn
733
+ ? [
734
+ {
735
+ cause: "The package root was never imported, so the built-in components never registered themselves.",
736
+ fix: 'Import it once before fetching: import "@contentstack/studio-react";',
737
+ },
738
+ {
739
+ cause: "The import was tree-shaken out of a server-only bundle.",
740
+ fix: "Keep the root import in the bundle that runs the fetch.",
741
+ },
742
+ ]
743
+ : [
744
+ {
745
+ cause: "The fetch ran before registerComponent() did.",
746
+ fix: "Import the module that registers them above the code that fetches.",
747
+ },
748
+ {
749
+ cause: "The composition uses a component this build does not have.",
750
+ fix: "Register it, or remove it from the composition.",
751
+ },
752
+ ],
753
+ context: buildStudioErrorContext(config),
754
+ findings: { componentTypes, areBuiltIn },
755
+ });
756
+ }
644
757
  /**
645
758
  * Adds FULL section entries inlined on `entry.linked_sections` (resolved by
646
759
  * `includeAll` depth) into `map`, RECURSIVELY — an inline section's own inline
@@ -664,7 +777,7 @@ function harvestInlineLinkedSections(entry, map) {
664
777
  if (map.has(e.uid))
665
778
  continue;
666
779
  const ui = typeof e.ui === "string"
667
- ? decompressSpec(e.ui)
780
+ ? parseUI(e.ui, e.composable_uid)
668
781
  : e.ui;
669
782
  map.set(e.uid, { ...e, ui });
670
783
  added.push(e.uid);
@@ -683,8 +796,10 @@ function referencedSectionUidsOf(entry) {
683
796
  uids.add(uid);
684
797
  }
685
798
  }
799
+ // This reader takes a narrowed shape that carries no uid, so the diagnosis
800
+ // names the case without naming the composition.
686
801
  const ui = typeof entry.ui === "string"
687
- ? decompressSpec(entry.ui)
802
+ ? parseUI(entry.ui)
688
803
  : entry.ui;
689
804
  if (ui)
690
805
  for (const u of collectSectionCompositionUIDs(ui))
@@ -704,7 +819,7 @@ async function getAllSectionCompositions(config, compositionEntry, options) {
704
819
  // that returned nothing (deleted section) or closing a cycle. Rounds =
705
820
  // nesting depth, not section count; breadth at a level is one call.
706
821
  const ui = typeof compositionEntry.ui === "string"
707
- ? decompressSpec(compositionEntry.ui)
822
+ ? parseUI(compositionEntry.ui, compositionEntry.composable_uid)
708
823
  : compositionEntry.ui;
709
824
  const requested = new Set();
710
825
  // Seed the frontier from the page UI + the page's linked_sections, plus the
@@ -755,14 +870,6 @@ async function getAllSectionCompositions(config, compositionEntry, options) {
755
870
  }
756
871
  return map;
757
872
  }
758
- function getAuthErrorMessage(err) {
759
- const detail = err?.error_message ||
760
- err?.errors?.api_key?.[0] ||
761
- err?.errors?.authorization?.[0] ||
762
- err?.message ||
763
- getErrorMessage(ErrorMessageKey.INVALID_CREDENTIALS_DEFAULT);
764
- return getErrorMessage(ErrorMessageKey.AUTHENTICATION_ERROR, { detail });
765
- }
766
873
  /**
767
874
  * SEO bindings are stored in the UI metadata with the same nested `value.path`
768
875
  * shape used by the normal data-binding system:
@@ -1044,20 +1151,10 @@ async function ensureUiComponentsLoaded(ui, sectionEntries) {
1044
1151
  }
1045
1152
  });
1046
1153
  if (missingBuiltInComponents.length > 0) {
1047
- throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, [
1048
- `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
1049
- "",
1050
- "Built-in components are auto-registered on first import of @contentstack/studio-react.",
1051
- "Fix: make sure the package root is imported at least once before fetch:",
1052
- ' import "@contentstack/studio-react";',
1053
- ].join("\n"));
1154
+ throw componentsNotRegistered(missingBuiltInComponents, true);
1054
1155
  }
1055
1156
  if (missingCustomComponents.length > 0) {
1056
- throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, [
1057
- `[Composable Studio SDK] Custom components not registered: ${missingCustomComponents.join(", ")}`,
1058
- "",
1059
- "Ensure all registerComponent() calls complete before fetching the composition.",
1060
- ].join("\n"));
1157
+ throw componentsNotRegistered(missingCustomComponents, false);
1061
1158
  }
1062
1159
  try {
1063
1160
  await componentRegistry.loadComponents(Array.from(usedComponents));
@@ -1067,116 +1164,6 @@ async function ensureUiComponentsLoaded(ui, sectionEntries) {
1067
1164
  throw error;
1068
1165
  }
1069
1166
  }
1070
- /**
1071
- * Helper function to detect and classify API errors
1072
- * @internal - Exported for testing purposes
1073
- */
1074
- function classifyApiError(err) {
1075
- const statusCode = getStatusCode(err);
1076
- // Check for authentication errors: Contentstack error_code 104/105 or errors.api_key/authorization (no HTTP status)
1077
- if (isContentstackAuthError(err) || (!statusCode && hasAuthErrorShape(err))) {
1078
- return {
1079
- errorType: ComposableStudioErrors.AUTHENTICATION_ERROR,
1080
- message: getAuthErrorMessage(err),
1081
- };
1082
- }
1083
- // Check for authentication errors (401, 403)
1084
- if (statusCode !== undefined && isAuthError(statusCode)) {
1085
- return {
1086
- errorType: ComposableStudioErrors.AUTHENTICATION_ERROR,
1087
- message: getAuthErrorMessage(err),
1088
- };
1089
- }
1090
- // Check for empty entry response (200 OK but no entries found)
1091
- // This happens when API succeeds but returns empty entry list
1092
- // Note: Pure empty objects {} should be treated as network errors, not empty responses
1093
- const isEmptyEntryResponse = statusCode === 200 &&
1094
- err &&
1095
- typeof err === "object" &&
1096
- err.entries &&
1097
- Array.isArray(err.entries) &&
1098
- err.entries.length === 0;
1099
- if (isEmptyEntryResponse) {
1100
- return {
1101
- errorType: ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND,
1102
- message: getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
1103
- contentType: "the composition",
1104
- }),
1105
- };
1106
- }
1107
- // Check for network errors (no response, timeout, connection refused)
1108
- if (!statusCode && isNetworkError(err)) {
1109
- // For empty objects, use the specific empty error message
1110
- if (typeof err === "object" && Object.keys(err).length === 0) {
1111
- return {
1112
- errorType: ComposableStudioErrors.NETWORK_ERROR,
1113
- message: getErrorMessage(ErrorMessageKey.NETWORK_ERROR_EMPTY),
1114
- };
1115
- }
1116
- // For other network errors, use the generic message with detail
1117
- return {
1118
- errorType: ComposableStudioErrors.NETWORK_ERROR,
1119
- message: getErrorMessage(ErrorMessageKey.NETWORK_ERROR_GENERIC, {
1120
- detail: err?.message ||
1121
- getErrorMessage(ErrorMessageKey.NETWORK_ERROR_DETAIL_DEFAULT),
1122
- }),
1123
- };
1124
- }
1125
- // Check for 404 - composition not found
1126
- if (statusCode === HttpStatus.NOT_FOUND ||
1127
- err?.error_code === ContentstackErrorCode.ENTRY_NOT_FOUND) {
1128
- return {
1129
- errorType: ComposableStudioErrors.COMPOSITION_NOT_FOUND,
1130
- message: err?.error_message ||
1131
- err?.message ||
1132
- getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404),
1133
- };
1134
- }
1135
- // Check for server errors (5xx)
1136
- if (statusCode !== undefined && isServerError(statusCode)) {
1137
- return {
1138
- errorType: ComposableStudioErrors.SERVER_ERROR,
1139
- message: getErrorMessage(ErrorMessageKey.SERVER_ERROR, {
1140
- statusCode,
1141
- detail: err?.error_message ||
1142
- err?.message ||
1143
- getErrorMessage(ErrorMessageKey.SERVER_ERROR_DETAIL_DEFAULT),
1144
- }),
1145
- };
1146
- }
1147
- // Other HTTP errors or default: single COMPOSITION_NOT_FOUND return with shared message builder
1148
- const message = statusCode !== undefined
1149
- ? getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_API, {
1150
- statusCode,
1151
- detail: err?.error_message ||
1152
- err?.message ||
1153
- getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_API_DETAIL_DEFAULT),
1154
- })
1155
- : err?.error_message ||
1156
- err?.message ||
1157
- getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_DEFAULT);
1158
- return {
1159
- errorType: ComposableStudioErrors.COMPOSITION_NOT_FOUND,
1160
- message,
1161
- };
1162
- }
1163
- /**
1164
- * Helper function to get troubleshooting information for composition fetch errors.
1165
- * Uses getTroubleshootingInfo from error-messages (single source of truth).
1166
- * @internal
1167
- */
1168
- function getTroubleshootingInfoForCompositionFetchError(errorType, isUrlBased = false) {
1169
- if (errorType === ComposableStudioErrors.NETWORK_ERROR) {
1170
- return getTroubleshootingInfo(TroubleshootingInfoKey.NETWORK_ERROR);
1171
- }
1172
- if (errorType === ComposableStudioErrors.AUTHENTICATION_ERROR) {
1173
- return getTroubleshootingInfo(TroubleshootingInfoKey.AUTHENTICATION_ERROR);
1174
- }
1175
- if (isUrlBased) {
1176
- return getTroubleshootingInfo(TroubleshootingInfoKey.COMPOSITION_NOT_FOUND_URL);
1177
- }
1178
- return getTroubleshootingInfo(TroubleshootingInfoKey.COMPOSITION_NOT_FOUND_UID);
1179
- }
1180
1167
  function addEditableTags(entry, contentTypeUid, tagsAsObject, locale = "en-us") {
1181
1168
  if (entry) {
1182
1169
  const appliedVariants = entry._applied_variants || entry?.system?.applied_variants || null;
@@ -1385,6 +1372,30 @@ function isSdkInitDebugEnabled() {
1385
1372
  * 🚀 RESTORED: Send INIT_STUDIO via Advanced Post Message from the right place
1386
1373
  * This fires IMMEDIATELY when SDK is created, ensuring proper timing (like original handshake)
1387
1374
  */
1375
+ /**
1376
+ * The connection's facts, as they stand when the configuration arrives.
1377
+ *
1378
+ * Only what is known is reported. With no stack there is nothing to read, so
1379
+ * nothing is said rather than a row of falsey values that would read as claims
1380
+ * about the site's setup.
1381
+ */
1382
+ function readSetupFacts(config) {
1383
+ const stack = config.stackSdk;
1384
+ if (!stack)
1385
+ return undefined;
1386
+ const livePreview = stack.livePreviewConfig;
1387
+ return {
1388
+ apiKey: stack.apiKey,
1389
+ environment: stack.environment,
1390
+ locale: config.locale,
1391
+ host: stack.host,
1392
+ livePreviewEnabled: livePreview?.enable === true,
1393
+ // A boolean, never the value: the token must not cross this boundary.
1394
+ hasPreviewToken: Boolean(livePreview?.preview_token),
1395
+ previewHost: livePreview?.host,
1396
+ hasPreviewHash: Boolean(livePreview?.live_preview),
1397
+ };
1398
+ }
1388
1399
  function sendInitStudioSignal(config) {
1389
1400
  try {
1390
1401
  const initPayload = {
@@ -1399,11 +1410,10 @@ function sendInitStudioSignal(config) {
1399
1410
  configPassedToTheSdk: {
1400
1411
  contentTypeUid: config.contentTypeUid,
1401
1412
  },
1413
+ setup: readSetupFacts(config),
1402
1414
  };
1403
1415
  // Send via Advanced Post Message using static imports
1404
- composableStudioEventManager
1405
- ?.send(POST_MESSAGE_EVENTS.INIT_STUDIO, initPayload)
1406
- .catch((error) => {
1416
+ sendStudioEvent(POST_MESSAGE_EVENTS.INIT_STUDIO, initPayload).catch((error) => {
1407
1417
  console.warn("⚠️ SDK: INIT_STUDIO failed:", error);
1408
1418
  });
1409
1419
  }
@@ -1411,12 +1421,129 @@ function sendInitStudioSignal(config) {
1411
1421
  console.warn("⚠️ SDK: Could not send INIT_STUDIO from generateSdk:", error);
1412
1422
  }
1413
1423
  }
1424
+ /** `data_sources` as stored — a JSON string, an array, or an object keyed by uid. */
1425
+ function parseDataSourceList(raw) {
1426
+ try {
1427
+ const value = typeof raw === "string" ? JSON.parse(raw) : raw;
1428
+ if (Array.isArray(value))
1429
+ return value;
1430
+ return value && typeof value === "object" ? Object.values(value) : [];
1431
+ }
1432
+ catch {
1433
+ return [];
1434
+ }
1435
+ }
1436
+ let extendQueryDeprecationWarned = false;
1437
+ /**
1438
+ * `extendQuery` predates reference ticking: an app passed extra include[] paths
1439
+ * per content type at fetch time. Studio now saves every reference a composition
1440
+ * needs, ticked by the author or implied by a binding, so the option is not
1441
+ * needed. Still honoured, and flagged once in development.
1442
+ */
1443
+ function warnIfExtendQueryPassed(extendQuery) {
1444
+ if (extendQueryDeprecationWarned)
1445
+ return;
1446
+ if (!extendQuery || typeof extendQuery !== "object")
1447
+ return;
1448
+ if (Object.keys(extendQuery).length === 0)
1449
+ return;
1450
+ extendQueryDeprecationWarned = true;
1451
+ if (process.env.NODE_ENV === "development") {
1452
+ console.warn("[studio] `extendQuery` is deprecated and will be removed in the next major. Tick the references in Studio instead — they are saved with the composition.");
1453
+ }
1454
+ }
1455
+ /**
1456
+ * The include[] paths the SDK works out for one placed section on top of what the
1457
+ * compositions persist: the section's own reference-condition paths composed onto
1458
+ * where the section sits, and each cumulative step of that position. They belong
1459
+ * on the request of the instance's fetch root (ADR 0017).
1460
+ *
1461
+ * For the template root, a step the page UI places as a modular-block field or a
1462
+ * block is left out — the Delivery API ignores include[] for those. Every other
1463
+ * step is kept, because one of them can be the reference the section sits on
1464
+ * (anchored at `author`, or under a Repeater over `related_articles`).
1465
+ */
1466
+ function derivedIncludePathsForInstance(binding, sectionDerivedPaths, modularBlocks) {
1467
+ const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids, { pageAbsolute: binding.fieldIsPageAbsolute });
1468
+ const remapSeg = (seg) => binding.uidRemapping?.[seg] ?? seg;
1469
+ const paths = new Set();
1470
+ for (const p of sectionDerivedPaths) {
1471
+ const full = [...prefix, ...sanitizeFieldPath(p).map(remapSeg)].join(".");
1472
+ if (full)
1473
+ paths.add(full);
1474
+ }
1475
+ const acc = [];
1476
+ for (const seg of prefix) {
1477
+ acc.push(seg);
1478
+ const hop = acc.join(".");
1479
+ if (binding.fetchRootKey !== TEMPLATE_FETCH_ROOT_KEY ||
1480
+ !isModularBlockPath(hop, modularBlocks)) {
1481
+ paths.add(hop);
1482
+ }
1483
+ }
1484
+ return [...paths];
1485
+ }
1486
+ /** `getEntriesQueries` reads `ui` as a string; a section entry carries it parsed. */
1487
+ const asCompositionEntryWithUiString = (entry) => ({
1488
+ ...entry,
1489
+ ui: typeof entry.ui === "string" ? entry.ui : JSON.stringify(entry.ui),
1490
+ });
1491
+ /**
1492
+ * Every include[] path the SDK would work out on its own for a composition,
1493
+ * grouped by the fetch root whose request it belongs on — `"template"`, a
1494
+ * `<ct>:<uid>` pinned entry, or `query:<uid>` (ADR 0017, ADR 0018):
1495
+ *
1496
+ * - the composition's own reference-condition paths, on `"template"`;
1497
+ * - for every placed section, its reference-condition paths composed onto where
1498
+ * it sits, and each step of that position (`derivedIncludePathsForInstance`).
1499
+ *
1500
+ * Below COMPLETE_INCLUDES_FROM_SCHEMA_VERSION the SDK adds these at render. From
1501
+ * that version on it adds none: Studio calls this at save, keeps what the schema
1502
+ * confirms is a reference, and persists it on the matching data source, so the
1503
+ * composition carries everything its fetch roots need. The render path and the
1504
+ * save path share `derivedIncludePathsForInstance`, so they cannot drift apart.
1505
+ *
1506
+ * Paths are unvalidated — the SDK has no schema. A caller persisting them must
1507
+ * validate them first.
1508
+ */
1509
+ function derivePlacementIncludePaths(compositionEntry, sectionEntries) {
1510
+ const pageUi = typeof compositionEntry.ui === "string"
1511
+ ? decompressSpec(compositionEntry.ui)
1512
+ : compositionEntry.ui;
1513
+ if (!pageUi)
1514
+ return {};
1515
+ const connectedContentTypeUid = compositionEntry.connected_content_type || "";
1516
+ const out = new Map();
1517
+ const add = (key, paths) => {
1518
+ const kept = paths.filter(Boolean);
1519
+ if (!kept.length)
1520
+ return;
1521
+ const existing = out.get(key) ?? new Set();
1522
+ for (const path of kept)
1523
+ existing.add(path);
1524
+ out.set(key, existing);
1525
+ };
1526
+ add(TEMPLATE_FETCH_ROOT_KEY, getEntriesQueries(asCompositionEntryWithUiString({
1527
+ ...compositionEntry,
1528
+ ui: JSON.stringify(pageUi),
1529
+ }), connectedContentTypeUid, {}).templateReferencesPath);
1530
+ const sectionsByUid = new Map(sectionEntries.map((s) => [s.uid, s]));
1531
+ const modularBlocks = indexModularBlocks(pageUi);
1532
+ for (const binding of collectSectionInstanceBindings(pageUi, sectionsByUid, connectedContentTypeUid)) {
1533
+ const section = sectionsByUid.get(binding.compositionUid);
1534
+ if (!section)
1535
+ continue;
1536
+ const sectionRefs = getEntriesQueries(asCompositionEntryWithUiString(section), "", {});
1537
+ add(binding.fetchRootKey, derivedIncludePathsForInstance(binding, sectionRefs.templateReferencesPath, modularBlocks));
1538
+ }
1539
+ return Object.fromEntries([...out].map(([key, paths]) => [key, [...paths]]));
1540
+ }
1414
1541
  function generateSdk(userConfig) {
1415
1542
  const config = processUserConfig(userConfig);
1416
1543
  if (clientRendererModeUtil.isInsideStudioFrame()) {
1417
1544
  const sp = new URLSearchParams(window.location.search);
1418
1545
  const hash = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) || "";
1419
- config.stackSdk.livePreviewQuery?.(hash);
1546
+ config.stackSdk?.livePreviewQuery?.(hash);
1420
1547
  // Studio is the source of truth for locale/variant when the SDK runs
1421
1548
  // inside its iframe. Overriding the user-supplied config values here
1422
1549
  // means every SDK-side fetch (initial spec, linked-entry references,
@@ -1518,13 +1645,26 @@ function generateSdk(userConfig) {
1518
1645
  * previously only the template entry saw the URL-pattern locale; the secondary
1519
1646
  * fetches dropped it.
1520
1647
  */
1521
- const resolveLocale = (patternLocale, optionLocale, searchParams) => {
1648
+ const resolveLocale = (patternLocale, optionLocale, searchParams) => resolveLocaleWithSource(patternLocale, optionLocale, searchParams).locale;
1649
+ /**
1650
+ * The same resolution, reporting which tier won — needed because a missing
1651
+ * language is the developer's fault or a visitor's typo depending on where
1652
+ * the locale came from. Inferring that from "a {{locale}} capture existed" is
1653
+ * wrong: the capture can lose to the Studio parameter. Shares the ranking
1654
+ * with resolveLocale so the two cannot disagree about what was sent.
1655
+ */
1656
+ const resolveLocaleWithSource = (patternLocale, optionLocale, searchParams) => {
1522
1657
  const studioLocale = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE, searchParams);
1523
- return (studioLocale ||
1524
- patternLocale ||
1525
- optionLocale ||
1526
- config.locale ||
1527
- config.stackSdk?.locale);
1658
+ // Studio's own parameter is a setting an author chose, not part of the
1659
+ // address a visitor asked for, so it ranks as configuration.
1660
+ if (studioLocale)
1661
+ return { locale: studioLocale, source: "configuration" };
1662
+ if (patternLocale)
1663
+ return { locale: patternLocale, source: "url-pattern" };
1664
+ return {
1665
+ locale: optionLocale || config.locale || config.stackSdk?.locale,
1666
+ source: "configuration",
1667
+ };
1528
1668
  };
1529
1669
  /**
1530
1670
  * Resolve the URL-pattern locale for a composition ONCE per fetch, and return
@@ -1579,6 +1719,179 @@ function generateSdk(userConfig) {
1579
1719
  // The raw postMessage approach has been consolidated into the proven INIT_STUDIO system
1580
1720
  // REMOVED: initiateStudioHandshake - no longer needed with Advanced Post Message
1581
1721
  // The INIT_STUDIO system via composableStudioEventManager handles reliable delivery
1722
+ /**
1723
+ * Names the entry a binding reads, for the middle of a sentence.
1724
+ *
1725
+ * A binding that names its own entry gets the uid and the content type,
1726
+ * because in a project with many entries that is the whole of the lookup. A
1727
+ * template binding names neither — it reads whichever entry the composition is
1728
+ * connected to on this request — so it gets a phrase instead, and the sentence
1729
+ * says less rather than printing a stand-in where a uid should be.
1730
+ */
1731
+ function describeBindingSubject(defect) {
1732
+ if (!defect.entryUid || !defect.contentTypeUid) {
1733
+ return "the entry this composition is connected to";
1734
+ }
1735
+ return `entry ${defect.entryUid} of "${defect.contentTypeUid}"`;
1736
+ }
1737
+ /**
1738
+ * Says which bindings will render blank, and why.
1739
+ *
1740
+ * Walks every binding on the page, so it is skipped outright unless somebody
1741
+ * will read the result.
1742
+ *
1743
+ * The missing-path case carries two causes and asserts neither, and that is
1744
+ * the rule for this whole group rather than a hedge. We hold the entry, not
1745
+ * the content type's schema, so a field that was renamed and a field the
1746
+ * author simply has not filled in are the same absence from here. Picking one
1747
+ * would send half of these readers to change something that is correct.
1748
+ */
1749
+ function reportBindingDefects(pageUi, data, request) {
1750
+ if (!degradedReportingIsOn(config))
1751
+ return;
1752
+ for (const defect of findBindingDefects(pageUi, data.dataSources, request)) {
1753
+ if (defect.code === DegradedCode.PREVIEW_ASSET_PROJECTION_NULL) {
1754
+ reportDegraded({
1755
+ code: DegradedCode.PREVIEW_ASSET_PROJECTION_NULL,
1756
+ headline: `The asset at "${defect.path}" on ` +
1757
+ describeBindingSubject(defect) +
1758
+ " came back empty from the preview service. The same request " +
1759
+ "returns it from the published CDN.",
1760
+ causes: [
1761
+ {
1762
+ cause: "A known Preview API defect empties an asset asked for by a " +
1763
+ "dotted path when a modular-blocks field is asked for beside it.",
1764
+ fix: "Check the published site before changing anything — the binding is probably fine. Nothing in this project fixes it.",
1765
+ },
1766
+ {
1767
+ cause: "The asset is genuinely not set on this entry.",
1768
+ fix: "Set it, or leave it — the binding works either way.",
1769
+ },
1770
+ ],
1771
+ findings: {
1772
+ path: defect.path,
1773
+ entryUid: defect.entryUid,
1774
+ contentTypeUid: defect.contentTypeUid,
1775
+ },
1776
+ }, config);
1777
+ continue;
1778
+ }
1779
+ if (defect.code === DegradedCode.BINDING_PATH_MISSING) {
1780
+ reportDegraded({
1781
+ code: DegradedCode.BINDING_PATH_MISSING,
1782
+ headline: `The binding "${defect.path}" does not exist on ` +
1783
+ describeBindingSubject(defect) +
1784
+ ".",
1785
+ causes: [
1786
+ {
1787
+ cause: "The field was renamed or removed on the content type.",
1788
+ fix: "Re-point the binding at the field it should read.",
1789
+ },
1790
+ {
1791
+ cause: "The field is there and nobody has filled it in yet.",
1792
+ fix: "Nothing to fix here — add the content.",
1793
+ },
1794
+ ],
1795
+ findings: {
1796
+ path: defect.path,
1797
+ entryUid: defect.entryUid,
1798
+ contentTypeUid: defect.contentTypeUid,
1799
+ },
1800
+ }, config);
1801
+ continue;
1802
+ }
1803
+ reportDegraded({
1804
+ code: DegradedCode.BINDING_SHAPE_MISMATCH,
1805
+ headline: `The binding "${defect.path}" reads a single value and resolved ` +
1806
+ `to a ${defect.resolvedTo}.`,
1807
+ causes: [
1808
+ {
1809
+ cause: "The binding points at a container rather than at a field inside it.",
1810
+ fix: `Point it at a field within "${defect.path}".`,
1811
+ },
1812
+ ],
1813
+ findings: {
1814
+ path: defect.path,
1815
+ entryUid: defect.entryUid,
1816
+ contentTypeUid: defect.contentTypeUid,
1817
+ resolvedTo: defect.resolvedTo,
1818
+ },
1819
+ }, config);
1820
+ }
1821
+ }
1822
+ /**
1823
+ * Says how many references came back as pointers rather than as entries.
1824
+ *
1825
+ * Runs over everything that was fetched, so it is skipped outright unless
1826
+ * somebody will read the result — a production page that is fine should not
1827
+ * pay to walk its own content looking for a report nobody asked for.
1828
+ *
1829
+ * Two causes, neither asserted. A composition nesting past the include depth
1830
+ * and a referenced entry that was deleted produce byte-identical pointers, so
1831
+ * there is nothing here that could tell them apart. Depth leads because it is
1832
+ * the one a whole branch of pointers points at.
1833
+ */
1834
+ function reportUnresolvedReferences(data) {
1835
+ if (!degradedReportingIsOn(config))
1836
+ return;
1837
+ const unresolvedCount = countUnresolvedReferences(data.dataSources);
1838
+ if (unresolvedCount === 0)
1839
+ return;
1840
+ reportDegraded({
1841
+ code: DegradedCode.REFERENCES_UNRESOLVED,
1842
+ headline: `${unresolvedCount} ` +
1843
+ `${unresolvedCount === 1 ? "reference" : "references"} came back ` +
1844
+ "as pointers rather than entries, so anything bound past them has " +
1845
+ "nothing to show.",
1846
+ causes: [
1847
+ {
1848
+ cause: "This composition nests references deeper than " +
1849
+ `${INCLUDE_DEPTH_COUNT} levels, which is as far as one request follows them.`,
1850
+ fix: "Bind the entries further down directly, or flatten the nesting.",
1851
+ },
1852
+ {
1853
+ cause: "A referenced entry was deleted after something pointed at it.",
1854
+ fix: "Re-point those references, or remove the elements that read them.",
1855
+ },
1856
+ ],
1857
+ findings: { unresolvedCount, includeDepth: INCLUDE_DEPTH_COUNT },
1858
+ }, config);
1859
+ }
1860
+ /**
1861
+ * Says which bound entries did not arrive.
1862
+ *
1863
+ * Silent when every entry came back, which is the ordinary case — the report
1864
+ * exists for the batch that quietly returns fewer rows than it was asked for,
1865
+ * because from the page that is indistinguishable from an element nobody ever
1866
+ * bound.
1867
+ */
1868
+ function reportMissingEntries(contentTypeUid, requestedUids, missingUids) {
1869
+ if (missingUids.length === 0)
1870
+ return;
1871
+ reportDegraded({
1872
+ code: DegradedCode.FEWER_ENTRIES_THAN_REQUESTED,
1873
+ headline: `Asked "${contentTypeUid}" for ${requestedUids.length} ` +
1874
+ `${requestedUids.length === 1 ? "entry" : "entries"} and got ` +
1875
+ `${requestedUids.length - missingUids.length}. ` +
1876
+ `Missing: ${missingUids.join(", ")}.`,
1877
+ causes: [
1878
+ {
1879
+ cause: "The missing entries are not published to this environment.",
1880
+ fix: "Publish them, or check which environment this site reads.",
1881
+ },
1882
+ {
1883
+ cause: "They were deleted after something was bound to them.",
1884
+ fix: "Re-point those bindings, or remove the elements that read them.",
1885
+ },
1886
+ ],
1887
+ findings: {
1888
+ contentTypeUid,
1889
+ requestedCount: requestedUids.length,
1890
+ returnedCount: requestedUids.length - missingUids.length,
1891
+ missingUids,
1892
+ },
1893
+ }, config);
1894
+ }
1582
1895
  async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}, searchParams) {
1583
1896
  const { variantAlias, locale } = options;
1584
1897
  const isInsideEditor = isEditorFetch(searchParams);
@@ -1594,7 +1907,14 @@ function generateSdk(userConfig) {
1594
1907
  let onlyQuery = [];
1595
1908
  // When inside Studio or Visual Builder, fetch all fields (don't use onlyQueries)
1596
1909
  if (!isInsideEditor) {
1597
- const entryProjections = entryUids.map((entry_uid) => staticBindingOnlyQueries[_content_type_uid][entry_uid] || []);
1910
+ // `?.` on the content type: an entry can reach `staticBindingQueries`
1911
+ // with no projection bucket at all (a section rooted at a whole
1912
+ // document asks for every field, so it contributes no only[] keys).
1913
+ // Indexing straight through threw a TypeError here, and because the
1914
+ // whole batch assembly sits inside a try/catch the failure surfaced
1915
+ // as NO REQUEST rather than as an error — the entry was silently
1916
+ // never fetched (E2E DR5.10).
1917
+ const entryProjections = entryUids.map((entry_uid) => staticBindingOnlyQueries[_content_type_uid]?.[entry_uid] || []);
1598
1918
  // An entry with no projection of its own (e.g. bound whole, path {})
1599
1919
  // is fetched with ALL fields; batching it with projected siblings
1600
1920
  // must not narrow it, so one unprojected entry makes the whole batch
@@ -1616,7 +1936,7 @@ function generateSdk(userConfig) {
1616
1936
  return chunk(entryUids, STATIC_ENTRY_BATCH_SIZE).map((uids) => ({
1617
1937
  ct_uid: _content_type_uid,
1618
1938
  uids,
1619
- promise: config.stackSdk
1939
+ promise: requireStack(config)
1620
1940
  .ctQuery(_content_type_uid, {
1621
1941
  only: onlyQuery,
1622
1942
  references,
@@ -1639,18 +1959,15 @@ function generateSdk(userConfig) {
1639
1959
  addEditableTags(entry, ct_uid, true, entry?.locale || "en-us");
1640
1960
  }
1641
1961
  }
1642
- if (process.env.NODE_ENV === "development") {
1643
- const returnedUids = new Set(entries.map((entry) => entry.uid));
1644
- const missingUids = uids.filter((entry_uid) => !returnedUids.has(entry_uid));
1645
- if (missingUids.length) {
1646
- console.log(`Static entries missing from ${ct_uid} response: ${missingUids.join(", ")}`);
1647
- }
1648
- }
1962
+ const returnedUids = new Set(entries.map((entry) => entry.uid));
1963
+ reportMissingEntries(ct_uid, uids, uids.filter((entry_uid) => !returnedUids.has(entry_uid)));
1649
1964
  }
1650
1965
  else {
1651
- if (process.env.NODE_ENV === "development") {
1652
- console.log("Unhandled message case");
1653
- }
1966
+ // The batch never answered, so every entry in it is missing. The
1967
+ // request's own failure belongs to the diagnosis of a failed fetch;
1968
+ // what is reported here is the consequence the author can see, which
1969
+ // is that the elements bound to these entries have nothing to show.
1970
+ reportMissingEntries(ct_uid, uids, uids);
1654
1971
  }
1655
1972
  }
1656
1973
  }
@@ -1665,13 +1982,36 @@ function generateSdk(userConfig) {
1665
1982
  * Supports custom fetcher overrides (per-query > global > SDK default).
1666
1983
  */
1667
1984
  async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions, urlPatternContext, searchParams) {
1668
- if (!config.stackSdk) {
1669
- return;
1670
- }
1671
- const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = fetchOptions;
1985
+ const { connected_content_type, compositionQuery, includeQueries, onlyQueries: requestedOnlyQueries, } = fetchOptions;
1672
1986
  if (!connected_content_type) {
1673
1987
  return;
1674
1988
  }
1989
+ // A page that binds many sections can push the projection past the Delivery
1990
+ // API's URL limit, which rejects the whole request and costs us the page.
1991
+ // The projection is an optimisation; the reference paths are not. Give up
1992
+ // the projection and accept a larger response rather than losing the entry.
1993
+ const urlBudget = applyUrlBudget({
1994
+ references: includeQueries,
1995
+ only: requestedOnlyQueries,
1996
+ });
1997
+ const onlyQueries = urlBudget.only;
1998
+ // Both of these are for whoever is building the site, not for its logs. The
1999
+ // first says we gave up an optimisation; the second predicts a request that
2000
+ // will fail. Neither is actionable from a production console, and a page
2001
+ // that trips one trips it on every render.
2002
+ if (process.env.NODE_ENV === "development") {
2003
+ if (urlBudget.dropped) {
2004
+ console.warn(`[Studio] Field projection dropped for "${connected_content_type}": ` +
2005
+ `${requestedOnlyQueries.length} only[] parameters would have exceeded ` +
2006
+ `the Delivery API URL limit. Fetching all fields instead — the page is ` +
2007
+ `correct but the response is larger than necessary.`);
2008
+ }
2009
+ if (referencesExceedBudget(includeQueries)) {
2010
+ console.warn(`[Studio] The reference paths for "${connected_content_type}" alone ` +
2011
+ `(${includeQueries.length} include[] parameters) exceed the Delivery ` +
2012
+ `API URL limit. This request is expected to fail with 414.`);
2013
+ }
2014
+ }
1675
2015
  const { fetchComposition: _, fetchTemplateEntry: perQueryFetchTemplateEntry, ...resolvedOptions } = compositionQueryOptions || {};
1676
2016
  // Safe access to enhanced options (available only when SDK provides Studio Intelligence)
1677
2017
  const enhancedOptions = compositionQueryOptions; // Type assertion for internal properties
@@ -1711,35 +2051,39 @@ function generateSdk(userConfig) {
1711
2051
  if (!isInsideVB && !isInsideStudio) {
1712
2052
  queryOptions.only = onlyQueries;
1713
2053
  }
1714
- let dataQuery = config.stackSdk
2054
+ let dataQuery = requireStack(config)
1715
2055
  .ctQuery(connected_content_type, queryOptions)
1716
2056
  .limit(1);
1717
- dataQuery = config.stackSdk.where(dataQuery, "uid", resolvedOptions.templateEntryUid);
2057
+ dataQuery = requireStack(config).where(dataQuery, "uid", resolvedOptions.templateEntryUid);
1718
2058
  const response = await dataQuery.find().catch((err) => {
1719
- const { errorType, message } = classifyApiError(err);
1720
- const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
1721
- ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
1722
- : errorType;
1723
- throw new ComposableStudioError(finalErrorType, finalErrorType ===
1724
- ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
1725
- ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
1726
- : message, {
1727
- options: fetchOptions,
1728
- response: err,
1729
- statusCode: err?.status || err?.statusCode,
1730
- errorCode: err?.error_code,
1731
- });
2059
+ // Classified by the same response rules as any other request. The
2060
+ // name it used to carry described the content it was after rather
2061
+ // than what went wrong, so a wrong api key and a delivery outage
2062
+ // both surfaced as "fetching connected data failed".
2063
+ const servedByNow = resolveServedBy(config.stackSdk?.livePreviewConfig);
2064
+ throw (classifyResponseError(err, config, { servedBy: servedByNow }) ??
2065
+ diagnoseUnreadableResponse(err, config, { servedBy: servedByNow }));
1732
2066
  });
1733
2067
  const entries = entriesFromResponse(response);
1734
2068
  if (!entries?.[0]) {
1735
- throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
1736
- contentType: connected_content_type,
1737
- }), {
1738
- contentType: connected_content_type,
1739
- hasStackSdk: !!config.stackSdk,
1740
- compositionQuery,
1741
- options: fetchOptions,
1742
- troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
2069
+ throw createStudioError({
2070
+ code: StudioErrorCode.CONNECTED_ENTRY_NOT_FOUND,
2071
+ headline: `No entry was found for the content type "${connected_content_type}" this composition is connected to.`,
2072
+ causes: [
2073
+ {
2074
+ cause: `No entry of "${connected_content_type}" matches this composition.`,
2075
+ fix: "Create one, or point the composition at a content type that has entries.",
2076
+ },
2077
+ {
2078
+ cause: "The entry exists and is not published to this environment.",
2079
+ fix: "Publish it, or check which environment this site reads.",
2080
+ },
2081
+ ],
2082
+ context: buildStudioErrorContext(config, resolveServedBy(config.stackSdk?.livePreviewConfig)),
2083
+ findings: {
2084
+ contentTypeUid: connected_content_type,
2085
+ templateEntryUid: resolvedOptions?.templateEntryUid,
2086
+ },
1743
2087
  });
1744
2088
  }
1745
2089
  return entries[0];
@@ -1749,6 +2093,12 @@ function generateSdk(userConfig) {
1749
2093
  ? parseUrlMetadata(compositionEntry.url_metadata)
1750
2094
  : null;
1751
2095
  if (parsedMetadata && "url" in compositionQuery && compositionQuery.url) {
2096
+ // The only request in the SDK whose locale can come from the address
2097
+ // rather than the setup, which is what decides whose fault it is.
2098
+ let localeSent = {
2099
+ locale: undefined,
2100
+ source: "configuration",
2101
+ };
1752
2102
  // Metadata path: resolve using url_queries + extracted variables
1753
2103
  try {
1754
2104
  // Enhanced include queries with Studio Intelligence
@@ -1761,7 +2111,7 @@ function generateSdk(userConfig) {
1761
2111
  if (parsedMetadata.url_source ===
1762
2112
  COMPOSITION_PREVIEW_URL_SOURCES.CONTENT_TYPE_URL_PATTERN) {
1763
2113
  // content_type_url_pattern: Direct URL match (no pattern variables).
1764
- let directQuery = config.stackSdk
2114
+ let directQuery = requireStack(config)
1765
2115
  .ctQuery(connected_content_type, {
1766
2116
  references: allIncludeQueries,
1767
2117
  variantAlias: resolveVariant(),
@@ -1769,7 +2119,7 @@ function generateSdk(userConfig) {
1769
2119
  only: finalOnlyQueries,
1770
2120
  })
1771
2121
  .limit(1);
1772
- directQuery = config.stackSdk.where(directQuery, "url", compositionQuery.url);
2122
+ directQuery = requireStack(config).where(directQuery, "url", compositionQuery.url);
1773
2123
  const response = await directQuery.find();
1774
2124
  const entries = entriesFromResponse(response);
1775
2125
  if (entries?.[0]) {
@@ -1792,8 +2142,9 @@ function generateSdk(userConfig) {
1792
2142
  });
1793
2143
  if (matchResult.matched && matchResult.variables) {
1794
2144
  const patternMetadata = matchResult.variables.metadata;
2145
+ localeSent = resolveLocaleWithSource(patternMetadata.locale, resolvedOptions.locale, searchParams);
1795
2146
  // Build query using extracted variables and metadata
1796
- const templateQuery = resolveByUrlSource(config.stackSdk, parsedMetadata.url_source, compositionQuery, matchResult.variables, parsedMetadata.url_queries, connected_content_type, {
2147
+ const templateQuery = resolveByUrlSource(requireStack(config), parsedMetadata.url_source, compositionQuery, matchResult.variables, parsedMetadata.url_queries, connected_content_type, {
1797
2148
  references: allIncludeQueries,
1798
2149
  variantAlias: resolveVariant(),
1799
2150
  locale: resolveLocale(patternMetadata.locale, resolvedOptions.locale, searchParams),
@@ -1813,6 +2164,17 @@ function generateSdk(userConfig) {
1813
2164
  }
1814
2165
  }
1815
2166
  catch (metadataError) {
2167
+ // The legacy fallback below is for a pattern that did not resolve.
2168
+ // A setup or credential failure is not: retrying asks the same broken
2169
+ // connection the same question, then blames a missing page. So
2170
+ // anything we can diagnose is raised here instead of swallowed.
2171
+ const diagnosed = classifyResponseError(metadataError, config, {
2172
+ locale: localeSent.locale,
2173
+ localeSource: localeSent.source,
2174
+ url: compositionQuery.url,
2175
+ });
2176
+ if (diagnosed)
2177
+ throw diagnosed;
1816
2178
  console.warn("Metadata template resolution failed, falling back to legacy:", metadataError);
1817
2179
  }
1818
2180
  }
@@ -1834,38 +2196,42 @@ function generateSdk(userConfig) {
1834
2196
  if (!isInsideVB && !isInsideStudio) {
1835
2197
  queryOptions.only = onlyQueries;
1836
2198
  }
1837
- let dataQuery = config.stackSdk
2199
+ let dataQuery = requireStack(config)
1838
2200
  .ctQuery(connected_content_type, queryOptions)
1839
2201
  .limit(1);
1840
2202
  // Legacy URL matching (note: this is likely incorrect for patterned URLs as mentioned in plan)
1841
2203
  if ("url" in compositionQuery && compositionQuery.url) {
1842
- dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
2204
+ dataQuery = requireStack(config).where(dataQuery, "url", compositionQuery.url);
1843
2205
  }
1844
2206
  const response = await dataQuery.find().catch((err) => {
1845
- const { errorType, message } = classifyApiError(err);
1846
- const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
1847
- ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
1848
- : errorType;
1849
- throw new ComposableStudioError(finalErrorType, finalErrorType ===
1850
- ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
1851
- ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
1852
- : message, {
1853
- options: fetchOptions,
1854
- response: err,
1855
- statusCode: err?.status || err?.statusCode,
1856
- errorCode: err?.error_code,
1857
- });
2207
+ // Classified by the same response rules as any other request. The
2208
+ // name it used to carry described the content it was after rather
2209
+ // than what went wrong, so a wrong api key and a delivery outage
2210
+ // both surfaced as "fetching connected data failed".
2211
+ const servedByNow = resolveServedBy(config.stackSdk?.livePreviewConfig);
2212
+ throw (classifyResponseError(err, config, { servedBy: servedByNow }) ??
2213
+ diagnoseUnreadableResponse(err, config, { servedBy: servedByNow }));
1858
2214
  });
1859
2215
  const entries = entriesFromResponse(response);
1860
2216
  if (!entries?.[0]) {
1861
- throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
1862
- contentType: connected_content_type,
1863
- }), {
1864
- contentType: connected_content_type,
1865
- hasStackSdk: !!config.stackSdk,
1866
- compositionQuery,
1867
- options: fetchOptions,
1868
- troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
2217
+ throw createStudioError({
2218
+ code: StudioErrorCode.CONNECTED_ENTRY_NOT_FOUND,
2219
+ headline: `No entry was found for the content type "${connected_content_type}" this composition is connected to.`,
2220
+ causes: [
2221
+ {
2222
+ cause: `No entry of "${connected_content_type}" matches this composition.`,
2223
+ fix: "Create one, or point the composition at a content type that has entries.",
2224
+ },
2225
+ {
2226
+ cause: "The entry exists and is not published to this environment.",
2227
+ fix: "Publish it, or check which environment this site reads.",
2228
+ },
2229
+ ],
2230
+ context: buildStudioErrorContext(config, resolveServedBy(config.stackSdk?.livePreviewConfig)),
2231
+ findings: {
2232
+ contentTypeUid: connected_content_type,
2233
+ templateEntryUid: resolvedOptions?.templateEntryUid,
2234
+ },
1869
2235
  });
1870
2236
  }
1871
2237
  return entries[0];
@@ -1880,22 +2246,54 @@ function generateSdk(userConfig) {
1880
2246
  options: resolvedOptions,
1881
2247
  includeReferences: includeQueries,
1882
2248
  only: isInsideStudio || isInsideVB ? [] : onlyQueries,
1883
- stackSdk: config.stackSdk.sdk,
2249
+ stackSdk: config.stackSdk?.sdk,
1884
2250
  defaultFetch: defaultImpl,
1885
2251
  });
1886
2252
  if (!entry) {
1887
- throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
1888
- contentType: connected_content_type,
1889
- }));
2253
+ throw createStudioError({
2254
+ code: StudioErrorCode.CONNECTED_ENTRY_NOT_FOUND,
2255
+ headline: `No entry was found for the content type "${connected_content_type}" this composition is connected to.`,
2256
+ causes: [
2257
+ {
2258
+ cause: `No entry of "${connected_content_type}" matches this composition.`,
2259
+ fix: "Create one, or point the composition at a content type that has entries.",
2260
+ },
2261
+ {
2262
+ cause: "The entry exists and is not published to this environment.",
2263
+ fix: "Publish it, or check which environment this site reads.",
2264
+ },
2265
+ ],
2266
+ context: buildStudioErrorContext(config, resolveServedBy(config.stackSdk?.livePreviewConfig)),
2267
+ findings: {
2268
+ contentTypeUid: connected_content_type,
2269
+ templateEntryUid: resolvedOptions?.templateEntryUid,
2270
+ },
2271
+ });
1890
2272
  }
1891
2273
  }
1892
2274
  else {
1893
2275
  entry = await defaultImpl();
1894
2276
  // Check if defaultImpl returned empty/null entry (e.g., empty entry list from API)
1895
2277
  if (!entry) {
1896
- throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
1897
- contentType: connected_content_type,
1898
- }));
2278
+ throw createStudioError({
2279
+ code: StudioErrorCode.CONNECTED_ENTRY_NOT_FOUND,
2280
+ headline: `No entry was found for the content type "${connected_content_type}" this composition is connected to.`,
2281
+ causes: [
2282
+ {
2283
+ cause: `No entry of "${connected_content_type}" matches this composition.`,
2284
+ fix: "Create one, or point the composition at a content type that has entries.",
2285
+ },
2286
+ {
2287
+ cause: "The entry exists and is not published to this environment.",
2288
+ fix: "Publish it, or check which environment this site reads.",
2289
+ },
2290
+ ],
2291
+ context: buildStudioErrorContext(config, resolveServedBy(config.stackSdk?.livePreviewConfig)),
2292
+ findings: {
2293
+ contentTypeUid: connected_content_type,
2294
+ templateEntryUid: resolvedOptions?.templateEntryUid,
2295
+ },
2296
+ });
1899
2297
  }
1900
2298
  }
1901
2299
  if (config.cslp.appendTags) {
@@ -1949,42 +2347,69 @@ function generateSdk(userConfig) {
1949
2347
  })
1950
2348
  .filter((p) => p.length > 0)),
1951
2349
  ];
1952
- // Static entries (contentstack DS) → extendQuery[ctUid].includeReferences
2350
+ // `extendQuery` carries only what the consuming app passes, and that option
2351
+ // is deprecated: references are ticked in Studio and saved with the
2352
+ // composition. The saved sets are routed to the one request each belongs to
2353
+ // instead — the template set to the template entry, a pinned entry's set to
2354
+ // that entry. Pushed through `extendQuery` they applied per CONTENT TYPE:
2355
+ // onto the template request whenever a pinned entry shared its type, and
2356
+ // never onto a pinned entry the page does not bind directly (a section's
2357
+ // Section data root), which is where they were needed.
2358
+ warnIfExtendQueryPassed(options?.extendQuery);
1953
2359
  const csDS = rawDataSources.find((ds) => ds.uid === DATA_SOURCES.CONTENTSTACK);
1954
- if (csDS?.resolvedReferences && Array.isArray(csDS.data)) {
1955
- for (const entry of csDS.data) {
1956
- const raw = csDS.resolvedReferences[entry.uid] ?? [];
1957
- const paths = sanitizeResolvedPaths(raw);
2360
+ // Each pinned entry's saved set, keyed `<ct>:<uid>` — the page's own pinned
2361
+ // entries and every section's.
2362
+ const savedByPinnedEntry = new Map();
2363
+ const collectPinnedSaved = (dataSources) => {
2364
+ const ds = dataSources.find((d) => d?.uid === DATA_SOURCES.CONTENTSTACK);
2365
+ if (!ds?.resolvedReferences || !Array.isArray(ds.data))
2366
+ return;
2367
+ for (const entry of ds.data) {
2368
+ if (!entry?.uid || !entry?._content_type_uid)
2369
+ continue;
2370
+ const paths = sanitizeResolvedPaths(ds.resolvedReferences[entry.uid] ?? []);
1958
2371
  if (!paths.length)
1959
2372
  continue;
1960
- const ct = entry._content_type_uid;
1961
- if (!extendQuery[ct])
1962
- extendQuery[ct] = { includeReferences: [] };
1963
- extendQuery[ct].includeReferences = [
1964
- ...new Set([...(extendQuery[ct].includeReferences ?? []), ...paths]),
1965
- ];
2373
+ const key = `${entry._content_type_uid}:${entry.uid}`;
2374
+ savedByPinnedEntry.set(key, [
2375
+ ...new Set([...(savedByPinnedEntry.get(key) ?? []), ...paths]),
2376
+ ]);
1966
2377
  }
2378
+ };
2379
+ collectPinnedSaved(rawDataSources);
2380
+ for (const section of sectionEntries) {
2381
+ collectPinnedSaved(parseDataSourceList(section.data_sources));
1967
2382
  }
1968
- // Template entry (contentstackPreview DS) → extendQuery[connectedContentTypeUid].includeReferences
1969
- // Now safe to inject because sanitizeResolvedPaths filters out picker-tree
1970
- // tracking paths (pure numeric indexes) before they reach the CDA query.
1971
2383
  const connectedContentTypeUid = compositionEntry.connected_content_type || "";
1972
2384
  const previewDS = rawDataSources.find((ds) => ds.uid === DATA_SOURCES.TEMPLATE);
1973
- if (previewDS?.resolvedReferences && connectedContentTypeUid) {
1974
- const previewPaths = sanitizeResolvedPaths(Object.values(previewDS.resolvedReferences).flat());
1975
- if (previewPaths.length) {
1976
- if (!extendQuery[connectedContentTypeUid])
1977
- extendQuery[connectedContentTypeUid] = { includeReferences: [] };
1978
- extendQuery[connectedContentTypeUid].includeReferences = [
1979
- ...new Set([
1980
- ...(extendQuery[connectedContentTypeUid].includeReferences ?? []),
1981
- ...previewPaths,
1982
- ]),
1983
- ];
1984
- }
1985
- }
2385
+ // The template entry's saved set, for the template request only. Every
2386
+ // owner key is read — ticks live under their own keys beside the save's.
2387
+ const templateSavedPaths = previewDS?.resolvedReferences && connectedContentTypeUid
2388
+ ? sanitizeResolvedPaths(Object.values(previewDS.resolvedReferences).flat())
2389
+ : [];
1986
2390
  const resolvedOptions = { ...options, extendQuery };
1987
- const { templateReferencesPath, templateOnlyKeys, contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, } = getEntriesQueries(compositionEntry, connectedContentTypeUid, resolvedOptions);
2391
+ // Whether this SDK adds include[] paths of its own on top of the set the
2392
+ // composition carries (ADR 0018).
2393
+ //
2394
+ // Decided per composition, not per app. A composition saved before the set
2395
+ // became authoritative may hold only the author's ticks — the save-time
2396
+ // derive did not exist until 2026-07-17 — so the SDK's own derivation is the
2397
+ // only thing fetching a reference that was bound but never ticked. Dropping
2398
+ // it there would render those sections blank, which is why the version is
2399
+ // read off the entry rather than assumed from the SDK being up to date.
2400
+ //
2401
+ // From that version on it speaks for EVERY fetch root. At save, Studio runs
2402
+ // `derivePlacementIncludePaths` — this SDK's own derivation — validates the
2403
+ // result against the schema, and persists it on the matching data source:
2404
+ // the template's paths on `template`, a pinned entry's under its uid, a
2405
+ // query's under the query uid. Each set is routed below to the one request
2406
+ // it belongs to, so nothing is left for the SDK to work out.
2407
+ //
2408
+ // `deriveIncludePaths` overrides in either direction for a consumer who
2409
+ // knows better than the marker does.
2410
+ const derivesIncludePaths = config.deriveIncludePaths ??
2411
+ !compositionCarriesCompleteIncludes(compositionEntry.schema_version);
2412
+ const { templateReferencesPath: uiAndPersistedReferencesPath, persistedReferencesPath, templateOnlyKeys, contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, } = getEntriesQueries(compositionEntry, connectedContentTypeUid, resolvedOptions);
1988
2413
  // When inside Studio, ensure ALL configured contentstack DS entries are in
1989
2414
  // contentstackEntriesReferencesPath — not just those with active bindings.
1990
2415
  // Entries without bindings are still shown in Studio's data picker and must
@@ -2100,11 +2525,41 @@ function generateSdk(userConfig) {
2100
2525
  // page-rooted `ancestorPrefix` + its own `selectedField`, so a multi-level
2101
2526
  // reference chain (W1 → W2 → …) fetches the full nested include depth.
2102
2527
  const sectionsByUid = new Map(sectionEntries.map((s) => [s.uid, s]));
2103
- const instanceBindings = collectSectionInstanceBindings(typeof compositionEntry.ui === "string"
2104
- ? decompressSpec(compositionEntry.ui)
2105
- : compositionEntry.ui, sectionsByUid, connectedContentTypeUid);
2106
- const mergedTemplateRefs = [...templateReferencesPath];
2528
+ const pageUi = typeof compositionEntry.ui === "string"
2529
+ ? parseUI(compositionEntry.ui, compositionEntry.composable_uid)
2530
+ : compositionEntry.ui;
2531
+ const instanceBindings = collectSectionInstanceBindings(pageUi, sectionsByUid, connectedContentTypeUid);
2532
+ // The author's own modular-block choices, used below to drop the include[]
2533
+ // paths the Delivery API discards.
2534
+ const modularBlocks = indexModularBlocks(pageUi);
2535
+ const templateReferencesPath = derivesIncludePaths
2536
+ ? uiAndPersistedReferencesPath
2537
+ : persistedReferencesPath;
2538
+ const mergedTemplateRefs = [
2539
+ ...templateReferencesPath,
2540
+ ...templateSavedPaths,
2541
+ ];
2107
2542
  const mergedTemplateOnly = [...templateOnlyKeys];
2543
+ // Include paths for sections whose Section data names a document OTHER than the
2544
+ // page template entry (ADR 0017). Keyed by fetch root so each set flushes to
2545
+ // its own request: `mergedTemplateRefs` above is just the "template" bucket.
2546
+ // Without this the paths are computed correctly and then discarded, and the
2547
+ // section renders structure with no content — references come back as
2548
+ // `{uid, _content_type_uid}` stubs and a repeater over them yields empty rows.
2549
+ const refsByFetchRoot = new Map();
2550
+ const pushForFetchRoot = (key, path) => {
2551
+ if (!path)
2552
+ return;
2553
+ if (key === TEMPLATE_FETCH_ROOT_KEY) {
2554
+ mergedTemplateRefs.push(path);
2555
+ return;
2556
+ }
2557
+ const existing = refsByFetchRoot.get(key);
2558
+ if (existing)
2559
+ existing.push(path);
2560
+ else
2561
+ refsByFetchRoot.set(key, [path]);
2562
+ };
2108
2563
  for (const binding of instanceBindings) {
2109
2564
  const section = sectionsByUid.get(binding.compositionUid);
2110
2565
  if (!section)
@@ -2116,8 +2571,25 @@ function generateSdk(userConfig) {
2116
2571
  // Reference-ancestor placement: when the section sits inside a page
2117
2572
  // Repeater(reference)+reference-ConditionBlock (see
2118
2573
  // composeSectionTemplatePrefix).
2119
- const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids);
2574
+ const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids, { pageAbsolute: binding.fieldIsPageAbsolute });
2120
2575
  const remapSeg = (seg) => binding.uidRemapping?.[seg] ?? seg;
2576
+ const fetchRootKey = binding.fetchRootKey;
2577
+ // Register the fetch root even when the section contributes NO reference
2578
+ // include paths. `pushForFetchRoot` only records a key that carries a
2579
+ // path, and the flush below turns each key into an entry request — so a
2580
+ // section rooted at a pinned entry whose bindings are all scalar
2581
+ // (`{ heading }`) named a document nobody ever asked the CDA for. The
2582
+ // pool came back without it, `buildScopedDataSources` logged "no pooled
2583
+ // entry" and the deployed page rendered component defaults while the
2584
+ // editor — which fetches every configured data source regardless of
2585
+ // bindings — rendered it fine (E2E DR5.10). An empty path list means "all
2586
+ // fields": `resolveStaticData` drops the projection for a batch that has
2587
+ // one unprojected entry, which is what a whole-document root wants.
2588
+ if (fetchRootKey && parseEntryFetchRootKey(fetchRootKey)) {
2589
+ if (!refsByFetchRoot.has(fetchRootKey)) {
2590
+ refsByFetchRoot.set(fetchRootKey, []);
2591
+ }
2592
+ }
2121
2593
  const sectionAsCompositionEntry = {
2122
2594
  ...section,
2123
2595
  ui: typeof section.ui === "string"
@@ -2125,9 +2597,11 @@ function generateSdk(userConfig) {
2125
2597
  : JSON.stringify(section.ui),
2126
2598
  };
2127
2599
  const sectionRefs = getEntriesQueries(sectionAsCompositionEntry, config.contentTypeUid, resolvedOptions);
2128
- // Section reference include paths: UI-derived (reference conditions) plus
2129
- // saved toggle paths from the SECTION's own data_sources[template].
2130
- const sectionTemplateRefPaths = new Set(sectionRefs.templateReferencesPath);
2600
+ // The SECTION's own saved paths, from its data_sources[template]. Stored
2601
+ // relative to the section's own scope, so they are composed onto where it
2602
+ // sits here — the one job that cannot leave the SDK, since only the host
2603
+ // knows the placement. Sent in both modes.
2604
+ const sectionTemplateRefPaths = new Set(sectionRefs.persistedReferencesPath);
2131
2605
  try {
2132
2606
  const sds = Array.isArray(section.data_sources)
2133
2607
  ? section.data_sources
@@ -2148,20 +2622,40 @@ function generateSdk(userConfig) {
2148
2622
  for (const p of sectionTemplateRefPaths) {
2149
2623
  const full = [...prefix, ...sanitizeFieldPath(p).map(remapSeg)].join(".");
2150
2624
  if (full)
2151
- mergedTemplateRefs.push(full);
2625
+ pushForFetchRoot(fetchRootKey, full);
2626
+ }
2627
+ // What the SDK works out on its own for this placement: the section's
2628
+ // reference-condition paths and each step of its position. From
2629
+ // COMPLETE_INCLUDES_FROM_SCHEMA_VERSION on, Studio has saved these on the
2630
+ // fetch root's data source (`derivePlacementIncludePaths`), so none are
2631
+ // added here.
2632
+ if (derivesIncludePaths) {
2633
+ for (const path of derivedIncludePathsForInstance(binding, sectionRefs.templateReferencesPath, modularBlocks)) {
2634
+ pushForFetchRoot(fetchRootKey, path);
2635
+ }
2152
2636
  }
2153
- // Include + project EVERY cumulative hop of the composed prefix so each
2154
- // reference in the chain is fetched and the next hop is reachable, e.g.
2155
- // include[]=related_articles, include[]=related_articles.author
2637
+ // Project every cumulative step of the composed prefix so the next step is
2638
+ // reachable in the response, e.g.
2156
2639
  // only[BASE][]=related_articles, only[related_articles][]=author
2640
+ // Wanted in both modes — it is what keeps a block or a referenced entry in
2641
+ // the response, independent of whether the step is sent as an include[].
2157
2642
  {
2158
2643
  let parent = "BASE";
2159
2644
  const acc = [];
2160
2645
  for (const seg of prefix) {
2161
2646
  acc.push(seg);
2162
- mergedTemplateRefs.push(acc.join("."));
2163
- mergedTemplateOnly.push([parent, seg]);
2164
- parent = acc.join(".");
2647
+ const hop = acc.join(".");
2648
+ // only[] is carried for the template fetch root only in v1 —
2649
+ // `MergedEntryNeed` has no projection slot, and an only[] union is
2650
+ // SUBTRACTIVE: several sections and the page can request the same
2651
+ // entry with different projections, and a union that misses one
2652
+ // requester silently drops fields. include[] unions are additive and
2653
+ // safe. Pinned entries are already fetched unprojected, so this costs
2654
+ // payload size, not correctness (ADR 0017).
2655
+ if (fetchRootKey === TEMPLATE_FETCH_ROOT_KEY) {
2656
+ mergedTemplateOnly.push([parent, seg]);
2657
+ }
2658
+ parent = hop;
2165
2659
  }
2166
2660
  }
2167
2661
  // Re-parent the section's field projections under the selectedField
@@ -2178,7 +2672,9 @@ function generateSdk(userConfig) {
2178
2672
  ? `${prefix.join(".")}.${remappedParent}`
2179
2673
  : remappedParent;
2180
2674
  }
2181
- mergedTemplateOnly.push([newParent, remappedChild]);
2675
+ if (fetchRootKey === TEMPLATE_FETCH_ROOT_KEY) {
2676
+ mergedTemplateOnly.push([newParent, remappedChild]);
2677
+ }
2182
2678
  }
2183
2679
  }
2184
2680
  // Cross-boundary repeater bindings: a page-authored Repeater/Text bound to a
@@ -2198,15 +2694,12 @@ function generateSdk(userConfig) {
2198
2694
  continue;
2199
2695
  const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids);
2200
2696
  const sectionUi = typeof section.ui === "string"
2201
- ? decompressSpec(section.ui)
2697
+ ? parseUI(section.ui, section.composable_uid)
2202
2698
  : section.ui;
2203
2699
  mapSectionRepeaterPaths(sectionUi, prefix, repeaterPathMap);
2204
2700
  }
2205
2701
  if (repeaterPathMap.size > 0) {
2206
- const pageUiForProjection = typeof compositionEntry.ui === "string"
2207
- ? decompressSpec(compositionEntry.ui)
2208
- : compositionEntry.ui;
2209
- projectCrossBoundaryRepeaterBindings(pageUiForProjection, repeaterPathMap, mergedTemplateOnly);
2702
+ projectCrossBoundaryRepeaterBindings(pageUi, repeaterPathMap, mergedTemplateOnly);
2210
2703
  }
2211
2704
  }
2212
2705
  // ---- D7: fold the template entry into the reference union ----
@@ -2240,7 +2733,70 @@ function generateSdk(userConfig) {
2240
2733
  delete mergedOnly[templateContentTypeUid][knownTemplateUid];
2241
2734
  }
2242
2735
  }
2243
- const dedupedTemplateRefs = [...new Set(mergedTemplateRefs)];
2736
+ // ---- Flush the non-template fetch roots (ADR 0017) ----
2737
+ // Each key that is not "template" names its own document, so its include
2738
+ // paths belong on THAT document's request. A `<ct>:<uid>` key routes into
2739
+ // `mergedRefs`, which `resolveStaticData` fetches and which already unions
2740
+ // include paths per (ct_uid, entry_uid) across requesters — the page asks
2741
+ // for the entry with its own includes, the section adds more, they merge.
2742
+ //
2743
+ // A `query:<uid>` key is handed to `resolveQueryData`, which assembles each
2744
+ // query's include[] and unions these in under that query's uid. They were
2745
+ // dropped here before — a section rooted at a query item got neither its
2746
+ // saved paths nor the steps of its position, and its references came back
2747
+ // as stubs.
2748
+ const sectionQueryIncludes = {};
2749
+ for (const [key, paths] of refsByFetchRoot.entries()) {
2750
+ const entryRef = parseEntryFetchRootKey(key);
2751
+ if (!entryRef) {
2752
+ const queryUid = key.startsWith("query:") ? key.slice(6) : "";
2753
+ if (queryUid) {
2754
+ sectionQueryIncludes[queryUid] = [
2755
+ ...new Set([...(sectionQueryIncludes[queryUid] ?? []), ...paths]),
2756
+ ];
2757
+ }
2758
+ else if (process.env.NODE_ENV === "development") {
2759
+ console.warn(`[studio] section include paths for fetch root "${key}" name no document the spec fetch knows. Paths: ${paths.join(", ")}`);
2760
+ }
2761
+ continue;
2762
+ }
2763
+ const { contentTypeUid, entryUid } = entryRef;
2764
+ if (!mergedRefs[contentTypeUid])
2765
+ mergedRefs[contentTypeUid] = {};
2766
+ const existing = mergedRefs[contentTypeUid][entryUid] ?? [];
2767
+ mergedRefs[contentTypeUid][entryUid] = Array.from(new Set([...existing, ...paths]));
2768
+ // Keep the projection map in step. An empty list means "no only[] keys of
2769
+ // its own", which makes the batch unprojected — every field — and that is
2770
+ // what a document-level fetch root wants.
2771
+ if (!mergedOnly[contentTypeUid])
2772
+ mergedOnly[contentTypeUid] = {};
2773
+ if (!mergedOnly[contentTypeUid][entryUid]) {
2774
+ mergedOnly[contentTypeUid][entryUid] = [];
2775
+ }
2776
+ }
2777
+ // Each pinned entry's saved set goes on that entry's own request — whether
2778
+ // the page binds the entry directly or only a section's Section data names
2779
+ // it. Applied to entries being fetched anyway; a saved set is never a reason
2780
+ // to fetch an entry nothing reads.
2781
+ for (const [key, saved] of savedByPinnedEntry) {
2782
+ const entryRef = parseEntryFetchRootKey(key);
2783
+ if (!entryRef)
2784
+ continue;
2785
+ const { contentTypeUid, entryUid } = entryRef;
2786
+ const existing = mergedRefs[contentTypeUid]?.[entryUid];
2787
+ if (!existing)
2788
+ continue;
2789
+ mergedRefs[contentTypeUid][entryUid] = [
2790
+ ...new Set([...existing, ...saved]),
2791
+ ];
2792
+ }
2793
+ // Sections, the page itself and the caller's own extra references have all
2794
+ // been merged by this point, so this is the first place we can tell whether
2795
+ // a path is just the start of a longer one. Drop those here, before the
2796
+ // projection patch below, so it sees the paths the request will carry.
2797
+ const dedupedTemplateRefs = dropImpliedParents([
2798
+ ...new Set(mergedTemplateRefs),
2799
+ ]);
2244
2800
  // A deep reference that lives inside a section slot only assembles its full
2245
2801
  // include[] path in this merged set (the page sees the slot child at the
2246
2802
  // wrong depth; the section sees its own reference repeater but not the
@@ -2257,6 +2813,14 @@ function generateSdk(userConfig) {
2257
2813
  seenOnly.add(sig);
2258
2814
  return true;
2259
2815
  });
2816
+ // Captured here rather than after the awaits below. Live-preview state sits
2817
+ // on a process-wide client, so under concurrent server rendering a value
2818
+ // read once these have resolved can belong to somebody else's request — and
2819
+ // a diagnosis that names the wrong service is worse than none.
2820
+ const requestFacts = {
2821
+ servedBy: resolveServedBy(config.stackSdk?.livePreviewConfig),
2822
+ projection: dedupedTemplateOnly,
2823
+ };
2260
2824
  await Promise.all([
2261
2825
  fetchTemplateEntry({
2262
2826
  connected_content_type: templateContentTypeUid,
@@ -2273,8 +2837,11 @@ function generateSdk(userConfig) {
2273
2837
  variantAlias: pageVariantAlias,
2274
2838
  locale: pageLocale,
2275
2839
  sectionEntries,
2840
+ sectionQueryIncludes,
2276
2841
  }, searchParams),
2277
2842
  ]);
2843
+ reportUnresolvedReferences(data);
2844
+ reportBindingDefects(pageUi, data, requestFacts);
2278
2845
  // D7: the folded template entry (fetched once, above) also feeds the static
2279
2846
  // entry pool so contentstack-entry references to it resolve without the
2280
2847
  // second fetch we removed from mergedRefs.
@@ -2288,24 +2855,24 @@ function generateSdk(userConfig) {
2288
2855
  }
2289
2856
  attachSectionCompositionContexts(data, compositionEntry, sectionEntries);
2290
2857
  // Build per-instance scoped data sources (pure) and attach to spec.
2291
- const pageUi = typeof compositionEntry.ui === "string"
2292
- ? decompressSpec(compositionEntry.ui)
2293
- : compositionEntry.ui;
2858
+ // `pageUi` is the spec decompressed once, above.
2294
2859
  data.section_scoped_data = buildSectionScopedData(compositionEntry, pageUi, sectionEntries, data.dataSources);
2860
+ // Store the page's dataSources ONCE for section subtrees to read back.
2861
+ // Entering a section replaces `dataSources`, so this is how a section
2862
+ // reaches the outer page's data. By reference — same object, not a copy.
2863
+ data.page_data_sources = data.dataSources;
2295
2864
  return data;
2296
2865
  }
2297
2866
  async function fetchSpec(queryOptions, options, skipComponentLoading = false, searchParams) {
2298
- if (!config.stackSdk) {
2299
- throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
2300
- }
2867
+ requireStack(config);
2301
2868
  // Phase 1: Get Studio Intelligence if available (graceful fallback)
2302
2869
  const studioIntelligence = await StudioIntelligenceManager.getStudioIntelligence(options, config);
2303
2870
  // Phase 2: Enhance options with Studio Intelligence (preserves user preferences)
2304
2871
  const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
2305
2872
  // Phase 3: Fetch with enhanced context (preserves custom fetchers)
2306
- const { compositionEntry, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch(searchParams));
2873
+ const { compositionEntry, urlResolution, requestContext } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch(searchParams));
2307
2874
  const ui = typeof compositionEntry.ui === "string"
2308
- ? decompressSpec(compositionEntry.ui)
2875
+ ? parseUI(compositionEntry.ui, compositionEntry.composable_uid)
2309
2876
  : compositionEntry.ui;
2310
2877
  const sectionEntries = await getAllSectionCompositions(config, compositionEntry, enhancedOptions);
2311
2878
  const data = await fetchData(compositionEntry, queryOptions, enhancedOptions, Array.from(sectionEntries.values()), searchParams);
@@ -2342,32 +2909,11 @@ function generateSdk(userConfig) {
2342
2909
  });
2343
2910
  // Handle missing internal components (SDK import issue)
2344
2911
  if (missingBuiltInComponents.length > 0) {
2345
- const errorMessage = [
2346
- `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
2347
- "",
2348
- "Built-in components are auto-registered on first import of @contentstack/studio-react.",
2349
- "If you're seeing this, the package root was either not imported on this code path",
2350
- "(e.g. a server-only bundle that pulls a subpath but not the root) or was tree-shaken away.",
2351
- "",
2352
- "Fix: make sure the package root is imported at least once before fetchSpec runs:",
2353
- ' import "@contentstack/studio-react";',
2354
- ].join("\n");
2355
- throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
2912
+ throw componentsNotRegistered(missingBuiltInComponents, true, config);
2356
2913
  }
2357
2914
  // Handle missing custom components (normal - user needs to register)
2358
2915
  if (missingCustomComponents.length > 0) {
2359
- const errorMessage = [
2360
- `[Composable Studio SDK] Custom components not registered: ${missingCustomComponents.join(", ")}`,
2361
- "",
2362
- "This error occurs when fetchSpec() is called before custom components are registered.",
2363
- "In SSR environments, ensure all registerComponent() calls complete before fetchSpec().",
2364
- "",
2365
- "Fix: Import your component registry module at the top of your server file:",
2366
- ' import "./components/registry"; // Register custom components',
2367
- " const spec = await fetchSpec({ ... }); // Now safe to use",
2368
- "",
2369
- ].join("\n");
2370
- throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
2916
+ throw componentsNotRegistered(missingCustomComponents, false, config);
2371
2917
  }
2372
2918
  // Load the components
2373
2919
  try {
@@ -2385,6 +2931,7 @@ function generateSdk(userConfig) {
2385
2931
  sectionCompositions: Array.from(sectionEntries.values()),
2386
2932
  // Studio-only resolution diagnostics (URL metadata path); undefined otherwise.
2387
2933
  urlResolution,
2934
+ requestContext,
2388
2935
  config: {
2389
2936
  ...getLightConfig(),
2390
2937
  // Debug information for compatibility checking (type assertion for internal properties)
@@ -2403,14 +2950,12 @@ function generateSdk(userConfig) {
2403
2950
  * Runs in both SSR and CSR (plain async, not a hook).
2404
2951
  */
2405
2952
  async function fetchCompositionSpecOnly(queryOptions, options, skipComponentLoading = false) {
2406
- if (!config.stackSdk) {
2407
- throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
2408
- }
2953
+ requireStack(config);
2409
2954
  const studioIntelligence = await StudioIntelligenceManager.getStudioIntelligence(options, config);
2410
2955
  const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
2411
- const { compositionEntry, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch());
2956
+ const { compositionEntry, urlResolution, requestContext } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch());
2412
2957
  const ui = typeof compositionEntry.ui === "string"
2413
- ? decompressSpec(compositionEntry.ui)
2958
+ ? parseUI(compositionEntry.ui, compositionEntry.composable_uid)
2414
2959
  : compositionEntry.ui;
2415
2960
  // Section composition entries are STRUCTURAL (their ui trees are needed to
2416
2961
  // render embedded section nodes and to compute section scoping) — keep them.
@@ -2429,6 +2974,7 @@ function generateSdk(userConfig) {
2429
2974
  compositionEntry,
2430
2975
  sectionCompositions: Array.from(sectionEntries.values()),
2431
2976
  urlResolution,
2977
+ requestContext,
2432
2978
  config: {
2433
2979
  ...getLightConfig(),
2434
2980
  _studioEnhanced: enhancedOptions._enhancementMode === "studio-aware",
@@ -2437,9 +2983,7 @@ function generateSdk(userConfig) {
2437
2983
  };
2438
2984
  }
2439
2985
  async function fetchMultipleSpecs(queries, options) {
2440
- if (!config.stackSdk) {
2441
- throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
2442
- }
2986
+ requireStack(config);
2443
2987
  // Fetch all specs in parallel (skip individual component loading)
2444
2988
  const specs = await Promise.all(queries.map((query) => fetchSpec(query, options, true)));
2445
2989
  // In production mode, perform union analysis and load components once.
@@ -2479,33 +3023,11 @@ function generateSdk(userConfig) {
2479
3023
  });
2480
3024
  // Handle missing internal components (SDK import issue)
2481
3025
  if (missingBuiltInComponents.length > 0) {
2482
- const errorMessage = [
2483
- `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
2484
- "",
2485
- "Built-in components are auto-registered on first import of @contentstack/studio-react.",
2486
- "If you're seeing this, the package root was either not imported on this code path",
2487
- "(e.g. a server-only bundle that pulls a subpath but not the root) or was tree-shaken away.",
2488
- "",
2489
- "Fix: make sure the package root is imported at least once before fetchSpec runs:",
2490
- ' import "@contentstack/studio-react";',
2491
- ].join("\n");
2492
- throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
3026
+ throw componentsNotRegistered(missingBuiltInComponents, true, config);
2493
3027
  }
2494
3028
  // Handle missing custom components (normal - user needs to register)
2495
3029
  if (missingCustomComponents.length > 0) {
2496
- const errorMessage = [
2497
- `[Composable Studio SDK] Custom components not registered: ${missingCustomComponents.join(", ")}`,
2498
- "",
2499
- "This error occurs when fetchMultipleSpecs() is called before custom components are registered.",
2500
- "In SSR environments, ensure all registerComponent() calls complete before fetchMultipleSpecs().",
2501
- "",
2502
- "Fix: Import your component registry module at the top of your server file:",
2503
- ' import "./components/registry"; // Register custom components',
2504
- " const specs = await fetchMultipleSpecs([...]); // Now safe to use",
2505
- "",
2506
- `Missing components: ${missingCustomComponents.join(", ")}`,
2507
- ].join("\n");
2508
- throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
3030
+ throw componentsNotRegistered(missingCustomComponents, false, config);
2509
3031
  }
2510
3032
  // Load all unique components in parallel (deduplication happens automatically)
2511
3033
  try {
@@ -2522,11 +3044,21 @@ function generateSdk(userConfig) {
2522
3044
  * Reusable helper to fetch data from Contentstack
2523
3045
  * Now uses QueryExecutor internally to support full QuerySpec with filters, sorting, etc.
2524
3046
  *
3047
+ * An empty result is reported from in here rather than by the caller, and
3048
+ * that placement is the point: every path out of this function returns an
3049
+ * empty list, so a caller cannot tell a query that ran and matched nothing
3050
+ * from one that never ran at all. Saying "this data source returned no
3051
+ * entries" about a query that failed is the same mistake as calling a broken
3052
+ * request a missing page.
3053
+ *
2525
3054
  * @param querySpec - Full QuerySpec with filters, sorting, pagination, etc.
2526
3055
  * @param context - RuntimeContext for expression resolution (URL params, etc.)
3056
+ * @param dataSourceUid - The data source this query belongs to, named in the
3057
+ * report when it comes back empty. Optional because a caller that has no
3058
+ * name for it would rather have the query than the report.
2527
3059
  * @returns Promise with data array and count
2528
3060
  */
2529
- async function fetchContentstackData(querySpec, context = {}, options) {
3061
+ async function fetchContentstackData(querySpec, context = {}, options, dataSourceUid) {
2530
3062
  if (!config.stackSdk) {
2531
3063
  return { entries: [], count: 0 };
2532
3064
  }
@@ -2540,6 +3072,21 @@ function generateSdk(userConfig) {
2540
3072
  const result = await executor.execute(querySpec, 1, context, options);
2541
3073
  const entries = result.entries || [];
2542
3074
  const count = result.count || 0;
3075
+ if (entries.length === 0 && dataSourceUid) {
3076
+ // Carries no causes on purpose. A query matching nothing is not a
3077
+ // failure by any measure available here — the filters may be right and
3078
+ // the content simply not written yet — so naming a fix would invent a
3079
+ // problem. It is reported because "why is my list empty" is the
3080
+ // question this whole group exists to answer.
3081
+ reportDegraded({
3082
+ code: DegradedCode.QUERY_RETURNED_NO_ROWS,
3083
+ headline: `The data source "${dataSourceUid}" returned no entries.`,
3084
+ findings: {
3085
+ dataSourceUid,
3086
+ contentTypeUid: querySpec.contentType,
3087
+ },
3088
+ }, config);
3089
+ }
2543
3090
  // Add editable tags (CSLP)
2544
3091
  if (config.cslp.appendTags && Array.isArray(entries)) {
2545
3092
  entries.forEach((entry) => {
@@ -2551,9 +3098,28 @@ function generateSdk(userConfig) {
2551
3098
  count: count,
2552
3099
  };
2553
3100
  }
2554
- catch (error) {
2555
- if (process.env.NODE_ENV === "development") {
2556
- console.error("Error resolving query data:", error);
3101
+ catch {
3102
+ // The same empty list as a query that matched nothing, and a completely
3103
+ // different thing to tell somebody. Without this the page shows an empty
3104
+ // list, the console says nothing, and the only available reading is that
3105
+ // the filters are wrong — which sends an author to edit a data source
3106
+ // that was never the problem.
3107
+ if (dataSourceUid) {
3108
+ reportDegraded({
3109
+ code: DegradedCode.QUERY_REQUEST_FAILED,
3110
+ headline: `The data source "${dataSourceUid}" could not be fetched, so ` +
3111
+ "its list is empty.",
3112
+ causes: [
3113
+ {
3114
+ cause: "The request did not reach Contentstack, or it failed.",
3115
+ fix: "Retry the page. Nothing about the data source's filters is involved.",
3116
+ },
3117
+ ],
3118
+ findings: {
3119
+ dataSourceUid,
3120
+ contentTypeUid: querySpec.contentType,
3121
+ },
3122
+ }, config);
2557
3123
  }
2558
3124
  return { entries: [], count: 0 };
2559
3125
  }
@@ -2568,10 +3134,26 @@ function generateSdk(userConfig) {
2568
3134
  ? parsed
2569
3135
  : Object.values(parsed);
2570
3136
  }
2571
- catch (error) {
2572
- if (process.env.NODE_ENV === "development") {
2573
- console.error("Error parsing data sources JSON:", error);
2574
- }
3137
+ catch {
3138
+ // Not fatal, and deliberately so: the layout rendered, and taking the
3139
+ // page down over its queries would turn a partly-empty page into no
3140
+ // page at all. The bytes never travel — a report is built to be pasted
3141
+ // somewhere public and this is the customer's content.
3142
+ reportDegraded({
3143
+ code: DegradedCode.DATA_SOURCES_UNREADABLE,
3144
+ headline: `The stored data sources for ${compositionEntry.composable_uid} ` +
3145
+ "could not be read, so none of its queries ran.",
3146
+ causes: [
3147
+ {
3148
+ cause: "The stored data sources are damaged.",
3149
+ fix: "Nothing in this project will fix it — report it.",
3150
+ },
3151
+ ],
3152
+ findings: {
3153
+ subject: compositionEntry.composable_uid,
3154
+ byteLength: compositionEntry.data_sources.length,
3155
+ },
3156
+ }, config);
2575
3157
  }
2576
3158
  }
2577
3159
  const queriesDS = pageDataSources.find((ds) => ds.uid === DATA_SOURCES.QUERY || ds.id === DATA_SOURCES.QUERY);
@@ -2629,6 +3211,11 @@ function generateSdk(userConfig) {
2629
3211
  /* per-section JSON failure already logged in collect-data-needs */
2630
3212
  }
2631
3213
  }
3214
+ for (const [queryUid, paths] of Object.entries(options?.sectionQueryIncludes ?? {})) {
3215
+ queriesResolvedRefs[queryUid] = [
3216
+ ...new Set([...(queriesResolvedRefs[queryUid] ?? []), ...paths]),
3217
+ ];
3218
+ }
2632
3219
  const dedupedQueries = Array.from(queryDeduper.values());
2633
3220
  // Nothing to resolve (neither page nor any section declared a query).
2634
3221
  if (dedupedQueries.length === 0)
@@ -2709,7 +3296,7 @@ function generateSdk(userConfig) {
2709
3296
  },
2710
3297
  }
2711
3298
  : spec;
2712
- const result = await fetchContentstackData(mergedSpec, context, options);
3299
+ const result = await fetchContentstackData(mergedSpec, context, options, uid);
2713
3300
  // Fan out result to every uid that resolved to this query spec
2714
3301
  // (page's data_source uid + each section instance's data_source uid).
2715
3302
  const hash = stableHashQuery(spec);
@@ -2785,9 +3372,7 @@ function generateSdk(userConfig) {
2785
3372
  * options object.
2786
3373
  */
2787
3374
  fetchCompositionData: async (queryOptions, options) => {
2788
- if (!config.stackSdk) {
2789
- throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
2790
- }
3375
+ requireStack(config);
2791
3376
  const { searchQuery, ...compositionQueryInput } = queryOptions;
2792
3377
  const compositionQuery = convertCompositionQueryInputToCompositionQuery(compositionQueryInput);
2793
3378
  const urlSearchParam = new URLSearchParams(searchQuery);
@@ -2805,7 +3390,7 @@ function generateSdk(userConfig) {
2805
3390
  const previewHash = urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
2806
3391
  urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH);
2807
3392
  if (previewHash) {
2808
- config.stackSdk.livePreviewQuery(previewHash);
3393
+ requireStack(config).livePreviewQuery(previewHash);
2809
3394
  }
2810
3395
  const rendererModeUtil = new RendererModeUtil(urlSearchParam);
2811
3396
  // P4.2 (ADR-0005): always fetch and return the spec — uniformly for the
@@ -2837,6 +3422,10 @@ function generateSdk(userConfig) {
2837
3422
  spec,
2838
3423
  hasSpec: !!spec.compositionEntry,
2839
3424
  hasTemplate: !!spec.data.dataSources[DATA_SOURCES.TEMPLATE],
3425
+ // Normalised here so a host does not have to: the CMS stores "no
3426
+ // connected content type" as an empty string on some entries and as an
3427
+ // absent field on others, and both mean freeform.
3428
+ connectedContentTypeUid: spec.compositionEntry?.connected_content_type || null,
2840
3429
  fetchOptions: {
2841
3430
  // TODO: @Nilesh - see if we can remove this as this config is already available in the spec.
2842
3431
  config: getLightConfig(),
@@ -2862,9 +3451,7 @@ function generateSdk(userConfig) {
2862
3451
  * @returns `Promise<StudioSpec>` — the composition spec with empty data.
2863
3452
  */
2864
3453
  fetchComposition: async (queryOptions, options) => {
2865
- if (!config.stackSdk) {
2866
- throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
2867
- }
3454
+ requireStack(config);
2868
3455
  const { searchQuery, ...compositionQueryInput } = queryOptions;
2869
3456
  const compositionQuery = convertCompositionQueryInputToCompositionQuery(compositionQueryInput);
2870
3457
  const urlSearchParam = new URLSearchParams(searchQuery);
@@ -2873,7 +3460,7 @@ function generateSdk(userConfig) {
2873
3460
  const previewHash = urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
2874
3461
  urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH);
2875
3462
  if (previewHash) {
2876
- config.stackSdk.livePreviewQuery(previewHash);
3463
+ requireStack(config).livePreviewQuery(previewHash);
2877
3464
  }
2878
3465
  return fetchCompositionSpecOnly(compositionQuery, options);
2879
3466
  },
@@ -2922,9 +3509,37 @@ function countFromResponse(response) {
2922
3509
  const count = response?.count;
2923
3510
  return typeof count === "number" ? count : undefined;
2924
3511
  }
3512
+ /**
3513
+ * Raises unless the reply is one we can actually read entries out of.
3514
+ *
3515
+ * The delivery client hands back either an array or an object carrying `entries`.
3516
+ * Anything else answered on the address we asked without being Contentstack, and
3517
+ * the absent entries list must not be mistaken for an empty project.
3518
+ */
3519
+ function assertReadableEntries(response, config) {
3520
+ const readable = Array.isArray(response) ||
3521
+ (typeof response === "object" &&
3522
+ response !== null &&
3523
+ Array.isArray(response.entries));
3524
+ if (readable)
3525
+ return;
3526
+ const host = config.stackSdk?.host;
3527
+ throw createStudioError({
3528
+ code: StudioErrorCode.RESPONSE_UNUSABLE,
3529
+ headline: `The reply from ${host ?? "Contentstack"} is not a usable delivery response.`,
3530
+ causes: [
3531
+ {
3532
+ cause: "Something answered on that address without being Contentstack.",
3533
+ fix: "Check anything sitting between this app and Contentstack — a proxy, a gateway, an offline page. If there is nothing, report it.",
3534
+ },
3535
+ ],
3536
+ context: buildStudioErrorContext(config),
3537
+ findings: { host },
3538
+ });
3539
+ }
2925
3540
  async function fetchAllPageCompositions(config, locale) {
2926
3541
  const fetchPage = (page, includeCount) => {
2927
- let query = config.stackSdk
3542
+ let query = requireStack(config)
2928
3543
  .ctQuery(config.contentTypeUid, {
2929
3544
  locale: locale || config.locale,
2930
3545
  query: { ...getPageLinkedPlacementFilter() },
@@ -2945,6 +3560,10 @@ async function fetchAllPageCompositions(config, locale) {
2945
3560
  // Page 0 carries include_count so the remaining pages can be fetched in one
2946
3561
  // parallel wave instead of one serial round-trip per page.
2947
3562
  const firstRes = await fetchPage(0, true);
3563
+ // A reply we cannot read is not a reply that said "nothing". Absent entries
3564
+ // here would read as an empty project and 404 every page at once, so the shape
3565
+ // is checked before it is believed.
3566
+ assertReadableEntries(firstRes, config);
2948
3567
  const first = entriesFromResponse(firstRes);
2949
3568
  if (first.length < CANDIDATE_PAGE_SIZE) {
2950
3569
  return { entries: first, truncated: false };
@@ -2984,6 +3603,93 @@ async function fetchAllPageCompositions(config, locale) {
2984
3603
  * Returns the winner's composable_uid (or undefined if nothing owns the URL) and
2985
3604
  * the per-candidate ownership outcome for diagnostics.
2986
3605
  */
3606
+ /**
3607
+ * The publishing line, and only when published content is what answered.
3608
+ *
3609
+ * On the preview service an unpublished composition is served anyway, so telling
3610
+ * that reader to check publishing sends them to rule out something that cannot be
3611
+ * the cause. `servedBy` is what makes the difference knowable.
3612
+ */
3613
+ function unpublishedCause(servedBy, config, subject) {
3614
+ if (servedBy !== "cdn")
3615
+ return [];
3616
+ const environment = config.stackSdk?.environment;
3617
+ return [
3618
+ {
3619
+ cause: environment
3620
+ ? `${subject} may not be published to "${environment}".`
3621
+ : `${subject} may not be published to the environment this site queries.`,
3622
+ fix: "Check its publish status in Contentstack.",
3623
+ },
3624
+ ];
3625
+ }
3626
+ /**
3627
+ * Why no composition matched an address.
3628
+ *
3629
+ * Deliberately never says "create an entry". On the legacy connected-entry path
3630
+ * the lookup compares an entry's address against the composition's raw pattern,
3631
+ * which for a patterned composition can never match — so the entry an author
3632
+ * would be told to create is one they already have.
3633
+ */
3634
+ function notFoundByUrlCauses(url, servedBy, config) {
3635
+ return [
3636
+ {
3637
+ cause: `The address "${url}" may not be the one the composition is set up for.`,
3638
+ fix: "Compare it with the composition's URL in Studio.",
3639
+ },
3640
+ {
3641
+ cause: "The composition's URL pattern may not produce this address.",
3642
+ fix: "Open the pattern in Studio and check it against the address.",
3643
+ },
3644
+ ...unpublishedCause(servedBy, config, "The composition"),
3645
+ ];
3646
+ }
3647
+ /**
3648
+ * Why an address that several compositions claim has nothing behind it.
3649
+ *
3650
+ * Never says "create an entry". On the legacy connected-entry path the lookup
3651
+ * compares an entry's address against the composition's raw pattern, which for a
3652
+ * patterned composition can never match — so the entry an author would be told to
3653
+ * create is one they may already have.
3654
+ */
3655
+ function matchedNoEntryCauses(considered, servedBy, config) {
3656
+ const contentTypes = Array.from(new Set(considered
3657
+ .map((row) => row.connected_content_type)
3658
+ .filter((uid) => Boolean(uid))));
3659
+ return [
3660
+ {
3661
+ cause: contentTypes.length
3662
+ ? `No entry in ${contentTypes.map((uid) => `"${uid}"`).join(" or ")} has this address.`
3663
+ : "No entry behind these compositions has this address.",
3664
+ fix: "Open the composition in Studio and check the entry it reads from.",
3665
+ },
3666
+ ...unpublishedCause(servedBy, config, "The entry"),
3667
+ {
3668
+ cause: "A composition may be connected to the wrong content type.",
3669
+ fix: "Check the connected content type on each of them in Studio.",
3670
+ },
3671
+ ];
3672
+ }
3673
+ /** Why a composition uid found nothing. Never claims the composition does not exist. */
3674
+ function uidNotFoundCauses(servedBy, config) {
3675
+ return [
3676
+ {
3677
+ cause: "The uid may not be the one this composition has.",
3678
+ fix: "You can find it on the composition in Studio.",
3679
+ },
3680
+ ...unpublishedCause(servedBy, config, "The composition"),
3681
+ ];
3682
+ }
3683
+ /** Why a content type has no composition connected to it. */
3684
+ function templateContentTypeCauses(contentTypeUid, servedBy, config) {
3685
+ return [
3686
+ {
3687
+ cause: `No composition in this project is connected to "${contentTypeUid}".`,
3688
+ fix: "Connect one in Studio, or ask for a different content type.",
3689
+ },
3690
+ ...unpublishedCause(servedBy, config, "A composition that uses it"),
3691
+ ];
3692
+ }
2987
3693
  async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale) {
2988
3694
  const topTier = ranking.matches;
2989
3695
  // Happy path — a single (or no) top-tier candidate needs no probe.
@@ -3002,10 +3708,10 @@ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, lo
3002
3708
  // content type) is unprobeable.
3003
3709
  const meta = parseUrlMetadata(lightweight?.url_metadata);
3004
3710
  if (!m.variables || !m.connected_content_type) {
3005
- return { uid: m.composable_uid, owns: false };
3711
+ return { uid: m.composable_uid, owns: false, answered: true };
3006
3712
  }
3007
3713
  try {
3008
- const probeQuery = resolveByUrlSource(config.stackSdk, meta.url_source, { url: requestUrl }, m.variables, meta.url_queries, m.connected_content_type, {
3714
+ const probeQuery = resolveByUrlSource(requireStack(config), meta.url_source, { url: requestUrl }, m.variables, meta.url_queries, m.connected_content_type, {
3009
3715
  references: [],
3010
3716
  only: [["BASE", "uid"]],
3011
3717
  locale: m.variables.metadata.locale || locale || config.locale,
@@ -3018,13 +3724,35 @@ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, lo
3018
3724
  return {
3019
3725
  uid: m.composable_uid,
3020
3726
  owns: entriesFromResponse(res).length > 0,
3727
+ answered: true,
3021
3728
  };
3022
3729
  }
3023
- catch {
3024
- // A failed probe counts as non-owning; another candidate may still own it.
3025
- return { uid: m.composable_uid, owns: false };
3730
+ catch (probeError) {
3731
+ // A failed probe counts as non-owning so the others still get their say.
3732
+ // `answered` is what stops that being mistaken for evidence: a check we
3733
+ // could not make says nothing, and if none of them could be made there is
3734
+ // no absence to report.
3735
+ if (isSetupFault(probeError))
3736
+ throw probeError;
3737
+ return { uid: m.composable_uid, owns: false, answered: false };
3026
3738
  }
3027
3739
  }));
3740
+ // Every check failing is an outage, not an answer. Reporting "no candidate owns
3741
+ // this address" here would 404 a page that exists.
3742
+ if (probeOutcomes.length > 0 && probeOutcomes.every((r) => !r.answered)) {
3743
+ throw createStudioError({
3744
+ code: StudioErrorCode.URL_OWNERSHIP_PROBE_FAILED,
3745
+ headline: `Could not check which composition owns "${requestUrl}" — every ownership check failed.`,
3746
+ causes: [
3747
+ {
3748
+ cause: "The checks against Contentstack did not complete.",
3749
+ fix: "Try again shortly; if it persists, report it.",
3750
+ },
3751
+ ],
3752
+ context: buildStudioErrorContext(config),
3753
+ findings: { url: requestUrl, probeCount: probeOutcomes.length },
3754
+ });
3755
+ }
3028
3756
  const ownsByUid = new Map(probeOutcomes.map((r) => [r.uid, r.owns]));
3029
3757
  return selectUrlWinner(topTier, ownsByUid);
3030
3758
  }
@@ -3045,9 +3773,23 @@ isInsideEditor = false) {
3045
3773
  // Captured by the URL metadata (Phase A) path for Studio resolution
3046
3774
  // diagnostics — every candidate considered, with specificity.
3047
3775
  let urlResolution;
3776
+ // Which service this request reached. Set inside `defaultImpl`, which is what
3777
+ // makes it honest in all three cases: the ordinary path records the real
3778
+ // route, a custom fetcher that delegates records it too, and one that never
3779
+ // delegates leaves it "unknown" rather than reporting a route we did not take.
3780
+ let servedBy = "unknown";
3048
3781
  const defaultImpl = async () => {
3782
+ // Settle the connection before any branch below can start falling back over
3783
+ // it. Every path here needs the stack, so this raises nothing new — it moves
3784
+ // the raise out of the fallbacks and in front of them. A caller's own
3785
+ // fetcher sits deliberately upstream of this: it may not need our stack.
3786
+ requireStack(config);
3787
+ // Read synchronously, before anything awaits: live-preview state is
3788
+ // process-wide, so a later read can belong to a different request.
3789
+ servedBy = resolveServedBy(config.stackSdk?.livePreviewConfig);
3049
3790
  if ("composableUid" in queryOptions) {
3050
- const uiQuery = config.stackSdk.where(config.stackSdk.ctQuery(config.contentTypeUid, {
3791
+ const stack = requireStack(config);
3792
+ const uiQuery = stack.where(stack.ctQuery(config.contentTypeUid, {
3051
3793
  locale: locale || config.locale,
3052
3794
  }), "composable_uid", queryOptions.composableUid);
3053
3795
  return await uiQuery
@@ -3061,11 +3803,15 @@ isInsideEditor = false) {
3061
3803
  response = res.entries[0];
3062
3804
  }
3063
3805
  if (!response) {
3064
- throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
3065
- compositionUid: queryOptions.composableUid,
3066
- hasStackSdk: !!config.stackSdk,
3067
- options: queryOptions,
3068
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
3806
+ throw createStudioError({
3807
+ code: StudioErrorCode.COMPOSITION_UID_NOT_FOUND,
3808
+ headline: `No composition with the uid "${queryOptions.composableUid}" in content type "${config.contentTypeUid}".`,
3809
+ causes: uidNotFoundCauses(servedBy, config),
3810
+ context: buildStudioErrorContext(config, servedBy),
3811
+ findings: {
3812
+ compositionUid: queryOptions.composableUid,
3813
+ contentTypeUid: config.contentTypeUid,
3814
+ },
3069
3815
  });
3070
3816
  }
3071
3817
  return response;
@@ -3073,21 +3819,29 @@ isInsideEditor = false) {
3073
3819
  .catch((err) => {
3074
3820
  if (err instanceof ComposableStudioError)
3075
3821
  throw err;
3076
- const { errorType, message } = classifyApiError(err);
3077
- throw new ComposableStudioError(errorType, message, {
3078
- compositionUid: queryOptions.composableUid,
3079
- hasStackSdk: !!config.stackSdk,
3080
- statusCode: err?.status || err?.statusCode || "none",
3081
- errorCode: err?.error_code || "none",
3082
- errorMessage: err?.error_message || err?.message || "none",
3083
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
3084
- });
3822
+ const diagnosed = classifyResponseError(err, config, { servedBy });
3823
+ if (diagnosed)
3824
+ throw diagnosed;
3825
+ // The request failed. Absence is settled on the success path above,
3826
+ // so nothing here is evidence that the page is missing.
3827
+ // An unplaceable 141 reads as a missing page, and which missing page
3828
+ // it is depends on what was asked for.
3829
+ throw diagnoseUnreadableResponse(err, config, { servedBy }, () => createStudioError({
3830
+ code: StudioErrorCode.COMPOSITION_UID_NOT_FOUND,
3831
+ headline: `No composition with the uid "${queryOptions.composableUid}" was found in content type "${config.contentTypeUid}".`,
3832
+ causes: uidNotFoundCauses(servedBy, config),
3833
+ context: buildStudioErrorContext(config, servedBy),
3834
+ findings: {
3835
+ compositionUid: queryOptions.composableUid,
3836
+ contentTypeUid: config.contentTypeUid,
3837
+ },
3838
+ }));
3085
3839
  });
3086
3840
  }
3087
3841
  else if ("templateContentTypeUid" in queryOptions) {
3088
3842
  // Fetch by connected content type - takes priority over url when both are present
3089
3843
  const placementFilter = getPageLinkedPlacementFilter();
3090
- return await config.stackSdk
3844
+ return await requireStack(config)
3091
3845
  .ctQuery(config.contentTypeUid, {
3092
3846
  includeAll: true,
3093
3847
  includeAllDepth: INCLUDE_DEPTH_COUNT,
@@ -3103,11 +3857,14 @@ isInsideEditor = false) {
3103
3857
  const entries = entriesFromResponse(res);
3104
3858
  const entry = entries[0];
3105
3859
  if (!entry) {
3106
- throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
3107
- templateContentTypeUid: queryOptions.templateContentTypeUid,
3108
- hasStackSdk: !!config.stackSdk,
3109
- options: queryOptions,
3110
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
3860
+ throw createStudioError({
3861
+ code: StudioErrorCode.NO_COMPOSITION_FOR_TEMPLATE_CONTENT_TYPE,
3862
+ headline: `No composition is connected to the content type "${queryOptions.templateContentTypeUid}".`,
3863
+ causes: templateContentTypeCauses(queryOptions.templateContentTypeUid, servedBy, config),
3864
+ context: buildStudioErrorContext(config, servedBy),
3865
+ findings: {
3866
+ templateContentTypeUid: queryOptions.templateContentTypeUid,
3867
+ },
3111
3868
  });
3112
3869
  }
3113
3870
  return entry;
@@ -3115,15 +3872,22 @@ isInsideEditor = false) {
3115
3872
  .catch((err) => {
3116
3873
  if (err instanceof ComposableStudioError)
3117
3874
  throw err;
3118
- const { errorType, message } = classifyApiError(err);
3119
- throw new ComposableStudioError(errorType, message, {
3120
- templateContentTypeUid: queryOptions.templateContentTypeUid,
3121
- hasStackSdk: !!config.stackSdk,
3122
- statusCode: err?.status || err?.statusCode || "none",
3123
- errorCode: err?.error_code || "none",
3124
- errorMessage: err?.error_message || err?.message || "none",
3125
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
3126
- });
3875
+ const diagnosed = classifyResponseError(err, config, { servedBy });
3876
+ if (diagnosed)
3877
+ throw diagnosed;
3878
+ // The request failed. Absence is settled on the success path above,
3879
+ // so nothing here is evidence that the page is missing.
3880
+ // An unplaceable 141 reads as a missing page, and which missing page
3881
+ // it is depends on what was asked for.
3882
+ throw diagnoseUnreadableResponse(err, config, { servedBy }, () => createStudioError({
3883
+ code: StudioErrorCode.NO_COMPOSITION_FOR_TEMPLATE_CONTENT_TYPE,
3884
+ headline: `No composition in this project is connected to the content type "${queryOptions.templateContentTypeUid}".`,
3885
+ causes: templateContentTypeCauses(queryOptions.templateContentTypeUid, servedBy, config),
3886
+ context: buildStudioErrorContext(config, servedBy),
3887
+ findings: {
3888
+ templateContentTypeUid: queryOptions.templateContentTypeUid,
3889
+ },
3890
+ }));
3127
3891
  });
3128
3892
  }
3129
3893
  else if ("url" in queryOptions) {
@@ -3144,7 +3908,7 @@ isInsideEditor = false) {
3144
3908
  // diagnostics keep the full candidate pool.
3145
3909
  if (requestUrl && !isInsideEditor) {
3146
3910
  try {
3147
- const exactRes = await config.stackSdk
3911
+ const exactRes = await requireStack(config)
3148
3912
  .ctQuery(config.contentTypeUid, {
3149
3913
  includeAll: true,
3150
3914
  includeAllDepth: INCLUDE_DEPTH_COUNT,
@@ -3174,17 +3938,22 @@ isInsideEditor = false) {
3174
3938
  }
3175
3939
  catch (fastPathError) {
3176
3940
  // The fast path must never make resolution less reliable than the
3177
- // scan it short-cuts — swallow and fall through.
3941
+ // scan it short-cuts — swallow and fall through. What it falls back
3942
+ // from is a request that did not work out; a failure we diagnosed is
3943
+ // not that. It is a conclusion, the scan would reach it again, and
3944
+ // burying it means the reader gets whatever the second attempt
3945
+ // happened to fail with instead.
3946
+ if (fastPathError instanceof ComposableStudioError &&
3947
+ fastPathError.code) {
3948
+ throw fastPathError;
3949
+ }
3178
3950
  if (process.env.NODE_ENV === "development") {
3179
- console.warn("[Composable Studio SDK] Exact-match URL lookup failed; falling back to the candidate scan:", fastPathError);
3951
+ console.warn("[Contentstack Studio] Exact-match URL lookup failed; falling back to the candidate scan:", fastPathError);
3180
3952
  }
3181
3953
  }
3182
3954
  }
3183
3955
  // 1. Fetch every page-linked candidate (lightweight, paginated).
3184
3956
  const { entries: candidates, truncated } = await fetchAllPageCompositions(config, locale);
3185
- if (truncated) {
3186
- console.warn(`[Composable Studio SDK] Composition candidate list hit the pagination cap while resolving "${requestUrl}"; some compositions may not have been considered.`);
3187
- }
3188
3957
  // 2. Rank the whole pool by literal-character specificity.
3189
3958
  const ranking = rankUrlMatches(requestUrl, candidates);
3190
3959
  if (ranking.composableUids.length > 0) {
@@ -3201,7 +3970,7 @@ isInsideEditor = false) {
3201
3970
  };
3202
3971
  if (winnerUid) {
3203
3972
  // 5. Full-fetch the winning composition only.
3204
- const fullQuery = config.stackSdk.ctQuery(config.contentTypeUid, {
3973
+ const fullQuery = requireStack(config).ctQuery(config.contentTypeUid, {
3205
3974
  includeAll: true,
3206
3975
  includeAllDepth: INCLUDE_DEPTH_COUNT,
3207
3976
  locale: locale || config.locale,
@@ -3214,33 +3983,78 @@ isInsideEditor = false) {
3214
3983
  }
3215
3984
  }
3216
3985
  }
3217
- // Nothing matched, or no tied candidate owns the URL.
3218
- throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
3219
- url: requestUrl,
3220
- }), {
3221
- url: requestUrl,
3222
- hasStackSdk: !!config.stackSdk,
3223
- options: queryOptions,
3224
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
3986
+ // Absence has to be established, not assumed. If the scan stopped at its
3987
+ // cap we never finished looking, so "nothing matched" is a statement we
3988
+ // are not entitled to make — and the 404 it becomes is the one answer a
3989
+ // crawler acts on permanently.
3990
+ if (truncated) {
3991
+ throw createStudioError({
3992
+ code: StudioErrorCode.SEARCH_INCOMPLETE,
3993
+ headline: `Stopped after considering ${candidates.length} compositions without finding a match for "${requestUrl}". The search did not finish, so this is not a 404.`,
3994
+ causes: [
3995
+ {
3996
+ cause: "This project has more compositions than one search can cover.",
3997
+ fix: "Nothing here will fix it — report it, and we will raise the cap or narrow the search.",
3998
+ },
3999
+ ],
4000
+ context: buildStudioErrorContext(config, servedBy),
4001
+ findings: { url: requestUrl, consideredCount: candidates.length },
4002
+ });
4003
+ }
4004
+ // The scan finished and every check answered, so this is absence rather
4005
+ // than a gap in what we know — which is what entitles a host to return
4006
+ // 404 for it. Which absence it is decides what the reader does next.
4007
+ const considered = urlResolution?.shortlisted ?? [];
4008
+ if (considered.length > 0) {
4009
+ // Compositions are set up for this address and none of them has an
4010
+ // entry. The routing is right; the content is what is missing.
4011
+ throw createStudioError({
4012
+ code: StudioErrorCode.URL_MATCHED_NO_ENTRY,
4013
+ headline: `${considered.length} compositions match "${requestUrl}", and none of them has an entry for it.`,
4014
+ causes: matchedNoEntryCauses(considered, servedBy, config),
4015
+ context: buildStudioErrorContext(config, servedBy),
4016
+ findings: { url: requestUrl, considered },
4017
+ });
4018
+ }
4019
+ throw createStudioError({
4020
+ code: StudioErrorCode.NO_COMPOSITION_FOR_URL,
4021
+ headline: `No composition matches "${requestUrl}". Considered ${candidates.length} compositions.`,
4022
+ causes: notFoundByUrlCauses(requestUrl, servedBy, config),
4023
+ context: buildStudioErrorContext(config, servedBy),
4024
+ findings: { url: requestUrl, consideredCount: candidates.length },
3225
4025
  });
3226
4026
  }
3227
4027
  catch (err) {
3228
4028
  if (err instanceof ComposableStudioError)
3229
4029
  throw err;
3230
- const { errorType, message } = classifyApiError(err);
3231
- throw new ComposableStudioError(errorType, message, {
3232
- url: requestUrl,
3233
- hasStackSdk: !!config.stackSdk,
3234
- statusCode: err?.status || err?.statusCode || "none",
3235
- errorCode: err?.error_code || "none",
3236
- errorMessage: err?.error_message || err?.message || "none",
3237
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
3238
- });
4030
+ const diagnosed = classifyResponseError(err, config, { servedBy });
4031
+ if (diagnosed)
4032
+ throw diagnosed;
4033
+ // The request failed. Absence is settled on the success path above,
4034
+ // so nothing here is evidence that the page is missing.
4035
+ // An unplaceable 141 reads as a missing page, and which missing page
4036
+ // it is depends on what was asked for.
4037
+ throw diagnoseUnreadableResponse(err, config, { servedBy }, () => createStudioError({
4038
+ code: StudioErrorCode.NO_COMPOSITION_FOR_URL,
4039
+ headline: `No composition is set up for the address ${requestUrl}.`,
4040
+ causes: notFoundByUrlCauses(requestUrl, servedBy, config),
4041
+ context: buildStudioErrorContext(config, servedBy),
4042
+ findings: { url: requestUrl, consideredCount: 0 },
4043
+ }));
3239
4044
  }
3240
4045
  }
3241
4046
  else {
3242
- throw new ComposableStudioError(ComposableStudioErrors.MISSING_COMPOSITION_IDENTIFIER, getErrorMessage(ErrorMessageKey.MISSING_COMPOSITION_IDENTIFIER), {
3243
- options: queryOptions,
4047
+ throw createStudioError({
4048
+ code: StudioErrorCode.COMPOSITION_IDENTIFIER_MISSING,
4049
+ headline: "No composition was asked for.",
4050
+ causes: [
4051
+ {
4052
+ cause: "The call named none of the three ways to identify a composition.",
4053
+ fix: "Pass one of compositionUid, url or templateContentTypeUid.",
4054
+ },
4055
+ ],
4056
+ context: buildStudioErrorContext(config, servedBy),
4057
+ findings: { lookedIn: "call" },
3244
4058
  });
3245
4059
  }
3246
4060
  };
@@ -3250,32 +4064,53 @@ isInsideEditor = false) {
3250
4064
  compositionQuery: queryOptions,
3251
4065
  contentTypeUid: config.contentTypeUid,
3252
4066
  options: resolvedOptions,
3253
- stackSdk: config.stackSdk.sdk,
4067
+ stackSdk: config.stackSdk?.sdk,
3254
4068
  defaultFetch: defaultImpl,
3255
4069
  });
3256
4070
  if (!entry) {
3257
- const isUrlBased = "url" in queryOptions;
3258
- throw new ComposableStudioError(isUrlBased
3259
- ? ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL
3260
- : ComposableStudioErrors.COMPOSITION_NOT_FOUND, isUrlBased
3261
- ? getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
3262
- url: queryOptions.url,
3263
- })
3264
- : getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404));
4071
+ // A caller's own fetcher returned nothing. Which not-found this is
4072
+ // depends on what was asked for, and the two take opposite advice: an
4073
+ // address that matches nothing is a routing problem, a uid that matches
4074
+ // nothing is a content one.
4075
+ const servedByNow = resolveServedBy(config.stackSdk?.livePreviewConfig);
4076
+ const notFoundContext = buildStudioErrorContext(config, servedByNow);
4077
+ if ("url" in queryOptions) {
4078
+ throw createStudioError({
4079
+ code: StudioErrorCode.NO_COMPOSITION_FOR_URL,
4080
+ headline: `No composition is set up for the address ${queryOptions.url}.`,
4081
+ causes: notFoundByUrlCauses(queryOptions.url, servedByNow, config),
4082
+ context: notFoundContext,
4083
+ findings: { url: queryOptions.url, consideredCount: 0 },
4084
+ });
4085
+ }
4086
+ throw createStudioError({
4087
+ code: StudioErrorCode.COMPOSITION_UID_NOT_FOUND,
4088
+ headline: `No composition with the uid "${"composableUid" in queryOptions ? queryOptions.composableUid : ""}" was returned.`,
4089
+ causes: uidNotFoundCauses(servedByNow, config),
4090
+ context: notFoundContext,
4091
+ findings: {
4092
+ compositionUid: "composableUid" in queryOptions ? queryOptions.composableUid : "",
4093
+ contentTypeUid: config.contentTypeUid,
4094
+ },
4095
+ });
3265
4096
  }
3266
4097
  return {
3267
4098
  compositionEntry: entry,
3268
4099
  // Populated if the custom fetcher delegated to `defaultFetch` and it
3269
4100
  // resolved via the URL metadata path; otherwise undefined.
3270
4101
  urlResolution,
4102
+ // Built here rather than at the surface, so it reports the route this
4103
+ // fetch actually took. A caller's own fetcher leaves `servedBy` unknown.
4104
+ requestContext: buildStudioErrorContext(config, servedBy),
3271
4105
  };
3272
4106
  }
3273
4107
  const entry = await defaultImpl();
3274
4108
  return {
3275
4109
  compositionEntry: entry,
3276
4110
  urlResolution,
4111
+ requestContext: buildStudioErrorContext(config, servedBy),
3277
4112
  };
3278
4113
  }
3279
4114
 
3280
- export { buildSectionScopedData, classifyApiError, collectSectionInstanceBindings as collectSectionInstanceBindingsForTest, composeSectionTemplatePrefix, fetchComposition as fetchCompositionForTest, flattenBindingPathFromValue, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, getSeoMetadataPure, isTemplateBinding, mapSectionRepeaterPaths as mapSectionRepeaterPathsForTest, projectCrossBoundaryRepeaterBindings as projectCrossBoundaryRepeaterBindingsForTest, resolveSeoBindingValue };
4115
+ export { buildSectionScopedData, collectSectionInstanceBindings as collectSectionInstanceBindingsForTest, composeSectionTemplatePrefix, derivePlacementIncludePaths, fetchComposition as fetchCompositionForTest, flattenBindingPathFromValue, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, getSeoMetadataPure, isTemplateBinding, mapSectionRepeaterPaths as mapSectionRepeaterPathsForTest, parseUI, projectCrossBoundaryRepeaterBindings as projectCrossBoundaryRepeaterBindingsForTest, resolveSeoBindingValue };
3281
4116
  //# sourceMappingURL=sdk.js.map