@builder.io/sdk-svelte 1.0.20 → 1.0.22

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 (63) hide show
  1. package/lib/browser/components/block/animator.d.ts +1 -1
  2. package/lib/browser/components/block/animator.js +1 -35
  3. package/lib/browser/components/block/block.svelte +1 -3
  4. package/lib/browser/components/block/components/block-styles.svelte +24 -1
  5. package/lib/browser/components/content/components/enable-editor.svelte +5 -2
  6. package/lib/browser/constants/sdk-version.d.ts +1 -1
  7. package/lib/browser/constants/sdk-version.js +1 -1
  8. package/lib/browser/functions/evaluate/node-runtime/init.d.ts +10 -0
  9. package/lib/browser/functions/evaluate/node-runtime/init.js +26 -0
  10. package/lib/browser/functions/evaluate/node-runtime/node-runtime.d.ts +6 -0
  11. package/lib/browser/functions/evaluate/node-runtime/node-runtime.js +32 -6
  12. package/lib/browser/functions/get-content/types.d.ts +3 -3
  13. package/lib/browser/functions/is-editing.js +3 -1
  14. package/lib/browser/functions/is-previewing.d.ts +1 -1
  15. package/lib/browser/functions/is-previewing.js +8 -7
  16. package/lib/browser/helpers/logger.d.ts +1 -0
  17. package/lib/browser/helpers/logger.js +1 -1
  18. package/lib/edge/components/block/animator.d.ts +1 -1
  19. package/lib/edge/components/block/animator.js +1 -35
  20. package/lib/edge/components/block/block.svelte +1 -3
  21. package/lib/edge/components/block/components/block-styles.svelte +24 -1
  22. package/lib/edge/components/content/components/enable-editor.svelte +5 -2
  23. package/lib/edge/constants/sdk-version.d.ts +1 -1
  24. package/lib/edge/constants/sdk-version.js +1 -1
  25. package/lib/edge/functions/evaluate/node-runtime/init.d.ts +10 -0
  26. package/lib/edge/functions/evaluate/node-runtime/init.js +26 -0
  27. package/lib/edge/functions/evaluate/node-runtime/node-runtime.d.ts +6 -0
  28. package/lib/edge/functions/evaluate/node-runtime/node-runtime.js +32 -6
  29. package/lib/edge/functions/get-content/types.d.ts +3 -3
  30. package/lib/edge/functions/is-editing.js +3 -1
  31. package/lib/edge/functions/is-previewing.d.ts +1 -1
  32. package/lib/edge/functions/is-previewing.js +8 -7
  33. package/lib/edge/helpers/logger.d.ts +1 -0
  34. package/lib/edge/helpers/logger.js +1 -1
  35. package/lib/node/components/block/animator.d.ts +1 -1
  36. package/lib/node/components/block/animator.js +1 -35
  37. package/lib/node/components/block/block.svelte +1 -3
  38. package/lib/node/components/block/components/block-styles.svelte +24 -1
  39. package/lib/node/components/content/components/enable-editor.svelte +5 -2
  40. package/lib/node/constants/sdk-version.d.ts +1 -1
  41. package/lib/node/constants/sdk-version.js +1 -1
  42. package/lib/node/functions/evaluate/node-runtime/init.d.ts +10 -0
  43. package/lib/node/functions/evaluate/node-runtime/init.js +26 -0
  44. package/lib/node/functions/evaluate/node-runtime/node-runtime.d.ts +6 -0
  45. package/lib/node/functions/evaluate/node-runtime/node-runtime.js +32 -6
  46. package/lib/node/functions/get-content/types.d.ts +3 -3
  47. package/lib/node/functions/is-editing.js +3 -1
  48. package/lib/node/functions/is-previewing.d.ts +1 -1
  49. package/lib/node/functions/is-previewing.js +8 -7
  50. package/lib/node/helpers/logger.d.ts +1 -0
  51. package/lib/node/helpers/logger.js +1 -1
  52. package/package.json +1 -1
  53. package/src/components/block/animator.ts +1 -35
  54. package/src/components/block/block.svelte +4 -6
  55. package/src/components/block/components/block-styles.svelte +27 -1
  56. package/src/components/content/components/enable-editor.svelte +5 -2
  57. package/src/constants/sdk-version.ts +1 -1
  58. package/src/functions/evaluate/node-runtime/init.ts +27 -0
  59. package/src/functions/evaluate/node-runtime/node-runtime.ts +30 -6
  60. package/src/functions/get-content/types.ts +3 -3
  61. package/src/functions/is-editing.ts +3 -1
  62. package/src/functions/is-previewing.ts +9 -7
  63. package/src/helpers/logger.ts +1 -1
@@ -1,5 +1,5 @@
1
1
  import type { BuilderAnimation } from '../../types/builder-block';
2
+ export declare const camelCaseToKebabCase: (str?: string) => string;
2
3
  export declare function bindAnimations(animations: BuilderAnimation[]): void;
3
4
  export declare function triggerAnimation(animation: BuilderAnimation): void;
4
- export declare function bindHoverAnimation(animation: BuilderAnimation): void;
5
5
  export declare function bindScrollInViewAnimation(animation: BuilderAnimation): void;
@@ -54,16 +54,13 @@ function assign(target, ..._args) {
54
54
  }
55
55
  return to;
56
56
  }
57
- const camelCaseToKebabCase = (str) => str ? str.replace(/([A-Z])/g, g => `-${g[0].toLowerCase()}`) : '';
57
+ export const camelCaseToKebabCase = (str) => str ? str.replace(/([A-Z])/g, g => `-${g[0].toLowerCase()}`) : '';
58
58
  export function bindAnimations(animations) {
59
59
  for (const animation of animations) {
60
60
  switch (animation.trigger) {
61
61
  case 'pageLoad':
62
62
  triggerAnimation(animation);
63
63
  break;
64
- case 'hover':
65
- bindHoverAnimation(animation);
66
- break;
67
64
  case 'scrollInView':
68
65
  bindScrollInViewAnimation(animation);
69
66
  break;
@@ -138,37 +135,6 @@ export function triggerAnimation(animation) {
138
135
  });
139
136
  });
140
137
  }
141
- export function bindHoverAnimation(animation) {
142
- // TODO: is it multiple binding when editing...?
143
- // TODO: unbind on element remove
144
- // TODO: apply to ALL elements
145
- const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ''));
146
- if (!elements.length) {
147
- warnElementNotPresent(animation.elementId || animation.id || '');
148
- return;
149
- }
150
- Array.from(elements).forEach(element => {
151
- augmentAnimation(animation, element);
152
- const defaultState = animation.steps[0].styles;
153
- const hoverState = animation.steps[1].styles;
154
- function attachDefaultState() {
155
- assign(element.style, defaultState);
156
- }
157
- function attachHoverState() {
158
- assign(element.style, hoverState);
159
- }
160
- attachDefaultState();
161
- element.addEventListener('mouseenter', attachHoverState);
162
- element.addEventListener('mouseleave', attachDefaultState);
163
- // TODO: queue/batch these timeouts
164
- setTimeout(() => {
165
- element.style.transition = `all ${animation.duration}s ${camelCaseToKebabCase(animation.easing)}`;
166
- if (animation.delay) {
167
- element.style.transitionDelay = animation.delay + 's';
168
- }
169
- });
170
- });
171
- }
172
138
  // TODO: unbind on element remove
173
139
  export function bindScrollInViewAnimation(animation) {
174
140
  // TODO: apply to ALL matching elements
@@ -104,9 +104,7 @@ onMount(() => {
104
104
  const blockId = processedBlock().id;
105
105
  const animations = processedBlock().animations;
106
106
  if (animations && blockId) {
107
- bindAnimations(animations
108
- .filter((item) => item.trigger !== "hover")
109
- .map((animation) => ({
107
+ bindAnimations(animations.map((animation) => ({
110
108
  ...animation,
111
109
  elementId: blockId,
112
110
  })));
@@ -6,6 +6,7 @@ import { getProcessedBlock } from "../../../functions/get-processed-block";
6
6
  import { createCssClass } from "../../../helpers/css";
7
7
  import { checkIsDefined } from "../../../helpers/nullable";
8
8
  import InlinedStyles from "../../inlined-styles.svelte";
9
+ import { camelCaseToKebabCase } from "../animator";
9
10
  export let block;
10
11
  export let context;
11
12
  $: canShowBlock = () => {
@@ -65,7 +66,29 @@ $: css = () => {
65
66
  mediaQuery: getMaxWidthQueryForSize("small", sizesWithUpdatedBreakpoints),
66
67
  })
67
68
  : "";
68
- return [largeStylesClass, mediumStylesClass, smallStylesClass].join(" ");
69
+ const hoverAnimation = processedBlock.animations &&
70
+ processedBlock.animations.find((item) => item.trigger === "hover");
71
+ let hoverStylesClass = "";
72
+ if (hoverAnimation) {
73
+ const hoverStyles = hoverAnimation.steps?.[1]?.styles || {};
74
+ hoverStylesClass =
75
+ createCssClass({
76
+ className: `${className}:hover`,
77
+ styles: {
78
+ ...hoverStyles,
79
+ transition: `all ${hoverAnimation.duration}s ${camelCaseToKebabCase(hoverAnimation.easing)}`,
80
+ transitionDelay: hoverAnimation.delay
81
+ ? `${hoverAnimation.delay}s`
82
+ : "0s",
83
+ },
84
+ }) || "";
85
+ }
86
+ return [
87
+ largeStylesClass,
88
+ mediumStylesClass,
89
+ smallStylesClass,
90
+ hoverStylesClass,
91
+ ].join(" ");
69
92
  };
70
93
  </script>
71
94
 
@@ -249,8 +249,11 @@ onMount(() => {
249
249
  variationId: variationId !== contentId ? variationId : undefined,
250
250
  });
251
251
  }
252
- // override normal content in preview mode
253
- if (isPreviewing()) {
252
+ /**
253
+ * Override normal content in preview mode.
254
+ * We ignore this when editing, since the edited content is already being sent from the editor via post messages.
255
+ */
256
+ if (isPreviewing() && !isEditing()) {
254
257
  if (elementRef) {
255
258
  elementRef.dispatchEvent(new CustomEvent("initpreviewingbldr"));
256
259
  }
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "1.0.20";
1
+ export declare const SDK_VERSION = "1.0.22";
@@ -1 +1 @@
1
- export const SDK_VERSION = "1.0.20";
1
+ export const SDK_VERSION = "1.0.22";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * This function initializes the SDK on a Node server. It handles importing the
3
+ * `isolated-vm` package which is needed for dynamic bindings.
4
+ *
5
+ * NOTE: this function cannot be called on the client. You must call this function
6
+ * from a server-only location, such as:
7
+ * - The NextJS Pages router's `_document.tsx`
8
+ * - Your Remix route's `loader`
9
+ */
10
+ export declare const initializeNodeRuntime: () => void;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * This file:
3
+ * - imports `isolated-vm`, which can only be made from a file that never runs
4
+ * on the client (e.g. Next's `_document.tsx`)
5
+ * - stores the ivm instance in a global variable using `setIvm`
6
+ *
7
+ * This is needed for when bundlers/meta-frameworks are not able to reliably
8
+ * import the `isolated-vm` package using our `safeDynamicRequire` trick.
9
+ *
10
+ * The `isolated-vm` import must exist in this separate file, or it will end up
11
+ * in the SDK's main entry point, causing errors for users.
12
+ */
13
+ import ivm from 'isolated-vm';
14
+ import { setIvm } from './node-runtime';
15
+ /**
16
+ * This function initializes the SDK on a Node server. It handles importing the
17
+ * `isolated-vm` package which is needed for dynamic bindings.
18
+ *
19
+ * NOTE: this function cannot be called on the client. You must call this function
20
+ * from a server-only location, such as:
21
+ * - The NextJS Pages router's `_document.tsx`
22
+ * - Your Remix route's `loader`
23
+ */
24
+ export const initializeNodeRuntime = () => {
25
+ setIvm(ivm);
26
+ };
@@ -1,2 +1,8 @@
1
1
  import type { ExecutorArgs } from '../helpers';
2
+ /**
3
+ * Set the `isolated-vm` instance to be used by the node runtime.
4
+ * This is useful for environments that are not able to rely on our
5
+ * `safeDynamicRequire` trick to import the `isolated-vm` package.
6
+ */
7
+ export declare const setIvm: (ivm: typeof import('isolated-vm')) => void;
2
8
  export declare const runInNode: ({ code, builder, context, event, localState, rootSetState, rootState }: ExecutorArgs) => any;
@@ -1,3 +1,4 @@
1
+ import { MSG_PREFIX, logger } from '../../../helpers/logger';
1
2
  import { fastClone } from '../../fast-clone';
2
3
  import { set } from '../../set';
3
4
  import { getFunctionArguments } from '../helpers';
@@ -53,19 +54,44 @@ if (typeof output === 'object' && output !== null) {
53
54
  output;
54
55
  `;
55
56
  };
57
+ let IVM_INSTANCE = null;
58
+ /**
59
+ * Set the `isolated-vm` instance to be used by the node runtime.
60
+ * This is useful for environments that are not able to rely on our
61
+ * `safeDynamicRequire` trick to import the `isolated-vm` package.
62
+ */
63
+ export const setIvm = (ivm) => {
64
+ IVM_INSTANCE = ivm;
65
+ };
66
+ const getIvm = () => {
67
+ try {
68
+ if (IVM_INSTANCE)
69
+ return IVM_INSTANCE;
70
+ const dynRequiredIvm = safeDynamicRequire('isolated-vm');
71
+ if (dynRequiredIvm)
72
+ return dynRequiredIvm;
73
+ }
74
+ catch (error) {
75
+ logger.error('isolated-vm import error.', error);
76
+ }
77
+ throw new Error(`${MSG_PREFIX}could not import \`isolated-vm\` module for safe script execution on Node server.
78
+
79
+ In certain Node environments, the SDK requires additional initialization steps. This can be achieved by
80
+ importing and calling \`initializeNodeRuntime()\` from "@builder.io/sdk-react/node/init". This must be done in
81
+ a server-only execution path within your application.
82
+
83
+ Please see the documentation for more information: https://builder.io/c/docs/integration-tips#enabling-data-bindings-in-node-environments
84
+ `);
85
+ };
56
86
  const getIsolateContext = () => {
57
- // if (Builder.serverContext) {
58
- // return Builder.serverContext;
59
- // }
60
- // Builder.setServerContext(isolate.createContextSync());
61
- const ivm = safeDynamicRequire('isolated-vm');
87
+ const ivm = getIvm();
62
88
  const isolate = new ivm.Isolate({
63
89
  memoryLimit: 128
64
90
  });
65
91
  return isolate.createContextSync();
66
92
  };
67
93
  export const runInNode = ({ code, builder, context, event, localState, rootSetState, rootState }) => {
68
- const ivm = safeDynamicRequire('isolated-vm');
94
+ const ivm = getIvm();
69
95
  const state = fastClone({
70
96
  ...rootState,
71
97
  ...localState
@@ -131,9 +131,9 @@ export interface GetContentOptions {
131
131
  /**
132
132
  * Optional override of the `fetch` function. (Defaults to global `fetch`)
133
133
  */
134
- fetch?: typeof global.fetch;
134
+ fetch?: (input: string, init?: object) => Promise<any>;
135
135
  /**
136
- * Optional fetch options to be passed to the `fetch` function.
136
+ * Optional fetch options to be passed as the second argument to the `fetch` function.
137
137
  */
138
- fetchOptions?: RequestInit;
138
+ fetchOptions?: object;
139
139
  }
@@ -2,5 +2,7 @@ import { TARGET } from '../constants/target';
2
2
  import { getSearchString } from '../helpers/search/search';
3
3
  import { isIframe } from './is-iframe';
4
4
  export function isEditing(search) {
5
- return isIframe() && (TARGET === 'reactNative' || getSearchString(search || window.location.search).indexOf('builder.frameEditing=') !== -1);
5
+ return isIframe() && (TARGET === 'reactNative' ||
6
+ // accessing window.location.search is safe here because `isIframe()` is only `true` if we're in a browser.
7
+ getSearchString(search || window.location.search).indexOf('builder.frameEditing=') !== -1);
6
8
  }
@@ -1,2 +1,2 @@
1
1
  import type { Search } from '../helpers/search/search';
2
- export declare function isPreviewing(search?: Search): boolean;
2
+ export declare function isPreviewing(_search?: Search): boolean;
@@ -1,13 +1,14 @@
1
1
  import { getSearchString } from '../helpers/search/search';
2
2
  import { isBrowser } from './is-browser';
3
- import { isEditing } from './is-editing';
4
- export function isPreviewing(search) {
5
- if (!isBrowser()) {
6
- return false;
7
- }
8
- const normalizedSearch = getSearchString(search || window.location.search);
9
- if (isEditing(normalizedSearch)) {
3
+ export function isPreviewing(_search) {
4
+ const search = _search || (isBrowser() ? window.location.search : undefined);
5
+ /**
6
+ * If this function is called on the server without an explicit `search` argument,
7
+ * then it can't check if the user is previewing, and will return `false`.
8
+ */
9
+ if (!search) {
10
10
  return false;
11
11
  }
12
+ const normalizedSearch = getSearchString(search);
12
13
  return Boolean(normalizedSearch.indexOf('builder.preview=') !== -1);
13
14
  }
@@ -1,3 +1,4 @@
1
+ export declare const MSG_PREFIX = "[Builder.io]: ";
1
2
  export declare const logger: {
2
3
  log: (...message: any[]) => void;
3
4
  error: (...message: any[]) => void;
@@ -1,4 +1,4 @@
1
- const MSG_PREFIX = '[Builder.io]: ';
1
+ export const MSG_PREFIX = '[Builder.io]: ';
2
2
  export const logger = {
3
3
  log: (...message) => console.log(MSG_PREFIX, ...message),
4
4
  error: (...message) => console.error(MSG_PREFIX, ...message),
@@ -1,5 +1,5 @@
1
1
  import type { BuilderAnimation } from '../../types/builder-block';
2
+ export declare const camelCaseToKebabCase: (str?: string) => string;
2
3
  export declare function bindAnimations(animations: BuilderAnimation[]): void;
3
4
  export declare function triggerAnimation(animation: BuilderAnimation): void;
4
- export declare function bindHoverAnimation(animation: BuilderAnimation): void;
5
5
  export declare function bindScrollInViewAnimation(animation: BuilderAnimation): void;
@@ -54,16 +54,13 @@ function assign(target, ..._args) {
54
54
  }
55
55
  return to;
56
56
  }
57
- const camelCaseToKebabCase = (str) => str ? str.replace(/([A-Z])/g, g => `-${g[0].toLowerCase()}`) : '';
57
+ export const camelCaseToKebabCase = (str) => str ? str.replace(/([A-Z])/g, g => `-${g[0].toLowerCase()}`) : '';
58
58
  export function bindAnimations(animations) {
59
59
  for (const animation of animations) {
60
60
  switch (animation.trigger) {
61
61
  case 'pageLoad':
62
62
  triggerAnimation(animation);
63
63
  break;
64
- case 'hover':
65
- bindHoverAnimation(animation);
66
- break;
67
64
  case 'scrollInView':
68
65
  bindScrollInViewAnimation(animation);
69
66
  break;
@@ -138,37 +135,6 @@ export function triggerAnimation(animation) {
138
135
  });
139
136
  });
140
137
  }
141
- export function bindHoverAnimation(animation) {
142
- // TODO: is it multiple binding when editing...?
143
- // TODO: unbind on element remove
144
- // TODO: apply to ALL elements
145
- const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ''));
146
- if (!elements.length) {
147
- warnElementNotPresent(animation.elementId || animation.id || '');
148
- return;
149
- }
150
- Array.from(elements).forEach(element => {
151
- augmentAnimation(animation, element);
152
- const defaultState = animation.steps[0].styles;
153
- const hoverState = animation.steps[1].styles;
154
- function attachDefaultState() {
155
- assign(element.style, defaultState);
156
- }
157
- function attachHoverState() {
158
- assign(element.style, hoverState);
159
- }
160
- attachDefaultState();
161
- element.addEventListener('mouseenter', attachHoverState);
162
- element.addEventListener('mouseleave', attachDefaultState);
163
- // TODO: queue/batch these timeouts
164
- setTimeout(() => {
165
- element.style.transition = `all ${animation.duration}s ${camelCaseToKebabCase(animation.easing)}`;
166
- if (animation.delay) {
167
- element.style.transitionDelay = animation.delay + 's';
168
- }
169
- });
170
- });
171
- }
172
138
  // TODO: unbind on element remove
173
139
  export function bindScrollInViewAnimation(animation) {
174
140
  // TODO: apply to ALL matching elements
@@ -104,9 +104,7 @@ onMount(() => {
104
104
  const blockId = processedBlock().id;
105
105
  const animations = processedBlock().animations;
106
106
  if (animations && blockId) {
107
- bindAnimations(animations
108
- .filter((item) => item.trigger !== "hover")
109
- .map((animation) => ({
107
+ bindAnimations(animations.map((animation) => ({
110
108
  ...animation,
111
109
  elementId: blockId,
112
110
  })));
@@ -6,6 +6,7 @@ import { getProcessedBlock } from "../../../functions/get-processed-block";
6
6
  import { createCssClass } from "../../../helpers/css";
7
7
  import { checkIsDefined } from "../../../helpers/nullable";
8
8
  import InlinedStyles from "../../inlined-styles.svelte";
9
+ import { camelCaseToKebabCase } from "../animator";
9
10
  export let block;
10
11
  export let context;
11
12
  $: canShowBlock = () => {
@@ -65,7 +66,29 @@ $: css = () => {
65
66
  mediaQuery: getMaxWidthQueryForSize("small", sizesWithUpdatedBreakpoints),
66
67
  })
67
68
  : "";
68
- return [largeStylesClass, mediumStylesClass, smallStylesClass].join(" ");
69
+ const hoverAnimation = processedBlock.animations &&
70
+ processedBlock.animations.find((item) => item.trigger === "hover");
71
+ let hoverStylesClass = "";
72
+ if (hoverAnimation) {
73
+ const hoverStyles = hoverAnimation.steps?.[1]?.styles || {};
74
+ hoverStylesClass =
75
+ createCssClass({
76
+ className: `${className}:hover`,
77
+ styles: {
78
+ ...hoverStyles,
79
+ transition: `all ${hoverAnimation.duration}s ${camelCaseToKebabCase(hoverAnimation.easing)}`,
80
+ transitionDelay: hoverAnimation.delay
81
+ ? `${hoverAnimation.delay}s`
82
+ : "0s",
83
+ },
84
+ }) || "";
85
+ }
86
+ return [
87
+ largeStylesClass,
88
+ mediumStylesClass,
89
+ smallStylesClass,
90
+ hoverStylesClass,
91
+ ].join(" ");
69
92
  };
70
93
  </script>
71
94
 
@@ -249,8 +249,11 @@ onMount(() => {
249
249
  variationId: variationId !== contentId ? variationId : undefined,
250
250
  });
251
251
  }
252
- // override normal content in preview mode
253
- if (isPreviewing()) {
252
+ /**
253
+ * Override normal content in preview mode.
254
+ * We ignore this when editing, since the edited content is already being sent from the editor via post messages.
255
+ */
256
+ if (isPreviewing() && !isEditing()) {
254
257
  if (elementRef) {
255
258
  elementRef.dispatchEvent(new CustomEvent("initpreviewingbldr"));
256
259
  }
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "1.0.20";
1
+ export declare const SDK_VERSION = "1.0.22";
@@ -1 +1 @@
1
- export const SDK_VERSION = "1.0.20";
1
+ export const SDK_VERSION = "1.0.22";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * This function initializes the SDK on a Node server. It handles importing the
3
+ * `isolated-vm` package which is needed for dynamic bindings.
4
+ *
5
+ * NOTE: this function cannot be called on the client. You must call this function
6
+ * from a server-only location, such as:
7
+ * - The NextJS Pages router's `_document.tsx`
8
+ * - Your Remix route's `loader`
9
+ */
10
+ export declare const initializeNodeRuntime: () => void;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * This file:
3
+ * - imports `isolated-vm`, which can only be made from a file that never runs
4
+ * on the client (e.g. Next's `_document.tsx`)
5
+ * - stores the ivm instance in a global variable using `setIvm`
6
+ *
7
+ * This is needed for when bundlers/meta-frameworks are not able to reliably
8
+ * import the `isolated-vm` package using our `safeDynamicRequire` trick.
9
+ *
10
+ * The `isolated-vm` import must exist in this separate file, or it will end up
11
+ * in the SDK's main entry point, causing errors for users.
12
+ */
13
+ import ivm from 'isolated-vm';
14
+ import { setIvm } from './node-runtime';
15
+ /**
16
+ * This function initializes the SDK on a Node server. It handles importing the
17
+ * `isolated-vm` package which is needed for dynamic bindings.
18
+ *
19
+ * NOTE: this function cannot be called on the client. You must call this function
20
+ * from a server-only location, such as:
21
+ * - The NextJS Pages router's `_document.tsx`
22
+ * - Your Remix route's `loader`
23
+ */
24
+ export const initializeNodeRuntime = () => {
25
+ setIvm(ivm);
26
+ };
@@ -1,2 +1,8 @@
1
1
  import type { ExecutorArgs } from '../helpers';
2
+ /**
3
+ * Set the `isolated-vm` instance to be used by the node runtime.
4
+ * This is useful for environments that are not able to rely on our
5
+ * `safeDynamicRequire` trick to import the `isolated-vm` package.
6
+ */
7
+ export declare const setIvm: (ivm: typeof import('isolated-vm')) => void;
2
8
  export declare const runInNode: ({ code, builder, context, event, localState, rootSetState, rootState }: ExecutorArgs) => any;
@@ -1,3 +1,4 @@
1
+ import { MSG_PREFIX, logger } from '../../../helpers/logger';
1
2
  import { fastClone } from '../../fast-clone';
2
3
  import { set } from '../../set';
3
4
  import { getFunctionArguments } from '../helpers';
@@ -53,19 +54,44 @@ if (typeof output === 'object' && output !== null) {
53
54
  output;
54
55
  `;
55
56
  };
57
+ let IVM_INSTANCE = null;
58
+ /**
59
+ * Set the `isolated-vm` instance to be used by the node runtime.
60
+ * This is useful for environments that are not able to rely on our
61
+ * `safeDynamicRequire` trick to import the `isolated-vm` package.
62
+ */
63
+ export const setIvm = (ivm) => {
64
+ IVM_INSTANCE = ivm;
65
+ };
66
+ const getIvm = () => {
67
+ try {
68
+ if (IVM_INSTANCE)
69
+ return IVM_INSTANCE;
70
+ const dynRequiredIvm = safeDynamicRequire('isolated-vm');
71
+ if (dynRequiredIvm)
72
+ return dynRequiredIvm;
73
+ }
74
+ catch (error) {
75
+ logger.error('isolated-vm import error.', error);
76
+ }
77
+ throw new Error(`${MSG_PREFIX}could not import \`isolated-vm\` module for safe script execution on Node server.
78
+
79
+ In certain Node environments, the SDK requires additional initialization steps. This can be achieved by
80
+ importing and calling \`initializeNodeRuntime()\` from "@builder.io/sdk-react/node/init". This must be done in
81
+ a server-only execution path within your application.
82
+
83
+ Please see the documentation for more information: https://builder.io/c/docs/integration-tips#enabling-data-bindings-in-node-environments
84
+ `);
85
+ };
56
86
  const getIsolateContext = () => {
57
- // if (Builder.serverContext) {
58
- // return Builder.serverContext;
59
- // }
60
- // Builder.setServerContext(isolate.createContextSync());
61
- const ivm = safeDynamicRequire('isolated-vm');
87
+ const ivm = getIvm();
62
88
  const isolate = new ivm.Isolate({
63
89
  memoryLimit: 128
64
90
  });
65
91
  return isolate.createContextSync();
66
92
  };
67
93
  export const runInNode = ({ code, builder, context, event, localState, rootSetState, rootState }) => {
68
- const ivm = safeDynamicRequire('isolated-vm');
94
+ const ivm = getIvm();
69
95
  const state = fastClone({
70
96
  ...rootState,
71
97
  ...localState
@@ -131,9 +131,9 @@ export interface GetContentOptions {
131
131
  /**
132
132
  * Optional override of the `fetch` function. (Defaults to global `fetch`)
133
133
  */
134
- fetch?: typeof global.fetch;
134
+ fetch?: (input: string, init?: object) => Promise<any>;
135
135
  /**
136
- * Optional fetch options to be passed to the `fetch` function.
136
+ * Optional fetch options to be passed as the second argument to the `fetch` function.
137
137
  */
138
- fetchOptions?: RequestInit;
138
+ fetchOptions?: object;
139
139
  }
@@ -2,5 +2,7 @@ import { TARGET } from '../constants/target';
2
2
  import { getSearchString } from '../helpers/search/search';
3
3
  import { isIframe } from './is-iframe';
4
4
  export function isEditing(search) {
5
- return isIframe() && (TARGET === 'reactNative' || getSearchString(search || window.location.search).indexOf('builder.frameEditing=') !== -1);
5
+ return isIframe() && (TARGET === 'reactNative' ||
6
+ // accessing window.location.search is safe here because `isIframe()` is only `true` if we're in a browser.
7
+ getSearchString(search || window.location.search).indexOf('builder.frameEditing=') !== -1);
6
8
  }
@@ -1,2 +1,2 @@
1
1
  import type { Search } from '../helpers/search/search';
2
- export declare function isPreviewing(search?: Search): boolean;
2
+ export declare function isPreviewing(_search?: Search): boolean;
@@ -1,13 +1,14 @@
1
1
  import { getSearchString } from '../helpers/search/search';
2
2
  import { isBrowser } from './is-browser';
3
- import { isEditing } from './is-editing';
4
- export function isPreviewing(search) {
5
- if (!isBrowser()) {
6
- return false;
7
- }
8
- const normalizedSearch = getSearchString(search || window.location.search);
9
- if (isEditing(normalizedSearch)) {
3
+ export function isPreviewing(_search) {
4
+ const search = _search || (isBrowser() ? window.location.search : undefined);
5
+ /**
6
+ * If this function is called on the server without an explicit `search` argument,
7
+ * then it can't check if the user is previewing, and will return `false`.
8
+ */
9
+ if (!search) {
10
10
  return false;
11
11
  }
12
+ const normalizedSearch = getSearchString(search);
12
13
  return Boolean(normalizedSearch.indexOf('builder.preview=') !== -1);
13
14
  }
@@ -1,3 +1,4 @@
1
+ export declare const MSG_PREFIX = "[Builder.io]: ";
1
2
  export declare const logger: {
2
3
  log: (...message: any[]) => void;
3
4
  error: (...message: any[]) => void;
@@ -1,4 +1,4 @@
1
- const MSG_PREFIX = '[Builder.io]: ';
1
+ export const MSG_PREFIX = '[Builder.io]: ';
2
2
  export const logger = {
3
3
  log: (...message) => console.log(MSG_PREFIX, ...message),
4
4
  error: (...message) => console.error(MSG_PREFIX, ...message),
@@ -1,5 +1,5 @@
1
1
  import type { BuilderAnimation } from '../../types/builder-block';
2
+ export declare const camelCaseToKebabCase: (str?: string) => string;
2
3
  export declare function bindAnimations(animations: BuilderAnimation[]): void;
3
4
  export declare function triggerAnimation(animation: BuilderAnimation): void;
4
- export declare function bindHoverAnimation(animation: BuilderAnimation): void;
5
5
  export declare function bindScrollInViewAnimation(animation: BuilderAnimation): void;