@builder.io/sdk-solid 0.2.3 → 0.4.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/CHANGELOG.md +13 -0
  2. package/package.json +2 -5
  3. package/src/blocks/columns/columns.jsx +1 -1
  4. package/src/blocks/symbol/symbol.jsx +1 -1
  5. package/src/components/render-block/block-styles.jsx +3 -1
  6. package/src/components/render-block/render-block.helpers.js +7 -19
  7. package/src/components/render-block/render-block.jsx +23 -23
  8. package/src/components/render-block/render-repeated-block.jsx +3 -2
  9. package/src/components/render-content/components/render-styles.jsx +4 -2
  10. package/src/components/render-content/render-content.jsx +52 -9
  11. package/src/components/render-content/wrap-component-ref.js +4 -0
  12. package/src/components/render-content-variants/helpers.js +139 -0
  13. package/src/components/render-content-variants/render-content-variants.jsx +94 -0
  14. package/src/components/render-inlined-styles.jsx +1 -23
  15. package/src/constants/sdk-version.js +1 -0
  16. package/src/context/builder.context.js +3 -2
  17. package/src/functions/evaluate.js +27 -3
  18. package/src/functions/evaluate.test.js +17 -0
  19. package/src/functions/get-block-actions-handler.js +3 -1
  20. package/src/functions/get-content/generate-content-url.js +2 -1
  21. package/src/functions/get-content/generate-content-url.test.js +15 -0
  22. package/src/functions/get-content/index.js +35 -18
  23. package/src/functions/get-processed-block.js +20 -4
  24. package/src/functions/get-processed-block.test.js +3 -1
  25. package/src/helpers/ab-tests.js +132 -10
  26. package/src/helpers/canTrack.js +5 -0
  27. package/src/helpers/cookie.js +9 -4
  28. package/src/helpers/logger.js +2 -1
  29. package/src/index-helpers/blocks-exports.js +10 -10
  30. package/src/index.js +18 -7
  31. package/src/scripts/init-editing.js +2 -0
  32. package/src/functions/get-content/ab-testing.js +0 -99
@@ -3,7 +3,9 @@ import { isEditing } from "./is-editing.js";
3
3
  function evaluate({
4
4
  code,
5
5
  context,
6
- state,
6
+ localState,
7
+ rootState,
8
+ rootSetState,
7
9
  event,
8
10
  isExpression = true
9
11
  }) {
@@ -19,11 +21,33 @@ function evaluate({
19
21
  const useReturn = isExpression && !(code.includes(";") || code.includes(" return ") || code.trim().startsWith("return "));
20
22
  const useCode = useReturn ? `return (${code});` : code;
21
23
  try {
22
- return new Function("builder", "Builder", "state", "context", "event", useCode)(builder, builder, state, context, event);
24
+ return new Function("builder", "Builder", "state", "context", "event", useCode)(builder, builder, flattenState(rootState, localState, rootSetState), context, event);
23
25
  } catch (e) {
24
26
  console.warn("Builder custom code error: \n While Evaluating: \n ", useCode, "\n", e);
25
27
  }
26
28
  }
29
+ function flattenState(rootState, localState, rootSetState) {
30
+ if (rootState === localState) {
31
+ throw new Error("rootState === localState");
32
+ }
33
+ return new Proxy(rootState, {
34
+ get: (_, prop) => {
35
+ if (localState && prop in localState) {
36
+ return localState[prop];
37
+ }
38
+ return rootState[prop];
39
+ },
40
+ set: (_, prop, value) => {
41
+ if (localState && prop in localState) {
42
+ throw new Error("Writing to local state is not allowed as it is read-only.");
43
+ }
44
+ rootState[prop] = value;
45
+ rootSetState == null ? void 0 : rootSetState(rootState);
46
+ return true;
47
+ }
48
+ });
49
+ }
27
50
  export {
28
- evaluate
51
+ evaluate,
52
+ flattenState
29
53
  };
@@ -0,0 +1,17 @@
1
+ import { flattenState } from "./evaluate";
2
+ describe("flatten state", () => {
3
+ it("should behave normally when no PROTO_STATE", () => {
4
+ const localState = {};
5
+ const rootState = { foo: "bar" };
6
+ const flattened = flattenState(rootState, localState, void 0);
7
+ expect(flattened.foo).toEqual("bar");
8
+ flattened.foo = "baz";
9
+ expect(rootState.foo).toEqual("baz");
10
+ });
11
+ it("should shadow write ", () => {
12
+ const rootState = { foo: "foo" };
13
+ const localState = { foo: "baz" };
14
+ const flattened = flattenState(rootState, localState, void 0);
15
+ expect(() => flattened.foo = "bar").toThrow("Writing to local state is not allowed as it is read-only.");
16
+ });
17
+ });
@@ -2,7 +2,9 @@ import { evaluate } from "./evaluate.js";
2
2
  const createEventHandler = (value, options) => (event) => evaluate({
3
3
  code: value,
4
4
  context: options.context,
5
- state: options.state,
5
+ localState: options.localState,
6
+ rootState: options.rootState,
7
+ rootSetState: options.rootSetState,
6
8
  event,
7
9
  isExpression: false
8
10
  });
@@ -29,6 +29,7 @@ const generateContentUrl = (options) => {
29
29
  model,
30
30
  apiKey,
31
31
  includeRefs = true,
32
+ enrich,
32
33
  locale,
33
34
  apiVersion = DEFAULT_API_VERSION
34
35
  } = options;
@@ -38,7 +39,7 @@ const generateContentUrl = (options) => {
38
39
  if (!["v2", "v3"].includes(apiVersion)) {
39
40
  throw new Error(`Invalid apiVersion: expected 'v2' or 'v3', received '${apiVersion}'`);
40
41
  }
41
- const url = new URL(`https://cdn.builder.io/api/${apiVersion}/content/${model}?apiKey=${apiKey}&limit=${limit}&noTraverse=${noTraverse}&includeRefs=${includeRefs}${locale ? `&locale=${locale}` : ""}`);
42
+ const url = new URL(`https://cdn.builder.io/api/${apiVersion}/content/${model}?apiKey=${apiKey}&limit=${limit}&noTraverse=${noTraverse}&includeRefs=${includeRefs}${locale ? `&locale=${locale}` : ""}${enrich ? `&enrich=${enrich}` : ""}`);
42
43
  const queryOptions = __spreadValues(__spreadValues({}, getBuilderSearchParamsFromWindow()), normalizeSearchParams(options.options || {}));
43
44
  const flattened = flatten(queryOptions);
44
45
  for (const key in flattened) {
@@ -79,4 +79,19 @@ describe("Generate Content URL", () => {
79
79
  });
80
80
  }).toThrow(`Invalid apiVersion: expected 'v2' or 'v3', received 'INVALID_API_VERSION'`);
81
81
  });
82
+ test("generate content url with enrich option true", () => {
83
+ const output = generateContentUrl({
84
+ apiKey: testKey,
85
+ model: testModel,
86
+ enrich: true
87
+ });
88
+ expect(output).toMatchSnapshot();
89
+ });
90
+ test("generate content url with enrich option not present", () => {
91
+ const output = generateContentUrl({
92
+ apiKey: testKey,
93
+ model: testModel
94
+ });
95
+ expect(output).toMatchSnapshot();
96
+ });
82
97
  });
@@ -37,40 +37,56 @@ var __async = (__this, __arguments, generator) => {
37
37
  step((generator = generator.apply(__this, __arguments)).next());
38
38
  });
39
39
  };
40
+ import { TARGET } from "../../constants/target.js";
41
+ import { handleABTesting } from "../../helpers/ab-tests.js";
42
+ import { getDefaultCanTrack } from "../../helpers/canTrack.js";
40
43
  import { logger } from "../../helpers/logger.js";
41
44
  import { fetch } from "../get-fetch.js";
42
- import { handleABTesting } from "./ab-testing.js";
45
+ import { isBrowser } from "../is-browser.js";
43
46
  import { generateContentUrl } from "./generate-content-url.js";
47
+ const checkContentHasResults = (content) => "results" in content;
44
48
  function getContent(options) {
45
49
  return __async(this, null, function* () {
46
50
  const allContent = yield getAllContent(__spreadProps(__spreadValues({}, options), { limit: 1 }));
47
- if (allContent && "results" in allContent) {
48
- return (allContent == null ? void 0 : allContent.results[0]) || null;
51
+ if (allContent && checkContentHasResults(allContent)) {
52
+ return allContent.results[0] || null;
49
53
  }
50
54
  return null;
51
55
  });
52
56
  }
57
+ const fetchContent = (options) => __async(void 0, null, function* () {
58
+ const url = generateContentUrl(options);
59
+ const res = yield fetch(url.href);
60
+ const content = yield res.json();
61
+ return content;
62
+ });
63
+ const processContentResult = (options, content) => __async(void 0, null, function* () {
64
+ const canTrack = getDefaultCanTrack(options.canTrack);
65
+ if (!canTrack)
66
+ return content;
67
+ if (!(isBrowser() || TARGET === "reactNative"))
68
+ return content;
69
+ try {
70
+ const newResults = [];
71
+ for (const item of content.results) {
72
+ newResults.push(yield handleABTesting({ item, canTrack }));
73
+ }
74
+ content.results = newResults;
75
+ } catch (e) {
76
+ logger.error("Could not process A/B tests. ", e);
77
+ }
78
+ return content;
79
+ });
53
80
  function getAllContent(options) {
54
81
  return __async(this, null, function* () {
55
82
  try {
56
83
  const url = generateContentUrl(options);
57
- const res = yield fetch(url.href);
58
- const content = yield res.json();
59
- if ("status" in content && !("results" in content)) {
84
+ const content = yield fetchContent(options);
85
+ if (!checkContentHasResults(content)) {
60
86
  logger.error("Error fetching data. ", { url, content, options });
61
87
  return content;
62
88
  }
63
- const canTrack = options.canTrack !== false;
64
- try {
65
- if (canTrack && Array.isArray(content.results)) {
66
- for (const item of content.results) {
67
- yield handleABTesting({ item, canTrack });
68
- }
69
- }
70
- } catch (e) {
71
- logger.error("Could not setup A/B testing. ", e);
72
- }
73
- return content;
89
+ return processContentResult(options, content);
74
90
  } catch (error) {
75
91
  logger.error("Error fetching data. ", error);
76
92
  return null;
@@ -79,5 +95,6 @@ function getAllContent(options) {
79
95
  }
80
96
  export {
81
97
  getAllContent,
82
- getContent
98
+ getContent,
99
+ processContentResult
83
100
  };
@@ -24,7 +24,9 @@ import { transformBlock } from "./transform-block.js";
24
24
  const evaluateBindings = ({
25
25
  block,
26
26
  context,
27
- state
27
+ localState,
28
+ rootState,
29
+ rootSetState
28
30
  }) => {
29
31
  if (!block.bindings) {
30
32
  return block;
@@ -36,7 +38,13 @@ const evaluateBindings = ({
36
38
  });
37
39
  for (const binding in block.bindings) {
38
40
  const expression = block.bindings[binding];
39
- const value = evaluate({ code: expression, state, context });
41
+ const value = evaluate({
42
+ code: expression,
43
+ localState,
44
+ rootState,
45
+ rootSetState,
46
+ context
47
+ });
40
48
  set(copied, binding, value);
41
49
  }
42
50
  return copied;
@@ -45,11 +53,19 @@ function getProcessedBlock({
45
53
  block,
46
54
  context,
47
55
  shouldEvaluateBindings,
48
- state
56
+ localState,
57
+ rootState,
58
+ rootSetState
49
59
  }) {
50
60
  const transformedBlock = transformBlock(block);
51
61
  if (shouldEvaluateBindings) {
52
- return evaluateBindings({ block: transformedBlock, state, context });
62
+ return evaluateBindings({
63
+ block: transformedBlock,
64
+ localState,
65
+ rootState,
66
+ rootSetState,
67
+ context
68
+ });
53
69
  } else {
54
70
  return transformedBlock;
55
71
  }
@@ -20,7 +20,9 @@ test("Can process bindings", () => {
20
20
  const processed = getProcessedBlock({
21
21
  block,
22
22
  context: {},
23
- state: { test: "hello" },
23
+ rootState: { test: "hello" },
24
+ rootSetState: void 0,
25
+ localState: void 0,
24
26
  shouldEvaluateBindings: true
25
27
  });
26
28
  expect(processed).not.toEqual(block);
@@ -1,16 +1,138 @@
1
- import { getCookie, setCookie } from "./cookie.js";
2
- const BUILDER_STORE_PREFIX = "builderio.variations";
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ var __async = (__this, __arguments, generator) => {
18
+ return new Promise((resolve, reject) => {
19
+ var fulfilled = (value) => {
20
+ try {
21
+ step(generator.next(value));
22
+ } catch (e) {
23
+ reject(e);
24
+ }
25
+ };
26
+ var rejected = (value) => {
27
+ try {
28
+ step(generator.throw(value));
29
+ } catch (e) {
30
+ reject(e);
31
+ }
32
+ };
33
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
34
+ step((generator = generator.apply(__this, __arguments)).next());
35
+ });
36
+ };
37
+ import { getCookie, getCookieSync, setCookie } from "./cookie.js";
38
+ import { checkIsDefined } from "../helpers/nullable.js";
39
+ import { logger } from "./logger.js";
40
+ const BUILDER_STORE_PREFIX = "builder.tests";
3
41
  const getContentTestKey = (id) => `${BUILDER_STORE_PREFIX}.${id}`;
4
- const getContentVariationCookie = ({
5
- contentId,
6
- canTrack
7
- }) => getCookie({ name: getContentTestKey(contentId), canTrack });
42
+ const getContentVariationCookie = ({ contentId }) => getCookie({ name: getContentTestKey(contentId), canTrack: true });
43
+ const getContentVariationCookieSync = ({ contentId }) => getCookieSync({ name: getContentTestKey(contentId), canTrack: true });
8
44
  const setContentVariationCookie = ({
9
45
  contentId,
10
- canTrack,
11
46
  value
12
- }) => setCookie({ name: getContentTestKey(contentId), value, canTrack });
47
+ }) => setCookie({ name: getContentTestKey(contentId), value, canTrack: true });
48
+ const checkIsBuilderContentWithVariations = (item) => checkIsDefined(item.id) && checkIsDefined(item.variations) && Object.keys(item.variations).length > 0;
49
+ const getRandomVariationId = ({
50
+ id,
51
+ variations
52
+ }) => {
53
+ var _a;
54
+ let n = 0;
55
+ const random = Math.random();
56
+ for (const id2 in variations) {
57
+ const testRatio = (_a = variations[id2]) == null ? void 0 : _a.testRatio;
58
+ n += testRatio;
59
+ if (random < n) {
60
+ return id2;
61
+ }
62
+ }
63
+ return id;
64
+ };
65
+ const getAndSetVariantId = (args) => {
66
+ const randomVariationId = getRandomVariationId(args);
67
+ setContentVariationCookie({
68
+ contentId: args.id,
69
+ value: randomVariationId
70
+ }).catch((err) => {
71
+ logger.error("could not store A/B test variation: ", err);
72
+ });
73
+ return randomVariationId;
74
+ };
75
+ const getTestFields = ({
76
+ item,
77
+ testGroupId
78
+ }) => {
79
+ const variationValue = item.variations[testGroupId];
80
+ if (testGroupId === item.id || !variationValue) {
81
+ return {
82
+ testVariationId: item.id,
83
+ testVariationName: "Default"
84
+ };
85
+ } else {
86
+ return {
87
+ data: variationValue.data,
88
+ testVariationId: variationValue.id,
89
+ testVariationName: variationValue.name || (variationValue.id === item.id ? "Default" : "")
90
+ };
91
+ }
92
+ };
93
+ const handleABTestingSync = ({
94
+ item,
95
+ canTrack
96
+ }) => {
97
+ if (!canTrack) {
98
+ return item;
99
+ }
100
+ if (!item) {
101
+ return void 0;
102
+ }
103
+ if (!checkIsBuilderContentWithVariations(item)) {
104
+ return item;
105
+ }
106
+ const testGroupId = getContentVariationCookieSync({
107
+ contentId: item.id
108
+ }) || getAndSetVariantId({
109
+ variations: item.variations,
110
+ id: item.id
111
+ });
112
+ const variationValue = getTestFields({ item, testGroupId });
113
+ return __spreadValues(__spreadValues({}, item), variationValue);
114
+ };
115
+ const handleABTesting = (_0) => __async(void 0, [_0], function* ({
116
+ item,
117
+ canTrack
118
+ }) {
119
+ if (!canTrack) {
120
+ return item;
121
+ }
122
+ if (!checkIsBuilderContentWithVariations(item)) {
123
+ return item;
124
+ }
125
+ const cookieValue = yield getContentVariationCookie({
126
+ contentId: item.id
127
+ });
128
+ const testGroupId = cookieValue || getAndSetVariantId({
129
+ variations: item.variations,
130
+ id: item.id
131
+ });
132
+ const variationValue = getTestFields({ item, testGroupId });
133
+ return __spreadValues(__spreadValues({}, item), variationValue);
134
+ });
13
135
  export {
14
- getContentVariationCookie,
15
- setContentVariationCookie
136
+ handleABTesting,
137
+ handleABTestingSync
16
138
  };
@@ -0,0 +1,5 @@
1
+ import { checkIsDefined } from "./nullable";
2
+ const getDefaultCanTrack = (canTrack) => checkIsDefined(canTrack) ? canTrack : true;
3
+ export {
4
+ getDefaultCanTrack
5
+ };
@@ -19,12 +19,13 @@ var __async = (__this, __arguments, generator) => {
19
19
  });
20
20
  };
21
21
  import { isBrowser } from "../functions/is-browser.js";
22
+ import { logger } from "./logger.js";
22
23
  import { checkIsDefined } from "./nullable.js";
23
24
  import { getTopLevelDomain } from "./url.js";
24
- const getCookie = (_0) => __async(void 0, [_0], function* ({
25
+ const getCookieSync = ({
25
26
  name,
26
27
  canTrack
27
- }) {
28
+ }) => {
28
29
  var _a;
29
30
  try {
30
31
  if (!canTrack) {
@@ -32,9 +33,12 @@ const getCookie = (_0) => __async(void 0, [_0], function* ({
32
33
  }
33
34
  return (_a = document.cookie.split("; ").find((row) => row.startsWith(`${name}=`))) == null ? void 0 : _a.split("=")[1];
34
35
  } catch (err) {
35
- console.debug("[COOKIE] GET error: ", err);
36
+ logger.warn("[COOKIE] GET error: ", (err == null ? void 0 : err.message) || err);
36
37
  return void 0;
37
38
  }
39
+ };
40
+ const getCookie = (args) => __async(void 0, null, function* () {
41
+ return getCookieSync(args);
38
42
  });
39
43
  const stringifyCookie = (cookie) => cookie.map(([key, value]) => value ? `${key}=${value}` : key).filter(checkIsDefined).join("; ");
40
44
  const SECURE_CONFIG = [
@@ -72,10 +76,11 @@ const setCookie = (_0) => __async(void 0, [_0], function* ({
72
76
  const cookie = createCookieString({ name, value, expires });
73
77
  document.cookie = cookie;
74
78
  } catch (err) {
75
- console.warn("[COOKIE] SET error: ", err);
79
+ logger.warn("[COOKIE] SET error: ", (err == null ? void 0 : err.message) || err);
76
80
  }
77
81
  });
78
82
  export {
79
83
  getCookie,
84
+ getCookieSync,
80
85
  setCookie
81
86
  };
@@ -2,7 +2,8 @@ const MSG_PREFIX = "[Builder.io]: ";
2
2
  const logger = {
3
3
  log: (...message) => console.log(MSG_PREFIX, ...message),
4
4
  error: (...message) => console.error(MSG_PREFIX, ...message),
5
- warn: (...message) => console.warn(MSG_PREFIX, ...message)
5
+ warn: (...message) => console.warn(MSG_PREFIX, ...message),
6
+ debug: (...message) => console.debug(MSG_PREFIX, ...message)
6
7
  };
7
8
  export {
8
9
  logger
@@ -3,20 +3,20 @@ import { default as default3 } from "../blocks/columns/columns";
3
3
  import { default as default4 } from "../blocks/fragment/fragment";
4
4
  import { default as default5 } from "../blocks/image/image";
5
5
  import { default as default6 } from "../components/render-blocks";
6
- import { default as default7 } from "../components/render-content/render-content";
7
- import { default as default8 } from "../blocks/section/section";
8
- import { default as default9 } from "../blocks/symbol/symbol";
9
- import { default as default10 } from "../blocks/text/text";
10
- import { default as default11 } from "../blocks/video/video";
6
+ import { default as default7 } from "../blocks/section/section";
7
+ import { default as default8 } from "../blocks/symbol/symbol";
8
+ import { default as default9 } from "../blocks/text/text";
9
+ import { default as default10 } from "../blocks/video/video";
10
+ import { default as default11 } from "../components/render-content-variants/render-content-variants";
11
11
  export {
12
12
  default2 as Button,
13
13
  default3 as Columns,
14
14
  default4 as Fragment,
15
15
  default5 as Image,
16
16
  default6 as RenderBlocks,
17
- default7 as RenderContent,
18
- default8 as Section,
19
- default9 as Symbol,
20
- default10 as Text,
21
- default11 as Video
17
+ default11 as RenderContent,
18
+ default7 as Section,
19
+ default8 as Symbol,
20
+ default9 as Text,
21
+ default10 as Video
22
22
  };
package/src/index.js CHANGED
@@ -1,13 +1,24 @@
1
1
  export * from "./index-helpers/top-of-file.js";
2
2
  export * from "./index-helpers/blocks-exports.js";
3
- export * from "./functions/is-editing.js";
4
- export * from "./functions/is-previewing.js";
5
- export * from "./functions/register-component.js";
6
- export * from "./functions/register.js";
7
- export * from "./functions/set-editor-settings.js";
8
- export * from "./functions/get-content/index.js";
9
- export * from "./functions/get-builder-search-params/index.js";
3
+ import { isEditing } from "./functions/is-editing.js";
4
+ import { isPreviewing } from "./functions/is-previewing.js";
5
+ import { createRegisterComponentMessage } from "./functions/register-component.js";
6
+ import { register } from "./functions/register.js";
7
+ import { setEditorSettings } from "./functions/set-editor-settings.js";
8
+ import {
9
+ getAllContent,
10
+ getContent,
11
+ processContentResult
12
+ } from "./functions/get-content/index.js";
10
13
  import { track } from "./functions/track/index.js";
11
14
  export {
15
+ createRegisterComponentMessage,
16
+ getAllContent,
17
+ getContent,
18
+ isEditing,
19
+ isPreviewing,
20
+ processContentResult,
21
+ register,
22
+ setEditorSettings,
12
23
  track
13
24
  };
@@ -1,3 +1,4 @@
1
+ import { SDK_VERSION } from "../constants/sdk-version.js";
1
2
  import { TARGET } from "../constants/target.js";
2
3
  import { isBrowser } from "../functions/is-browser.js";
3
4
  import { register } from "../functions/register.js";
@@ -31,6 +32,7 @@ const setupBrowserForEditing = (options = {}) => {
31
32
  type: "builder.sdkInfo",
32
33
  data: {
33
34
  target: TARGET,
35
+ version: SDK_VERSION,
34
36
  supportsPatchUpdates: false,
35
37
  supportsAddBlockScoping: true,
36
38
  supportsCustomBreakpoints: true
@@ -1,99 +0,0 @@
1
- var __async = (__this, __arguments, generator) => {
2
- return new Promise((resolve, reject) => {
3
- var fulfilled = (value) => {
4
- try {
5
- step(generator.next(value));
6
- } catch (e) {
7
- reject(e);
8
- }
9
- };
10
- var rejected = (value) => {
11
- try {
12
- step(generator.throw(value));
13
- } catch (e) {
14
- reject(e);
15
- }
16
- };
17
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
- step((generator = generator.apply(__this, __arguments)).next());
19
- });
20
- };
21
- import {
22
- getContentVariationCookie,
23
- setContentVariationCookie
24
- } from "../../helpers/ab-tests.js";
25
- import { checkIsDefined } from "../../helpers/nullable.js";
26
- const checkIsBuilderContentWithVariations = (item) => checkIsDefined(item.id) && checkIsDefined(item.variations) && Object.keys(item.variations).length > 0;
27
- const getRandomVariationId = ({
28
- id,
29
- variations
30
- }) => {
31
- var _a;
32
- let n = 0;
33
- const random = Math.random();
34
- for (const id2 in variations) {
35
- const testRatio = (_a = variations[id2]) == null ? void 0 : _a.testRatio;
36
- n += testRatio;
37
- if (random < n) {
38
- return id2;
39
- }
40
- }
41
- return id;
42
- };
43
- const getTestFields = ({
44
- item,
45
- testGroupId
46
- }) => {
47
- const variationValue = item.variations[testGroupId];
48
- if (testGroupId === item.id || !variationValue) {
49
- return {
50
- testVariationId: item.id,
51
- testVariationName: "Default"
52
- };
53
- } else {
54
- return {
55
- data: variationValue.data,
56
- testVariationId: variationValue.id,
57
- testVariationName: variationValue.name || (variationValue.id === item.id ? "Default" : "")
58
- };
59
- }
60
- };
61
- const getContentVariation = (_0) => __async(void 0, [_0], function* ({
62
- item,
63
- canTrack
64
- }) {
65
- const testGroupId = yield getContentVariationCookie({
66
- canTrack,
67
- contentId: item.id
68
- });
69
- const testFields = testGroupId ? getTestFields({ item, testGroupId }) : void 0;
70
- if (testFields) {
71
- return testFields;
72
- } else {
73
- const randomVariationId = getRandomVariationId({
74
- variations: item.variations,
75
- id: item.id
76
- });
77
- setContentVariationCookie({
78
- contentId: item.id,
79
- value: randomVariationId,
80
- canTrack
81
- }).catch((err) => {
82
- console.error("could not store A/B test variation: ", err);
83
- });
84
- return getTestFields({ item, testGroupId: randomVariationId });
85
- }
86
- });
87
- const handleABTesting = (_0) => __async(void 0, [_0], function* ({
88
- item,
89
- canTrack
90
- }) {
91
- if (!checkIsBuilderContentWithVariations(item)) {
92
- return;
93
- }
94
- const variationValue = yield getContentVariation({ item, canTrack });
95
- Object.assign(item, variationValue);
96
- });
97
- export {
98
- handleABTesting
99
- };