@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
@@ -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),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@builder.io/sdk-svelte",
3
3
  "description": "Builder.io SDK for Svelte",
4
- "version": "1.0.20",
4
+ "version": "1.0.22",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "lib",
@@ -52,16 +52,13 @@ function assign(target: object, ..._args: any[]) {
52
52
  }
53
53
  return to;
54
54
  }
55
- const camelCaseToKebabCase = (str?: string) => str ? str.replace(/([A-Z])/g, g => `-${g[0].toLowerCase()}`) : '';
55
+ export const camelCaseToKebabCase = (str?: string) => str ? str.replace(/([A-Z])/g, g => `-${g[0].toLowerCase()}`) : '';
56
56
  export function bindAnimations(animations: BuilderAnimation[]) {
57
57
  for (const animation of animations) {
58
58
  switch (animation.trigger) {
59
59
  case 'pageLoad':
60
60
  triggerAnimation(animation);
61
61
  break;
62
- case 'hover':
63
- bindHoverAnimation(animation);
64
- break;
65
62
  case 'scrollInView':
66
63
  bindScrollInViewAnimation(animation);
67
64
  break;
@@ -140,37 +137,6 @@ export function triggerAnimation(animation: BuilderAnimation) {
140
137
  });
141
138
  });
142
139
  }
143
- export function bindHoverAnimation(animation: BuilderAnimation) {
144
- // TODO: is it multiple binding when editing...?
145
- // TODO: unbind on element remove
146
- // TODO: apply to ALL elements
147
- const elements = (Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || '')) as HTMLElement[]);
148
- if (!elements.length) {
149
- warnElementNotPresent(animation.elementId || animation.id || '');
150
- return;
151
- }
152
- Array.from(elements).forEach(element => {
153
- augmentAnimation(animation, element);
154
- const defaultState = animation.steps[0].styles;
155
- const hoverState = animation.steps[1].styles;
156
- function attachDefaultState() {
157
- assign(element!.style, defaultState);
158
- }
159
- function attachHoverState() {
160
- assign(element!.style, hoverState);
161
- }
162
- attachDefaultState();
163
- element.addEventListener('mouseenter', attachHoverState);
164
- element.addEventListener('mouseleave', attachDefaultState);
165
- // TODO: queue/batch these timeouts
166
- setTimeout(() => {
167
- element.style.transition = `all ${animation.duration}s ${camelCaseToKebabCase(animation.easing)}`;
168
- if (animation.delay) {
169
- element.style.transitionDelay = animation.delay + 's';
170
- }
171
- });
172
- });
173
- }
174
140
 
175
141
  // TODO: unbind on element remove
176
142
  export function bindScrollInViewAnimation(animation: BuilderAnimation) {
@@ -131,12 +131,10 @@
131
131
  const animations = processedBlock().animations;
132
132
  if (animations && blockId) {
133
133
  bindAnimations(
134
- animations
135
- .filter((item) => item.trigger !== "hover")
136
- .map((animation) => ({
137
- ...animation,
138
- elementId: blockId,
139
- }))
134
+ animations.map((animation) => ({
135
+ ...animation,
136
+ elementId: blockId,
137
+ }))
140
138
  );
141
139
  }
142
140
  });
@@ -17,6 +17,7 @@
17
17
  import { checkIsDefined } from "../../../helpers/nullable";
18
18
  import type { BuilderBlock } from "../../../types/builder-block";
19
19
  import InlinedStyles from "../../inlined-styles.svelte";
20
+ import { camelCaseToKebabCase } from "../animator";
20
21
 
21
22
  export let block: BlockStylesProps["block"];
22
23
  export let context: BlockStylesProps["context"];
@@ -86,7 +87,32 @@
86
87
  ),
87
88
  })
88
89
  : "";
89
- return [largeStylesClass, mediumStylesClass, smallStylesClass].join(" ");
90
+ const hoverAnimation =
91
+ processedBlock.animations &&
92
+ processedBlock.animations.find((item) => item.trigger === "hover");
93
+ let hoverStylesClass = "";
94
+ if (hoverAnimation) {
95
+ const hoverStyles = hoverAnimation.steps?.[1]?.styles || {};
96
+ hoverStylesClass =
97
+ createCssClass({
98
+ className: `${className}:hover`,
99
+ styles: {
100
+ ...hoverStyles,
101
+ transition: `all ${hoverAnimation.duration}s ${camelCaseToKebabCase(
102
+ hoverAnimation.easing
103
+ )}`,
104
+ transitionDelay: hoverAnimation.delay
105
+ ? `${hoverAnimation.delay}s`
106
+ : "0s",
107
+ },
108
+ }) || "";
109
+ }
110
+ return [
111
+ largeStylesClass,
112
+ mediumStylesClass,
113
+ smallStylesClass,
114
+ hoverStylesClass,
115
+ ].join(" ");
90
116
  };
91
117
  </script>
92
118
 
@@ -306,8 +306,11 @@
306
306
  });
307
307
  }
308
308
 
309
- // override normal content in preview mode
310
- if (isPreviewing()) {
309
+ /**
310
+ * Override normal content in preview mode.
311
+ * We ignore this when editing, since the edited content is already being sent from the editor via post messages.
312
+ */
313
+ if (isPreviewing() && !isEditing()) {
311
314
  if (elementRef) {
312
315
  elementRef.dispatchEvent(new CustomEvent("initpreviewingbldr"));
313
316
  }
@@ -1 +1 @@
1
- export const SDK_VERSION = "1.0.20"
1
+ export const SDK_VERSION = "1.0.22"
@@ -0,0 +1,27 @@
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
+ /**
17
+ * This function initializes the SDK on a Node server. It handles importing the
18
+ * `isolated-vm` package which is needed for dynamic bindings.
19
+ *
20
+ * NOTE: this function cannot be called on the client. You must call this function
21
+ * from a server-only location, such as:
22
+ * - The NextJS Pages router's `_document.tsx`
23
+ * - Your Remix route's `loader`
24
+ */
25
+ export const initializeNodeRuntime = () => {
26
+ setIvm(ivm);
27
+ }
@@ -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 type { BuilderGlobals, ExecutorArgs, FunctionArguments } from '../helpers';
@@ -62,12 +63,35 @@ if (typeof output === 'object' && output !== null) {
62
63
  output;
63
64
  `;
64
65
  };
66
+ let IVM_INSTANCE: typeof import('isolated-vm') | null = null;
67
+
68
+ /**
69
+ * Set the `isolated-vm` instance to be used by the node runtime.
70
+ * This is useful for environments that are not able to rely on our
71
+ * `safeDynamicRequire` trick to import the `isolated-vm` package.
72
+ */
73
+ export const setIvm = (ivm: typeof import('isolated-vm')) => {
74
+ IVM_INSTANCE = ivm;
75
+ };
76
+ const getIvm = (): typeof import('isolated-vm') => {
77
+ try {
78
+ if (IVM_INSTANCE) return IVM_INSTANCE;
79
+ const dynRequiredIvm = safeDynamicRequire('isolated-vm');
80
+ if (dynRequiredIvm) return dynRequiredIvm;
81
+ } catch (error) {
82
+ logger.error('isolated-vm import error.', error);
83
+ }
84
+ throw new Error(`${MSG_PREFIX}could not import \`isolated-vm\` module for safe script execution on Node server.
85
+
86
+ In certain Node environments, the SDK requires additional initialization steps. This can be achieved by
87
+ importing and calling \`initializeNodeRuntime()\` from "@builder.io/sdk-react/node/init". This must be done in
88
+ a server-only execution path within your application.
89
+
90
+ Please see the documentation for more information: https://builder.io/c/docs/integration-tips#enabling-data-bindings-in-node-environments
91
+ `);
92
+ };
65
93
  const getIsolateContext = () => {
66
- // if (Builder.serverContext) {
67
- // return Builder.serverContext;
68
- // }
69
- // Builder.setServerContext(isolate.createContextSync());
70
- const ivm: typeof import('isolated-vm') = safeDynamicRequire('isolated-vm');
94
+ const ivm = getIvm();
71
95
  const isolate = new ivm.Isolate({
72
96
  memoryLimit: 128
73
97
  });
@@ -82,7 +106,7 @@ export const runInNode = ({
82
106
  rootSetState,
83
107
  rootState
84
108
  }: ExecutorArgs) => {
85
- const ivm: typeof import('isolated-vm') = safeDynamicRequire('isolated-vm');
109
+ const ivm = getIvm();
86
110
  const state = fastClone({
87
111
  ...rootState,
88
112
  ...localState
@@ -148,10 +148,10 @@ export interface GetContentOptions {
148
148
  /**
149
149
  * Optional override of the `fetch` function. (Defaults to global `fetch`)
150
150
  */
151
- fetch?: typeof global.fetch;
151
+ fetch?: (input: string, init?: object) => Promise<any>;
152
152
 
153
153
  /**
154
- * Optional fetch options to be passed to the `fetch` function.
154
+ * Optional fetch options to be passed as the second argument to the `fetch` function.
155
155
  */
156
- fetchOptions?: RequestInit;
156
+ fetchOptions?: object;
157
157
  }
@@ -2,5 +2,7 @@ import { TARGET } from '../constants/target';
2
2
  import { getSearchString, type Search } from '../helpers/search/search';
3
3
  import { isIframe } from './is-iframe';
4
4
  export function isEditing(search?: 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,14 +1,16 @@
1
1
  import type { Search } from '../helpers/search/search';
2
2
  import { getSearchString } from '../helpers/search/search';
3
3
  import { isBrowser } from './is-browser';
4
- import { isEditing } from './is-editing';
5
- export function isPreviewing(search?: Search) {
6
- if (!isBrowser()) {
7
- return false;
8
- }
9
- const normalizedSearch = getSearchString(search || window.location.search);
10
- if (isEditing(normalizedSearch)) {
4
+ export function isPreviewing(_search?: Search) {
5
+ const search = _search || (isBrowser() ? window.location.search : undefined);
6
+
7
+ /**
8
+ * If this function is called on the server without an explicit `search` argument,
9
+ * then it can't check if the user is previewing, and will return `false`.
10
+ */
11
+ if (!search) {
11
12
  return false;
12
13
  }
14
+ const normalizedSearch = getSearchString(search);
13
15
  return Boolean(normalizedSearch.indexOf('builder.preview=') !== -1);
14
16
  }
@@ -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: any[]) => console.log(MSG_PREFIX, ...message),
4
4
  error: (...message: any[]) => console.error(MSG_PREFIX, ...message),