@contentstack/studio-client 3.0.0 → 3.2.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 (51) hide show
  1. package/README.md +21 -0
  2. package/dist/breakpoints/BreakpointManager.js +1 -0
  3. package/dist/breakpoints/BreakpointManager.js.map +1 -1
  4. package/dist/canvas/canvas.utils.js +18 -1
  5. package/dist/canvas/canvas.utils.js.map +1 -1
  6. package/dist/composable-studio/build-scoped-data.js +58 -3
  7. package/dist/composable-studio/build-scoped-data.js.map +1 -1
  8. package/dist/composable-studio/collect-data-needs.js +24 -4
  9. package/dist/composable-studio/collect-data-needs.js.map +1 -1
  10. package/dist/composable-studio/data/pre-process-static-values.js +13 -0
  11. package/dist/composable-studio/data/pre-process-static-values.js.map +1 -1
  12. package/dist/composable-studio/sdk.js +496 -136
  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 +1 -0
  17. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -1
  18. package/dist/config/config.schema.js +26 -0
  19. package/dist/config/config.schema.js.map +1 -1
  20. package/dist/config/process-user-config.js +6 -0
  21. package/dist/config/process-user-config.js.map +1 -1
  22. package/dist/config/stack-sdk-wrapper.js +36 -1
  23. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  24. package/dist/context-menu/context-menu.js +1 -0
  25. package/dist/context-menu/context-menu.js.map +1 -1
  26. package/dist/dnd/dnd-manager.js +1 -0
  27. package/dist/dnd/dnd-manager.js.map +1 -1
  28. package/dist/get-active-node-screenshot/get-node-screenshot-event.js +45 -4
  29. package/dist/get-active-node-screenshot/get-node-screenshot-event.js.map +1 -1
  30. package/dist/highlight-node/highlight-node-manager.js +2 -4
  31. package/dist/highlight-node/highlight-node-manager.js.map +1 -1
  32. package/dist/highlight-node/highlight-node.js +1 -0
  33. package/dist/highlight-node/highlight-node.js.map +1 -1
  34. package/dist/index.d.ts +347 -25
  35. package/dist/index.js +2 -1
  36. package/dist/index.js.map +1 -1
  37. package/dist/url-metadata/build-template-query.js +13 -3
  38. package/dist/url-metadata/build-template-query.js.map +1 -1
  39. package/dist/utils/conditionBlock.js +132 -5
  40. package/dist/utils/conditionBlock.js.map +1 -1
  41. package/dist/utils/constants.js +1 -1
  42. package/dist/utils/include-path-rules.js +102 -0
  43. package/dist/utils/include-path-rules.js.map +1 -0
  44. package/dist/utils/query-url-budget.js +79 -0
  45. package/dist/utils/query-url-budget.js.map +1 -0
  46. package/dist/utils/reference_fetcher.js +22 -2
  47. package/dist/utils/reference_fetcher.js.map +1 -1
  48. package/dist/utils/spec-analyzer.js +2 -2
  49. package/dist/utils/spec-analyzer.js.map +1 -1
  50. package/package.json +8 -9
  51. package/LICENSE +0 -21
@@ -1,6 +1,6 @@
1
1
  import { COMPOSABLE_STUDIO_QUERY_PARAM, composableStudioEventManager, POST_MESSAGE_EVENTS } from '@contentstack/studio-messenger';
2
- import { INTERNAL_COMPONENTS_NAMES, DATA_SOURCES, getComponentRegistryInstance, DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
3
- import { get, pick } from 'lodash-es';
2
+ import { INTERNAL_COMPONENTS_NAMES, DATA_SOURCES, getStateStoreInstance, getComponentRegistryInstance, DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
3
+ import { get, pick, uniq, uniqBy, chunk, range } from 'lodash-es';
4
4
  import { processUserConfig } from '../config/process-user-config.js';
5
5
  import { setStackSdkInstance } from '../json-rte-registry/stack-sdk-store.js';
6
6
  import { SCHEMA_VERSION, SDK_VERSION, INCLUDE_DEPTH_COUNT } from '../utils/constants.js';
@@ -8,6 +8,7 @@ import { isCompositionBeingEdited } from '../utils/is-composition-being-edited.j
8
8
  import { setTemplateEntryInDS, setStaticEntryInDS, entriesFromResponse, getBindingStringForCS } from '../utils/sdk.js';
9
9
  import '../utils/editor-mode.js';
10
10
  import { ComposableStudioError, ComposableStudioErrors } from '../utils/composable-studio-error.js';
11
+ import '../utils/conditionBlock.js';
11
12
  import { clientRendererModeUtil, RendererModeUtil } from '../utils/canvas.js';
12
13
  import { analyzeUsedComponents } from '../utils/spec-analyzer.js';
13
14
  import { convertCompositionQueryInputToCompositionQuery } from '../utils/convertCompositionQueryInputToCompositionQuery.js';
@@ -20,11 +21,14 @@ import { selectUrlWinner } from '../url-metadata/select-url-winner.js';
20
21
  import { COMPOSITION_PREVIEW_URL_SOURCES } from '../url-metadata/types.js';
21
22
  import { matchCompositionUrl } from '../url-metadata/url-pattern-matcher.js';
22
23
  import { getStatusCode, isContentstackAuthError, hasAuthErrorShape, isAuthError, isNetworkError, HttpStatus, ContentstackErrorCode, isServerError } from '../utils/http-error.constants.js';
24
+ import { indexModularBlocks, isModularBlockPath, dropImpliedParents } from '../utils/include-path-rules.js';
23
25
  import { getEntriesQueries, projectIncludePathsOntoOnlyKeys, getSchemaPath } from '../utils/reference_fetcher.js';
26
+ import { applyUrlBudget, referencesExceedBudget } from '../utils/query-url-budget.js';
24
27
  import { collectAllDataNeeds, stableHashQuery, parseExternalDataForComponentProps } from './collect-data-needs.js';
25
28
  import { buildScopedDataSources } from './build-scoped-data.js';
26
29
  import { preProcessStaticValues } from './data/pre-process-static-values.js';
27
30
  import { StudioIntelligenceManager } from './studio-intelligence.manager.js';
31
+ import { parseEntryFetchRootKey, TEMPLATE_FETCH_ROOT_KEY, resolveInstanceRootBinding, fetchRootFromBinding, resolveLegacySelectedFieldWithProvenance, isTemplateRootBinding, getRootBindingPath, resolveLegacySelectedField, isPageAbsoluteField, templateFetchRoot } from './section-data.js';
28
32
  import { decompressSpec } from '../studio-internal/dist/utils/spec-compression.js';
29
33
  import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages.default.js';
30
34
 
@@ -33,6 +37,12 @@ import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages
33
37
  // All are registered synchronously during React initialization via getBasicComponents()
34
38
  const INTERNAL_COMPONENT_TYPES = Object.values(INTERNAL_COMPONENTS_NAMES);
35
39
  const SECTION_COMPOSITION_NODE_TYPE = "section-composition";
40
+ /**
41
+ * CDA query responses return at most 100 entries per request, so batched
42
+ * static-entry fetches split their uid lists at this size — a longer list
43
+ * would silently truncate to the first response page.
44
+ */
45
+ const STATIC_ENTRY_BATCH_SIZE = 100;
36
46
  function findParentRepeaterUidInTree(ui, compositionUID) {
37
47
  function traverse(node, nearestRepeaterUID) {
38
48
  if (node.type === "section-composition" &&
@@ -54,7 +64,7 @@ function findParentRepeaterUidInTree(ui, compositionUID) {
54
64
  const result = traverse(ui, null);
55
65
  return result !== undefined ? result : null;
56
66
  }
57
- function setSectionCompositionContext(dataSources, sectionUid, selectedField, parentRepeaterUID = null) {
67
+ function setSectionCompositionContext(dataSources, sectionUid, selectedField, parentRepeaterUID = null, cardinality) {
58
68
  if (!dataSources["section_compositions"]) {
59
69
  dataSources["section_compositions"] = {};
60
70
  }
@@ -62,6 +72,13 @@ function setSectionCompositionContext(dataSources, sectionUid, selectedField, pa
62
72
  selectedField,
63
73
  uidRemapping: {},
64
74
  parentRepeaterUID,
75
+ // Carried so the live re-scope (rebuildScopedFromBindings in the editor
76
+ // hook) can collapse a single-element section's index-free terminal array
77
+ // to its first element. Without it, a spec refetch re-writes this slice
78
+ // index-free and the rebuilt scoped template becomes the WHOLE array —
79
+ // every template binding inside the section then resolves undefined
80
+ // (placeholder) until Studio's next indexed context push wins the merge.
81
+ cardinality,
65
82
  };
66
83
  }
67
84
  function findMatchingSectionSchema(section, templateEntry) {
@@ -76,7 +93,10 @@ function findMatchingSectionSchema(section, templateEntry) {
76
93
  function resolveSectionContext(section, templateEntry) {
77
94
  const matchingSchema = findMatchingSectionSchema(section, templateEntry);
78
95
  if (matchingSchema) {
79
- return { selectedField: matchingSchema.selected_field };
96
+ return {
97
+ selectedField: matchingSchema.selected_field,
98
+ cardinality: matchingSchema.cardinality,
99
+ };
80
100
  }
81
101
  if (!(section.linked_schemas || []).length) {
82
102
  return { selectedField: undefined };
@@ -100,7 +120,8 @@ function attachSectionCompositionContexts(data, compositionEntry, sectionEntries
100
120
  if (compositionEntry.place_composition_as === "section") {
101
121
  const ownContext = resolveSectionContext(compositionEntry, templateEntry);
102
122
  if (ownContext) {
103
- setSectionCompositionContext(data.dataSources, compositionEntry.uid, ownContext.selectedField, null);
123
+ setSectionCompositionContext(data.dataSources, compositionEntry.uid, ownContext.selectedField, null, // root section compositions are never inside a repeater
124
+ ownContext.cardinality);
104
125
  }
105
126
  }
106
127
  const rootUI = compositionEntry.ui ?? null;
@@ -109,7 +130,7 @@ function attachSectionCompositionContexts(data, compositionEntry, sectionEntries
109
130
  if (!sectionContext)
110
131
  return;
111
132
  const parentRepeaterUID = findParentRepeaterUidInTree(rootUI, sectionEntry.uid);
112
- setSectionCompositionContext(data.dataSources, sectionEntry.uid, sectionContext.selectedField, parentRepeaterUID);
133
+ setSectionCompositionContext(data.dataSources, sectionEntry.uid, sectionContext.selectedField, parentRepeaterUID, sectionContext.cardinality);
113
134
  });
114
135
  }
115
136
  /**
@@ -127,7 +148,7 @@ function walkUiForCompositionMapping(ui, visit) {
127
148
  visit(node.uid, node.metadata.compositionUID);
128
149
  }
129
150
  if (node.slots && typeof node.slots === "object") {
130
- for (const slotNodes of Object.values(node.slots)) {
151
+ for (const slotNodes of Object.values(node.slots ?? {})) {
131
152
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
132
153
  for (const c of arr)
133
154
  walkUiForCompositionMapping(c, visit);
@@ -224,9 +245,18 @@ function sanitizeFieldPath(path) {
224
245
  * other shape (wrapper chains, cross-CT ref-target binds) keeps the original
225
246
  * `[...ancestorPrefix, ...selectedField]` behavior unchanged.
226
247
  */
227
- function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCtUids) {
248
+ function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCtUids, options) {
228
249
  const dropCtUids = new Set(referenceCtUids);
229
250
  const sf = sanitizeFieldPath(selectedField).filter((seg) => !dropCtUids.has(seg));
251
+ // A page-absolute field REPLACES the inherited prefix. The leading-overlap
252
+ // collapse below only catches an absolute path that happens to share a
253
+ // leading segment with its ancestor; one that does not overlap was blindly
254
+ // concatenated, producing e.g. `author.related_block` — a path the referenced
255
+ // content type does not have, which CDA silently drops so the section renders
256
+ // component defaults. Provenance answers this directly instead of guessing
257
+ // from the string. See `isPageAbsoluteField`.
258
+ if (options?.pageAbsolute && sf.length > 0)
259
+ return sf;
230
260
  // Collapse the leading overlap with `ancestorPrefix`. A section whose
231
261
  // `selected_field` is rooted at the PAGE content type re-declares the
232
262
  // ancestor's path FROM THE PAGE ROOT — e.g. nested passthrough sections each
@@ -292,7 +322,7 @@ function mapSectionRepeaterPaths(node, runningPath, map) {
292
322
  }
293
323
  }
294
324
  if (node.slots && typeof node.slots === "object") {
295
- for (const slotNodes of Object.values(node.slots)) {
325
+ for (const slotNodes of Object.values(node.slots ?? {})) {
296
326
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
297
327
  for (const c of arr)
298
328
  mapSectionRepeaterPaths(c, childPath, map);
@@ -303,6 +333,54 @@ function mapSectionRepeaterPaths(node, runningPath, map) {
303
333
  mapSectionRepeaterPaths(c, childPath, map);
304
334
  }
305
335
  }
336
+ /**
337
+ * Map every `section-slot` uid in a section's authored UI to the cumulative
338
+ * page-relative schema segments of the Repeater / ConditionBlock chain that
339
+ * wraps it — mirrors the studio-app include analyzer's `indexSectionSlotsContext`.
340
+ * A modular-block ConditionBlock contributes its block-uid segment; a Repeater
341
+ * contributes its items-binding field path (the root template repeater's empty
342
+ * path adds nothing — the section's `selected_field` anchors it); a reference
343
+ * ConditionBlock adds no segment (its enclosing repeater's reference field is
344
+ * already the segment). Used so a SECTION dropped into a slot buried inside the
345
+ * outer section's OWN internal repeater/CB chain roots its references at the
346
+ * full slot path — not just the outer section's `selected_field`. Without this,
347
+ * the slotted section's field projections land on the shallow prefix and its
348
+ * referenced entries come back field-stripped (only[…card][]=_content_type_uid).
349
+ */
350
+ function mapSectionSlotSegments(node, runningPath, map) {
351
+ if (!node || typeof node !== "object")
352
+ return;
353
+ let childPath = runningPath;
354
+ if (node.type === "condition-block") {
355
+ const cond = node.metadata?.condition;
356
+ if (cond?.type === "modular_block" && typeof cond.value === "string") {
357
+ childPath = [...runningPath, cond.value];
358
+ }
359
+ }
360
+ if (node.type === "repeater") {
361
+ const binding = node.props?.items?.binding;
362
+ if (binding) {
363
+ childPath = [
364
+ ...runningPath,
365
+ ...sanitizeFieldPath(getBindingStringForCS(binding)),
366
+ ];
367
+ }
368
+ }
369
+ if (node.type === "section-slot" && typeof node.uid === "string") {
370
+ map.set(node.uid, childPath);
371
+ }
372
+ if (node.slots && typeof node.slots === "object") {
373
+ for (const slotNodes of Object.values(node.slots ?? {})) {
374
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
375
+ for (const c of arr)
376
+ mapSectionSlotSegments(c, childPath, map);
377
+ }
378
+ }
379
+ if (Array.isArray(node.children)) {
380
+ for (const c of node.children)
381
+ mapSectionSlotSegments(c, childPath, map);
382
+ }
383
+ }
306
384
  /**
307
385
  * Walk the PAGE UI and, for every node whose binding is a REPEATER binding
308
386
  * referencing a repeater already in `map` (a section-internal repeater, or a
@@ -351,7 +429,7 @@ function projectCrossBoundaryRepeaterBindings(node, map, onlyOut) {
351
429
  }
352
430
  }
353
431
  if (node.slots && typeof node.slots === "object") {
354
- for (const slotNodes of Object.values(node.slots)) {
432
+ for (const slotNodes of Object.values(node.slots ?? {})) {
355
433
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
356
434
  for (const c of arr)
357
435
  projectCrossBoundaryRepeaterBindings(c, map, onlyOut);
@@ -380,20 +458,23 @@ function projectCrossBoundaryRepeaterBindings(node, map, onlyOut) {
380
458
  * instead of the array → "items.map is not a function").
381
459
  */
382
460
  function resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid) {
461
+ const linkedSchemasFor = (compositionUid) => (sectionsByUid.get(compositionUid)?.linked_schemas ||
462
+ []);
463
+ // A Section data that names ANOTHER document (pinned entry / query / repeater)
464
+ // has no page-template path to project, and a cleared root (`null`) has none
465
+ // by definition — both yield "". Otherwise fall through to the legacy ladder,
466
+ // which both this and `resolveInstanceRootBinding` share, so the page-template
467
+ // projection and the Section data can never drift apart.
383
468
  const override = node.metadata?.sectionBindingOverride;
384
- let selectedField = typeof override?.selectedField === "string"
385
- ? override.selectedField
386
- : node.metadata?.selectedField;
387
- if (selectedField == null) {
388
- const linked = (sectionsByUid.get(node.metadata?.compositionUID)
389
- ?.linked_schemas || []);
390
- selectedField =
391
- linked.find((s) => s.content_type_uid === pageContentTypeUid)
392
- ?.selected_field ??
393
- linked[0]?.selected_field ??
394
- "";
395
- }
396
- return selectedField || "";
469
+ if (override && "rootBinding" in override) {
470
+ const root = resolveInstanceRootBinding(node, linkedSchemasFor, pageContentTypeUid);
471
+ if (!isTemplateRootBinding(root))
472
+ return "";
473
+ return getRootBindingPath(root).join(".");
474
+ }
475
+ // Unsanitised on purpose — callers sanitise at the point of use, and an
476
+ // indexed path (`navigation_menu_3[0].menu_subitems`) must survive to them.
477
+ return resolveLegacySelectedField(node, linkedSchemasFor, pageContentTypeUid);
397
478
  }
398
479
  /**
399
480
  * Walks the page UI tree and resolves every section-composition instance's
@@ -405,7 +486,10 @@ function resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid) {
405
486
  */
406
487
  function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
407
488
  const out = [];
408
- const walk = (node, parentRepeaterUID, ancestorPrefix,
489
+ const walk = (node, parentRepeaterUID,
490
+ // The document `ancestorPrefix` counts from, threaded together with it so a
491
+ // prefix can never travel without its fetch root (ADR 0017).
492
+ inheritedFetchRoot, ancestorPrefix,
409
493
  // Binding field path of the nearest enclosing TEMPLATE-bound Repeater that
410
494
  // hasn't yet been confirmed as a reference. A Repeater's template binding
411
495
  // alone can't be told apart from a plain array; the reference condition-
@@ -427,8 +511,16 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
427
511
  // Children that descend into THIS node's slots inherit `ancestorPrefix`,
428
512
  // extended by this node's reference path when it is a wrapper section.
429
513
  let childPrefix = ancestorPrefix;
514
+ // Always assigned together with `childPrefix` — a prefix is meaningless
515
+ // without the document it counts from (ADR 0017).
516
+ let childFetchRoot = inheritedFetchRoot;
430
517
  let childRepeaterRefField = enclosingRepeaterRefField;
431
518
  let childRefCtUids = refCtUids;
519
+ // For a wrapper section, the per-section-slot internal Repeater/CB segments
520
+ // (from the wrapper's OWN authored UI) that a slotted section inherits as
521
+ // part of its page-rooted prefix. Populated only for section-composition
522
+ // nodes whose entry carries a `ui`; null (no extension) otherwise.
523
+ let slotSegments = null;
432
524
  // Remember a Repeater's template binding path; it becomes a reference hop
433
525
  // only once a reference condition-block downstream confirms the field is a
434
526
  // reference (committed below). A CONTENTSTACK/REPEATER-typed binding is not
@@ -464,17 +556,53 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
464
556
  node.metadata?.compositionUID &&
465
557
  node.uid) {
466
558
  const compositionUid = node.metadata.compositionUID;
559
+ const linkedSchemasFor = (uid) => (sectionsByUid.get(uid)?.linked_schemas ||
560
+ []);
467
561
  const selectedField = resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid);
468
562
  const override = node.metadata?.sectionBindingOverride;
469
563
  const uidRemapping = override?.uidRemapping ?? node.metadata.uidRemapping ?? {};
564
+ // Resolve the Section data, then decide which document this instance's paths
565
+ // belong to. A root naming ANOTHER document (pinned entry / query)
566
+ // rebases the fetch root for this instance and for everything in its
567
+ // slots — inside such a wrapper, paths really are relative to that
568
+ // document, not to the page entry.
569
+ // Only an EXPLICIT Section data can rebase the document. A section with no
570
+ // stored `rootBinding` derives a template-typed one from its
571
+ // `linked_schemas` — that means "no opinion", so it must inherit the
572
+ // enclosing document rather than reset it to the page template entry.
573
+ // Getting this wrong sends a slot child's include paths to a template
574
+ // entry a freeform page does not have.
575
+ const hasExplicitRoot = !!override &&
576
+ Object.prototype.hasOwnProperty.call(override, "rootBinding");
577
+ const sectionData = hasExplicitRoot
578
+ ? resolveInstanceRootBinding(node, linkedSchemasFor, pageContentTypeUid)
579
+ : undefined;
580
+ const ownFetchRoot = hasExplicitRoot
581
+ ? fetchRootFromBinding(sectionData, {
582
+ key: inheritedFetchRoot.key,
583
+ prefix: ancestorPrefix,
584
+ })
585
+ : { key: inheritedFetchRoot.key, prefix: ancestorPrefix };
586
+ const rebasedDocument = ownFetchRoot.key !== inheritedFetchRoot.key;
587
+ const { provenance } = resolveLegacySelectedFieldWithProvenance(node, linkedSchemasFor, pageContentTypeUid);
588
+ // A rebased document makes the inherited prefix meaningless, so the field
589
+ // is absolute within the new document by construction.
590
+ const fieldIsPageAbsolute = rebasedDocument || isPageAbsoluteField(selectedField, provenance);
591
+ // Paths for a rebased instance count from the new document's own prefix,
592
+ // not from the page-rooted chain we walked in on.
593
+ const effectiveAncestorPrefix = rebasedDocument
594
+ ? ownFetchRoot.prefix
595
+ : ancestorPrefix;
470
596
  out.push({
471
597
  instanceUid: node.uid,
472
598
  compositionUid,
473
599
  selectedField,
474
600
  uidRemapping,
475
601
  parentRepeaterUID,
476
- ancestorPrefix,
602
+ ancestorPrefix: effectiveAncestorPrefix,
477
603
  referenceCtUids: refCtUids,
604
+ fetchRootKey: ownFetchRoot.key,
605
+ fieldIsPageAbsolute,
478
606
  });
479
607
  // A whole-CT wrapper (selectedField "") adds no segment — correct, it
480
608
  // creates no reference hop. A reference-bound wrapper extends the prefix
@@ -483,7 +611,24 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
483
611
  // re-declare an overlapping page-root-absolute selected_field (e.g.
484
612
  // `modular_blocks` → `modular_blocks.ref_block` → `modular_blocks.ref_block`)
485
613
  // does not double-count segments into an invalid include[] path.
486
- childPrefix = extendAncestorPrefix(ancestorPrefix, selectedField);
614
+ // Slot children inherit this wrapper's document. When the wrapper rebased,
615
+ // they inherit the NEW one and the page-rooted chain is dropped; when the
616
+ // wrapper's own field is page-absolute, it replaces rather than extends.
617
+ childFetchRoot = rebasedDocument ? ownFetchRoot : inheritedFetchRoot;
618
+ childPrefix = rebasedDocument
619
+ ? extendAncestorPrefix(ownFetchRoot.prefix, "")
620
+ : fieldIsPageAbsolute
621
+ ? sanitizeFieldPath(selectedField)
622
+ : extendAncestorPrefix(ancestorPrefix, selectedField);
623
+ // Compute this wrapper's slot-internal context so a section dropped into
624
+ // a slot buried inside the wrapper's OWN Repeater/CB chain roots at the
625
+ // full slot path (mirrors the editor's `indexSectionSlotsContext`).
626
+ const wrapperUi = sectionsByUid.get(compositionUid)?.ui;
627
+ if (wrapperUi) {
628
+ const wrapperUiNode = typeof wrapperUi === "string" ? decompressSpec(wrapperUi) : wrapperUi;
629
+ slotSegments = new Map();
630
+ mapSectionSlotSegments(wrapperUiNode, [], slotSegments);
631
+ }
487
632
  // Empty slots fall back to their authored default section (COMS-1659).
488
633
  // The default isn't a real child in the page UI, so synthesize the same
489
634
  // node the renderer makes and walk it here — otherwise the default's data
@@ -512,23 +657,28 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
512
657
  metadata: { compositionUID: defaultUid },
513
658
  slots: {},
514
659
  };
515
- walk(synth, nextRepeater, childPrefix, childRepeaterRefField, childRefCtUids, chain);
660
+ walk(synth, nextRepeater, childFetchRoot, slotSegments
661
+ ? [...childPrefix, ...(slotSegments.get(slotUid) || [])]
662
+ : childPrefix, childRepeaterRefField, childRefCtUids, chain);
516
663
  }
517
664
  }
518
665
  if (node.slots && typeof node.slots === "object") {
519
- for (const slotNodes of Object.values(node.slots)) {
666
+ for (const [slotUid, slotNodes] of Object.entries(node.slots ?? {})) {
520
667
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
668
+ const slotPrefix = slotSegments
669
+ ? [...childPrefix, ...(slotSegments.get(slotUid) || [])]
670
+ : childPrefix;
521
671
  for (const c of arr)
522
- walk(c, nextRepeater, childPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
672
+ walk(c, nextRepeater, childFetchRoot, slotPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
523
673
  }
524
674
  }
525
675
  if (Array.isArray(node.children)) {
526
676
  // children (non-slot) stay in the same scope as this node.
527
677
  for (const c of node.children)
528
- walk(c, nextRepeater, ancestorPrefix, childRepeaterRefField, refCtUids, defaultAncestors);
678
+ walk(c, nextRepeater, inheritedFetchRoot, ancestorPrefix, childRepeaterRefField, refCtUids, defaultAncestors);
529
679
  }
530
680
  };
531
- walk(ui, null, [], null, []);
681
+ walk(ui, null, templateFetchRoot(), [], null, []);
532
682
  return out;
533
683
  }
534
684
  async function fetchSectionCompositionEntries(config, sectionUids, options) {
@@ -1349,6 +1499,13 @@ function generateSdk(userConfig) {
1349
1499
  }
1350
1500
  if (config.stackSdk)
1351
1501
  setStackSdkInstance(config.stackSdk);
1502
+ // Bring-Your-Own-State: wire the user's getState/setState (+ declared
1503
+ // variables) into the page-global state store so useStudioState, author
1504
+ // bindings, and custom code all read/write the user's store. Omitted →
1505
+ // the store's internal Map fallback still serves ad-hoc/declared state.
1506
+ if (config.state) {
1507
+ getStateStoreInstance().configure(config.state);
1508
+ }
1352
1509
  /**
1353
1510
  * The variant alias every SDK-side data fetch should use, in priority order:
1354
1511
  * 1. The `cs-variant-alias` URL param when running inside Studio — Studio
@@ -1491,51 +1648,74 @@ function generateSdk(userConfig) {
1491
1648
  const { variantAlias, locale } = options;
1492
1649
  const isInsideEditor = isEditorFetch(searchParams);
1493
1650
  try {
1494
- const promises = [];
1495
- for (const _content_type_uid in staticBindingQueries) {
1496
- const ct_promises = [];
1497
- for (const entry_uid in staticBindingQueries[_content_type_uid]) {
1498
- const references = staticBindingQueries[_content_type_uid][entry_uid];
1499
- let onlyQuery = [];
1500
- // When inside Studio or Visual Builder, fetch all fields (don't use onlyQueries)
1501
- if (!isInsideEditor) {
1502
- onlyQuery =
1503
- staticBindingOnlyQueries[_content_type_uid][entry_uid] || [];
1651
+ // One collection query per content type (`containedIn` over the entry
1652
+ // uids) instead of one request per entry — bound-entry fetch cost stays
1653
+ // flat as a page binds more entries of the same type. Uid lists longer
1654
+ // than the CDA's per-query entry cap are split so no entry is silently
1655
+ // dropped past the first response page.
1656
+ const batches = Object.keys(staticBindingQueries).flatMap((_content_type_uid) => {
1657
+ const entryUids = Object.keys(staticBindingQueries[_content_type_uid]);
1658
+ const references = uniq(entryUids.flatMap((entry_uid) => staticBindingQueries[_content_type_uid][entry_uid]));
1659
+ let onlyQuery = [];
1660
+ // When inside Studio or Visual Builder, fetch all fields (don't use onlyQueries)
1661
+ if (!isInsideEditor) {
1662
+ // `?.` on the content type: an entry can reach `staticBindingQueries`
1663
+ // with no projection bucket at all (a section rooted at a whole
1664
+ // document asks for every field, so it contributes no only[] keys).
1665
+ // Indexing straight through threw a TypeError here, and because the
1666
+ // whole batch assembly sits inside a try/catch the failure surfaced
1667
+ // as NO REQUEST rather than as an error — the entry was silently
1668
+ // never fetched (E2E DR5.10).
1669
+ const entryProjections = entryUids.map((entry_uid) => staticBindingOnlyQueries[_content_type_uid]?.[entry_uid] || []);
1670
+ // An entry with no projection of its own (e.g. bound whole, path {})
1671
+ // is fetched with ALL fields; batching it with projected siblings
1672
+ // must not narrow it, so one unprojected entry makes the whole batch
1673
+ // unprojected. Otherwise the batch carries the union of every
1674
+ // entry's projection — over-fetching a field is fine, dropping one
1675
+ // is a regression.
1676
+ const everyEntryProjected = entryProjections.every((projection) => projection.length > 0);
1677
+ if (everyEntryProjected) {
1678
+ onlyQuery = uniqBy(entryProjections.flat(), ([reference, field]) => `${reference}|${field}`);
1504
1679
  // We need locale for redirect to the correct locale.
1505
1680
  if (config.cslp.appendTags) {
1506
1681
  onlyQuery.push(["BASE", "locale"]);
1507
1682
  }
1683
+ // Batch results map back per entry by uid, so an active projection
1684
+ // must keep it in the response.
1685
+ onlyQuery.push(["BASE", "uid"]);
1508
1686
  }
1509
- const query = config.stackSdk.entryQuery(_content_type_uid, entry_uid, {
1687
+ }
1688
+ return chunk(entryUids, STATIC_ENTRY_BATCH_SIZE).map((uids) => ({
1689
+ ct_uid: _content_type_uid,
1690
+ uids,
1691
+ promise: config.stackSdk
1692
+ .ctQuery(_content_type_uid, {
1510
1693
  only: onlyQuery,
1694
+ references,
1511
1695
  variantAlias,
1512
1696
  locale: locale || config.locale, // Use override locale or default
1513
- });
1514
- if (references.length) {
1515
- query.includeReference(references);
1516
- }
1517
- ct_promises.push(query.fetch());
1518
- }
1519
- promises.push(Promise.allSettled(ct_promises));
1520
- }
1521
- const ct_entries_res = await Promise.allSettled(promises);
1522
- const ct_uids = Object.keys(staticBindingQueries);
1697
+ })
1698
+ .containedIn("uid", uids)
1699
+ .find(),
1700
+ }));
1701
+ });
1702
+ const ct_entries_res = await Promise.allSettled(batches.map((batch) => batch.promise));
1523
1703
  for (let i = 0; i < ct_entries_res.length; i++) {
1524
1704
  const ct_entries = ct_entries_res[i];
1525
- const ct_uid = ct_uids[i];
1705
+ const { ct_uid, uids } = batches[i];
1526
1706
  if (ct_entries.status === "fulfilled") {
1527
- for (const entry of ct_entries.value) {
1528
- if (entry.status === "fulfilled") {
1529
- setStaticEntryInDS(data.dataSources, ct_uid, [entry.value]);
1530
- if (config.cslp.appendTags) {
1531
- addEditableTags(entry.value, ct_uid, true, entry.value?.locale || "en-us");
1532
- }
1707
+ const entries = entriesFromResponse(ct_entries.value) ?? [];
1708
+ setStaticEntryInDS(data.dataSources, ct_uid, entries);
1709
+ if (config.cslp.appendTags) {
1710
+ for (const entry of entries) {
1711
+ addEditableTags(entry, ct_uid, true, entry?.locale || "en-us");
1533
1712
  }
1534
- else {
1535
- //TODO: Add logger support general to have studio prefix
1536
- if (process.env.NODE_ENV === "development") {
1537
- console.log("Message handling fallback");
1538
- }
1713
+ }
1714
+ if (process.env.NODE_ENV === "development") {
1715
+ const returnedUids = new Set(entries.map((entry) => entry.uid));
1716
+ const missingUids = uids.filter((entry_uid) => !returnedUids.has(entry_uid));
1717
+ if (missingUids.length) {
1718
+ console.log(`Static entries missing from ${ct_uid} response: ${missingUids.join(", ")}`);
1539
1719
  }
1540
1720
  }
1541
1721
  }
@@ -1560,10 +1740,36 @@ function generateSdk(userConfig) {
1560
1740
  if (!config.stackSdk) {
1561
1741
  return;
1562
1742
  }
1563
- const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = fetchOptions;
1743
+ const { connected_content_type, compositionQuery, includeQueries, onlyQueries: requestedOnlyQueries, } = fetchOptions;
1564
1744
  if (!connected_content_type) {
1565
1745
  return;
1566
1746
  }
1747
+ // A page that binds many sections can push the projection past the Delivery
1748
+ // API's URL limit, which rejects the whole request and costs us the page.
1749
+ // The projection is an optimisation; the reference paths are not. Give up
1750
+ // the projection and accept a larger response rather than losing the entry.
1751
+ const urlBudget = applyUrlBudget({
1752
+ references: includeQueries,
1753
+ only: requestedOnlyQueries,
1754
+ });
1755
+ const onlyQueries = urlBudget.only;
1756
+ // Both of these are for whoever is building the site, not for its logs. The
1757
+ // first says we gave up an optimisation; the second predicts a request that
1758
+ // will fail. Neither is actionable from a production console, and a page
1759
+ // that trips one trips it on every render.
1760
+ if (process.env.NODE_ENV === "development") {
1761
+ if (urlBudget.dropped) {
1762
+ console.warn(`[Studio] Field projection dropped for "${connected_content_type}": ` +
1763
+ `${requestedOnlyQueries.length} only[] parameters would have exceeded ` +
1764
+ `the Delivery API URL limit. Fetching all fields instead — the page is ` +
1765
+ `correct but the response is larger than necessary.`);
1766
+ }
1767
+ if (referencesExceedBudget(includeQueries)) {
1768
+ console.warn(`[Studio] The reference paths for "${connected_content_type}" alone ` +
1769
+ `(${includeQueries.length} include[] parameters) exceed the Delivery ` +
1770
+ `API URL limit. This request is expected to fail with 414.`);
1771
+ }
1772
+ }
1567
1773
  const { fetchComposition: _, fetchTemplateEntry: perQueryFetchTemplateEntry, ...resolvedOptions } = compositionQueryOptions || {};
1568
1774
  // Safe access to enhanced options (available only when SDK provides Studio Intelligence)
1569
1775
  const enhancedOptions = compositionQueryOptions; // Type assertion for internal properties
@@ -1992,11 +2198,35 @@ function generateSdk(userConfig) {
1992
2198
  // page-rooted `ancestorPrefix` + its own `selectedField`, so a multi-level
1993
2199
  // reference chain (W1 → W2 → …) fetches the full nested include depth.
1994
2200
  const sectionsByUid = new Map(sectionEntries.map((s) => [s.uid, s]));
1995
- const instanceBindings = collectSectionInstanceBindings(typeof compositionEntry.ui === "string"
2201
+ const pageUi = typeof compositionEntry.ui === "string"
1996
2202
  ? decompressSpec(compositionEntry.ui)
1997
- : compositionEntry.ui, sectionsByUid, connectedContentTypeUid);
2203
+ : compositionEntry.ui;
2204
+ const instanceBindings = collectSectionInstanceBindings(pageUi, sectionsByUid, connectedContentTypeUid);
2205
+ // The author's own modular-block choices, used below to drop the include[]
2206
+ // paths the Delivery API discards.
2207
+ const modularBlocks = indexModularBlocks(pageUi);
1998
2208
  const mergedTemplateRefs = [...templateReferencesPath];
1999
2209
  const mergedTemplateOnly = [...templateOnlyKeys];
2210
+ // Include paths for sections whose Section data names a document OTHER than the
2211
+ // page template entry (ADR 0017). Keyed by fetch root so each set flushes to
2212
+ // its own request: `mergedTemplateRefs` above is just the "template" bucket.
2213
+ // Without this the paths are computed correctly and then discarded, and the
2214
+ // section renders structure with no content — references come back as
2215
+ // `{uid, _content_type_uid}` stubs and a repeater over them yields empty rows.
2216
+ const refsByFetchRoot = new Map();
2217
+ const pushForFetchRoot = (key, path) => {
2218
+ if (!path)
2219
+ return;
2220
+ if (key === TEMPLATE_FETCH_ROOT_KEY) {
2221
+ mergedTemplateRefs.push(path);
2222
+ return;
2223
+ }
2224
+ const existing = refsByFetchRoot.get(key);
2225
+ if (existing)
2226
+ existing.push(path);
2227
+ else
2228
+ refsByFetchRoot.set(key, [path]);
2229
+ };
2000
2230
  for (const binding of instanceBindings) {
2001
2231
  const section = sectionsByUid.get(binding.compositionUid);
2002
2232
  if (!section)
@@ -2008,8 +2238,25 @@ function generateSdk(userConfig) {
2008
2238
  // Reference-ancestor placement: when the section sits inside a page
2009
2239
  // Repeater(reference)+reference-ConditionBlock (see
2010
2240
  // composeSectionTemplatePrefix).
2011
- const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids);
2241
+ const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids, { pageAbsolute: binding.fieldIsPageAbsolute });
2012
2242
  const remapSeg = (seg) => binding.uidRemapping?.[seg] ?? seg;
2243
+ const fetchRootKey = binding.fetchRootKey;
2244
+ // Register the fetch root even when the section contributes NO reference
2245
+ // include paths. `pushForFetchRoot` only records a key that carries a
2246
+ // path, and the flush below turns each key into an entry request — so a
2247
+ // section rooted at a pinned entry whose bindings are all scalar
2248
+ // (`{ heading }`) named a document nobody ever asked the CDA for. The
2249
+ // pool came back without it, `buildScopedDataSources` logged "no pooled
2250
+ // entry" and the deployed page rendered component defaults while the
2251
+ // editor — which fetches every configured data source regardless of
2252
+ // bindings — rendered it fine (E2E DR5.10). An empty path list means "all
2253
+ // fields": `resolveStaticData` drops the projection for a batch that has
2254
+ // one unprojected entry, which is what a whole-document root wants.
2255
+ if (fetchRootKey && parseEntryFetchRootKey(fetchRootKey)) {
2256
+ if (!refsByFetchRoot.has(fetchRootKey)) {
2257
+ refsByFetchRoot.set(fetchRootKey, []);
2258
+ }
2259
+ }
2013
2260
  const sectionAsCompositionEntry = {
2014
2261
  ...section,
2015
2262
  ui: typeof section.ui === "string"
@@ -2040,7 +2287,7 @@ function generateSdk(userConfig) {
2040
2287
  for (const p of sectionTemplateRefPaths) {
2041
2288
  const full = [...prefix, ...sanitizeFieldPath(p).map(remapSeg)].join(".");
2042
2289
  if (full)
2043
- mergedTemplateRefs.push(full);
2290
+ pushForFetchRoot(fetchRootKey, full);
2044
2291
  }
2045
2292
  // Include + project EVERY cumulative hop of the composed prefix so each
2046
2293
  // reference in the chain is fetched and the next hop is reachable, e.g.
@@ -2051,9 +2298,31 @@ function generateSdk(userConfig) {
2051
2298
  const acc = [];
2052
2299
  for (const seg of prefix) {
2053
2300
  acc.push(seg);
2054
- mergedTemplateRefs.push(acc.join("."));
2055
- mergedTemplateOnly.push([parent, seg]);
2056
- parent = acc.join(".");
2301
+ const hop = acc.join(".");
2302
+ // Most hops of a section's position are the field holding the blocks,
2303
+ // or a block itself. The Delivery API ignores an include[] for those,
2304
+ // so adding one only costs URL space. The only[] row below is still
2305
+ // wanted either way — it is what keeps the block in the response.
2306
+ //
2307
+ // The block index is read off the PAGE UI, so it can only judge a hop
2308
+ // inside the page template entry. A hop inside another document — a
2309
+ // pinned entry or query the section is rooted at (ADR 0017) — is
2310
+ // routed to that document's request unconditionally.
2311
+ if (fetchRootKey !== TEMPLATE_FETCH_ROOT_KEY ||
2312
+ !isModularBlockPath(hop, modularBlocks)) {
2313
+ pushForFetchRoot(fetchRootKey, hop);
2314
+ }
2315
+ // only[] is carried for the template fetch root only in v1 —
2316
+ // `MergedEntryNeed` has no projection slot, and an only[] union is
2317
+ // SUBTRACTIVE: several sections and the page can request the same
2318
+ // entry with different projections, and a union that misses one
2319
+ // requester silently drops fields. include[] unions are additive and
2320
+ // safe. Pinned entries are already fetched unprojected, so this costs
2321
+ // payload size, not correctness (ADR 0017).
2322
+ if (fetchRootKey === TEMPLATE_FETCH_ROOT_KEY) {
2323
+ mergedTemplateOnly.push([parent, seg]);
2324
+ }
2325
+ parent = hop;
2057
2326
  }
2058
2327
  }
2059
2328
  // Re-parent the section's field projections under the selectedField
@@ -2070,7 +2339,9 @@ function generateSdk(userConfig) {
2070
2339
  ? `${prefix.join(".")}.${remappedParent}`
2071
2340
  : remappedParent;
2072
2341
  }
2073
- mergedTemplateOnly.push([newParent, remappedChild]);
2342
+ if (fetchRootKey === TEMPLATE_FETCH_ROOT_KEY) {
2343
+ mergedTemplateOnly.push([newParent, remappedChild]);
2344
+ }
2074
2345
  }
2075
2346
  }
2076
2347
  // Cross-boundary repeater bindings: a page-authored Repeater/Text bound to a
@@ -2095,10 +2366,7 @@ function generateSdk(userConfig) {
2095
2366
  mapSectionRepeaterPaths(sectionUi, prefix, repeaterPathMap);
2096
2367
  }
2097
2368
  if (repeaterPathMap.size > 0) {
2098
- const pageUiForProjection = typeof compositionEntry.ui === "string"
2099
- ? decompressSpec(compositionEntry.ui)
2100
- : compositionEntry.ui;
2101
- projectCrossBoundaryRepeaterBindings(pageUiForProjection, repeaterPathMap, mergedTemplateOnly);
2369
+ projectCrossBoundaryRepeaterBindings(pageUi, repeaterPathMap, mergedTemplateOnly);
2102
2370
  }
2103
2371
  }
2104
2372
  // ---- D7: fold the template entry into the reference union ----
@@ -2132,7 +2400,46 @@ function generateSdk(userConfig) {
2132
2400
  delete mergedOnly[templateContentTypeUid][knownTemplateUid];
2133
2401
  }
2134
2402
  }
2135
- const dedupedTemplateRefs = [...new Set(mergedTemplateRefs)];
2403
+ // ---- Flush the non-template fetch roots (ADR 0017) ----
2404
+ // Each key that is not "template" names its own document, so its include
2405
+ // paths belong on THAT document's request. A `<ct>:<uid>` key routes into
2406
+ // `mergedRefs`, which `resolveStaticData` fetches and which already unions
2407
+ // include paths per (ct_uid, entry_uid) across requesters — the page asks
2408
+ // for the entry with its own includes, the section adds more, they merge.
2409
+ //
2410
+ // A `query:<dsUid>` key is not flushed here: query includes are assembled
2411
+ // from `resolvedReferences` inside `resolveQueryData`, so a query-rooted
2412
+ // section contributes through the persisted path (step 9) rather than this
2413
+ // one. Logged rather than dropped silently.
2414
+ for (const [key, paths] of refsByFetchRoot.entries()) {
2415
+ const entryRef = parseEntryFetchRootKey(key);
2416
+ if (!entryRef) {
2417
+ if (process.env.NODE_ENV === "development") {
2418
+ console.warn(`[studio] section include paths for fetch root "${key}" are not routed by the spec fetch; they must come from persisted resolvedReferences. Paths: ${paths.join(", ")}`);
2419
+ }
2420
+ continue;
2421
+ }
2422
+ const { contentTypeUid, entryUid } = entryRef;
2423
+ if (!mergedRefs[contentTypeUid])
2424
+ mergedRefs[contentTypeUid] = {};
2425
+ const existing = mergedRefs[contentTypeUid][entryUid] ?? [];
2426
+ mergedRefs[contentTypeUid][entryUid] = Array.from(new Set([...existing, ...paths]));
2427
+ // Keep the projection map in step. An empty list means "no only[] keys of
2428
+ // its own", which makes the batch unprojected — every field — and that is
2429
+ // what a document-level fetch root wants.
2430
+ if (!mergedOnly[contentTypeUid])
2431
+ mergedOnly[contentTypeUid] = {};
2432
+ if (!mergedOnly[contentTypeUid][entryUid]) {
2433
+ mergedOnly[contentTypeUid][entryUid] = [];
2434
+ }
2435
+ }
2436
+ // Sections, the page itself and the caller's own extra references have all
2437
+ // been merged by this point, so this is the first place we can tell whether
2438
+ // a path is just the start of a longer one. Drop those here, before the
2439
+ // projection patch below, so it sees the paths the request will carry.
2440
+ const dedupedTemplateRefs = dropImpliedParents([
2441
+ ...new Set(mergedTemplateRefs),
2442
+ ]);
2136
2443
  // A deep reference that lives inside a section slot only assembles its full
2137
2444
  // include[] path in this merged set (the page sees the slot child at the
2138
2445
  // wrong depth; the section sees its own reference repeater but not the
@@ -2180,10 +2487,12 @@ function generateSdk(userConfig) {
2180
2487
  }
2181
2488
  attachSectionCompositionContexts(data, compositionEntry, sectionEntries);
2182
2489
  // Build per-instance scoped data sources (pure) and attach to spec.
2183
- const pageUi = typeof compositionEntry.ui === "string"
2184
- ? decompressSpec(compositionEntry.ui)
2185
- : compositionEntry.ui;
2490
+ // `pageUi` is the spec decompressed once, above.
2186
2491
  data.section_scoped_data = buildSectionScopedData(compositionEntry, pageUi, sectionEntries, data.dataSources);
2492
+ // Store the page's dataSources ONCE for section subtrees to read back.
2493
+ // Entering a section replaces `dataSources`, so this is how a section
2494
+ // reaches the outer page's data. By reference — same object, not a copy.
2495
+ data.page_data_sources = data.dataSources;
2187
2496
  return data;
2188
2497
  }
2189
2498
  async function fetchSpec(queryOptions, options, skipComponentLoading = false, searchParams) {
@@ -2195,21 +2504,11 @@ function generateSdk(userConfig) {
2195
2504
  // Phase 2: Enhance options with Studio Intelligence (preserves user preferences)
2196
2505
  const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
2197
2506
  // Phase 3: Fetch with enhanced context (preserves custom fetchers)
2198
- const { compositionEntry, symbolEntries, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions);
2507
+ const { compositionEntry, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch(searchParams));
2199
2508
  const ui = typeof compositionEntry.ui === "string"
2200
2509
  ? decompressSpec(compositionEntry.ui)
2201
2510
  : compositionEntry.ui;
2202
2511
  const sectionEntries = await getAllSectionCompositions(config, compositionEntry, enhancedOptions);
2203
- const allSymbolEntries = [...symbolEntries];
2204
- const seenSymbolUids = new Set(symbolEntries.map((symbol) => symbol.uid));
2205
- for (const sectionEntry of sectionEntries.values()) {
2206
- getAllSymbols(sectionEntry).forEach((symbol) => {
2207
- if (seenSymbolUids.has(symbol.uid))
2208
- return;
2209
- seenSymbolUids.add(symbol.uid);
2210
- allSymbolEntries.push(symbol);
2211
- });
2212
- }
2213
2512
  const data = await fetchData(compositionEntry, queryOptions, enhancedOptions, Array.from(sectionEntries.values()), searchParams);
2214
2513
  // Lazy loading and SSR validation for production mode
2215
2514
  // Skip if called from fetchMultipleSpecs (which handles loading in batch)
@@ -2284,7 +2583,6 @@ function generateSdk(userConfig) {
2284
2583
  data,
2285
2584
  ui,
2286
2585
  compositionEntry,
2287
- symbols: allSymbolEntries,
2288
2586
  sectionCompositions: Array.from(sectionEntries.values()),
2289
2587
  // Studio-only resolution diagnostics (URL metadata path); undefined otherwise.
2290
2588
  urlResolution,
@@ -2299,8 +2597,8 @@ function generateSdk(userConfig) {
2299
2597
  /**
2300
2598
  * Spec-only composition fetch. Resolves the composition STRUCTURE — `ui`,
2301
2599
  * `compositionEntry`, linked `sectionCompositions`, `config`, and the raw
2302
- * `ui.metadata.seo` — but SKIPS the data fetch (`fetchData`/CDA) entirely and
2303
- * omits symbols. `data` comes back empty; the caller supplies it at render
2600
+ * `ui.metadata.seo` — but SKIPS the data fetch (`fetchData`/CDA) entirely.
2601
+ * `data` comes back empty; the caller supplies it at render
2304
2602
  * time (see `StudioComposition` in `@contentstack/studio-react`).
2305
2603
  *
2306
2604
  * Runs in both SSR and CSR (plain async, not a hook).
@@ -2311,7 +2609,7 @@ function generateSdk(userConfig) {
2311
2609
  }
2312
2610
  const studioIntelligence = await StudioIntelligenceManager.getStudioIntelligence(options, config);
2313
2611
  const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
2314
- const { compositionEntry, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions);
2612
+ const { compositionEntry, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch());
2315
2613
  const ui = typeof compositionEntry.ui === "string"
2316
2614
  ? decompressSpec(compositionEntry.ui)
2317
2615
  : compositionEntry.ui;
@@ -2330,8 +2628,6 @@ function generateSdk(userConfig) {
2330
2628
  data: { dataSources: {}, static_value: {} },
2331
2629
  ui,
2332
2630
  compositionEntry,
2333
- // Symbols are deprecated for this path.
2334
- symbols: [],
2335
2631
  sectionCompositions: Array.from(sectionEntries.values()),
2336
2632
  urlResolution,
2337
2633
  config: {
@@ -2803,30 +3099,6 @@ function generateSdk(userConfig) {
2803
3099
  }
2804
3100
  return sdkSingleton;
2805
3101
  }
2806
- const parseUI = (ui) => {
2807
- try {
2808
- return decompressSpec(ui);
2809
- }
2810
- catch (error) {
2811
- throw new ComposableStudioError(ComposableStudioErrors.UI_PARSING_ERROR, getErrorMessage(ErrorMessageKey.UI_PARSING_ERROR), { ui, error });
2812
- }
2813
- };
2814
- function getAllSymbols(compositionEntry) {
2815
- const res = [];
2816
- const Q = [
2817
- compositionEntry,
2818
- ];
2819
- while (Q.length > 0) {
2820
- const curr = Q.shift();
2821
- const symbols = (curr?.symbols || []);
2822
- for (const symbol of symbols) {
2823
- symbol.ui = parseUI(symbol.ui);
2824
- res.push(symbol);
2825
- Q.push(symbol);
2826
- }
2827
- }
2828
- return res;
2829
- }
2830
3102
  /** CDA entries page size for the lightweight candidate fetch. */
2831
3103
  const CANDIDATE_PAGE_SIZE = 100;
2832
3104
  /** Safety cap on candidate pages (server-side resolution will own this later). */
@@ -2838,10 +3110,22 @@ const MAX_CANDIDATE_PAGES = 20;
2838
3110
  * placement filter. Paginates with skip/limit; `truncated` is true if the safety
2839
3111
  * cap is hit.
2840
3112
  */
3113
+ /**
3114
+ * Total-count of a `find()` response when `include_count` was requested —
3115
+ * `{ entries, count }` on the TS delivery SDK, `[entries, count]` on the JS
3116
+ * SDK. Undefined when the response carries no count.
3117
+ */
3118
+ function countFromResponse(response) {
3119
+ if (Array.isArray(response)) {
3120
+ const last = response[response.length - 1];
3121
+ return typeof last === "number" ? last : undefined;
3122
+ }
3123
+ const count = response?.count;
3124
+ return typeof count === "number" ? count : undefined;
3125
+ }
2841
3126
  async function fetchAllPageCompositions(config, locale) {
2842
- const all = [];
2843
- for (let page = 0; page < MAX_CANDIDATE_PAGES; page++) {
2844
- const res = await config.stackSdk
3127
+ const fetchPage = (page, includeCount) => {
3128
+ let query = config.stackSdk
2845
3129
  .ctQuery(config.contentTypeUid, {
2846
3130
  locale: locale || config.locale,
2847
3131
  query: { ...getPageLinkedPlacementFilter() },
@@ -2853,15 +3137,40 @@ async function fetchAllPageCompositions(config, locale) {
2853
3137
  ],
2854
3138
  })
2855
3139
  .limit(CANDIDATE_PAGE_SIZE)
2856
- .skip(page * CANDIDATE_PAGE_SIZE)
2857
- .find();
2858
- const batch = entriesFromResponse(res);
2859
- all.push(...batch);
2860
- if (batch.length < CANDIDATE_PAGE_SIZE) {
2861
- return { entries: all, truncated: false };
3140
+ .skip(page * CANDIDATE_PAGE_SIZE);
3141
+ if (includeCount) {
3142
+ query = query.includeCount();
3143
+ }
3144
+ return query.find();
3145
+ };
3146
+ // Page 0 carries include_count so the remaining pages can be fetched in one
3147
+ // parallel wave instead of one serial round-trip per page.
3148
+ const firstRes = await fetchPage(0, true);
3149
+ const first = entriesFromResponse(firstRes);
3150
+ if (first.length < CANDIDATE_PAGE_SIZE) {
3151
+ return { entries: first, truncated: false };
3152
+ }
3153
+ const total = countFromResponse(firstRes);
3154
+ if (total === undefined) {
3155
+ // No usable count — fall back to the serial walk.
3156
+ const all = [...first];
3157
+ for (let page = 1; page < MAX_CANDIDATE_PAGES; page++) {
3158
+ const batch = entriesFromResponse(await fetchPage(page, false));
3159
+ all.push(...batch);
3160
+ if (batch.length < CANDIDATE_PAGE_SIZE) {
3161
+ return { entries: all, truncated: false };
3162
+ }
2862
3163
  }
3164
+ return { entries: all, truncated: true };
2863
3165
  }
2864
- return { entries: all, truncated: true };
3166
+ const totalPages = Math.ceil(total / CANDIDATE_PAGE_SIZE);
3167
+ const pageCount = Math.min(totalPages, MAX_CANDIDATE_PAGES);
3168
+ const rest = await Promise.all(range(1, pageCount).map((page) => fetchPage(page, false)));
3169
+ const all = [
3170
+ first,
3171
+ ...rest.map((res) => entriesFromResponse(res)),
3172
+ ].flat();
3173
+ return { entries: all, truncated: totalPages > MAX_CANDIDATE_PAGES };
2865
3174
  }
2866
3175
  /**
2867
3176
  * Decide which composition wins among the ranking's top-tier candidates.
@@ -2924,7 +3233,14 @@ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, lo
2924
3233
  * This function fetches UI Composition from defined options.
2925
3234
  * Supports custom fetcher overrides (per-query > global > SDK default).
2926
3235
  **/
2927
- async function fetchComposition(config, queryOptions, compositionQueryOptions) {
3236
+ async function fetchComposition(config, queryOptions, compositionQueryOptions,
3237
+ /**
3238
+ * Whether this fetch renders inside an editor (Studio or Visual Builder) —
3239
+ * callers compute it via `isEditorFetch`. Editor fetches keep the full
3240
+ * candidate scan for URL resolution so Studio's diagnostics list every
3241
+ * considered candidate; the exact-match fast path is production-only.
3242
+ */
3243
+ isInsideEditor = false) {
2928
3244
  const { fetchComposition: perQueryFetchComposition, fetchTemplateEntry: _, ...resolvedOptions } = compositionQueryOptions || {};
2929
3245
  const locale = resolvedOptions.locale;
2930
3246
  // Captured by the URL metadata (Phase A) path for Studio resolution
@@ -3019,6 +3335,52 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
3019
3335
  // descent to lower tiers, no legacy fallback.
3020
3336
  const requestUrl = queryOptions.url;
3021
3337
  try {
3338
+ // 0. Exact-match fast path (production only). A literal `url` equal to
3339
+ // the request is always the most specific possible match (a pattern
3340
+ // match spends at least one character on a variable), so one equality
3341
+ // query both resolves and full-fetches the page — no candidate scan,
3342
+ // no separate winner fetch. A miss, an error, or an ownerless hit set
3343
+ // falls through to the unified scan below, whose outcome is
3344
+ // authoritative. Editor fetches skip this so Studio's resolution
3345
+ // diagnostics keep the full candidate pool.
3346
+ if (requestUrl && !isInsideEditor) {
3347
+ try {
3348
+ const exactRes = await config.stackSdk
3349
+ .ctQuery(config.contentTypeUid, {
3350
+ includeAll: true,
3351
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
3352
+ locale: locale || config.locale,
3353
+ query: { url: requestUrl, ...getPageLinkedPlacementFilter() },
3354
+ })
3355
+ .find();
3356
+ const exactHits = entriesFromResponse(exactRes) ?? [];
3357
+ if (exactHits.length) {
3358
+ // Duplicate literal urls can tie — rank + ownership-probe within
3359
+ // the hit set, exactly like the unified path's top tier.
3360
+ const ranking = rankUrlMatches(requestUrl, exactHits);
3361
+ if (ranking.composableUids.length) {
3362
+ const hitsByUid = new Map(exactHits.map((hit) => [
3363
+ hit.composable_uid,
3364
+ hit,
3365
+ ]));
3366
+ const { winnerUid } = await resolveUrlWinner(config, requestUrl, ranking, hitsByUid, locale);
3367
+ const winner = winnerUid
3368
+ ? exactHits.find((hit) => hit.composable_uid === winnerUid)
3369
+ : undefined;
3370
+ if (winner) {
3371
+ return winner;
3372
+ }
3373
+ }
3374
+ }
3375
+ }
3376
+ catch (fastPathError) {
3377
+ // The fast path must never make resolution less reliable than the
3378
+ // scan it short-cuts — swallow and fall through.
3379
+ if (process.env.NODE_ENV === "development") {
3380
+ console.warn("[Composable Studio SDK] Exact-match URL lookup failed; falling back to the candidate scan:", fastPathError);
3381
+ }
3382
+ }
3383
+ }
3022
3384
  // 1. Fetch every page-linked candidate (lightweight, paginated).
3023
3385
  const { entries: candidates, truncated } = await fetchAllPageCompositions(config, locale);
3024
3386
  if (truncated) {
@@ -3104,7 +3466,6 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
3104
3466
  }
3105
3467
  return {
3106
3468
  compositionEntry: entry,
3107
- symbolEntries: getAllSymbols(entry),
3108
3469
  // Populated if the custom fetcher delegated to `defaultFetch` and it
3109
3470
  // resolved via the URL metadata path; otherwise undefined.
3110
3471
  urlResolution,
@@ -3113,10 +3474,9 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
3113
3474
  const entry = await defaultImpl();
3114
3475
  return {
3115
3476
  compositionEntry: entry,
3116
- symbolEntries: getAllSymbols(entry),
3117
3477
  urlResolution,
3118
3478
  };
3119
3479
  }
3120
3480
 
3121
- export { buildSectionScopedData, classifyApiError, collectSectionInstanceBindings as collectSectionInstanceBindingsForTest, composeSectionTemplatePrefix, fetchComposition as fetchCompositionForTest, flattenBindingPathFromValue, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, getSeoMetadataPure, isTemplateBinding, mapSectionRepeaterPaths as mapSectionRepeaterPathsForTest, parseUI, projectCrossBoundaryRepeaterBindings as projectCrossBoundaryRepeaterBindingsForTest, resolveSeoBindingValue };
3481
+ export { buildSectionScopedData, classifyApiError, collectSectionInstanceBindings as collectSectionInstanceBindingsForTest, composeSectionTemplatePrefix, fetchComposition as fetchCompositionForTest, flattenBindingPathFromValue, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, getSeoMetadataPure, isTemplateBinding, mapSectionRepeaterPaths as mapSectionRepeaterPathsForTest, projectCrossBoundaryRepeaterBindings as projectCrossBoundaryRepeaterBindingsForTest, resolveSeoBindingValue };
3122
3482
  //# sourceMappingURL=sdk.js.map