@contentstack/studio-client 1.4.0 → 1.5.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 (32) hide show
  1. package/dist/composable-studio/initializer-sdk.js +1 -9
  2. package/dist/composable-studio/initializer-sdk.js.map +1 -1
  3. package/dist/composable-studio/sdk.js +313 -160
  4. package/dist/composable-studio/sdk.js.map +1 -1
  5. package/dist/config/config.schema.js +10 -0
  6. package/dist/config/config.schema.js.map +1 -1
  7. package/dist/config/process-user-config.js +6 -0
  8. package/dist/config/process-user-config.js.map +1 -1
  9. package/dist/highlight-node/highlight-node.js +30 -13
  10. package/dist/highlight-node/highlight-node.js.map +1 -1
  11. package/dist/index.d.ts +189 -12
  12. package/dist/index.js +5 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/node_modules/fflate/esm/browser.js +384 -0
  15. package/dist/node_modules/fflate/esm/browser.js.map +1 -0
  16. package/dist/packages/studio-internal/dist/utils/spec-compression.js +43 -0
  17. package/dist/packages/studio-internal/dist/utils/spec-compression.js.map +1 -0
  18. package/dist/query/expression-resolver.js +124 -0
  19. package/dist/query/expression-resolver.js.map +1 -0
  20. package/dist/query/query-executor.js +327 -0
  21. package/dist/query/query-executor.js.map +1 -0
  22. package/dist/url-change/url-change.js +65 -0
  23. package/dist/url-change/url-change.js.map +1 -0
  24. package/dist/utils/conditionBlock.js +16 -4
  25. package/dist/utils/conditionBlock.js.map +1 -1
  26. package/dist/utils/is-inside-iframe.js +16 -0
  27. package/dist/utils/is-inside-iframe.js.map +1 -0
  28. package/dist/utils/reference_fetcher.js +104 -8
  29. package/dist/utils/reference_fetcher.js.map +1 -1
  30. package/dist/utils/sdk.js +3 -0
  31. package/dist/utils/sdk.js.map +1 -1
  32. package/package.json +8 -8
@@ -1,8 +1,5 @@
1
1
  import { pick } from 'lodash-es';
2
2
  import { generateSdk } from './sdk.js';
3
- import { composableStudioEventManager, POST_MESSAGE_EVENTS } from '@contentstack/studio-messenger';
4
- import '@contentstack/studio-registry';
5
- import { isInsideVisualBuilderFrame } from '../utils/is-inside-visual-builder-frame.js';
6
3
 
7
4
  const studioSdk = {
8
5
  init(userConfig) {
@@ -21,11 +18,6 @@ const studioSdk = {
21
18
  };
22
19
  },
23
20
  };
24
- const sendInitMessage = (message) => {
25
- if (!isInsideVisualBuilderFrame())
26
- return;
27
- composableStudioEventManager?.send(POST_MESSAGE_EVENTS.INIT_STUDIO, message);
28
- };
29
21
 
30
- export { sendInitMessage, studioSdk };
22
+ export { studioSdk };
31
23
  //# sourceMappingURL=initializer-sdk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"initializer-sdk.js","sources":["../../src/composable-studio/initializer-sdk.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;;;AAUO,MAAM,SAAS,GAAG;AACvB,IAAA,IAAI,CAAC,UAAsB,EAAA;AACzB,QAAA,OAAO,WAAW,CAAC,UAAU,CAAC;IAChC,CAAC;AACD,IAAA,SAAS,CAAC,UAAuB,EAAA;AAC/B,QAAA,MAAM,cAAc,GAAG,IAAI,CAAC,UAAU,EAAE;YACtC,oBAAoB;YACpB,gBAAgB;YAChB,MAAM;AACP,SAAA,CAAC;QACF,OAAO;AACL,YAAA,QAAQ,EAAE;AACR,gBAAA,SAAS,EAAE,MAAM,cAAc;AAChC,aAAA;SACF;IACH,CAAC;;AAGI,MAAM,eAAe,GAAG,CAAC,OAAoB,KAAI;IACtD,IAAI,CAAC,0BAA0B,EAAE;QAAE;IACnC,4BAA4B,EAAE,IAAI,CAAC,mBAAmB,CAAC,WAAW,EAAE,OAAO,CAAC;AAC9E;;;;"}
1
+ {"version":3,"file":"initializer-sdk.js","sources":["../../src/composable-studio/initializer-sdk.ts"],"sourcesContent":[null],"names":[],"mappings":";;;AAIO,MAAM,SAAS,GAAG;AACvB,IAAA,IAAI,CAAC,UAAsB,EAAA;AACzB,QAAA,OAAO,WAAW,CAAC,UAAU,CAAC;IAChC,CAAC;AACD,IAAA,SAAS,CAAC,UAAuB,EAAA;AAC/B,QAAA,MAAM,cAAc,GAAG,IAAI,CAAC,UAAU,EAAE;YACtC,oBAAoB;YACpB,gBAAgB;YAChB,MAAM;AACP,SAAA,CAAC;QACF,OAAO;AACL,YAAA,QAAQ,EAAE;AACR,gBAAA,SAAS,EAAE,MAAM,cAAc;AAChC,aAAA;SACF;IACH,CAAC;;;;;"}
@@ -5,7 +5,7 @@ import { processUserConfig } from '../config/process-user-config.js';
5
5
  import { getCompositionFromSlug } from '../get-composition-from-slug/get-composition-from-slug.js';
6
6
  import { INCLUDE_DEPTH_COUNT } from '../utils/constants.js';
7
7
  import { isCompositionBeingEdited } from '../utils/is-composition-being-edited.js';
8
- import { entriesFromResponse, setTemplateEntryInDS, setStaticEntryInDS } from '../utils/sdk.js';
8
+ import { setTemplateEntryInDS, entriesFromResponse, setStaticEntryInDS } from '../utils/sdk.js';
9
9
  import { ComposableStudioError, ComposableStudioErrors } from '../utils/composable-studio-error.js';
10
10
  import { clientRendererModeUtil, RendererModeUtil } from '../utils/canvas.js';
11
11
  import { getEntriesQueries } from '../utils/reference_fetcher.js';
@@ -14,6 +14,7 @@ import { convertCompositionQueryInputToCompositionQuery } from '../utils/convert
14
14
  import { getUrlPatterns } from '../utils/get-url-patterns.js';
15
15
  import { getStatusCode, isContentstackAuthError, hasAuthErrorShape, isAuthError, isNetworkError, HttpStatus, ContentstackErrorCode, isServerError } from '../utils/http-error.constants.js';
16
16
  import { getErrorMessage, getTroubleshootingInfo } from '../utils/error-messages.js';
17
+ import { decompressSpec } from '../packages/studio-internal/dist/utils/spec-compression.js';
17
18
  import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages.default.js';
18
19
 
19
20
  function getAuthErrorMessage(err) {
@@ -359,81 +360,107 @@ function generateSdk(userConfig) {
359
360
  }
360
361
  /**
361
362
  * When composition is binded to a content type, we need to fetch the entry for that content type. Called template entry.
363
+ * Supports custom fetcher overrides (per-query > global > SDK default).
362
364
  */
363
- async function fetchTemplateEntry(options, data) {
365
+ async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions) {
364
366
  if (!config.stackSdk) {
365
367
  console.error("Fetching template entry not possible without stackSdk");
366
368
  return;
367
369
  }
368
- const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = options;
370
+ const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = fetchOptions;
369
371
  if (!connected_content_type) {
370
372
  return;
371
373
  }
374
+ const { fetchComposition: _, fetchTemplateEntry: perQueryFetchTemplateEntry, ...resolvedOptions } = compositionQueryOptions || {};
372
375
  const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
373
- // When inside Visual Builder, fetch all fields (don't use onlyQueries)
374
- const queryOptions = {
375
- references: includeQueries,
376
- variantAlias: options.variantAlias,
377
- locale: options.locale || config.locale, // Use override locale or default
378
- };
379
- if (!isInsideVB) {
380
- queryOptions.only = onlyQueries;
381
- }
382
- let dataQuery = config.stackSdk
383
- .ctQuery(connected_content_type, queryOptions)
384
- .limit(1);
385
- if ("url" in compositionQuery) {
386
- dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
387
- }
388
- // We used the `find` instead of `findOne` because it
389
- // caused issues with the fetch data.
390
- const response = await dataQuery.find().catch((err) => {
391
- const { errorType, message } = classifyApiError(err);
392
- console.error("SDK Error (connected data):", {
393
- errorType,
394
- message,
395
- originalError: err,
396
- });
397
- // For connected data, use specific error or fall back to FETCHING_CONNECTED_DATA_FAILED
398
- const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
399
- ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
400
- : errorType;
401
- throw new ComposableStudioError(finalErrorType, finalErrorType === ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
402
- ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
403
- : message, {
404
- options,
405
- response: err,
406
- statusCode: err?.status || err?.statusCode,
407
- errorCode: err?.error_code,
408
- });
409
- });
410
- const entries = entriesFromResponse(response);
411
- if (!entries?.[0]) {
412
- console.error("Preview/Template entry not found", {
413
- contentType: connected_content_type,
414
- compositionQuery,
376
+ const defaultImpl = async () => {
377
+ const queryOptions = {
378
+ references: includeQueries,
379
+ variantAlias: resolvedOptions.variantAlias,
380
+ locale: resolvedOptions.locale || config.locale,
381
+ };
382
+ if (!isInsideVB) {
383
+ queryOptions.only = onlyQueries;
384
+ }
385
+ let dataQuery = config.stackSdk
386
+ .ctQuery(connected_content_type, queryOptions)
387
+ .limit(1);
388
+ // Resolution priority: templateEntryUid > url > first entry
389
+ if (resolvedOptions.templateEntryUid) {
390
+ dataQuery = config.stackSdk.where(dataQuery, "uid", resolvedOptions.templateEntryUid);
391
+ }
392
+ else if ("url" in compositionQuery) {
393
+ dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
394
+ }
395
+ const response = await dataQuery.find().catch((err) => {
396
+ const { errorType, message } = classifyApiError(err);
397
+ console.error("SDK Error (connected data):", {
398
+ errorType,
399
+ message,
400
+ originalError: err,
401
+ });
402
+ const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
403
+ ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
404
+ : errorType;
405
+ throw new ComposableStudioError(finalErrorType, finalErrorType ===
406
+ ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
407
+ ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
408
+ : message, {
409
+ options: fetchOptions,
410
+ response: err,
411
+ statusCode: err?.status || err?.statusCode,
412
+ errorCode: err?.error_code,
413
+ });
415
414
  });
416
- throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
417
- contentType: connected_content_type,
418
- }), {
419
- contentType: connected_content_type,
420
- hasStackSdk: !!config.stackSdk,
415
+ const entries = entriesFromResponse(response);
416
+ if (!entries?.[0]) {
417
+ console.error("Preview/Template entry not found", {
418
+ contentType: connected_content_type,
419
+ compositionQuery,
420
+ });
421
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
422
+ contentType: connected_content_type,
423
+ }), {
424
+ contentType: connected_content_type,
425
+ hasStackSdk: !!config.stackSdk,
426
+ compositionQuery,
427
+ options: fetchOptions,
428
+ troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
429
+ });
430
+ }
431
+ return entries[0];
432
+ };
433
+ const customFetcher = perQueryFetchTemplateEntry ?? config.fetchTemplateEntry;
434
+ let entry;
435
+ if (customFetcher) {
436
+ entry = await customFetcher({
437
+ compositionEntry,
421
438
  compositionQuery,
422
- options,
423
- troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
439
+ connectedContentType: connected_content_type,
440
+ options: resolvedOptions,
441
+ includeReferences: includeQueries,
442
+ only: isInsideVB ? [] : onlyQueries,
443
+ stackSdk: config.stackSdk.sdk,
444
+ defaultFetch: defaultImpl,
424
445
  });
446
+ if (!entry) {
447
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
448
+ contentType: connected_content_type,
449
+ }));
450
+ }
451
+ }
452
+ else {
453
+ entry = await defaultImpl();
425
454
  }
426
- const entry = entries[0];
427
455
  if (config.cslp.appendTags) {
428
456
  addEditableTags(entry, connected_content_type, true, entry.locale);
429
457
  }
430
458
  setTemplateEntryInDS(data.dataSources, entry);
431
- if (!isCompositionBeingEdited(options?.composableUid || ""))
459
+ if (!isCompositionBeingEdited(fetchOptions?.composableUid || ""))
432
460
  return;
433
461
  }
434
462
  async function fetchData(compositionEntry, queryOptions, options) {
435
463
  const { variantAlias, locale } = options || {};
436
- // This will iterate over ui and collect all data to fetch ( entries and depth of refrerences for both template and static contentstack)
437
464
  const { templateReferencesPath, templateOnlyKeys, contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, } = getEntriesQueries(compositionEntry, compositionEntry.connected_content_type || "", options);
438
465
  const data = {
439
466
  [DATA_SOURCES_PREFIX]: {},
@@ -446,13 +473,15 @@ function generateSdk(userConfig) {
446
473
  includeQueries: templateReferencesPath,
447
474
  onlyQueries: templateOnlyKeys,
448
475
  composableUid: compositionEntry.composable_uid,
449
- variantAlias: variantAlias,
450
- locale: locale,
451
- }, data),
476
+ }, data, compositionEntry, options),
452
477
  resolveStaticData(contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, data, {
453
478
  variantAlias: variantAlias,
454
479
  locale: locale,
455
480
  }),
481
+ resolveQueryData(compositionEntry, data, {
482
+ variantAlias,
483
+ locale: locale || config.locale,
484
+ }),
456
485
  ]);
457
486
  return data;
458
487
  }
@@ -460,21 +489,110 @@ function generateSdk(userConfig) {
460
489
  if (!config.stackSdk) {
461
490
  throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
462
491
  }
463
- const { compositionEntry, symbolEntries } = await fetchComposition(config, queryOptions);
492
+ const { compositionEntry, symbolEntries } = await fetchComposition(config, queryOptions, options);
464
493
  const data = await fetchData(compositionEntry, queryOptions, options);
465
- const page = typeof compositionEntry.ui === "string"
466
- ? JSON.parse(compositionEntry.ui)
494
+ const ui = typeof compositionEntry.ui === "string"
495
+ ? decompressSpec(compositionEntry.ui)
467
496
  : compositionEntry.ui;
468
- const ui = page;
469
497
  return {
470
498
  data,
471
499
  ui,
472
500
  compositionEntry,
473
- //TODO: Need to fetch symbols from the server
474
501
  symbols: symbolEntries,
475
502
  config: getLightConfig(),
476
503
  };
477
504
  }
505
+ /**
506
+ * Reusable helper to fetch data from Contentstack
507
+ * Now uses QueryExecutor internally to support full QuerySpec with filters, sorting, etc.
508
+ *
509
+ * @param querySpec - Full QuerySpec with filters, sorting, pagination, etc.
510
+ * @param context - RuntimeContext for expression resolution (URL params, etc.)
511
+ * @returns Promise with data array and count
512
+ */
513
+ async function fetchContentstackData(querySpec, context = {}, options) {
514
+ if (!config.stackSdk) {
515
+ console.warn("Stack SDK not available for fetchContentstackData");
516
+ return { entries: [], count: 0 };
517
+ }
518
+ try {
519
+ // Use QueryExecutor to execute the full QuerySpec
520
+ // This supports filters, sorting, pagination, includes, only, and expression resolution
521
+ const { QueryExecutor } = await import('../query/query-executor.js');
522
+ const executor = new QueryExecutor(config.stackSdk.sdk);
523
+ // Execute query using QueryExecutor
524
+ // ExpressionResolver inside QueryExecutor will resolve expressions at execution time
525
+ const result = await executor.execute(querySpec, 1, context, options);
526
+ const entries = result.entries || [];
527
+ const count = result.count || 0;
528
+ // Add editable tags (CSLP)
529
+ if (config.cslp.appendTags && Array.isArray(entries)) {
530
+ entries.forEach((entry) => {
531
+ addEditableTags(entry, querySpec.contentType, true, entry.locale || "en-us");
532
+ });
533
+ }
534
+ return {
535
+ entries: entries,
536
+ count: count,
537
+ };
538
+ }
539
+ catch (err) {
540
+ console.error(`[SDK] Failed to fetch data for ${querySpec.contentType}`, err);
541
+ return { entries: [], count: 0 };
542
+ }
543
+ }
544
+ async function resolveQueryData(compositionEntry, data, options) {
545
+ if (!compositionEntry.data_sources) {
546
+ return;
547
+ }
548
+ let dataSources = [];
549
+ try {
550
+ const parsed = JSON.parse(compositionEntry.data_sources);
551
+ dataSources = Array.isArray(parsed) ? parsed : Object.values(parsed);
552
+ }
553
+ catch (e) {
554
+ console.warn("[SDK] Failed to parse data_sources from composition", e);
555
+ return;
556
+ }
557
+ const queriesDS = dataSources.find((ds) => ds.uid === "contentstack_queries" || ds.id === "contentstack_queries");
558
+ if (!queriesDS || !queriesDS.data) {
559
+ return;
560
+ }
561
+ const queries = queriesDS.data || queriesDS.queries || [];
562
+ if (!Array.isArray(queries))
563
+ return;
564
+ const queryResults = {};
565
+ // Build RuntimeContext for expression resolution
566
+ // In SDK, use window.location.href for URL params
567
+ const urlParams = {};
568
+ if (typeof window !== "undefined" && window.location) {
569
+ const searchParams = new URLSearchParams(window.location.search);
570
+ searchParams.forEach((value, key) => {
571
+ urlParams[key] = value;
572
+ });
573
+ }
574
+ const context = {
575
+ url: {
576
+ params: urlParams,
577
+ path: {}, // Can be extended if path params are needed
578
+ hash: typeof window !== "undefined" ? window.location.hash : undefined,
579
+ },
580
+ // NO componentProps or user context - expressions only support URL params and time
581
+ };
582
+ await Promise.all(queries.map(async (queryConfig) => {
583
+ const { uid, spec } = queryConfig;
584
+ if (!uid || !spec?.contentType)
585
+ return;
586
+ // Use fetchContentstackData with full QuerySpec
587
+ // This now uses QueryExecutor internally to support filters, sorting, etc.
588
+ const result = await fetchContentstackData(spec, context, options);
589
+ queryResults[uid] = result;
590
+ }));
591
+ if (!data.dataSources[DATA_SOURCES.QUERY]) {
592
+ data.dataSources[DATA_SOURCES.QUERY] = {};
593
+ }
594
+ Object.assign(data.dataSources[DATA_SOURCES.QUERY], queryResults);
595
+ }
478
596
  function getLightConfig() {
479
597
  return pick(config, ["openInStudioButton", "contentTypeUid", "cslp"]);
480
598
  }
@@ -575,7 +693,7 @@ function generateSdk(userConfig) {
575
693
  }
576
694
  const parseUI = (ui) => {
577
695
  try {
578
- return JSON.parse(ui);
696
+ return decompressSpec(ui);
579
697
  }
580
698
  catch (error) {
581
699
  console.error("UI parsing error", error);
@@ -598,113 +716,148 @@ function getAllSymbols(compositionEntry) {
598
716
  }
599
717
  /**
600
718
  * This function fetches UI Composition from defined options.
719
+ * Supports custom fetcher overrides (per-query > global > SDK default).
601
720
  **/
602
- async function fetchComposition(config, options, locale) {
603
- let uiQuery;
604
- if ("composableUid" in options) {
605
- uiQuery = config.stackSdk.where(config.stackSdk.ctQuery(config.contentTypeUid, {
606
- locale: config.locale,
607
- }), "composable_uid", options.composableUid);
608
- const response = await uiQuery
609
- .find()
610
- .then((res) => {
611
- let response;
612
- if (Array.isArray(res)) {
613
- response = res[0][0];
614
- }
615
- else {
616
- response = res.entries[0];
617
- }
618
- if (!response) {
619
- throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
620
- compositionUid: options.composableUid,
721
+ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
722
+ const { fetchComposition: perQueryFetchComposition, fetchTemplateEntry: _, ...resolvedOptions } = compositionQueryOptions || {};
723
+ const locale = resolvedOptions.locale;
724
+ const defaultImpl = async () => {
725
+ if ("composableUid" in queryOptions) {
726
+ const uiQuery = config.stackSdk.where(config.stackSdk.ctQuery(config.contentTypeUid, {
727
+ locale: locale || config.locale,
728
+ }), "composable_uid", queryOptions.composableUid);
729
+ return await uiQuery
730
+ .find()
731
+ .then((res) => {
732
+ let response;
733
+ if (Array.isArray(res)) {
734
+ response = res[0][0];
735
+ }
736
+ else {
737
+ response = res.entries[0];
738
+ }
739
+ if (!response) {
740
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
741
+ compositionUid: queryOptions.composableUid,
742
+ hasStackSdk: !!config.stackSdk,
743
+ options: queryOptions,
744
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
745
+ });
746
+ }
747
+ return response;
748
+ })
749
+ .catch((err) => {
750
+ if (err instanceof ComposableStudioError)
751
+ throw err;
752
+ const { errorType, message } = classifyApiError(err);
753
+ console.error("SDK Error:", {
754
+ errorType,
755
+ message,
756
+ originalError: err,
757
+ });
758
+ throw new ComposableStudioError(errorType, message, {
759
+ compositionUid: queryOptions.composableUid,
621
760
  hasStackSdk: !!config.stackSdk,
622
- options,
623
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
761
+ statusCode: err?.status || err?.statusCode || "none",
762
+ errorCode: err?.error_code || "none",
763
+ errorMessage: err?.error_message || err?.message || "none",
764
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
624
765
  });
625
- }
626
- return response;
627
- })
628
- .catch((err) => {
629
- const { errorType, message } = classifyApiError(err);
630
- console.error("SDK Error:", { errorType, message, originalError: err });
631
- throw new ComposableStudioError(errorType, message, {
632
- compositionUid: options.composableUid,
633
- hasStackSdk: !!config.stackSdk,
634
- statusCode: err?.status || err?.statusCode || "none",
635
- errorCode: err?.error_code || "none",
636
- errorMessage: err?.error_message || err?.message || "none",
637
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
638
766
  });
639
- });
640
- return {
641
- compositionEntry: response,
642
- symbolEntries: getAllSymbols(response),
643
- };
644
- }
645
- else if ("url" in options) {
646
- const possibleEntryUrlPatterns = getUrlPatterns(options.url);
647
- return await config.stackSdk
648
- .ctQuery(config.contentTypeUid, {
649
- includeAll: true,
650
- includeAllDepth: INCLUDE_DEPTH_COUNT,
651
- locale: config.locale,
652
- query: {
653
- url: {
654
- $in: possibleEntryUrlPatterns,
767
+ }
768
+ else if ("url" in queryOptions) {
769
+ const possibleEntryUrlPatterns = getUrlPatterns(queryOptions.url);
770
+ return await config.stackSdk
771
+ .ctQuery(config.contentTypeUid, {
772
+ includeAll: true,
773
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
774
+ locale: locale || config.locale,
775
+ query: {
776
+ url: {
777
+ $in: possibleEntryUrlPatterns,
778
+ },
779
+ $or: [
780
+ { place_composition_as: "page" },
781
+ { place_composition_as: "" },
782
+ { place_composition_as: null },
783
+ { place_composition_as: undefined },
784
+ { place_composition_as: { $exists: false } },
785
+ { connected_content_type: { $exists: true } },
786
+ ],
655
787
  },
656
- $or: [
657
- { place_composition_as: "page" },
658
- { place_composition_as: "" },
659
- { place_composition_as: { $exists: false } },
660
- { connected_content_type: true },
661
- ],
662
- },
663
- })
664
- .find()
665
- .then((res) => {
666
- const entries = entriesFromResponse(res);
667
- const entry = getCompositionFromSlug(options.url, entries);
668
- if (!entry) {
669
- throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
670
- url: options.url,
671
- }), {
672
- url: options.url,
788
+ })
789
+ .find()
790
+ .then((res) => {
791
+ const entries = entriesFromResponse(res);
792
+ const entry = getCompositionFromSlug(queryOptions.url, entries);
793
+ if (!entry) {
794
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
795
+ url: queryOptions.url,
796
+ }), {
797
+ url: queryOptions.url,
798
+ hasStackSdk: !!config.stackSdk,
799
+ searchedPatterns: possibleEntryUrlPatterns,
800
+ entriesFound: entries.length,
801
+ options: queryOptions,
802
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
803
+ });
804
+ }
805
+ return entry;
806
+ })
807
+ .catch((err) => {
808
+ if (err instanceof ComposableStudioError)
809
+ throw err;
810
+ const { errorType, message } = classifyApiError(err);
811
+ console.error("SDK Error (URL-based fetch):", {
812
+ errorType,
813
+ message,
814
+ originalError: err,
815
+ });
816
+ throw new ComposableStudioError(errorType, message, {
817
+ url: queryOptions.url,
673
818
  hasStackSdk: !!config.stackSdk,
674
- searchedPatterns: possibleEntryUrlPatterns,
675
- entriesFound: entries.length,
676
- options,
677
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
819
+ statusCode: err?.status || err?.statusCode || "none",
820
+ errorCode: err?.error_code || "none",
821
+ errorMessage: err?.error_message || err?.message || "none",
822
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
678
823
  });
679
- }
680
- return {
681
- compositionEntry: entry,
682
- symbolEntries: getAllSymbols(entry),
683
- };
684
- })
685
- .catch((err) => {
686
- // This error is different. Here, we have issues while fetching the entries.
687
- const { errorType, message } = classifyApiError(err);
688
- console.error("SDK Error (URL-based fetch):", {
689
- errorType,
690
- message,
691
- originalError: err,
692
824
  });
693
- throw new ComposableStudioError(errorType, message, {
694
- url: options.url,
695
- hasStackSdk: !!config.stackSdk,
696
- statusCode: err?.status || err?.statusCode || "none",
697
- errorCode: err?.error_code || "none",
698
- errorMessage: err?.error_message || err?.message || "none",
699
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
825
+ }
826
+ else {
827
+ throw new ComposableStudioError(ComposableStudioErrors.MISSING_COMPOSITION_IDENTIFIER, getErrorMessage(ErrorMessageKey.MISSING_COMPOSITION_IDENTIFIER), {
828
+ options: queryOptions,
700
829
  });
830
+ }
831
+ };
832
+ const customFetcher = perQueryFetchComposition ?? config.fetchComposition;
833
+ if (customFetcher) {
834
+ const entry = await customFetcher({
835
+ compositionQuery: queryOptions,
836
+ contentTypeUid: config.contentTypeUid,
837
+ options: resolvedOptions,
838
+ stackSdk: config.stackSdk.sdk,
839
+ defaultFetch: defaultImpl,
701
840
  });
841
+ if (!entry) {
842
+ const isUrlBased = "url" in queryOptions;
843
+ throw new ComposableStudioError(isUrlBased
844
+ ? ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL
845
+ : ComposableStudioErrors.COMPOSITION_NOT_FOUND, isUrlBased
846
+ ? getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
847
+ url: queryOptions.url,
848
+ })
849
+ : getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404));
850
+ }
851
+ return {
852
+ compositionEntry: entry,
853
+ symbolEntries: getAllSymbols(entry),
854
+ };
702
855
  }
703
- else {
704
- throw new ComposableStudioError(ComposableStudioErrors.MISSING_COMPOSITION_IDENTIFIER, getErrorMessage(ErrorMessageKey.MISSING_COMPOSITION_IDENTIFIER), {
705
- options,
706
- });
707
- }
856
+ const entry = await defaultImpl();
857
+ return {
858
+ compositionEntry: entry,
859
+ symbolEntries: getAllSymbols(entry),
860
+ };
708
861
  }
709
862
 
710
863
  export { classifyApiError, generateSdk, parseUI };