@contentstack/studio-client 3.0.0-alpha-20260721T1325-1838437.0 → 3.1.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 (37) hide show
  1. package/dist/breakpoints/BreakpointManager.js +1 -0
  2. package/dist/breakpoints/BreakpointManager.js.map +1 -1
  3. package/dist/canvas/canvas.utils.js +18 -1
  4. package/dist/canvas/canvas.utils.js.map +1 -1
  5. package/dist/composable-studio/build-scoped-data.js +11 -1
  6. package/dist/composable-studio/build-scoped-data.js.map +1 -1
  7. package/dist/composable-studio/collect-data-needs.js +4 -2
  8. package/dist/composable-studio/collect-data-needs.js.map +1 -1
  9. package/dist/composable-studio/data/pre-process-static-values.js +13 -0
  10. package/dist/composable-studio/data/pre-process-static-values.js.map +1 -1
  11. package/dist/composable-studio/sdk.js +256 -97
  12. package/dist/composable-studio/sdk.js.map +1 -1
  13. package/dist/composable-studio/studio-intelligence.manager.js +1 -0
  14. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -1
  15. package/dist/config/config.schema.js +26 -0
  16. package/dist/config/config.schema.js.map +1 -1
  17. package/dist/config/process-user-config.js +6 -0
  18. package/dist/config/process-user-config.js.map +1 -1
  19. package/dist/config/stack-sdk-wrapper.js +1 -0
  20. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  21. package/dist/context-menu/context-menu.js +1 -0
  22. package/dist/context-menu/context-menu.js.map +1 -1
  23. package/dist/dnd/dnd-manager.js +1 -0
  24. package/dist/dnd/dnd-manager.js.map +1 -1
  25. package/dist/get-active-node-screenshot/get-node-screenshot-event.js +45 -4
  26. package/dist/get-active-node-screenshot/get-node-screenshot-event.js.map +1 -1
  27. package/dist/highlight-node/highlight-node-manager.js +2 -4
  28. package/dist/highlight-node/highlight-node-manager.js.map +1 -1
  29. package/dist/highlight-node/highlight-node.js +1 -0
  30. package/dist/highlight-node/highlight-node.js.map +1 -1
  31. package/dist/index.d.ts +40 -15
  32. package/dist/utils/conditionBlock.js +52 -2
  33. package/dist/utils/conditionBlock.js.map +1 -1
  34. package/dist/utils/constants.js +1 -1
  35. package/dist/utils/reference_fetcher.js +7 -1
  36. package/dist/utils/reference_fetcher.js.map +1 -1
  37. package/package.json +8 -8
@@ -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';
@@ -33,6 +34,12 @@ import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages
33
34
  // All are registered synchronously during React initialization via getBasicComponents()
34
35
  const INTERNAL_COMPONENT_TYPES = Object.values(INTERNAL_COMPONENTS_NAMES);
35
36
  const SECTION_COMPOSITION_NODE_TYPE = "section-composition";
37
+ /**
38
+ * CDA query responses return at most 100 entries per request, so batched
39
+ * static-entry fetches split their uid lists at this size — a longer list
40
+ * would silently truncate to the first response page.
41
+ */
42
+ const STATIC_ENTRY_BATCH_SIZE = 100;
36
43
  function findParentRepeaterUidInTree(ui, compositionUID) {
37
44
  function traverse(node, nearestRepeaterUID) {
38
45
  if (node.type === "section-composition" &&
@@ -54,7 +61,7 @@ function findParentRepeaterUidInTree(ui, compositionUID) {
54
61
  const result = traverse(ui, null);
55
62
  return result !== undefined ? result : null;
56
63
  }
57
- function setSectionCompositionContext(dataSources, sectionUid, selectedField, parentRepeaterUID = null) {
64
+ function setSectionCompositionContext(dataSources, sectionUid, selectedField, parentRepeaterUID = null, cardinality) {
58
65
  if (!dataSources["section_compositions"]) {
59
66
  dataSources["section_compositions"] = {};
60
67
  }
@@ -62,6 +69,13 @@ function setSectionCompositionContext(dataSources, sectionUid, selectedField, pa
62
69
  selectedField,
63
70
  uidRemapping: {},
64
71
  parentRepeaterUID,
72
+ // Carried so the live re-scope (rebuildScopedFromBindings in the editor
73
+ // hook) can collapse a single-element section's index-free terminal array
74
+ // to its first element. Without it, a spec refetch re-writes this slice
75
+ // index-free and the rebuilt scoped template becomes the WHOLE array —
76
+ // every template binding inside the section then resolves undefined
77
+ // (placeholder) until Studio's next indexed context push wins the merge.
78
+ cardinality,
65
79
  };
66
80
  }
67
81
  function findMatchingSectionSchema(section, templateEntry) {
@@ -76,7 +90,10 @@ function findMatchingSectionSchema(section, templateEntry) {
76
90
  function resolveSectionContext(section, templateEntry) {
77
91
  const matchingSchema = findMatchingSectionSchema(section, templateEntry);
78
92
  if (matchingSchema) {
79
- return { selectedField: matchingSchema.selected_field };
93
+ return {
94
+ selectedField: matchingSchema.selected_field,
95
+ cardinality: matchingSchema.cardinality,
96
+ };
80
97
  }
81
98
  if (!(section.linked_schemas || []).length) {
82
99
  return { selectedField: undefined };
@@ -100,7 +117,8 @@ function attachSectionCompositionContexts(data, compositionEntry, sectionEntries
100
117
  if (compositionEntry.place_composition_as === "section") {
101
118
  const ownContext = resolveSectionContext(compositionEntry, templateEntry);
102
119
  if (ownContext) {
103
- setSectionCompositionContext(data.dataSources, compositionEntry.uid, ownContext.selectedField, null);
120
+ setSectionCompositionContext(data.dataSources, compositionEntry.uid, ownContext.selectedField, null, // root section compositions are never inside a repeater
121
+ ownContext.cardinality);
104
122
  }
105
123
  }
106
124
  const rootUI = compositionEntry.ui ?? null;
@@ -109,7 +127,7 @@ function attachSectionCompositionContexts(data, compositionEntry, sectionEntries
109
127
  if (!sectionContext)
110
128
  return;
111
129
  const parentRepeaterUID = findParentRepeaterUidInTree(rootUI, sectionEntry.uid);
112
- setSectionCompositionContext(data.dataSources, sectionEntry.uid, sectionContext.selectedField, parentRepeaterUID);
130
+ setSectionCompositionContext(data.dataSources, sectionEntry.uid, sectionContext.selectedField, parentRepeaterUID, sectionContext.cardinality);
113
131
  });
114
132
  }
115
133
  /**
@@ -303,6 +321,54 @@ function mapSectionRepeaterPaths(node, runningPath, map) {
303
321
  mapSectionRepeaterPaths(c, childPath, map);
304
322
  }
305
323
  }
324
+ /**
325
+ * Map every `section-slot` uid in a section's authored UI to the cumulative
326
+ * page-relative schema segments of the Repeater / ConditionBlock chain that
327
+ * wraps it — mirrors the studio-app include analyzer's `indexSectionSlotsContext`.
328
+ * A modular-block ConditionBlock contributes its block-uid segment; a Repeater
329
+ * contributes its items-binding field path (the root template repeater's empty
330
+ * path adds nothing — the section's `selected_field` anchors it); a reference
331
+ * ConditionBlock adds no segment (its enclosing repeater's reference field is
332
+ * already the segment). Used so a SECTION dropped into a slot buried inside the
333
+ * outer section's OWN internal repeater/CB chain roots its references at the
334
+ * full slot path — not just the outer section's `selected_field`. Without this,
335
+ * the slotted section's field projections land on the shallow prefix and its
336
+ * referenced entries come back field-stripped (only[…card][]=_content_type_uid).
337
+ */
338
+ function mapSectionSlotSegments(node, runningPath, map) {
339
+ if (!node || typeof node !== "object")
340
+ return;
341
+ let childPath = runningPath;
342
+ if (node.type === "condition-block") {
343
+ const cond = node.metadata?.condition;
344
+ if (cond?.type === "modular_block" && typeof cond.value === "string") {
345
+ childPath = [...runningPath, cond.value];
346
+ }
347
+ }
348
+ if (node.type === "repeater") {
349
+ const binding = node.props?.items?.binding;
350
+ if (binding) {
351
+ childPath = [
352
+ ...runningPath,
353
+ ...sanitizeFieldPath(getBindingStringForCS(binding)),
354
+ ];
355
+ }
356
+ }
357
+ if (node.type === "section-slot" && typeof node.uid === "string") {
358
+ map.set(node.uid, childPath);
359
+ }
360
+ if (node.slots && typeof node.slots === "object") {
361
+ for (const slotNodes of Object.values(node.slots)) {
362
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
363
+ for (const c of arr)
364
+ mapSectionSlotSegments(c, childPath, map);
365
+ }
366
+ }
367
+ if (Array.isArray(node.children)) {
368
+ for (const c of node.children)
369
+ mapSectionSlotSegments(c, childPath, map);
370
+ }
371
+ }
306
372
  /**
307
373
  * Walk the PAGE UI and, for every node whose binding is a REPEATER binding
308
374
  * referencing a repeater already in `map` (a section-internal repeater, or a
@@ -429,6 +495,11 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
429
495
  let childPrefix = ancestorPrefix;
430
496
  let childRepeaterRefField = enclosingRepeaterRefField;
431
497
  let childRefCtUids = refCtUids;
498
+ // For a wrapper section, the per-section-slot internal Repeater/CB segments
499
+ // (from the wrapper's OWN authored UI) that a slotted section inherits as
500
+ // part of its page-rooted prefix. Populated only for section-composition
501
+ // nodes whose entry carries a `ui`; null (no extension) otherwise.
502
+ let slotSegments = null;
432
503
  // Remember a Repeater's template binding path; it becomes a reference hop
433
504
  // only once a reference condition-block downstream confirms the field is a
434
505
  // reference (committed below). A CONTENTSTACK/REPEATER-typed binding is not
@@ -484,6 +555,15 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
484
555
  // `modular_blocks` → `modular_blocks.ref_block` → `modular_blocks.ref_block`)
485
556
  // does not double-count segments into an invalid include[] path.
486
557
  childPrefix = extendAncestorPrefix(ancestorPrefix, selectedField);
558
+ // Compute this wrapper's slot-internal context so a section dropped into
559
+ // a slot buried inside the wrapper's OWN Repeater/CB chain roots at the
560
+ // full slot path (mirrors the editor's `indexSectionSlotsContext`).
561
+ const wrapperUi = sectionsByUid.get(compositionUid)?.ui;
562
+ if (wrapperUi) {
563
+ const wrapperUiNode = typeof wrapperUi === "string" ? decompressSpec(wrapperUi) : wrapperUi;
564
+ slotSegments = new Map();
565
+ mapSectionSlotSegments(wrapperUiNode, [], slotSegments);
566
+ }
487
567
  // Empty slots fall back to their authored default section (COMS-1659).
488
568
  // The default isn't a real child in the page UI, so synthesize the same
489
569
  // node the renderer makes and walk it here — otherwise the default's data
@@ -512,14 +592,19 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
512
592
  metadata: { compositionUID: defaultUid },
513
593
  slots: {},
514
594
  };
515
- walk(synth, nextRepeater, childPrefix, childRepeaterRefField, childRefCtUids, chain);
595
+ walk(synth, nextRepeater, slotSegments
596
+ ? [...childPrefix, ...(slotSegments.get(slotUid) || [])]
597
+ : childPrefix, childRepeaterRefField, childRefCtUids, chain);
516
598
  }
517
599
  }
518
600
  if (node.slots && typeof node.slots === "object") {
519
- for (const slotNodes of Object.values(node.slots)) {
601
+ for (const [slotUid, slotNodes] of Object.entries(node.slots)) {
520
602
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
603
+ const slotPrefix = slotSegments
604
+ ? [...childPrefix, ...(slotSegments.get(slotUid) || [])]
605
+ : childPrefix;
521
606
  for (const c of arr)
522
- walk(c, nextRepeater, childPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
607
+ walk(c, nextRepeater, slotPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
523
608
  }
524
609
  }
525
610
  if (Array.isArray(node.children)) {
@@ -1349,6 +1434,13 @@ function generateSdk(userConfig) {
1349
1434
  }
1350
1435
  if (config.stackSdk)
1351
1436
  setStackSdkInstance(config.stackSdk);
1437
+ // Bring-Your-Own-State: wire the user's getState/setState (+ declared
1438
+ // variables) into the page-global state store so useStudioState, author
1439
+ // bindings, and custom code all read/write the user's store. Omitted →
1440
+ // the store's internal Map fallback still serves ad-hoc/declared state.
1441
+ if (config.state) {
1442
+ getStateStoreInstance().configure(config.state);
1443
+ }
1352
1444
  /**
1353
1445
  * The variant alias every SDK-side data fetch should use, in priority order:
1354
1446
  * 1. The `cs-variant-alias` URL param when running inside Studio — Studio
@@ -1491,51 +1583,67 @@ function generateSdk(userConfig) {
1491
1583
  const { variantAlias, locale } = options;
1492
1584
  const isInsideEditor = isEditorFetch(searchParams);
1493
1585
  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] || [];
1586
+ // One collection query per content type (`containedIn` over the entry
1587
+ // uids) instead of one request per entry — bound-entry fetch cost stays
1588
+ // flat as a page binds more entries of the same type. Uid lists longer
1589
+ // than the CDA's per-query entry cap are split so no entry is silently
1590
+ // dropped past the first response page.
1591
+ const batches = Object.keys(staticBindingQueries).flatMap((_content_type_uid) => {
1592
+ const entryUids = Object.keys(staticBindingQueries[_content_type_uid]);
1593
+ const references = uniq(entryUids.flatMap((entry_uid) => staticBindingQueries[_content_type_uid][entry_uid]));
1594
+ let onlyQuery = [];
1595
+ // When inside Studio or Visual Builder, fetch all fields (don't use onlyQueries)
1596
+ if (!isInsideEditor) {
1597
+ const entryProjections = entryUids.map((entry_uid) => staticBindingOnlyQueries[_content_type_uid][entry_uid] || []);
1598
+ // An entry with no projection of its own (e.g. bound whole, path {})
1599
+ // is fetched with ALL fields; batching it with projected siblings
1600
+ // must not narrow it, so one unprojected entry makes the whole batch
1601
+ // unprojected. Otherwise the batch carries the union of every
1602
+ // entry's projection — over-fetching a field is fine, dropping one
1603
+ // is a regression.
1604
+ const everyEntryProjected = entryProjections.every((projection) => projection.length > 0);
1605
+ if (everyEntryProjected) {
1606
+ onlyQuery = uniqBy(entryProjections.flat(), ([reference, field]) => `${reference}|${field}`);
1504
1607
  // We need locale for redirect to the correct locale.
1505
1608
  if (config.cslp.appendTags) {
1506
1609
  onlyQuery.push(["BASE", "locale"]);
1507
1610
  }
1611
+ // Batch results map back per entry by uid, so an active projection
1612
+ // must keep it in the response.
1613
+ onlyQuery.push(["BASE", "uid"]);
1508
1614
  }
1509
- const query = config.stackSdk.entryQuery(_content_type_uid, entry_uid, {
1615
+ }
1616
+ return chunk(entryUids, STATIC_ENTRY_BATCH_SIZE).map((uids) => ({
1617
+ ct_uid: _content_type_uid,
1618
+ uids,
1619
+ promise: config.stackSdk
1620
+ .ctQuery(_content_type_uid, {
1510
1621
  only: onlyQuery,
1622
+ references,
1511
1623
  variantAlias,
1512
1624
  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);
1625
+ })
1626
+ .containedIn("uid", uids)
1627
+ .find(),
1628
+ }));
1629
+ });
1630
+ const ct_entries_res = await Promise.allSettled(batches.map((batch) => batch.promise));
1523
1631
  for (let i = 0; i < ct_entries_res.length; i++) {
1524
1632
  const ct_entries = ct_entries_res[i];
1525
- const ct_uid = ct_uids[i];
1633
+ const { ct_uid, uids } = batches[i];
1526
1634
  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
- }
1635
+ const entries = entriesFromResponse(ct_entries.value) ?? [];
1636
+ setStaticEntryInDS(data.dataSources, ct_uid, entries);
1637
+ if (config.cslp.appendTags) {
1638
+ for (const entry of entries) {
1639
+ addEditableTags(entry, ct_uid, true, entry?.locale || "en-us");
1533
1640
  }
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
- }
1641
+ }
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(", ")}`);
1539
1647
  }
1540
1648
  }
1541
1649
  }
@@ -2195,21 +2303,11 @@ function generateSdk(userConfig) {
2195
2303
  // Phase 2: Enhance options with Studio Intelligence (preserves user preferences)
2196
2304
  const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
2197
2305
  // Phase 3: Fetch with enhanced context (preserves custom fetchers)
2198
- const { compositionEntry, symbolEntries, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions);
2306
+ const { compositionEntry, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch(searchParams));
2199
2307
  const ui = typeof compositionEntry.ui === "string"
2200
2308
  ? decompressSpec(compositionEntry.ui)
2201
2309
  : compositionEntry.ui;
2202
2310
  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
2311
  const data = await fetchData(compositionEntry, queryOptions, enhancedOptions, Array.from(sectionEntries.values()), searchParams);
2214
2312
  // Lazy loading and SSR validation for production mode
2215
2313
  // Skip if called from fetchMultipleSpecs (which handles loading in batch)
@@ -2284,7 +2382,6 @@ function generateSdk(userConfig) {
2284
2382
  data,
2285
2383
  ui,
2286
2384
  compositionEntry,
2287
- symbols: allSymbolEntries,
2288
2385
  sectionCompositions: Array.from(sectionEntries.values()),
2289
2386
  // Studio-only resolution diagnostics (URL metadata path); undefined otherwise.
2290
2387
  urlResolution,
@@ -2299,8 +2396,8 @@ function generateSdk(userConfig) {
2299
2396
  /**
2300
2397
  * Spec-only composition fetch. Resolves the composition STRUCTURE — `ui`,
2301
2398
  * `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
2399
+ * `ui.metadata.seo` — but SKIPS the data fetch (`fetchData`/CDA) entirely.
2400
+ * `data` comes back empty; the caller supplies it at render
2304
2401
  * time (see `StudioComposition` in `@contentstack/studio-react`).
2305
2402
  *
2306
2403
  * Runs in both SSR and CSR (plain async, not a hook).
@@ -2311,7 +2408,7 @@ function generateSdk(userConfig) {
2311
2408
  }
2312
2409
  const studioIntelligence = await StudioIntelligenceManager.getStudioIntelligence(options, config);
2313
2410
  const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
2314
- const { compositionEntry, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions);
2411
+ const { compositionEntry, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch());
2315
2412
  const ui = typeof compositionEntry.ui === "string"
2316
2413
  ? decompressSpec(compositionEntry.ui)
2317
2414
  : compositionEntry.ui;
@@ -2330,8 +2427,6 @@ function generateSdk(userConfig) {
2330
2427
  data: { dataSources: {}, static_value: {} },
2331
2428
  ui,
2332
2429
  compositionEntry,
2333
- // Symbols are deprecated for this path.
2334
- symbols: [],
2335
2430
  sectionCompositions: Array.from(sectionEntries.values()),
2336
2431
  urlResolution,
2337
2432
  config: {
@@ -2803,30 +2898,6 @@ function generateSdk(userConfig) {
2803
2898
  }
2804
2899
  return sdkSingleton;
2805
2900
  }
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
2901
  /** CDA entries page size for the lightweight candidate fetch. */
2831
2902
  const CANDIDATE_PAGE_SIZE = 100;
2832
2903
  /** Safety cap on candidate pages (server-side resolution will own this later). */
@@ -2838,10 +2909,22 @@ const MAX_CANDIDATE_PAGES = 20;
2838
2909
  * placement filter. Paginates with skip/limit; `truncated` is true if the safety
2839
2910
  * cap is hit.
2840
2911
  */
2912
+ /**
2913
+ * Total-count of a `find()` response when `include_count` was requested —
2914
+ * `{ entries, count }` on the TS delivery SDK, `[entries, count]` on the JS
2915
+ * SDK. Undefined when the response carries no count.
2916
+ */
2917
+ function countFromResponse(response) {
2918
+ if (Array.isArray(response)) {
2919
+ const last = response[response.length - 1];
2920
+ return typeof last === "number" ? last : undefined;
2921
+ }
2922
+ const count = response?.count;
2923
+ return typeof count === "number" ? count : undefined;
2924
+ }
2841
2925
  async function fetchAllPageCompositions(config, locale) {
2842
- const all = [];
2843
- for (let page = 0; page < MAX_CANDIDATE_PAGES; page++) {
2844
- const res = await config.stackSdk
2926
+ const fetchPage = (page, includeCount) => {
2927
+ let query = config.stackSdk
2845
2928
  .ctQuery(config.contentTypeUid, {
2846
2929
  locale: locale || config.locale,
2847
2930
  query: { ...getPageLinkedPlacementFilter() },
@@ -2853,15 +2936,40 @@ async function fetchAllPageCompositions(config, locale) {
2853
2936
  ],
2854
2937
  })
2855
2938
  .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 };
2939
+ .skip(page * CANDIDATE_PAGE_SIZE);
2940
+ if (includeCount) {
2941
+ query = query.includeCount();
2862
2942
  }
2943
+ return query.find();
2944
+ };
2945
+ // Page 0 carries include_count so the remaining pages can be fetched in one
2946
+ // parallel wave instead of one serial round-trip per page.
2947
+ const firstRes = await fetchPage(0, true);
2948
+ const first = entriesFromResponse(firstRes);
2949
+ if (first.length < CANDIDATE_PAGE_SIZE) {
2950
+ return { entries: first, truncated: false };
2951
+ }
2952
+ const total = countFromResponse(firstRes);
2953
+ if (total === undefined) {
2954
+ // No usable count — fall back to the serial walk.
2955
+ const all = [...first];
2956
+ for (let page = 1; page < MAX_CANDIDATE_PAGES; page++) {
2957
+ const batch = entriesFromResponse(await fetchPage(page, false));
2958
+ all.push(...batch);
2959
+ if (batch.length < CANDIDATE_PAGE_SIZE) {
2960
+ return { entries: all, truncated: false };
2961
+ }
2962
+ }
2963
+ return { entries: all, truncated: true };
2863
2964
  }
2864
- return { entries: all, truncated: true };
2965
+ const totalPages = Math.ceil(total / CANDIDATE_PAGE_SIZE);
2966
+ const pageCount = Math.min(totalPages, MAX_CANDIDATE_PAGES);
2967
+ const rest = await Promise.all(range(1, pageCount).map((page) => fetchPage(page, false)));
2968
+ const all = [
2969
+ first,
2970
+ ...rest.map((res) => entriesFromResponse(res)),
2971
+ ].flat();
2972
+ return { entries: all, truncated: totalPages > MAX_CANDIDATE_PAGES };
2865
2973
  }
2866
2974
  /**
2867
2975
  * Decide which composition wins among the ranking's top-tier candidates.
@@ -2924,7 +3032,14 @@ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, lo
2924
3032
  * This function fetches UI Composition from defined options.
2925
3033
  * Supports custom fetcher overrides (per-query > global > SDK default).
2926
3034
  **/
2927
- async function fetchComposition(config, queryOptions, compositionQueryOptions) {
3035
+ async function fetchComposition(config, queryOptions, compositionQueryOptions,
3036
+ /**
3037
+ * Whether this fetch renders inside an editor (Studio or Visual Builder) —
3038
+ * callers compute it via `isEditorFetch`. Editor fetches keep the full
3039
+ * candidate scan for URL resolution so Studio's diagnostics list every
3040
+ * considered candidate; the exact-match fast path is production-only.
3041
+ */
3042
+ isInsideEditor = false) {
2928
3043
  const { fetchComposition: perQueryFetchComposition, fetchTemplateEntry: _, ...resolvedOptions } = compositionQueryOptions || {};
2929
3044
  const locale = resolvedOptions.locale;
2930
3045
  // Captured by the URL metadata (Phase A) path for Studio resolution
@@ -3019,6 +3134,52 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
3019
3134
  // descent to lower tiers, no legacy fallback.
3020
3135
  const requestUrl = queryOptions.url;
3021
3136
  try {
3137
+ // 0. Exact-match fast path (production only). A literal `url` equal to
3138
+ // the request is always the most specific possible match (a pattern
3139
+ // match spends at least one character on a variable), so one equality
3140
+ // query both resolves and full-fetches the page — no candidate scan,
3141
+ // no separate winner fetch. A miss, an error, or an ownerless hit set
3142
+ // falls through to the unified scan below, whose outcome is
3143
+ // authoritative. Editor fetches skip this so Studio's resolution
3144
+ // diagnostics keep the full candidate pool.
3145
+ if (requestUrl && !isInsideEditor) {
3146
+ try {
3147
+ const exactRes = await config.stackSdk
3148
+ .ctQuery(config.contentTypeUid, {
3149
+ includeAll: true,
3150
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
3151
+ locale: locale || config.locale,
3152
+ query: { url: requestUrl, ...getPageLinkedPlacementFilter() },
3153
+ })
3154
+ .find();
3155
+ const exactHits = entriesFromResponse(exactRes) ?? [];
3156
+ if (exactHits.length) {
3157
+ // Duplicate literal urls can tie — rank + ownership-probe within
3158
+ // the hit set, exactly like the unified path's top tier.
3159
+ const ranking = rankUrlMatches(requestUrl, exactHits);
3160
+ if (ranking.composableUids.length) {
3161
+ const hitsByUid = new Map(exactHits.map((hit) => [
3162
+ hit.composable_uid,
3163
+ hit,
3164
+ ]));
3165
+ const { winnerUid } = await resolveUrlWinner(config, requestUrl, ranking, hitsByUid, locale);
3166
+ const winner = winnerUid
3167
+ ? exactHits.find((hit) => hit.composable_uid === winnerUid)
3168
+ : undefined;
3169
+ if (winner) {
3170
+ return winner;
3171
+ }
3172
+ }
3173
+ }
3174
+ }
3175
+ catch (fastPathError) {
3176
+ // The fast path must never make resolution less reliable than the
3177
+ // scan it short-cuts — swallow and fall through.
3178
+ if (process.env.NODE_ENV === "development") {
3179
+ console.warn("[Composable Studio SDK] Exact-match URL lookup failed; falling back to the candidate scan:", fastPathError);
3180
+ }
3181
+ }
3182
+ }
3022
3183
  // 1. Fetch every page-linked candidate (lightweight, paginated).
3023
3184
  const { entries: candidates, truncated } = await fetchAllPageCompositions(config, locale);
3024
3185
  if (truncated) {
@@ -3104,7 +3265,6 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
3104
3265
  }
3105
3266
  return {
3106
3267
  compositionEntry: entry,
3107
- symbolEntries: getAllSymbols(entry),
3108
3268
  // Populated if the custom fetcher delegated to `defaultFetch` and it
3109
3269
  // resolved via the URL metadata path; otherwise undefined.
3110
3270
  urlResolution,
@@ -3113,10 +3273,9 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
3113
3273
  const entry = await defaultImpl();
3114
3274
  return {
3115
3275
  compositionEntry: entry,
3116
- symbolEntries: getAllSymbols(entry),
3117
3276
  urlResolution,
3118
3277
  };
3119
3278
  }
3120
3279
 
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 };
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 };
3122
3281
  //# sourceMappingURL=sdk.js.map