@builder.io/sdk-solid 5.1.0 → 5.1.1

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/lib/edge/dev.jsx CHANGED
@@ -216,139 +216,430 @@ var getUserAttributes = () => {
216
216
  };
217
217
  };
218
218
 
219
- // src/functions/evaluate/helpers.ts
220
- var getFunctionArguments = ({
221
- builder,
222
- context,
223
- event,
224
- state
219
+ // src/constants/sdk-version.ts
220
+ var SDK_VERSION = "5.1.1";
221
+
222
+ // src/helpers/sdk-headers.ts
223
+ var getSdkHeaders = () => ({
224
+ "X-Builder-SDK": TARGET,
225
+ "X-Builder-SDK-GEN": "2",
226
+ "X-Builder-SDK-Version": SDK_VERSION
227
+ });
228
+
229
+ // src/helpers/nullable.ts
230
+ var checkIsDefined = (maybeT) => maybeT !== null && maybeT !== void 0;
231
+
232
+ // src/helpers/url.ts
233
+ var getTopLevelDomain = (host) => {
234
+ if (host === "localhost" || host === "127.0.0.1") {
235
+ return host;
236
+ }
237
+ const parts = host.split(".");
238
+ if (parts.length > 2) {
239
+ return parts.slice(1).join(".");
240
+ }
241
+ return host;
242
+ };
243
+
244
+ // src/helpers/cookie.ts
245
+ var getCookieSync = ({
246
+ name,
247
+ canTrack
225
248
  }) => {
226
- return Object.entries({
227
- state,
228
- Builder: builder,
229
- // legacy
230
- builder,
231
- context,
232
- event
233
- });
249
+ try {
250
+ if (!canTrack) {
251
+ return void 0;
252
+ }
253
+ return document.cookie.split("; ").find((row) => row.startsWith(`${name}=`))?.split("=")[1];
254
+ } catch (err) {
255
+ logger.warn("[COOKIE] GET error: ", err?.message || err);
256
+ return void 0;
257
+ }
234
258
  };
235
- var getBuilderGlobals = () => ({
236
- isEditing: isEditing(),
237
- isBrowser: isBrowser(),
238
- isServer: !isBrowser(),
239
- getUserAttributes: () => getUserAttributes()
240
- });
241
- var parseCode = (code, {
242
- isExpression = true
259
+ var getCookie = async (args) => getCookieSync(args);
260
+ var stringifyCookie = (cookie) => cookie.map(([key, value]) => value ? `${key}=${value}` : key).filter(checkIsDefined).join("; ");
261
+ var SECURE_CONFIG = [["secure", ""], ["SameSite", "None"]];
262
+ var createCookieString = ({
263
+ name,
264
+ value,
265
+ expires
243
266
  }) => {
244
- const useReturn = (
245
- // we disable this for cases where we definitely don't want a return
246
- isExpression && !(code.includes(";") || code.includes(" return ") || code.trim().startsWith("return "))
247
- );
248
- const useCode = useReturn ? `return (${code});` : code;
249
- return useCode;
267
+ const secure = isBrowser() ? location.protocol === "https:" : true;
268
+ const secureObj = secure ? SECURE_CONFIG : [[]];
269
+ const expiresObj = expires ? [["expires", expires.toUTCString()]] : [[]];
270
+ const cookieValue = [[name, value], ...expiresObj, ["path", "/"], ["domain", getTopLevelDomain(window.location.hostname)], ...secureObj];
271
+ const cookie = stringifyCookie(cookieValue);
272
+ return cookie;
250
273
  };
251
- function flattenState({
252
- rootState,
253
- localState,
254
- rootSetState
255
- }) {
256
- return new Proxy(rootState, {
257
- get: (target, prop) => {
258
- if (localState && prop in localState) {
259
- return localState[prop];
260
- }
261
- const val = target[prop];
262
- if (typeof val === "object" && val !== null) {
263
- return flattenState({
264
- rootState: val,
265
- localState: void 0,
266
- rootSetState: rootSetState ? (subState) => {
267
- target[prop] = subState;
268
- rootSetState(target);
269
- } : void 0
270
- });
271
- }
272
- return val;
273
- },
274
- set: (target, prop, value) => {
275
- if (localState && prop in localState) {
276
- throw new Error("Writing to local state is not allowed as it is read-only.");
277
- }
278
- target[prop] = value;
279
- rootSetState?.(target);
280
- return true;
274
+ var setCookie = async ({
275
+ name,
276
+ value,
277
+ expires,
278
+ canTrack
279
+ }) => {
280
+ try {
281
+ if (!canTrack) {
282
+ return;
281
283
  }
284
+ const cookie = createCookieString({
285
+ name,
286
+ value,
287
+ expires
288
+ });
289
+ document.cookie = cookie;
290
+ } catch (err) {
291
+ logger.warn("[COOKIE] SET error: ", err?.message || err);
292
+ }
293
+ };
294
+
295
+ // src/helpers/uuid.ts
296
+ function uuidv4() {
297
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
298
+ const r = Math.random() * 16 | 0, v2 = c == "x" ? r : r & 3 | 8;
299
+ return v2.toString(16);
282
300
  });
283
301
  }
302
+ function uuid() {
303
+ return uuidv4().replace(/-/g, "");
304
+ }
284
305
 
285
- // src/functions/evaluate/browser-runtime/browser.ts
286
- var runInBrowser = ({
287
- code,
288
- builder,
289
- context,
290
- event,
291
- localState,
292
- rootSetState,
293
- rootState
306
+ // src/helpers/sessionId.ts
307
+ var SESSION_LOCAL_STORAGE_KEY = "builderSessionId";
308
+ var getSessionId = async ({
309
+ canTrack
294
310
  }) => {
295
- const functionArgs = getFunctionArguments({
296
- builder,
297
- context,
298
- event,
299
- state: flattenState({
300
- rootState,
301
- localState,
302
- rootSetState
303
- })
311
+ if (!canTrack) {
312
+ return void 0;
313
+ }
314
+ const sessionId = await getCookie({
315
+ name: SESSION_LOCAL_STORAGE_KEY,
316
+ canTrack
304
317
  });
305
- return new Function(...functionArgs.map(([name]) => name), code)(...functionArgs.map(([, value]) => value));
318
+ if (checkIsDefined(sessionId)) {
319
+ return sessionId;
320
+ } else {
321
+ const newSessionId = createSessionId();
322
+ setSessionId({
323
+ id: newSessionId,
324
+ canTrack
325
+ });
326
+ return newSessionId;
327
+ }
306
328
  };
329
+ var createSessionId = () => uuid();
330
+ var setSessionId = ({
331
+ id: id2,
332
+ canTrack
333
+ }) => setCookie({
334
+ name: SESSION_LOCAL_STORAGE_KEY,
335
+ value: id2,
336
+ canTrack
337
+ });
307
338
 
308
- // src/functions/evaluate/edge-runtime/acorn-interpreter.ts
309
- var p;
310
- var ca = function(a) {
311
- function b(f) {
312
- return 48 > f ? 36 === f : 58 > f ? true : 65 > f ? false : 91 > f ? true : 97 > f ? 95 === f : 123 > f ? true : 170 <= f && Jc.test(String.fromCharCode(f));
313
- }
314
- function d(f) {
315
- return 65 > f ? 36 === f : 91 > f ? true : 97 > f ? 95 === f : 123 > f ? true : 170 <= f && Pb.test(String.fromCharCode(f));
316
- }
317
- function c(f, g) {
318
- var l = r;
319
- for (var n = 1, w = 0; ; ) {
320
- Sa.lastIndex = w;
321
- var J = Sa.exec(l);
322
- if (J && J.index < f)
323
- ++n, w = J.index + J[0].length;
324
- else
325
- break;
339
+ // src/helpers/localStorage.ts
340
+ var getLocalStorage = () => isBrowser() && typeof localStorage !== "undefined" ? localStorage : void 0;
341
+ var getLocalStorageItem = ({
342
+ key,
343
+ canTrack
344
+ }) => {
345
+ try {
346
+ if (canTrack) {
347
+ return getLocalStorage()?.getItem(key);
326
348
  }
327
- l = {
328
- line: n,
329
- ab: f - w
330
- };
331
- g += " (" + l.line + ":" + l.ab + ")";
332
- g = new SyntaxError(g);
333
- g.j = f;
334
- g.X = l;
335
- g.o = m;
336
- throw g;
349
+ return void 0;
350
+ } catch (err) {
351
+ console.debug("[LocalStorage] GET error: ", err);
352
+ return void 0;
337
353
  }
338
- function e(f) {
339
- f = f.split(" ");
340
- for (var g = /* @__PURE__ */ Object.create(null), l = 0; l < f.length; l++)
341
- g[f[l]] = true;
342
- return function(n) {
343
- return g[n] || false;
344
- };
354
+ };
355
+ var setLocalStorageItem = ({
356
+ key,
357
+ canTrack,
358
+ value
359
+ }) => {
360
+ try {
361
+ if (canTrack) {
362
+ getLocalStorage()?.setItem(key, value);
363
+ }
364
+ } catch (err) {
365
+ console.debug("[LocalStorage] SET error: ", err);
345
366
  }
346
- function h() {
347
- this.line = la;
348
- this.ab = m - X;
367
+ };
368
+
369
+ // src/helpers/visitorId.ts
370
+ var VISITOR_LOCAL_STORAGE_KEY = "builderVisitorId";
371
+ var getVisitorId = ({
372
+ canTrack
373
+ }) => {
374
+ if (!canTrack) {
375
+ return void 0;
349
376
  }
350
- function k(f, g) {
351
- oa = m;
377
+ const visitorId = getLocalStorageItem({
378
+ key: VISITOR_LOCAL_STORAGE_KEY,
379
+ canTrack
380
+ });
381
+ if (checkIsDefined(visitorId)) {
382
+ return visitorId;
383
+ } else {
384
+ const newVisitorId = createVisitorId();
385
+ setVisitorId({
386
+ id: newVisitorId,
387
+ canTrack
388
+ });
389
+ return newVisitorId;
390
+ }
391
+ };
392
+ var createVisitorId = () => uuid();
393
+ var setVisitorId = ({
394
+ id: id2,
395
+ canTrack
396
+ }) => setLocalStorageItem({
397
+ key: VISITOR_LOCAL_STORAGE_KEY,
398
+ value: id2,
399
+ canTrack
400
+ });
401
+
402
+ // src/functions/log-fetch.ts
403
+ function logFetch(url) {
404
+ if (typeof process !== "undefined" && process.env?.DEBUG) {
405
+ if (String(process.env.DEBUG) == "true") {
406
+ logger.log(url);
407
+ }
408
+ }
409
+ }
410
+
411
+ // src/functions/track/index.ts
412
+ var getTrackingEventData = async ({
413
+ canTrack
414
+ }) => {
415
+ if (!canTrack) {
416
+ return {
417
+ visitorId: void 0,
418
+ sessionId: void 0
419
+ };
420
+ }
421
+ const sessionId = await getSessionId({
422
+ canTrack
423
+ });
424
+ const visitorId = getVisitorId({
425
+ canTrack
426
+ });
427
+ return {
428
+ sessionId,
429
+ visitorId
430
+ };
431
+ };
432
+ var createEvent = async ({
433
+ type: eventType,
434
+ canTrack,
435
+ apiKey,
436
+ metadata,
437
+ ...properties
438
+ }) => ({
439
+ type: eventType,
440
+ data: {
441
+ ...properties,
442
+ metadata: {
443
+ url: location.href,
444
+ ...metadata
445
+ },
446
+ ...await getTrackingEventData({
447
+ canTrack
448
+ }),
449
+ userAttributes: getUserAttributes(),
450
+ ownerId: apiKey
451
+ }
452
+ });
453
+ async function _track({
454
+ apiHost,
455
+ ...eventProps
456
+ }) {
457
+ if (!eventProps.apiKey) {
458
+ logger.error("Missing API key for track call. Please provide your API key.");
459
+ return;
460
+ }
461
+ if (!eventProps.canTrack) {
462
+ return;
463
+ }
464
+ if (isEditing()) {
465
+ return;
466
+ }
467
+ if (!(isBrowser() || TARGET === "reactNative")) {
468
+ return;
469
+ }
470
+ const baseUrl = apiHost || "https://cdn.builder.io";
471
+ const url = `${baseUrl}/api/v1/track`;
472
+ logFetch(url);
473
+ return fetch(url, {
474
+ method: "POST",
475
+ body: JSON.stringify({
476
+ events: [await createEvent(eventProps)]
477
+ }),
478
+ headers: {
479
+ "content-type": "application/json",
480
+ ...getSdkHeaders()
481
+ },
482
+ mode: "cors"
483
+ }).catch((err) => {
484
+ console.error("Failed to track: ", err);
485
+ });
486
+ }
487
+ var track = (args) => _track({
488
+ ...args,
489
+ canTrack: true
490
+ });
491
+
492
+ // src/functions/evaluate/helpers.ts
493
+ var getFunctionArguments = ({
494
+ builder,
495
+ context,
496
+ event,
497
+ state
498
+ }) => {
499
+ return Object.entries({
500
+ state,
501
+ Builder: builder,
502
+ // legacy
503
+ builder,
504
+ context,
505
+ event
506
+ });
507
+ };
508
+ var getBuilderGlobals = (trackingContext) => ({
509
+ isEditing: isEditing(),
510
+ isBrowser: isBrowser(),
511
+ isServer: !isBrowser(),
512
+ getUserAttributes: () => getUserAttributes(),
513
+ trackConversion: (amount, customProperties) => {
514
+ if (!trackingContext?.apiKey || trackingContext?.canTrack === false) {
515
+ return;
516
+ }
517
+ _track({
518
+ type: "conversion",
519
+ apiKey: trackingContext.apiKey,
520
+ canTrack: trackingContext.canTrack ?? true,
521
+ contentId: trackingContext.contentId,
522
+ variationId: trackingContext.variationId !== trackingContext.contentId ? trackingContext.variationId : void 0,
523
+ metadata: {
524
+ ...customProperties || {},
525
+ ...amount !== void 0 ? {
526
+ amount
527
+ } : {}
528
+ }
529
+ });
530
+ }
531
+ });
532
+ var parseCode = (code, {
533
+ isExpression = true
534
+ }) => {
535
+ const useReturn = (
536
+ // we disable this for cases where we definitely don't want a return
537
+ isExpression && !(code.includes(";") || code.includes(" return ") || code.trim().startsWith("return "))
538
+ );
539
+ const useCode = useReturn ? `return (${code});` : code;
540
+ return useCode;
541
+ };
542
+ function flattenState({
543
+ rootState,
544
+ localState,
545
+ rootSetState
546
+ }) {
547
+ return new Proxy(rootState, {
548
+ get: (target, prop) => {
549
+ if (localState && prop in localState) {
550
+ return localState[prop];
551
+ }
552
+ const val = target[prop];
553
+ if (typeof val === "object" && val !== null) {
554
+ return flattenState({
555
+ rootState: val,
556
+ localState: void 0,
557
+ rootSetState: rootSetState ? (subState) => {
558
+ target[prop] = subState;
559
+ rootSetState(target);
560
+ } : void 0
561
+ });
562
+ }
563
+ return val;
564
+ },
565
+ set: (target, prop, value) => {
566
+ if (localState && prop in localState) {
567
+ throw new Error("Writing to local state is not allowed as it is read-only.");
568
+ }
569
+ target[prop] = value;
570
+ rootSetState?.(target);
571
+ return true;
572
+ }
573
+ });
574
+ }
575
+
576
+ // src/functions/evaluate/browser-runtime/browser.ts
577
+ var runInBrowser = ({
578
+ code,
579
+ builder,
580
+ context,
581
+ event,
582
+ localState,
583
+ rootSetState,
584
+ rootState
585
+ }) => {
586
+ const functionArgs = getFunctionArguments({
587
+ builder,
588
+ context,
589
+ event,
590
+ state: flattenState({
591
+ rootState,
592
+ localState,
593
+ rootSetState
594
+ })
595
+ });
596
+ return new Function(...functionArgs.map(([name]) => name), code)(...functionArgs.map(([, value]) => value));
597
+ };
598
+
599
+ // src/functions/evaluate/edge-runtime/acorn-interpreter.ts
600
+ var p;
601
+ var ca = function(a) {
602
+ function b(f) {
603
+ return 48 > f ? 36 === f : 58 > f ? true : 65 > f ? false : 91 > f ? true : 97 > f ? 95 === f : 123 > f ? true : 170 <= f && Jc.test(String.fromCharCode(f));
604
+ }
605
+ function d(f) {
606
+ return 65 > f ? 36 === f : 91 > f ? true : 97 > f ? 95 === f : 123 > f ? true : 170 <= f && Pb.test(String.fromCharCode(f));
607
+ }
608
+ function c(f, g) {
609
+ var l = r;
610
+ for (var n = 1, w = 0; ; ) {
611
+ Sa.lastIndex = w;
612
+ var J = Sa.exec(l);
613
+ if (J && J.index < f)
614
+ ++n, w = J.index + J[0].length;
615
+ else
616
+ break;
617
+ }
618
+ l = {
619
+ line: n,
620
+ ab: f - w
621
+ };
622
+ g += " (" + l.line + ":" + l.ab + ")";
623
+ g = new SyntaxError(g);
624
+ g.j = f;
625
+ g.X = l;
626
+ g.o = m;
627
+ throw g;
628
+ }
629
+ function e(f) {
630
+ f = f.split(" ");
631
+ for (var g = /* @__PURE__ */ Object.create(null), l = 0; l < f.length; l++)
632
+ g[f[l]] = true;
633
+ return function(n) {
634
+ return g[n] || false;
635
+ };
636
+ }
637
+ function h() {
638
+ this.line = la;
639
+ this.ab = m - X;
640
+ }
641
+ function k(f, g) {
642
+ oa = m;
352
643
  z.C && (cb = new h());
353
644
  x = f;
354
645
  C();
@@ -3480,9 +3771,6 @@ theFunction();
3480
3771
  return output;
3481
3772
  };
3482
3773
 
3483
- // src/helpers/nullable.ts
3484
- var checkIsDefined = (maybeT) => maybeT !== null && maybeT !== void 0;
3485
-
3486
3774
  // src/functions/is-node-runtime.ts
3487
3775
  function isNodeRuntime() {
3488
3776
  return typeof process !== "undefined" && checkIsDefined(process?.versions?.node);
@@ -3527,7 +3815,8 @@ function evaluate({
3527
3815
  rootState,
3528
3816
  rootSetState,
3529
3817
  event,
3530
- isExpression = true
3818
+ isExpression = true,
3819
+ trackingContext
3531
3820
  }) {
3532
3821
  if (code.trim() === "") {
3533
3822
  return void 0;
@@ -3543,7 +3832,7 @@ function evaluate({
3543
3832
  code: parseCode(code, {
3544
3833
  isExpression
3545
3834
  }),
3546
- builder: getBuilderGlobals(),
3835
+ builder: getBuilderGlobals(trackingContext),
3547
3836
  context,
3548
3837
  event,
3549
3838
  rootSetState,
@@ -3805,801 +4094,538 @@ function throttle(func, wait, options = {}) {
3805
4094
  previous = now;
3806
4095
  result = func.apply(context, args);
3807
4096
  if (!timeout)
3808
- context = args = null;
3809
- } else if (!timeout && options.trailing !== false) {
3810
- timeout = setTimeout(later, remaining);
3811
- }
3812
- return result;
3813
- };
3814
- }
3815
- function assign(target, ..._args) {
3816
- const to = Object(target);
3817
- for (let index = 1; index < arguments.length; index++) {
3818
- const nextSource = arguments[index];
3819
- if (nextSource != null) {
3820
- for (const nextKey in nextSource) {
3821
- if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
3822
- to[nextKey] = nextSource[nextKey];
3823
- }
3824
- }
3825
- }
3826
- }
3827
- return to;
3828
- }
3829
- function bindAnimations(animations) {
3830
- if (TARGET === "reactNative") {
3831
- return;
3832
- }
3833
- for (const animation of animations) {
3834
- switch (animation.trigger) {
3835
- case "pageLoad":
3836
- triggerAnimation(animation);
3837
- break;
3838
- case "scrollInView":
3839
- bindScrollInViewAnimation(animation);
3840
- break;
3841
- }
3842
- }
3843
- }
3844
- function warnElementNotPresent(id2) {
3845
- console.warn(`Cannot animate element: element with ID ${id2} not found!`);
3846
- }
3847
- function augmentAnimation(animation, element) {
3848
- const stylesUsed = getAllStylesUsed(animation);
3849
- const computedStyle = getComputedStyle(element);
3850
- const firstStyles = animation.steps[0].styles;
3851
- const lastStyles = animation.steps[animation.steps.length - 1].styles;
3852
- const bothStyles = [firstStyles, lastStyles];
3853
- for (const styles of bothStyles) {
3854
- for (const style of stylesUsed) {
3855
- if (!(style in styles)) {
3856
- styles[style] = computedStyle[style];
3857
- }
3858
- }
3859
- }
3860
- }
3861
- function getAllStylesUsed(animation) {
3862
- const properties = [];
3863
- for (const step of animation.steps) {
3864
- for (const key in step.styles) {
3865
- if (properties.indexOf(key) === -1) {
3866
- properties.push(key);
3867
- }
3868
- }
3869
- }
3870
- return properties;
3871
- }
3872
- function triggerAnimation(animation) {
3873
- const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
3874
- if (!elements.length) {
3875
- warnElementNotPresent(animation.elementId || animation.id || "");
3876
- return;
3877
- }
3878
- Array.from(elements).forEach((element) => {
3879
- augmentAnimation(animation, element);
3880
- element.style.transition = "none";
3881
- element.style.transitionDelay = "0";
3882
- assign(element.style, animation.steps[0].styles);
3883
- setTimeout(() => {
3884
- element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
3885
- if (animation.delay) {
3886
- element.style.transitionDelay = animation.delay + "s";
3887
- }
3888
- assign(element.style, animation.steps[1].styles);
3889
- setTimeout(() => {
3890
- element.style.transition = "";
3891
- element.style.transitionDelay = "";
3892
- }, (animation.delay || 0) * 1e3 + animation.duration * 1e3 + 100);
3893
- });
3894
- });
3895
- }
3896
- function bindScrollInViewAnimation(animation) {
3897
- const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
3898
- if (!elements.length) {
3899
- warnElementNotPresent(animation.elementId || animation.id || "");
3900
- return;
3901
- }
3902
- Array.from(elements).forEach((element) => {
3903
- augmentAnimation(animation, element);
3904
- let triggered = false;
3905
- let pendingAnimation = false;
3906
- function immediateOnScroll() {
3907
- if (!triggered && isScrolledIntoView(element)) {
3908
- triggered = true;
3909
- pendingAnimation = true;
3910
- setTimeout(() => {
3911
- assign(element.style, animation.steps[1].styles);
3912
- if (!animation.repeat) {
3913
- document.removeEventListener("scroll", onScroll);
3914
- }
3915
- setTimeout(() => {
3916
- pendingAnimation = false;
3917
- if (!animation.repeat) {
3918
- element.style.transition = "";
3919
- element.style.transitionDelay = "";
3920
- }
3921
- }, (animation.duration + (animation.delay || 0)) * 1e3 + 100);
3922
- });
3923
- } else if (animation.repeat && triggered && !pendingAnimation && !isScrolledIntoView(element)) {
3924
- triggered = false;
3925
- assign(element.style, animation.steps[0].styles);
3926
- }
3927
- }
3928
- const onScroll = throttle(immediateOnScroll, 200, {
3929
- leading: false
3930
- });
3931
- function isScrolledIntoView(elem) {
3932
- const rect = elem.getBoundingClientRect();
3933
- const windowHeight = window.innerHeight;
3934
- const thresholdPercent = (animation.thresholdPercent || 0) / 100;
3935
- const threshold = thresholdPercent * windowHeight;
3936
- return rect.bottom > threshold && rect.top < windowHeight - threshold;
3937
- }
3938
- const defaultState = animation.steps[0].styles;
3939
- function attachDefaultState() {
3940
- assign(element.style, defaultState);
3941
- }
3942
- attachDefaultState();
3943
- setTimeout(() => {
3944
- element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
3945
- if (animation.delay) {
3946
- element.style.transitionDelay = animation.delay + "s";
3947
- }
3948
- });
3949
- document.addEventListener("scroll", onScroll, {
3950
- capture: true,
3951
- passive: true
3952
- });
3953
- immediateOnScroll();
3954
- });
3955
- }
3956
-
3957
- // src/helpers/css.ts
3958
- var convertStyleMapToCSSArray = (style) => {
3959
- const cssProps = Object.entries(style).map(([key, value]) => {
3960
- if (typeof value === "string") {
3961
- return `${camelToKebabCase(key)}: ${value};`;
3962
- } else {
3963
- return void 0;
3964
- }
3965
- });
3966
- return cssProps.filter(checkIsDefined);
3967
- };
3968
- var convertStyleMapToCSS = (style) => convertStyleMapToCSSArray(style).join("\n");
3969
- var createCssClass = ({
3970
- mediaQuery,
3971
- className,
3972
- styles
3973
- }) => {
3974
- const cssClass = `.${className} {
3975
- ${convertStyleMapToCSS(styles)}
3976
- }`;
3977
- if (mediaQuery) {
3978
- return `${mediaQuery} {
3979
- ${cssClass}
3980
- }`;
3981
- } else {
3982
- return cssClass;
3983
- }
3984
- };
3985
-
3986
- // src/functions/transform-style-property.ts
3987
- function transformStyleProperty({
3988
- style
3989
- }) {
3990
- return style;
3991
- }
3992
-
3993
- // src/functions/get-style.ts
3994
- var getStyle = ({
3995
- block,
3996
- context
3997
- }) => {
3998
- return mapStyleObjToStrIfNeeded(transformStyleProperty({
3999
- style: block.style || {},
4000
- context,
4001
- block
4002
- }));
4003
- };
4004
- function mapStyleObjToStrIfNeeded(style) {
4005
- switch (TARGET) {
4006
- case "svelte":
4007
- case "vue":
4008
- case "solid":
4009
- case "angular":
4010
- return convertStyleMapToCSSArray(style).join(" ");
4011
- case "qwik":
4012
- case "reactNative":
4013
- case "react":
4014
- case "rsc":
4015
- return style;
4016
- }
4017
- }
4018
-
4019
- // src/components/block/block.helpers.ts
4020
- var checkIsComponentRestricted = (component, model) => {
4021
- if (!component)
4022
- return true;
4023
- if (!model)
4024
- return false;
4025
- return component.models && component.models.length > 0 && !component.models.includes(model);
4026
- };
4027
- var getComponent = ({
4028
- block,
4029
- registeredComponents,
4030
- model
4031
- }) => {
4032
- const componentName = block.component?.name;
4033
- if (!componentName) {
4034
- return null;
4035
- }
4036
- const ref = registeredComponents[componentName];
4037
- if (!ref || checkIsComponentRestricted(ref, model)) {
4038
- console.warn(`
4039
- Could not find a registered component named "${componentName}".
4040
- If you registered it, is the file that registered it imported by the file that needs to render it?`);
4041
- return void 0;
4042
- } else {
4043
- return ref;
4044
- }
4045
- };
4046
- var getRepeatItemData = ({
4047
- block,
4048
- context
4049
- }) => {
4050
- const {
4051
- repeat,
4052
- ...blockWithoutRepeat
4053
- } = block;
4054
- if (!repeat?.collection) {
4055
- return void 0;
4056
- }
4057
- const itemsArray = evaluate({
4058
- code: repeat.collection,
4059
- localState: context.localState,
4060
- rootState: context.rootState,
4061
- rootSetState: context.rootSetState,
4062
- context: context.context
4063
- });
4064
- if (!Array.isArray(itemsArray)) {
4065
- return void 0;
4066
- }
4067
- const collectionName = repeat.collection.split(".").pop();
4068
- const itemNameToUse = repeat.itemName || (collectionName ? collectionName + "Item" : "item");
4069
- const repeatArray = itemsArray.map((item, index) => ({
4070
- context: {
4071
- ...context,
4072
- localState: {
4073
- ...context.localState,
4074
- $index: index,
4075
- $item: item,
4076
- [itemNameToUse]: item,
4077
- [`$${itemNameToUse}Index`]: index
4078
- }
4079
- },
4080
- block: blockWithoutRepeat
4081
- }));
4082
- return repeatArray;
4083
- };
4084
- var provideLinkComponent = (block, linkComponent) => {
4085
- if (block?.shouldReceiveBuilderProps?.builderLinkComponent)
4086
- return {
4087
- builderLinkComponent: linkComponent
4088
- };
4089
- return {};
4090
- };
4091
- var provideRegisteredComponents = (block, registeredComponents, model) => {
4092
- if (block?.shouldReceiveBuilderProps?.builderComponents) {
4093
- const filteredRegisteredComponents = Object.fromEntries(Object.entries(registeredComponents).filter(([_, component]) => {
4094
- return !checkIsComponentRestricted(component, model);
4095
- }));
4096
- return {
4097
- builderComponents: filteredRegisteredComponents
4098
- };
4099
- }
4100
- return {};
4101
- };
4102
- var provideBuilderBlock = (block, builderBlock) => {
4103
- if (block?.shouldReceiveBuilderProps?.builderBlock)
4104
- return {
4105
- builderBlock
4106
- };
4107
- return {};
4108
- };
4109
- var provideBuilderContext = (block, context) => {
4110
- if (block?.shouldReceiveBuilderProps?.builderContext)
4111
- return {
4112
- builderContext: context
4113
- };
4114
- return {};
4115
- };
4116
- var generateKey = (index) => {
4117
- return index.toString();
4118
- };
4119
-
4120
- // src/functions/event-handler-name.ts
4121
- function capitalizeFirstLetter(string) {
4122
- return string.charAt(0).toUpperCase() + string.slice(1);
4123
- }
4124
- var getEventHandlerName = (key) => `on${capitalizeFirstLetter(key)}`;
4125
-
4126
- // src/functions/get-block-actions-handler.ts
4127
- var createEventHandler = (value, options) => (event) => evaluate({
4128
- code: value,
4129
- context: options.context,
4130
- localState: options.localState,
4131
- rootState: options.rootState,
4132
- rootSetState: options.rootSetState,
4133
- event,
4134
- isExpression: false
4135
- });
4136
-
4137
- // src/functions/get-block-actions.ts
4138
- function getBlockActions(options) {
4139
- const obj = {};
4140
- const optionActions = options.block.actions ?? {};
4141
- for (const key in optionActions) {
4142
- if (!optionActions.hasOwnProperty(key)) {
4143
- continue;
4144
- }
4145
- const value = optionActions[key];
4146
- let eventHandlerName = getEventHandlerName(key);
4147
- if (options.stripPrefix) {
4148
- switch (TARGET) {
4149
- case "vue":
4150
- eventHandlerName = eventHandlerName.replace("v-on:", "");
4151
- break;
4152
- case "svelte":
4153
- eventHandlerName = eventHandlerName.replace("on:", "");
4154
- break;
4155
- }
4156
- }
4157
- obj[eventHandlerName] = createEventHandler(value, options);
4158
- }
4159
- return obj;
4160
- }
4161
-
4162
- // src/functions/transform-block-properties.ts
4163
- function transformBlockProperties({
4164
- properties
4165
- }) {
4166
- return properties;
4167
- }
4168
-
4169
- // src/functions/get-block-properties.ts
4170
- var extractRelevantRootBlockProperties = (block) => {
4171
- return {
4172
- href: block.href
4173
- };
4174
- };
4175
- function getBlockProperties({
4176
- block,
4177
- context
4178
- }) {
4179
- const properties = {
4180
- ...extractRelevantRootBlockProperties(block),
4181
- ...block.properties,
4182
- "builder-id": block.id,
4183
- style: getStyle({
4184
- block,
4185
- context
4186
- }),
4187
- [getClassPropName()]: [block.id, "builder-block", block.class, block.properties?.class].filter(Boolean).join(" ")
4188
- };
4189
- return transformBlockProperties({
4190
- properties,
4191
- context,
4192
- block
4193
- });
4194
- }
4195
-
4196
- // src/components/block/components/block-wrapper.tsx
4197
- function BlockWrapper(props) {
4198
- return <><Dynamic_renderer_default
4199
- TagName={props.Wrapper}
4200
- attributes={getBlockProperties({
4201
- block: props.block,
4202
- context: props.context
4203
- })}
4204
- actionAttributes={getBlockActions({
4205
- block: props.block,
4206
- rootState: props.context.rootState,
4207
- rootSetState: props.context.rootSetState,
4208
- localState: props.context.localState,
4209
- context: props.context.context,
4210
- stripPrefix: true
4211
- })}
4212
- >{props.children}</Dynamic_renderer_default></>;
4213
- }
4214
- var Block_wrapper_default = BlockWrapper;
4215
-
4216
- // src/components/block/components/component-ref/component-ref.tsx
4217
- import { Show as Show3, For, createSignal as createSignal3 } from "solid-js";
4218
- import { Dynamic as Dynamic4 } from "solid-js/web";
4219
-
4220
- // src/components/block/components/interactive-element.tsx
4221
- import { Show as Show2, on, createEffect, createMemo as createMemo2, createSignal as createSignal2 } from "solid-js";
4222
- import { Dynamic as Dynamic3 } from "solid-js/web";
4223
-
4224
- // src/functions/is-previewing.ts
4225
- function isPreviewing(search) {
4226
- const searchToUse = search || (isBrowser() ? window.location.search : void 0);
4227
- if (!searchToUse) {
4228
- return false;
4229
- }
4230
- const normalizedSearch = getSearchString(searchToUse);
4231
- return Boolean(normalizedSearch.indexOf("builder.preview=") !== -1);
4232
- }
4233
-
4234
- // src/functions/register-component.ts
4235
- var createRegisterComponentMessage = (info) => ({
4236
- type: "builder.registerComponent",
4237
- data: serializeIncludingFunctions(info)
4238
- });
4239
- var serializeFn = (fnValue) => {
4240
- const fnStr = fnValue.toString().trim();
4241
- const isArrowWithoutParens = /^[a-zA-Z0-9_]+\s*=>/i.test(fnStr);
4242
- const appendFunction = !fnStr.startsWith("function") && !fnStr.startsWith("async") && !fnStr.startsWith("(") && !isArrowWithoutParens;
4243
- return `return (${appendFunction ? "function " : ""}${fnStr}).apply(this, arguments)`;
4244
- };
4245
- function serializeIncludingFunctions(info) {
4246
- return JSON.parse(JSON.stringify(info, (key, value) => {
4247
- if (typeof value === "function") {
4248
- return serializeFn(value);
4097
+ context = args = null;
4098
+ } else if (!timeout && options.trailing !== false) {
4099
+ timeout = setTimeout(later, remaining);
4249
4100
  }
4250
- return value;
4251
- }));
4101
+ return result;
4102
+ };
4252
4103
  }
4253
-
4254
- // src/functions/register.ts
4255
- var registry = {};
4256
- function register(type, info) {
4257
- if (type === "plugin") {
4258
- info = serializeIncludingFunctions(info);
4259
- }
4260
- let typeList = registry[type];
4261
- if (!typeList) {
4262
- typeList = registry[type] = [];
4263
- }
4264
- typeList.push(info);
4265
- if (isBrowser()) {
4266
- const message = {
4267
- type: "builder.register",
4268
- data: {
4269
- type,
4270
- info
4271
- }
4272
- };
4273
- try {
4274
- parent.postMessage(message, "*");
4275
- if (parent !== window) {
4276
- window.postMessage(message, "*");
4104
+ function assign(target, ..._args) {
4105
+ const to = Object(target);
4106
+ for (let index = 1; index < arguments.length; index++) {
4107
+ const nextSource = arguments[index];
4108
+ if (nextSource != null) {
4109
+ for (const nextKey in nextSource) {
4110
+ if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
4111
+ to[nextKey] = nextSource[nextKey];
4112
+ }
4277
4113
  }
4278
- } catch (err) {
4279
- console.debug("Could not postmessage", err);
4280
4114
  }
4281
4115
  }
4116
+ return to;
4282
4117
  }
4283
- function registerAction(action) {
4284
- if (isBrowser()) {
4285
- const actionClone = JSON.parse(JSON.stringify(action));
4286
- if (action.action) {
4287
- actionClone.action = action.action.toString();
4118
+ function bindAnimations(animations) {
4119
+ if (TARGET === "reactNative") {
4120
+ return;
4121
+ }
4122
+ for (const animation of animations) {
4123
+ switch (animation.trigger) {
4124
+ case "pageLoad":
4125
+ triggerAnimation(animation);
4126
+ break;
4127
+ case "scrollInView":
4128
+ bindScrollInViewAnimation(animation);
4129
+ break;
4288
4130
  }
4289
- window.parent?.postMessage({
4290
- type: "builder.registerAction",
4291
- data: actionClone
4292
- }, "*");
4293
4131
  }
4294
4132
  }
4295
-
4296
- // src/functions/set-editor-settings.ts
4297
- var settings = {};
4298
- function setEditorSettings(newSettings) {
4299
- if (isBrowser()) {
4300
- Object.assign(settings, newSettings);
4301
- const message = {
4302
- type: "builder.settingsChange",
4303
- data: settings
4304
- };
4305
- parent.postMessage(message, "*");
4306
- }
4133
+ function warnElementNotPresent(id2) {
4134
+ console.warn(`Cannot animate element: element with ID ${id2} not found!`);
4307
4135
  }
4308
-
4309
- // src/functions/get-builder-search-params/index.ts
4310
- var BUILDER_SEARCHPARAMS_PREFIX = "builder.";
4311
- var BUILDER_OPTIONS_PREFIX = "options.";
4312
- var getBuilderSearchParams = (_options) => {
4313
- if (!_options) {
4314
- return {};
4136
+ function augmentAnimation(animation, element) {
4137
+ const stylesUsed = getAllStylesUsed(animation);
4138
+ const computedStyle = getComputedStyle(element);
4139
+ const firstStyles = animation.steps[0].styles;
4140
+ const lastStyles = animation.steps[animation.steps.length - 1].styles;
4141
+ const bothStyles = [firstStyles, lastStyles];
4142
+ for (const styles of bothStyles) {
4143
+ for (const style of stylesUsed) {
4144
+ if (!(style in styles)) {
4145
+ styles[style] = computedStyle[style];
4146
+ }
4147
+ }
4315
4148
  }
4316
- const options = normalizeSearchParams(_options);
4317
- const newOptions = {};
4318
- Object.keys(options).forEach((key) => {
4319
- if (key.startsWith(BUILDER_SEARCHPARAMS_PREFIX)) {
4320
- const trimmedKey = key.replace(BUILDER_SEARCHPARAMS_PREFIX, "").replace(BUILDER_OPTIONS_PREFIX, "");
4321
- newOptions[trimmedKey] = options[key];
4149
+ }
4150
+ function getAllStylesUsed(animation) {
4151
+ const properties = [];
4152
+ for (const step of animation.steps) {
4153
+ for (const key in step.styles) {
4154
+ if (properties.indexOf(key) === -1) {
4155
+ properties.push(key);
4156
+ }
4322
4157
  }
4323
- });
4324
- return newOptions;
4325
- };
4326
- var getBuilderSearchParamsFromWindow = () => {
4327
- if (!isBrowser()) {
4328
- return {};
4329
4158
  }
4330
- const searchParams = new URLSearchParams(window.location.search);
4331
- return getBuilderSearchParams(searchParams);
4332
- };
4333
-
4334
- // src/constants/sdk-version.ts
4335
- var SDK_VERSION = "5.1.0";
4336
-
4337
- // src/helpers/sdk-headers.ts
4338
- var getSdkHeaders = () => ({
4339
- "X-Builder-SDK": TARGET,
4340
- "X-Builder-SDK-GEN": "2",
4341
- "X-Builder-SDK-Version": SDK_VERSION
4342
- });
4343
-
4344
- // src/helpers/url.ts
4345
- var getTopLevelDomain = (host) => {
4346
- if (host === "localhost" || host === "127.0.0.1") {
4347
- return host;
4159
+ return properties;
4160
+ }
4161
+ function triggerAnimation(animation) {
4162
+ const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
4163
+ if (!elements.length) {
4164
+ warnElementNotPresent(animation.elementId || animation.id || "");
4165
+ return;
4348
4166
  }
4349
- const parts = host.split(".");
4350
- if (parts.length > 2) {
4351
- return parts.slice(1).join(".");
4167
+ Array.from(elements).forEach((element) => {
4168
+ augmentAnimation(animation, element);
4169
+ element.style.transition = "none";
4170
+ element.style.transitionDelay = "0";
4171
+ assign(element.style, animation.steps[0].styles);
4172
+ setTimeout(() => {
4173
+ element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
4174
+ if (animation.delay) {
4175
+ element.style.transitionDelay = animation.delay + "s";
4176
+ }
4177
+ assign(element.style, animation.steps[1].styles);
4178
+ setTimeout(() => {
4179
+ element.style.transition = "";
4180
+ element.style.transitionDelay = "";
4181
+ }, (animation.delay || 0) * 1e3 + animation.duration * 1e3 + 100);
4182
+ });
4183
+ });
4184
+ }
4185
+ function bindScrollInViewAnimation(animation) {
4186
+ const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
4187
+ if (!elements.length) {
4188
+ warnElementNotPresent(animation.elementId || animation.id || "");
4189
+ return;
4352
4190
  }
4353
- return host;
4354
- };
4355
-
4356
- // src/helpers/cookie.ts
4357
- var getCookieSync = ({
4358
- name,
4359
- canTrack
4360
- }) => {
4361
- try {
4362
- if (!canTrack) {
4363
- return void 0;
4191
+ Array.from(elements).forEach((element) => {
4192
+ augmentAnimation(animation, element);
4193
+ let triggered = false;
4194
+ let pendingAnimation = false;
4195
+ function immediateOnScroll() {
4196
+ if (!triggered && isScrolledIntoView(element)) {
4197
+ triggered = true;
4198
+ pendingAnimation = true;
4199
+ setTimeout(() => {
4200
+ assign(element.style, animation.steps[1].styles);
4201
+ if (!animation.repeat) {
4202
+ document.removeEventListener("scroll", onScroll);
4203
+ }
4204
+ setTimeout(() => {
4205
+ pendingAnimation = false;
4206
+ if (!animation.repeat) {
4207
+ element.style.transition = "";
4208
+ element.style.transitionDelay = "";
4209
+ }
4210
+ }, (animation.duration + (animation.delay || 0)) * 1e3 + 100);
4211
+ });
4212
+ } else if (animation.repeat && triggered && !pendingAnimation && !isScrolledIntoView(element)) {
4213
+ triggered = false;
4214
+ assign(element.style, animation.steps[0].styles);
4215
+ }
4364
4216
  }
4365
- return document.cookie.split("; ").find((row) => row.startsWith(`${name}=`))?.split("=")[1];
4366
- } catch (err) {
4367
- logger.warn("[COOKIE] GET error: ", err?.message || err);
4368
- return void 0;
4369
- }
4370
- };
4371
- var getCookie = async (args) => getCookieSync(args);
4372
- var stringifyCookie = (cookie) => cookie.map(([key, value]) => value ? `${key}=${value}` : key).filter(checkIsDefined).join("; ");
4373
- var SECURE_CONFIG = [["secure", ""], ["SameSite", "None"]];
4374
- var createCookieString = ({
4375
- name,
4376
- value,
4377
- expires
4378
- }) => {
4379
- const secure = isBrowser() ? location.protocol === "https:" : true;
4380
- const secureObj = secure ? SECURE_CONFIG : [[]];
4381
- const expiresObj = expires ? [["expires", expires.toUTCString()]] : [[]];
4382
- const cookieValue = [[name, value], ...expiresObj, ["path", "/"], ["domain", getTopLevelDomain(window.location.hostname)], ...secureObj];
4383
- const cookie = stringifyCookie(cookieValue);
4384
- return cookie;
4385
- };
4386
- var setCookie = async ({
4387
- name,
4388
- value,
4389
- expires,
4390
- canTrack
4391
- }) => {
4392
- try {
4393
- if (!canTrack) {
4394
- return;
4217
+ const onScroll = throttle(immediateOnScroll, 200, {
4218
+ leading: false
4219
+ });
4220
+ function isScrolledIntoView(elem) {
4221
+ const rect = elem.getBoundingClientRect();
4222
+ const windowHeight = window.innerHeight;
4223
+ const thresholdPercent = (animation.thresholdPercent || 0) / 100;
4224
+ const threshold = thresholdPercent * windowHeight;
4225
+ return rect.bottom > threshold && rect.top < windowHeight - threshold;
4395
4226
  }
4396
- const cookie = createCookieString({
4397
- name,
4398
- value,
4399
- expires
4227
+ const defaultState = animation.steps[0].styles;
4228
+ function attachDefaultState() {
4229
+ assign(element.style, defaultState);
4230
+ }
4231
+ attachDefaultState();
4232
+ setTimeout(() => {
4233
+ element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
4234
+ if (animation.delay) {
4235
+ element.style.transitionDelay = animation.delay + "s";
4236
+ }
4400
4237
  });
4401
- document.cookie = cookie;
4402
- } catch (err) {
4403
- logger.warn("[COOKIE] SET error: ", err?.message || err);
4404
- }
4405
- };
4406
-
4407
- // src/helpers/uuid.ts
4408
- function uuidv4() {
4409
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
4410
- const r = Math.random() * 16 | 0, v2 = c == "x" ? r : r & 3 | 8;
4411
- return v2.toString(16);
4238
+ document.addEventListener("scroll", onScroll, {
4239
+ capture: true,
4240
+ passive: true
4241
+ });
4242
+ immediateOnScroll();
4412
4243
  });
4413
4244
  }
4414
- function uuid() {
4415
- return uuidv4().replace(/-/g, "");
4416
- }
4417
4245
 
4418
- // src/helpers/sessionId.ts
4419
- var SESSION_LOCAL_STORAGE_KEY = "builderSessionId";
4420
- var getSessionId = async ({
4421
- canTrack
4422
- }) => {
4423
- if (!canTrack) {
4424
- return void 0;
4425
- }
4426
- const sessionId = await getCookie({
4427
- name: SESSION_LOCAL_STORAGE_KEY,
4428
- canTrack
4246
+ // src/helpers/css.ts
4247
+ var convertStyleMapToCSSArray = (style) => {
4248
+ const cssProps = Object.entries(style).map(([key, value]) => {
4249
+ if (typeof value === "string") {
4250
+ return `${camelToKebabCase(key)}: ${value};`;
4251
+ } else {
4252
+ return void 0;
4253
+ }
4429
4254
  });
4430
- if (checkIsDefined(sessionId)) {
4431
- return sessionId;
4255
+ return cssProps.filter(checkIsDefined);
4256
+ };
4257
+ var convertStyleMapToCSS = (style) => convertStyleMapToCSSArray(style).join("\n");
4258
+ var createCssClass = ({
4259
+ mediaQuery,
4260
+ className,
4261
+ styles
4262
+ }) => {
4263
+ const cssClass = `.${className} {
4264
+ ${convertStyleMapToCSS(styles)}
4265
+ }`;
4266
+ if (mediaQuery) {
4267
+ return `${mediaQuery} {
4268
+ ${cssClass}
4269
+ }`;
4432
4270
  } else {
4433
- const newSessionId = createSessionId();
4434
- setSessionId({
4435
- id: newSessionId,
4436
- canTrack
4437
- });
4438
- return newSessionId;
4271
+ return cssClass;
4439
4272
  }
4440
4273
  };
4441
- var createSessionId = () => uuid();
4442
- var setSessionId = ({
4443
- id: id2,
4444
- canTrack
4445
- }) => setCookie({
4446
- name: SESSION_LOCAL_STORAGE_KEY,
4447
- value: id2,
4448
- canTrack
4449
- });
4450
4274
 
4451
- // src/helpers/localStorage.ts
4452
- var getLocalStorage = () => isBrowser() && typeof localStorage !== "undefined" ? localStorage : void 0;
4453
- var getLocalStorageItem = ({
4454
- key,
4455
- canTrack
4275
+ // src/functions/transform-style-property.ts
4276
+ function transformStyleProperty({
4277
+ style
4278
+ }) {
4279
+ return style;
4280
+ }
4281
+
4282
+ // src/functions/get-style.ts
4283
+ var getStyle = ({
4284
+ block,
4285
+ context
4456
4286
  }) => {
4457
- try {
4458
- if (canTrack) {
4459
- return getLocalStorage()?.getItem(key);
4460
- }
4461
- return void 0;
4462
- } catch (err) {
4463
- console.debug("[LocalStorage] GET error: ", err);
4464
- return void 0;
4287
+ return mapStyleObjToStrIfNeeded(transformStyleProperty({
4288
+ style: block.style || {},
4289
+ context,
4290
+ block
4291
+ }));
4292
+ };
4293
+ function mapStyleObjToStrIfNeeded(style) {
4294
+ switch (TARGET) {
4295
+ case "svelte":
4296
+ case "vue":
4297
+ case "solid":
4298
+ case "angular":
4299
+ return convertStyleMapToCSSArray(style).join(" ");
4300
+ case "qwik":
4301
+ case "reactNative":
4302
+ case "react":
4303
+ case "rsc":
4304
+ return style;
4465
4305
  }
4306
+ }
4307
+
4308
+ // src/components/block/block.helpers.ts
4309
+ var checkIsComponentRestricted = (component, model) => {
4310
+ if (!component)
4311
+ return true;
4312
+ if (!model)
4313
+ return false;
4314
+ return component.models && component.models.length > 0 && !component.models.includes(model);
4466
4315
  };
4467
- var setLocalStorageItem = ({
4468
- key,
4469
- canTrack,
4470
- value
4316
+ var getComponent = ({
4317
+ block,
4318
+ registeredComponents,
4319
+ model
4471
4320
  }) => {
4472
- try {
4473
- if (canTrack) {
4474
- getLocalStorage()?.setItem(key, value);
4475
- }
4476
- } catch (err) {
4477
- console.debug("[LocalStorage] SET error: ", err);
4321
+ const componentName = block.component?.name;
4322
+ if (!componentName) {
4323
+ return null;
4324
+ }
4325
+ const ref = registeredComponents[componentName];
4326
+ if (!ref || checkIsComponentRestricted(ref, model)) {
4327
+ console.warn(`
4328
+ Could not find a registered component named "${componentName}".
4329
+ If you registered it, is the file that registered it imported by the file that needs to render it?`);
4330
+ return void 0;
4331
+ } else {
4332
+ return ref;
4478
4333
  }
4479
4334
  };
4480
-
4481
- // src/helpers/visitorId.ts
4482
- var VISITOR_LOCAL_STORAGE_KEY = "builderVisitorId";
4483
- var getVisitorId = ({
4484
- canTrack
4335
+ var getRepeatItemData = ({
4336
+ block,
4337
+ context
4485
4338
  }) => {
4486
- if (!canTrack) {
4339
+ const {
4340
+ repeat,
4341
+ ...blockWithoutRepeat
4342
+ } = block;
4343
+ if (!repeat?.collection) {
4487
4344
  return void 0;
4488
4345
  }
4489
- const visitorId = getLocalStorageItem({
4490
- key: VISITOR_LOCAL_STORAGE_KEY,
4491
- canTrack
4346
+ const itemsArray = evaluate({
4347
+ code: repeat.collection,
4348
+ localState: context.localState,
4349
+ rootState: context.rootState,
4350
+ rootSetState: context.rootSetState,
4351
+ context: context.context
4492
4352
  });
4493
- if (checkIsDefined(visitorId)) {
4494
- return visitorId;
4495
- } else {
4496
- const newVisitorId = createVisitorId();
4497
- setVisitorId({
4498
- id: newVisitorId,
4499
- canTrack
4500
- });
4501
- return newVisitorId;
4353
+ if (!Array.isArray(itemsArray)) {
4354
+ return void 0;
4355
+ }
4356
+ const collectionName = repeat.collection.split(".").pop();
4357
+ const itemNameToUse = repeat.itemName || (collectionName ? collectionName + "Item" : "item");
4358
+ const repeatArray = itemsArray.map((item, index) => ({
4359
+ context: {
4360
+ ...context,
4361
+ localState: {
4362
+ ...context.localState,
4363
+ $index: index,
4364
+ $item: item,
4365
+ [itemNameToUse]: item,
4366
+ [`$${itemNameToUse}Index`]: index
4367
+ }
4368
+ },
4369
+ block: blockWithoutRepeat
4370
+ }));
4371
+ return repeatArray;
4372
+ };
4373
+ var provideLinkComponent = (block, linkComponent) => {
4374
+ if (block?.shouldReceiveBuilderProps?.builderLinkComponent)
4375
+ return {
4376
+ builderLinkComponent: linkComponent
4377
+ };
4378
+ return {};
4379
+ };
4380
+ var provideRegisteredComponents = (block, registeredComponents, model) => {
4381
+ if (block?.shouldReceiveBuilderProps?.builderComponents) {
4382
+ const filteredRegisteredComponents = Object.fromEntries(Object.entries(registeredComponents).filter(([_, component]) => {
4383
+ return !checkIsComponentRestricted(component, model);
4384
+ }));
4385
+ return {
4386
+ builderComponents: filteredRegisteredComponents
4387
+ };
4502
4388
  }
4389
+ return {};
4503
4390
  };
4504
- var createVisitorId = () => uuid();
4505
- var setVisitorId = ({
4506
- id: id2,
4507
- canTrack
4508
- }) => setLocalStorageItem({
4509
- key: VISITOR_LOCAL_STORAGE_KEY,
4510
- value: id2,
4511
- canTrack
4391
+ var provideBuilderBlock = (block, builderBlock) => {
4392
+ if (block?.shouldReceiveBuilderProps?.builderBlock)
4393
+ return {
4394
+ builderBlock
4395
+ };
4396
+ return {};
4397
+ };
4398
+ var provideBuilderContext = (block, context) => {
4399
+ if (block?.shouldReceiveBuilderProps?.builderContext)
4400
+ return {
4401
+ builderContext: context
4402
+ };
4403
+ return {};
4404
+ };
4405
+ var generateKey = (index) => {
4406
+ return index.toString();
4407
+ };
4408
+
4409
+ // src/functions/event-handler-name.ts
4410
+ function capitalizeFirstLetter(string) {
4411
+ return string.charAt(0).toUpperCase() + string.slice(1);
4412
+ }
4413
+ var getEventHandlerName = (key) => `on${capitalizeFirstLetter(key)}`;
4414
+
4415
+ // src/functions/get-block-actions-handler.ts
4416
+ var createEventHandler = (value, options) => (event) => evaluate({
4417
+ code: value,
4418
+ context: options.context,
4419
+ localState: options.localState,
4420
+ rootState: options.rootState,
4421
+ rootSetState: options.rootSetState,
4422
+ event,
4423
+ isExpression: false,
4424
+ trackingContext: options.trackingContext
4512
4425
  });
4513
4426
 
4514
- // src/functions/log-fetch.ts
4515
- function logFetch(url) {
4516
- if (typeof process !== "undefined" && process.env?.DEBUG) {
4517
- if (String(process.env.DEBUG) == "true") {
4518
- logger.log(url);
4427
+ // src/functions/get-block-actions.ts
4428
+ function getBlockActions(options) {
4429
+ const obj = {};
4430
+ const optionActions = options.block.actions ?? {};
4431
+ for (const key in optionActions) {
4432
+ if (!optionActions.hasOwnProperty(key)) {
4433
+ continue;
4434
+ }
4435
+ const value = optionActions[key];
4436
+ let eventHandlerName = getEventHandlerName(key);
4437
+ if (options.stripPrefix) {
4438
+ switch (TARGET) {
4439
+ case "vue":
4440
+ eventHandlerName = eventHandlerName.replace("v-on:", "");
4441
+ break;
4442
+ case "svelte":
4443
+ eventHandlerName = eventHandlerName.replace("on:", "");
4444
+ break;
4445
+ }
4519
4446
  }
4447
+ obj[eventHandlerName] = createEventHandler(value, options);
4520
4448
  }
4449
+ return obj;
4521
4450
  }
4522
4451
 
4523
- // src/functions/track/index.ts
4524
- var getTrackingEventData = async ({
4525
- canTrack
4526
- }) => {
4527
- if (!canTrack) {
4528
- return {
4529
- visitorId: void 0,
4530
- sessionId: void 0
4531
- };
4532
- }
4533
- const sessionId = await getSessionId({
4534
- canTrack
4535
- });
4536
- const visitorId = getVisitorId({
4537
- canTrack
4538
- });
4452
+ // src/functions/transform-block-properties.ts
4453
+ function transformBlockProperties({
4454
+ properties
4455
+ }) {
4456
+ return properties;
4457
+ }
4458
+
4459
+ // src/functions/get-block-properties.ts
4460
+ var extractRelevantRootBlockProperties = (block) => {
4539
4461
  return {
4540
- sessionId,
4541
- visitorId
4462
+ href: block.href
4542
4463
  };
4543
4464
  };
4544
- var createEvent = async ({
4545
- type: eventType,
4546
- canTrack,
4547
- apiKey,
4548
- metadata,
4549
- ...properties
4550
- }) => ({
4551
- type: eventType,
4552
- data: {
4553
- ...properties,
4554
- metadata: {
4555
- url: location.href,
4556
- ...metadata
4557
- },
4558
- ...await getTrackingEventData({
4559
- canTrack
4465
+ function getBlockProperties({
4466
+ block,
4467
+ context
4468
+ }) {
4469
+ const properties = {
4470
+ ...extractRelevantRootBlockProperties(block),
4471
+ ...block.properties,
4472
+ "builder-id": block.id,
4473
+ style: getStyle({
4474
+ block,
4475
+ context
4560
4476
  }),
4561
- userAttributes: getUserAttributes(),
4562
- ownerId: apiKey
4477
+ [getClassPropName()]: [block.id, "builder-block", block.class, block.properties?.class].filter(Boolean).join(" ")
4478
+ };
4479
+ return transformBlockProperties({
4480
+ properties,
4481
+ context,
4482
+ block
4483
+ });
4484
+ }
4485
+
4486
+ // src/components/block/components/block-wrapper.tsx
4487
+ function BlockWrapper(props) {
4488
+ return <><Dynamic_renderer_default
4489
+ TagName={props.Wrapper}
4490
+ attributes={getBlockProperties({
4491
+ block: props.block,
4492
+ context: props.context
4493
+ })}
4494
+ actionAttributes={getBlockActions({
4495
+ block: props.block,
4496
+ rootState: props.context.rootState,
4497
+ rootSetState: props.context.rootSetState,
4498
+ localState: props.context.localState,
4499
+ context: props.context.context,
4500
+ stripPrefix: true,
4501
+ trackingContext: {
4502
+ apiKey: props.context.apiKey,
4503
+ canTrack: props.context.canTrack ?? true,
4504
+ contentId: props.context.content?.id,
4505
+ variationId: props.context.content?.testVariationId
4506
+ }
4507
+ })}
4508
+ >{props.children}</Dynamic_renderer_default></>;
4509
+ }
4510
+ var Block_wrapper_default = BlockWrapper;
4511
+
4512
+ // src/components/block/components/component-ref/component-ref.tsx
4513
+ import { Show as Show3, For, createSignal as createSignal3 } from "solid-js";
4514
+ import { Dynamic as Dynamic4 } from "solid-js/web";
4515
+
4516
+ // src/components/block/components/interactive-element.tsx
4517
+ import { Show as Show2, on, createEffect, createMemo as createMemo2, createSignal as createSignal2 } from "solid-js";
4518
+ import { Dynamic as Dynamic3 } from "solid-js/web";
4519
+
4520
+ // src/functions/is-previewing.ts
4521
+ function isPreviewing(search) {
4522
+ const searchToUse = search || (isBrowser() ? window.location.search : void 0);
4523
+ if (!searchToUse) {
4524
+ return false;
4563
4525
  }
4526
+ const normalizedSearch = getSearchString(searchToUse);
4527
+ return Boolean(normalizedSearch.indexOf("builder.preview=") !== -1);
4528
+ }
4529
+
4530
+ // src/functions/register-component.ts
4531
+ var createRegisterComponentMessage = (info) => ({
4532
+ type: "builder.registerComponent",
4533
+ data: serializeIncludingFunctions(info)
4564
4534
  });
4565
- async function _track({
4566
- apiHost,
4567
- ...eventProps
4568
- }) {
4569
- if (!eventProps.apiKey) {
4570
- logger.error("Missing API key for track call. Please provide your API key.");
4571
- return;
4535
+ var serializeFn = (fnValue) => {
4536
+ const fnStr = fnValue.toString().trim();
4537
+ const isArrowWithoutParens = /^[a-zA-Z0-9_]+\s*=>/i.test(fnStr);
4538
+ const appendFunction = !fnStr.startsWith("function") && !fnStr.startsWith("async") && !fnStr.startsWith("(") && !isArrowWithoutParens;
4539
+ return `return (${appendFunction ? "function " : ""}${fnStr}).apply(this, arguments)`;
4540
+ };
4541
+ function serializeIncludingFunctions(info) {
4542
+ return JSON.parse(JSON.stringify(info, (key, value) => {
4543
+ if (typeof value === "function") {
4544
+ return serializeFn(value);
4545
+ }
4546
+ return value;
4547
+ }));
4548
+ }
4549
+
4550
+ // src/functions/register.ts
4551
+ var registry = {};
4552
+ function register(type, info) {
4553
+ if (type === "plugin") {
4554
+ info = serializeIncludingFunctions(info);
4572
4555
  }
4573
- if (!eventProps.canTrack) {
4574
- return;
4556
+ let typeList = registry[type];
4557
+ if (!typeList) {
4558
+ typeList = registry[type] = [];
4575
4559
  }
4576
- if (isEditing()) {
4577
- return;
4560
+ typeList.push(info);
4561
+ if (isBrowser()) {
4562
+ const message = {
4563
+ type: "builder.register",
4564
+ data: {
4565
+ type,
4566
+ info
4567
+ }
4568
+ };
4569
+ try {
4570
+ parent.postMessage(message, "*");
4571
+ if (parent !== window) {
4572
+ window.postMessage(message, "*");
4573
+ }
4574
+ } catch (err) {
4575
+ console.debug("Could not postmessage", err);
4576
+ }
4578
4577
  }
4579
- if (!(isBrowser() || TARGET === "reactNative")) {
4580
- return;
4578
+ }
4579
+ function registerAction(action) {
4580
+ if (isBrowser()) {
4581
+ const actionClone = JSON.parse(JSON.stringify(action));
4582
+ if (action.action) {
4583
+ actionClone.action = action.action.toString();
4584
+ }
4585
+ window.parent?.postMessage({
4586
+ type: "builder.registerAction",
4587
+ data: actionClone
4588
+ }, "*");
4581
4589
  }
4582
- const baseUrl = apiHost || "https://cdn.builder.io";
4583
- const url = `${baseUrl}/api/v1/track`;
4584
- logFetch(url);
4585
- return fetch(url, {
4586
- method: "POST",
4587
- body: JSON.stringify({
4588
- events: [await createEvent(eventProps)]
4589
- }),
4590
- headers: {
4591
- "content-type": "application/json",
4592
- ...getSdkHeaders()
4593
- },
4594
- mode: "cors"
4595
- }).catch((err) => {
4596
- console.error("Failed to track: ", err);
4597
- });
4598
4590
  }
4599
- var track = (args) => _track({
4600
- ...args,
4601
- canTrack: true
4602
- });
4591
+
4592
+ // src/functions/set-editor-settings.ts
4593
+ var settings = {};
4594
+ function setEditorSettings(newSettings) {
4595
+ if (isBrowser()) {
4596
+ Object.assign(settings, newSettings);
4597
+ const message = {
4598
+ type: "builder.settingsChange",
4599
+ data: settings
4600
+ };
4601
+ parent.postMessage(message, "*");
4602
+ }
4603
+ }
4604
+
4605
+ // src/functions/get-builder-search-params/index.ts
4606
+ var BUILDER_SEARCHPARAMS_PREFIX = "builder.";
4607
+ var BUILDER_OPTIONS_PREFIX = "options.";
4608
+ var getBuilderSearchParams = (_options) => {
4609
+ if (!_options) {
4610
+ return {};
4611
+ }
4612
+ const options = normalizeSearchParams(_options);
4613
+ const newOptions = {};
4614
+ Object.keys(options).forEach((key) => {
4615
+ if (key.startsWith(BUILDER_SEARCHPARAMS_PREFIX)) {
4616
+ const trimmedKey = key.replace(BUILDER_SEARCHPARAMS_PREFIX, "").replace(BUILDER_OPTIONS_PREFIX, "");
4617
+ newOptions[trimmedKey] = options[key];
4618
+ }
4619
+ });
4620
+ return newOptions;
4621
+ };
4622
+ var getBuilderSearchParamsFromWindow = () => {
4623
+ if (!isBrowser()) {
4624
+ return {};
4625
+ }
4626
+ const searchParams = new URLSearchParams(window.location.search);
4627
+ return getBuilderSearchParams(searchParams);
4628
+ };
4603
4629
 
4604
4630
  // src/functions/is-from-trusted-host.ts
4605
4631
  var DEFAULT_TRUSTED_HOSTS = ["*.beta.builder.io", "beta.builder.io", "builder.io", "localhost", "qa.builder.io"];
@@ -5343,7 +5369,13 @@ function InteractiveElement(props) {
5343
5369
  rootState: props.context.rootState,
5344
5370
  rootSetState: props.context.rootSetState,
5345
5371
  localState: props.context.localState,
5346
- context: props.context.context
5372
+ context: props.context.context,
5373
+ trackingContext: {
5374
+ apiKey: props.context.apiKey,
5375
+ canTrack: props.context.canTrack ?? true,
5376
+ contentId: props.context.content?.id,
5377
+ variationId: props.context.content?.testVariationId
5378
+ }
5347
5379
  })
5348
5380
  } : {};
5349
5381
  });