@builder.io/sdk-solid 0.3.1 → 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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,16 @@
1
+ ### 0.4.0
2
+
3
+ - Feature: A/B tests are now rendered correctly during server-side rendering (SSR) when applicable. This behaviour is backwards compatible with previous versions.
4
+
5
+ ### 0.3.1
6
+
7
+ - Feature: Added SDK version to data sent to visual editor for improved debugging.
8
+ - Fix: Columns block: removed redundant margin-left in first column.
9
+
10
+ ### 0.3.0
11
+
12
+ - No Changes.
13
+
1
14
  ### 0.2.3
2
15
 
3
16
  - No Changes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@builder.io/sdk-solid",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./solid-index.jsx",
@@ -25,7 +25,7 @@ function RenderBlock(props) {
25
25
  })
26
26
  );
27
27
 
28
- const [tag, setTag] = createSignal(props.block.tagName || "div");
28
+ const [Tag, setTag] = createSignal(props.block.tagName || "div");
29
29
 
30
30
  function repeatItem() {
31
31
  return getRepeatItemData({
@@ -152,10 +152,10 @@ function RenderBlock(props) {
152
152
  }
153
153
  when={!component()?.noWrap}
154
154
  >
155
- <Show when={isEmptyHtmlElement(tag())}>
156
- <Dynamic {...attributes()} {...actions()} component={tag()}></Dynamic>
155
+ <Show when={isEmptyHtmlElement(Tag())}>
156
+ <Dynamic {...attributes()} {...actions()} component={Tag()}></Dynamic>
157
157
  </Show>
158
- <Show when={!isEmptyHtmlElement(tag()) && repeatItem()}>
158
+ <Show when={!isEmptyHtmlElement(Tag()) && repeatItem()}>
159
159
  <For each={repeatItem()}>
160
160
  {(data, _index) => {
161
161
  const index = _index();
@@ -169,8 +169,8 @@ function RenderBlock(props) {
169
169
  }}
170
170
  </For>
171
171
  </Show>
172
- <Show when={!isEmptyHtmlElement(tag()) && !repeatItem()}>
173
- <Dynamic {...attributes()} {...actions()} component={tag()}>
172
+ <Show when={!isEmptyHtmlElement(Tag()) && !repeatItem()}>
173
+ <Dynamic {...attributes()} {...actions()} component={Tag()}>
174
174
  <RenderComponent {...renderComponentProps()}></RenderComponent>
175
175
  <For each={childrenWithoutParentComponent()}>
176
176
  {(child, _index) => {
@@ -5,7 +5,8 @@ import { getCss } from "./render-styles.helpers";
5
5
  import { getFontCss } from "./render-styles.helpers";
6
6
 
7
7
  function RenderContentStyles(props) {
8
- const [injectedStyles, setInjectedStyles] = createSignal(`
8
+ const [injectedStyles, setInjectedStyles] = createSignal(
9
+ `
9
10
  ${getCss({
10
11
  cssCode: props.cssCode,
11
12
  contentId: props.contentId,
@@ -26,7 +27,8 @@ ${getFontCss({
26
27
  text-align: inherit;
27
28
  font-family: inherit;
28
29
  }
29
- `);
30
+ `.trim()
31
+ );
30
32
 
31
33
  return <RenderInlinedStyles styles={injectedStyles()}></RenderInlinedStyles>;
32
34
  }
@@ -29,6 +29,8 @@ import {
29
29
  } from "./render-content.helpers.js";
30
30
  import { TARGET } from "../../constants/target.js";
31
31
  import { logger } from "../../helpers/logger.js";
32
+ import { getRenderContentScriptString } from "../render-content-variants/helpers.js";
33
+ import { wrapComponentRef } from "./wrap-component-ref.js";
32
34
 
33
35
  function RenderContent(props) {
34
36
  const [forceReRenderCount, setForceReRenderCount] = createSignal(0);
@@ -60,9 +62,13 @@ function RenderContent(props) {
60
62
  ...components,
61
63
  ...(props.customComponents || []),
62
64
  ].reduce(
63
- (acc, curr) => ({
65
+ (acc, { component, ...curr }) => ({
64
66
  ...acc,
65
- [curr.name]: curr,
67
+ [curr.name]: {
68
+ component:
69
+ TARGET === "vue3" ? wrapComponentRef(component) : component,
70
+ ...curr,
71
+ },
66
72
  }),
67
73
  {}
68
74
  )
@@ -72,6 +78,14 @@ function RenderContent(props) {
72
78
 
73
79
  const [clicked, setClicked] = createSignal(false);
74
80
 
81
+ const [scriptStr, setScriptStr] = createSignal(
82
+ getRenderContentScriptString({
83
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-non-null-asserted-optional-chain
84
+ contentId: props.content?.id,
85
+ parentContentId: props.parentContentId,
86
+ })
87
+ );
88
+
75
89
  function mergeNewContent(newContent) {
76
90
  setUseContent({
77
91
  ...useContent,
@@ -259,6 +273,11 @@ function RenderContent(props) {
259
273
  includeRefs: props.includeRefs,
260
274
  }
261
275
  : {}),
276
+ ...(props.enrich
277
+ ? {
278
+ enrich: props.enrich,
279
+ }
280
+ : {}),
262
281
  });
263
282
  Object.values(allRegisteredComponents()).forEach(
264
283
  (registeredComponent) => {
@@ -365,11 +384,30 @@ function RenderContent(props) {
365
384
  >
366
385
  <Show when={useContent}>
367
386
  <div
387
+ class={props.classNameProp}
368
388
  ref={elementRef}
369
389
  onClick={(event) => onClick(event)}
370
390
  builder-content-id={useContent?.id}
371
391
  builder-model={props.model}
392
+ {...(TARGET === "reactNative"
393
+ ? {
394
+ dataSet: {
395
+ // currently, we can't set the actual ID here.
396
+ // we don't need it right now, we just need to identify content divs for testing.
397
+ "builder-content-id": "",
398
+ },
399
+ }
400
+ : {})}
401
+ {...(props.hideContent
402
+ ? {
403
+ hidden: true,
404
+ "aria-hidden": true,
405
+ }
406
+ : {})}
372
407
  >
408
+ <Show when={props.isSsrAbTest}>
409
+ <script innerHTML={scriptStr()}></script>
410
+ </Show>
373
411
  <Show when={TARGET !== "reactNative"}>
374
412
  <RenderContentStyles
375
413
  contentId={useContent?.id}
@@ -0,0 +1,4 @@
1
+ const wrapComponentRef = (component) => component;
2
+ export {
3
+ wrapComponentRef
4
+ };
@@ -0,0 +1,139 @@
1
+ import { isBrowser } from "../../functions/is-browser";
2
+ const getVariants = (content) => Object.values((content == null ? void 0 : content.variations) || {});
3
+ const checkShouldRunVariants = ({
4
+ canTrack,
5
+ content
6
+ }) => {
7
+ const hasVariants = getVariants(content).length > 0;
8
+ if (!hasVariants) {
9
+ return false;
10
+ }
11
+ if (!canTrack) {
12
+ return false;
13
+ }
14
+ if (isBrowser()) {
15
+ return false;
16
+ }
17
+ return true;
18
+ };
19
+ function bldrAbTest(contentId, variants, isHydrationTarget2) {
20
+ function getAndSetVariantId() {
21
+ function setCookie(name, value, days) {
22
+ let expires = "";
23
+ if (days) {
24
+ const date = new Date();
25
+ date.setTime(date.getTime() + days * 24 * 60 * 60 * 1e3);
26
+ expires = "; expires=" + date.toUTCString();
27
+ }
28
+ document.cookie = name + "=" + (value || "") + expires + "; path=/; Secure; SameSite=None";
29
+ }
30
+ function getCookie(name) {
31
+ const nameEQ = name + "=";
32
+ const ca = document.cookie.split(";");
33
+ for (let i = 0; i < ca.length; i++) {
34
+ let c = ca[i];
35
+ while (c.charAt(0) === " ")
36
+ c = c.substring(1, c.length);
37
+ if (c.indexOf(nameEQ) === 0)
38
+ return c.substring(nameEQ.length, c.length);
39
+ }
40
+ return null;
41
+ }
42
+ const cookieName = `builder.tests.${contentId}`;
43
+ const variantInCookie = getCookie(cookieName);
44
+ const availableIDs = variants.map((vr) => vr.id).concat(contentId);
45
+ if (variantInCookie && availableIDs.includes(variantInCookie)) {
46
+ return variantInCookie;
47
+ }
48
+ let n = 0;
49
+ const random = Math.random();
50
+ for (let i = 0; i < variants.length; i++) {
51
+ const variant = variants[i];
52
+ const testRatio = variant.testRatio;
53
+ n += testRatio;
54
+ if (random < n) {
55
+ setCookie(cookieName, variant.id);
56
+ return variant.id;
57
+ }
58
+ }
59
+ setCookie(cookieName, contentId);
60
+ return contentId;
61
+ }
62
+ const winningVariantId = getAndSetVariantId();
63
+ const styleEl = document.getElementById(`variants-styles-${contentId}`);
64
+ if (isHydrationTarget2) {
65
+ styleEl.remove();
66
+ const thisScriptEl = document.getElementById(`variants-script-${contentId}`);
67
+ thisScriptEl == null ? void 0 : thisScriptEl.remove();
68
+ } else {
69
+ const newStyleStr = variants.concat({ id: contentId }).filter((variant) => variant.id !== winningVariantId).map((value) => {
70
+ return `.variant-${value.id} { display: none; }
71
+ `;
72
+ }).join("");
73
+ styleEl.innerHTML = newStyleStr;
74
+ }
75
+ }
76
+ function bldrCntntScrpt(variantContentId, defaultContentId, isHydrationTarget2) {
77
+ if (!navigator.cookieEnabled) {
78
+ return;
79
+ }
80
+ function getCookie(name) {
81
+ const nameEQ = name + "=";
82
+ const ca = document.cookie.split(";");
83
+ for (let i = 0; i < ca.length; i++) {
84
+ let c = ca[i];
85
+ while (c.charAt(0) === " ")
86
+ c = c.substring(1, c.length);
87
+ if (c.indexOf(nameEQ) === 0)
88
+ return c.substring(nameEQ.length, c.length);
89
+ }
90
+ return null;
91
+ }
92
+ const cookieName = `builder.tests.${defaultContentId}`;
93
+ const variantId = getCookie(cookieName);
94
+ const parentDiv = document.querySelector(`[builder-content-id="${variantContentId}"]`);
95
+ const variantIsDefaultContent = variantContentId === defaultContentId;
96
+ if (variantId === variantContentId) {
97
+ if (variantIsDefaultContent) {
98
+ return;
99
+ }
100
+ parentDiv == null ? void 0 : parentDiv.removeAttribute("hidden");
101
+ parentDiv == null ? void 0 : parentDiv.removeAttribute("aria-hidden");
102
+ } else {
103
+ if (variantIsDefaultContent) {
104
+ if (isHydrationTarget2) {
105
+ parentDiv == null ? void 0 : parentDiv.remove();
106
+ } else {
107
+ parentDiv == null ? void 0 : parentDiv.setAttribute("hidden", "true");
108
+ parentDiv == null ? void 0 : parentDiv.setAttribute("aria-hidden", "true");
109
+ }
110
+ }
111
+ return;
112
+ }
113
+ return;
114
+ }
115
+ const isHydrationTarget = (target) => target === "react" || target === "reactNative" || target === "vue3" || target === "vue2";
116
+ const AB_TEST_FN_NAME = "bldrAbTest";
117
+ const CONTENT_FN_NAME = "bldrCntntScrpt";
118
+ const getVariantsScriptString = (variants, contentId) => {
119
+ const fnStr = bldrAbTest.toString().replace(/\s+/g, " ");
120
+ const fnStr2 = bldrCntntScrpt.toString().replace(/\s+/g, " ");
121
+ return `
122
+ const ${AB_TEST_FN_NAME} = ${fnStr}
123
+ const ${CONTENT_FN_NAME} = ${fnStr2}
124
+ ${AB_TEST_FN_NAME}("${contentId}", ${JSON.stringify(variants)}, ${isHydrationTarget})
125
+ `;
126
+ };
127
+ const getRenderContentScriptString = ({
128
+ parentContentId,
129
+ contentId
130
+ }) => {
131
+ return `
132
+ ${CONTENT_FN_NAME}("${contentId}", "${parentContentId}", ${isHydrationTarget})`;
133
+ };
134
+ export {
135
+ checkShouldRunVariants,
136
+ getRenderContentScriptString,
137
+ getVariants,
138
+ getVariantsScriptString
139
+ };
@@ -0,0 +1,94 @@
1
+ import { Show, For, createSignal } from "solid-js";
2
+
3
+ import {
4
+ checkShouldRunVariants,
5
+ getVariants,
6
+ getVariantsScriptString,
7
+ } from "./helpers";
8
+ import RenderContent from "../render-content/render-content.jsx";
9
+ import { getDefaultCanTrack } from "../../helpers/canTrack";
10
+ import RenderInlinedStyles from "../render-inlined-styles.jsx";
11
+ import { handleABTestingSync } from "../../helpers/ab-tests";
12
+
13
+ function RenderContentVariants(props) {
14
+ const [variantScriptStr, setVariantScriptStr] = createSignal(
15
+ getVariantsScriptString(
16
+ getVariants(props.content).map((value) => ({
17
+ id: value.id,
18
+ testRatio: value.testRatio,
19
+ })),
20
+ props.content?.id || ""
21
+ )
22
+ );
23
+
24
+ const [shouldRenderVariants, setShouldRenderVariants] = createSignal(
25
+ checkShouldRunVariants({
26
+ canTrack: getDefaultCanTrack(props.canTrack),
27
+ content: props.content,
28
+ })
29
+ );
30
+
31
+ const [hideVariantsStyleString, setHideVariantsStyleString] = createSignal(
32
+ getVariants(props.content)
33
+ .map((value) => `.variant-${value.id} { display: none; } `)
34
+ .join("")
35
+ );
36
+
37
+ const [contentToRender, setContentToRender] = createSignal(
38
+ checkShouldRunVariants({
39
+ canTrack: getDefaultCanTrack(props.canTrack),
40
+ content: props.content,
41
+ })
42
+ ? props.content
43
+ : handleABTestingSync({
44
+ item: props.content,
45
+ canTrack: getDefaultCanTrack(props.canTrack),
46
+ })
47
+ );
48
+
49
+ return (
50
+ <>
51
+ <Show when={shouldRenderVariants()}>
52
+ <RenderInlinedStyles
53
+ id={`variants-styles-${props.content?.id}`}
54
+ styles={hideVariantsStyleString()}
55
+ ></RenderInlinedStyles>
56
+ <script
57
+ id={`variants-script-${props.content?.id}`}
58
+ innerHTML={variantScriptStr()}
59
+ ></script>
60
+ <For each={getVariants(props.content)}>
61
+ {(variant, _index) => {
62
+ const index = _index();
63
+ return (
64
+ <RenderContent
65
+ key={variant.id}
66
+ content={variant}
67
+ apiKey={props.apiKey}
68
+ apiVersion={props.apiVersion}
69
+ canTrack={props.canTrack}
70
+ customComponents={props.customComponents}
71
+ hideContent={true}
72
+ parentContentId={props.content?.id}
73
+ isSsrAbTest={shouldRenderVariants()}
74
+ ></RenderContent>
75
+ );
76
+ }}
77
+ </For>
78
+ </Show>
79
+ <RenderContent
80
+ model={props.model}
81
+ content={contentToRender()}
82
+ apiKey={props.apiKey}
83
+ apiVersion={props.apiVersion}
84
+ canTrack={props.canTrack}
85
+ customComponents={props.customComponents}
86
+ classNameProp={`variant-${props.content?.id}`}
87
+ parentContentId={props.content?.id}
88
+ isSsrAbTest={shouldRenderVariants()}
89
+ ></RenderContent>
90
+ </>
91
+ );
92
+ }
93
+
94
+ export default RenderContentVariants;
@@ -1,27 +1,5 @@
1
- import { Show, createSignal } from "solid-js";
2
- import { Dynamic } from "solid-js/web";
3
-
4
- import { TARGET } from "../constants/target.js";
5
-
6
1
  function RenderInlinedStyles(props) {
7
- function tag() {
8
- // NOTE: we have to obfuscate the name of the tag due to a limitation in the svelte-preprocessor plugin.
9
- // https://github.com/sveltejs/vite-plugin-svelte/issues/315#issuecomment-1109000027
10
- return "sty" + "le";
11
- }
12
-
13
- function injectedStyleScript() {
14
- return `<${tag()}>${props.styles}</${tag()}>`;
15
- }
16
-
17
- return (
18
- <Show
19
- fallback={<Dynamic component={tag()}>{props.styles}</Dynamic>}
20
- when={TARGET === "svelte" || TARGET === "qwik"}
21
- >
22
- <Dynamic innerHTML={props.styles} component={tag()}></Dynamic>
23
- </Show>
24
- );
2
+ return <style innerHTML={props.styles} id={props.id}></style>;
25
3
  }
26
4
 
27
5
  export default RenderInlinedStyles;
@@ -1 +1 @@
1
- export const SDK_VERSION = "0.3.1"
1
+ export const SDK_VERSION = "0.4.0"
@@ -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
  };
@@ -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,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
- };