@builder.io/sdk-solid 5.0.1 → 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.
@@ -214,141 +214,429 @@ var getUserAttributes = () => {
214
214
  };
215
215
  };
216
216
 
217
- // src/functions/evaluate/helpers.ts
218
- var getFunctionArguments = ({
219
- builder,
220
- context,
221
- event,
222
- state
217
+ // src/constants/sdk-version.ts
218
+ var SDK_VERSION = "5.1.1";
219
+
220
+ // src/helpers/sdk-headers.ts
221
+ var getSdkHeaders = () => ({
222
+ "X-Builder-SDK": TARGET,
223
+ "X-Builder-SDK-GEN": "2",
224
+ "X-Builder-SDK-Version": SDK_VERSION
225
+ });
226
+
227
+ // src/helpers/nullable.ts
228
+ var checkIsDefined = (maybeT) => maybeT !== null && maybeT !== void 0;
229
+
230
+ // src/helpers/url.ts
231
+ var getTopLevelDomain = (host) => {
232
+ if (host === "localhost" || host === "127.0.0.1") {
233
+ return host;
234
+ }
235
+ const parts = host.split(".");
236
+ if (parts.length > 2) {
237
+ return parts.slice(1).join(".");
238
+ }
239
+ return host;
240
+ };
241
+
242
+ // src/helpers/cookie.ts
243
+ var getCookieSync = ({
244
+ name,
245
+ canTrack
223
246
  }) => {
224
- return Object.entries({
225
- state,
226
- Builder: builder,
227
- // legacy
228
- builder,
229
- context,
230
- event
231
- });
247
+ try {
248
+ if (!canTrack) {
249
+ return void 0;
250
+ }
251
+ return document.cookie.split("; ").find((row) => row.startsWith(`${name}=`))?.split("=")[1];
252
+ } catch (err) {
253
+ logger.warn("[COOKIE] GET error: ", err?.message || err);
254
+ return void 0;
255
+ }
232
256
  };
233
- var getBuilderGlobals = () => ({
234
- isEditing: isEditing(),
235
- isBrowser: isBrowser(),
236
- isServer: !isBrowser(),
237
- getUserAttributes: () => getUserAttributes()
238
- });
239
- var parseCode = (code, {
240
- isExpression = true
257
+ var getCookie = async (args) => getCookieSync(args);
258
+ var stringifyCookie = (cookie) => cookie.map(([key, value]) => value ? `${key}=${value}` : key).filter(checkIsDefined).join("; ");
259
+ var SECURE_CONFIG = [["secure", ""], ["SameSite", "None"]];
260
+ var createCookieString = ({
261
+ name,
262
+ value,
263
+ expires
241
264
  }) => {
242
- const useReturn = (
243
- // we disable this for cases where we definitely don't want a return
244
- isExpression && !(code.includes(";") || code.includes(" return ") || code.trim().startsWith("return "))
245
- );
246
- const useCode = useReturn ? `return (${code});` : code;
247
- return useCode;
265
+ const secure = isBrowser() ? location.protocol === "https:" : true;
266
+ const secureObj = secure ? SECURE_CONFIG : [[]];
267
+ const expiresObj = expires ? [["expires", expires.toUTCString()]] : [[]];
268
+ const cookieValue = [[name, value], ...expiresObj, ["path", "/"], ["domain", getTopLevelDomain(window.location.hostname)], ...secureObj];
269
+ const cookie = stringifyCookie(cookieValue);
270
+ return cookie;
248
271
  };
249
- function flattenState({
250
- rootState,
251
- localState,
252
- rootSetState
253
- }) {
254
- return new Proxy(rootState, {
255
- get: (target, prop) => {
256
- if (localState && prop in localState) {
257
- return localState[prop];
258
- }
259
- const val = target[prop];
260
- if (typeof val === "object" && val !== null) {
261
- return flattenState({
262
- rootState: val,
263
- localState: void 0,
264
- rootSetState: rootSetState ? (subState) => {
265
- target[prop] = subState;
266
- rootSetState(target);
267
- } : void 0
268
- });
269
- }
270
- return val;
271
- },
272
- set: (target, prop, value) => {
273
- if (localState && prop in localState) {
274
- throw new Error("Writing to local state is not allowed as it is read-only.");
275
- }
276
- target[prop] = value;
277
- rootSetState?.(target);
278
- return true;
272
+ var setCookie = async ({
273
+ name,
274
+ value,
275
+ expires,
276
+ canTrack
277
+ }) => {
278
+ try {
279
+ if (!canTrack) {
280
+ return;
279
281
  }
282
+ const cookie = createCookieString({
283
+ name,
284
+ value,
285
+ expires
286
+ });
287
+ document.cookie = cookie;
288
+ } catch (err) {
289
+ logger.warn("[COOKIE] SET error: ", err?.message || err);
290
+ }
291
+ };
292
+
293
+ // src/helpers/uuid.ts
294
+ function uuidv4() {
295
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
296
+ const r = Math.random() * 16 | 0, v2 = c == "x" ? r : r & 3 | 8;
297
+ return v2.toString(16);
280
298
  });
281
299
  }
300
+ function uuid() {
301
+ return uuidv4().replace(/-/g, "");
302
+ }
282
303
 
283
- // src/functions/evaluate/browser-runtime/browser.ts
284
- var runInBrowser = ({
285
- code,
286
- builder,
287
- context,
288
- event,
289
- localState,
290
- rootSetState,
291
- rootState
304
+ // src/helpers/sessionId.ts
305
+ var SESSION_LOCAL_STORAGE_KEY = "builderSessionId";
306
+ var getSessionId = async ({
307
+ canTrack
292
308
  }) => {
293
- const functionArgs = getFunctionArguments({
294
- builder,
295
- context,
296
- event,
297
- state: flattenState({
298
- rootState,
299
- localState,
300
- rootSetState
301
- })
309
+ if (!canTrack) {
310
+ return void 0;
311
+ }
312
+ const sessionId = await getCookie({
313
+ name: SESSION_LOCAL_STORAGE_KEY,
314
+ canTrack
302
315
  });
303
- return new Function(...functionArgs.map(([name]) => name), code)(...functionArgs.map(([, value]) => value));
316
+ if (checkIsDefined(sessionId)) {
317
+ return sessionId;
318
+ } else {
319
+ const newSessionId = createSessionId();
320
+ setSessionId({
321
+ id: newSessionId,
322
+ canTrack
323
+ });
324
+ return newSessionId;
325
+ }
304
326
  };
327
+ var createSessionId = () => uuid();
328
+ var setSessionId = ({
329
+ id: id2,
330
+ canTrack
331
+ }) => setCookie({
332
+ name: SESSION_LOCAL_STORAGE_KEY,
333
+ value: id2,
334
+ canTrack
335
+ });
305
336
 
306
- // src/functions/evaluate/edge-runtime/acorn-interpreter.ts
307
- var p;
308
- var ca = function(a) {
309
- function b(f) {
310
- 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));
311
- }
312
- function d(f) {
313
- return 65 > f ? 36 === f : 91 > f ? true : 97 > f ? 95 === f : 123 > f ? true : 170 <= f && Pb.test(String.fromCharCode(f));
314
- }
315
- function c(f, g) {
316
- var l = r;
317
- for (var n = 1, w = 0; ; ) {
318
- Sa.lastIndex = w;
319
- var J = Sa.exec(l);
320
- if (J && J.index < f)
321
- ++n, w = J.index + J[0].length;
322
- else
323
- break;
337
+ // src/helpers/localStorage.ts
338
+ var getLocalStorage = () => isBrowser() && typeof localStorage !== "undefined" ? localStorage : void 0;
339
+ var getLocalStorageItem = ({
340
+ key,
341
+ canTrack
342
+ }) => {
343
+ try {
344
+ if (canTrack) {
345
+ return getLocalStorage()?.getItem(key);
324
346
  }
325
- l = {
326
- line: n,
327
- ab: f - w
328
- };
329
- g += " (" + l.line + ":" + l.ab + ")";
330
- g = new SyntaxError(g);
331
- g.j = f;
332
- g.X = l;
333
- g.o = m;
334
- throw g;
347
+ return void 0;
348
+ } catch (err) {
349
+ return void 0;
335
350
  }
336
- function e(f) {
337
- f = f.split(" ");
338
- for (var g = /* @__PURE__ */ Object.create(null), l = 0; l < f.length; l++)
339
- g[f[l]] = true;
340
- return function(n) {
341
- return g[n] || false;
342
- };
351
+ };
352
+ var setLocalStorageItem = ({
353
+ key,
354
+ canTrack,
355
+ value
356
+ }) => {
357
+ try {
358
+ if (canTrack) {
359
+ getLocalStorage()?.setItem(key, value);
360
+ }
361
+ } catch (err) {
343
362
  }
344
- function h() {
345
- this.line = la;
346
- this.ab = m - X;
363
+ };
364
+
365
+ // src/helpers/visitorId.ts
366
+ var VISITOR_LOCAL_STORAGE_KEY = "builderVisitorId";
367
+ var getVisitorId = ({
368
+ canTrack
369
+ }) => {
370
+ if (!canTrack) {
371
+ return void 0;
347
372
  }
348
- function k(f, g) {
349
- oa = m;
350
- z.C && (cb = new h());
351
- x = f;
373
+ const visitorId = getLocalStorageItem({
374
+ key: VISITOR_LOCAL_STORAGE_KEY,
375
+ canTrack
376
+ });
377
+ if (checkIsDefined(visitorId)) {
378
+ return visitorId;
379
+ } else {
380
+ const newVisitorId = createVisitorId();
381
+ setVisitorId({
382
+ id: newVisitorId,
383
+ canTrack
384
+ });
385
+ return newVisitorId;
386
+ }
387
+ };
388
+ var createVisitorId = () => uuid();
389
+ var setVisitorId = ({
390
+ id: id2,
391
+ canTrack
392
+ }) => setLocalStorageItem({
393
+ key: VISITOR_LOCAL_STORAGE_KEY,
394
+ value: id2,
395
+ canTrack
396
+ });
397
+
398
+ // src/functions/log-fetch.ts
399
+ function logFetch(url) {
400
+ if (typeof process !== "undefined" && process.env?.DEBUG) {
401
+ if (String(process.env.DEBUG) == "true") {
402
+ logger.log(url);
403
+ }
404
+ }
405
+ }
406
+
407
+ // src/functions/track/index.ts
408
+ var getTrackingEventData = async ({
409
+ canTrack
410
+ }) => {
411
+ if (!canTrack) {
412
+ return {
413
+ visitorId: void 0,
414
+ sessionId: void 0
415
+ };
416
+ }
417
+ const sessionId = await getSessionId({
418
+ canTrack
419
+ });
420
+ const visitorId = getVisitorId({
421
+ canTrack
422
+ });
423
+ return {
424
+ sessionId,
425
+ visitorId
426
+ };
427
+ };
428
+ var createEvent = async ({
429
+ type: eventType,
430
+ canTrack,
431
+ apiKey,
432
+ metadata,
433
+ ...properties
434
+ }) => ({
435
+ type: eventType,
436
+ data: {
437
+ ...properties,
438
+ metadata: {
439
+ url: location.href,
440
+ ...metadata
441
+ },
442
+ ...await getTrackingEventData({
443
+ canTrack
444
+ }),
445
+ userAttributes: getUserAttributes(),
446
+ ownerId: apiKey
447
+ }
448
+ });
449
+ async function _track({
450
+ apiHost,
451
+ ...eventProps
452
+ }) {
453
+ if (!eventProps.apiKey) {
454
+ logger.error("Missing API key for track call. Please provide your API key.");
455
+ return;
456
+ }
457
+ if (!eventProps.canTrack) {
458
+ return;
459
+ }
460
+ if (isEditing()) {
461
+ return;
462
+ }
463
+ if (!(isBrowser() || TARGET === "reactNative")) {
464
+ return;
465
+ }
466
+ const baseUrl = apiHost || "https://cdn.builder.io";
467
+ const url = `${baseUrl}/api/v1/track`;
468
+ logFetch(url);
469
+ return fetch(url, {
470
+ method: "POST",
471
+ body: JSON.stringify({
472
+ events: [await createEvent(eventProps)]
473
+ }),
474
+ headers: {
475
+ "content-type": "application/json",
476
+ ...getSdkHeaders()
477
+ },
478
+ mode: "cors"
479
+ }).catch((err) => {
480
+ });
481
+ }
482
+ var track = (args) => _track({
483
+ ...args,
484
+ canTrack: true
485
+ });
486
+
487
+ // src/functions/evaluate/helpers.ts
488
+ var getFunctionArguments = ({
489
+ builder,
490
+ context,
491
+ event,
492
+ state
493
+ }) => {
494
+ return Object.entries({
495
+ state,
496
+ Builder: builder,
497
+ // legacy
498
+ builder,
499
+ context,
500
+ event
501
+ });
502
+ };
503
+ var getBuilderGlobals = (trackingContext) => ({
504
+ isEditing: isEditing(),
505
+ isBrowser: isBrowser(),
506
+ isServer: !isBrowser(),
507
+ getUserAttributes: () => getUserAttributes(),
508
+ trackConversion: (amount, customProperties) => {
509
+ if (!trackingContext?.apiKey || trackingContext?.canTrack === false) {
510
+ return;
511
+ }
512
+ _track({
513
+ type: "conversion",
514
+ apiKey: trackingContext.apiKey,
515
+ canTrack: trackingContext.canTrack ?? true,
516
+ contentId: trackingContext.contentId,
517
+ variationId: trackingContext.variationId !== trackingContext.contentId ? trackingContext.variationId : void 0,
518
+ metadata: {
519
+ ...customProperties || {},
520
+ ...amount !== void 0 ? {
521
+ amount
522
+ } : {}
523
+ }
524
+ });
525
+ }
526
+ });
527
+ var parseCode = (code, {
528
+ isExpression = true
529
+ }) => {
530
+ const useReturn = (
531
+ // we disable this for cases where we definitely don't want a return
532
+ isExpression && !(code.includes(";") || code.includes(" return ") || code.trim().startsWith("return "))
533
+ );
534
+ const useCode = useReturn ? `return (${code});` : code;
535
+ return useCode;
536
+ };
537
+ function flattenState({
538
+ rootState,
539
+ localState,
540
+ rootSetState
541
+ }) {
542
+ return new Proxy(rootState, {
543
+ get: (target, prop) => {
544
+ if (localState && prop in localState) {
545
+ return localState[prop];
546
+ }
547
+ const val = target[prop];
548
+ if (typeof val === "object" && val !== null) {
549
+ return flattenState({
550
+ rootState: val,
551
+ localState: void 0,
552
+ rootSetState: rootSetState ? (subState) => {
553
+ target[prop] = subState;
554
+ rootSetState(target);
555
+ } : void 0
556
+ });
557
+ }
558
+ return val;
559
+ },
560
+ set: (target, prop, value) => {
561
+ if (localState && prop in localState) {
562
+ throw new Error("Writing to local state is not allowed as it is read-only.");
563
+ }
564
+ target[prop] = value;
565
+ rootSetState?.(target);
566
+ return true;
567
+ }
568
+ });
569
+ }
570
+
571
+ // src/functions/evaluate/browser-runtime/browser.ts
572
+ var runInBrowser = ({
573
+ code,
574
+ builder,
575
+ context,
576
+ event,
577
+ localState,
578
+ rootSetState,
579
+ rootState
580
+ }) => {
581
+ const functionArgs = getFunctionArguments({
582
+ builder,
583
+ context,
584
+ event,
585
+ state: flattenState({
586
+ rootState,
587
+ localState,
588
+ rootSetState
589
+ })
590
+ });
591
+ return new Function(...functionArgs.map(([name]) => name), code)(...functionArgs.map(([, value]) => value));
592
+ };
593
+
594
+ // src/functions/evaluate/edge-runtime/acorn-interpreter.ts
595
+ var p;
596
+ var ca = function(a) {
597
+ function b(f) {
598
+ 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));
599
+ }
600
+ function d(f) {
601
+ return 65 > f ? 36 === f : 91 > f ? true : 97 > f ? 95 === f : 123 > f ? true : 170 <= f && Pb.test(String.fromCharCode(f));
602
+ }
603
+ function c(f, g) {
604
+ var l = r;
605
+ for (var n = 1, w = 0; ; ) {
606
+ Sa.lastIndex = w;
607
+ var J = Sa.exec(l);
608
+ if (J && J.index < f)
609
+ ++n, w = J.index + J[0].length;
610
+ else
611
+ break;
612
+ }
613
+ l = {
614
+ line: n,
615
+ ab: f - w
616
+ };
617
+ g += " (" + l.line + ":" + l.ab + ")";
618
+ g = new SyntaxError(g);
619
+ g.j = f;
620
+ g.X = l;
621
+ g.o = m;
622
+ throw g;
623
+ }
624
+ function e(f) {
625
+ f = f.split(" ");
626
+ for (var g = /* @__PURE__ */ Object.create(null), l = 0; l < f.length; l++)
627
+ g[f[l]] = true;
628
+ return function(n) {
629
+ return g[n] || false;
630
+ };
631
+ }
632
+ function h() {
633
+ this.line = la;
634
+ this.ab = m - X;
635
+ }
636
+ function k(f, g) {
637
+ oa = m;
638
+ z.C && (cb = new h());
639
+ x = f;
352
640
  C();
353
641
  T = g;
354
642
  ya = f.m;
@@ -3478,1117 +3766,855 @@ theFunction();
3478
3766
  return output;
3479
3767
  };
3480
3768
 
3481
- // src/helpers/nullable.ts
3482
- var checkIsDefined = (maybeT) => maybeT !== null && maybeT !== void 0;
3483
-
3484
3769
  // src/functions/is-node-runtime.ts
3485
3770
  function isNodeRuntime() {
3486
3771
  return typeof process !== "undefined" && checkIsDefined(process?.versions?.node);
3487
- }
3488
-
3489
- // src/functions/evaluate/should-force-browser-runtime-in-node.ts
3490
- var shouldForceBrowserRuntimeInNode = ({
3491
- shouldLogWarning
3492
- }) => {
3493
- if (!isNodeRuntime())
3494
- return false;
3495
- const isArm64 = process.arch === "arm64";
3496
- const isNode20 = process.version.startsWith("v20");
3497
- const hasNoNodeSnapshotNodeOption = process.env.NODE_OPTIONS?.includes("--no-node-snapshot");
3498
- if (isArm64 && isNode20 && !hasNoNodeSnapshotNodeOption) {
3499
- if (shouldLogWarning) {
3500
- logger.log(`Skipping usage of \`isolated-vm\` to avoid crashes in Node v20 on an arm64 machine.
3501
- If you would like to use the \`isolated-vm\` package on this machine, please provide the \`NODE_OPTIONS=--no-node-snapshot\` config to your Node process.
3502
- See https://github.com/BuilderIO/builder/blob/main/packages/sdks/README.md#node-v20--m1-macs-apple-silicon-support for more information.
3503
- `);
3504
- }
3505
- return true;
3506
- }
3507
- return false;
3508
- };
3509
-
3510
- // src/functions/evaluate/choose-eval.ts
3511
- var chooseBrowserOrServerEval = (args) => isBrowser() || shouldForceBrowserRuntimeInNode({
3512
- shouldLogWarning: true
3513
- }) ? runInBrowser(args) : runInEdge(args);
3514
-
3515
- // src/functions/evaluate/evaluate.ts
3516
- var STATE_GETTER_REGEX = /^(return )?(\s*)?state(?<getPath>(\.\w+)+)(\s*);?$/;
3517
- var VIRTUAL_INDEX_REGEX = /(\s)*var(\s)+_virtual_index(\s)*=(\s)*state(?<getPath>(\.\w+)+)(\s*);?(\s)*return(\s)*_virtual_index(\s)*/;
3518
- var getSimpleExpressionGetPath = (code) => {
3519
- return STATE_GETTER_REGEX.exec(code.trim())?.groups?.getPath?.slice(1) || VIRTUAL_INDEX_REGEX.exec(code.trim())?.groups?.getPath?.slice(1);
3520
- };
3521
- function evaluate({
3522
- code,
3523
- context,
3524
- localState,
3525
- rootState,
3526
- rootSetState,
3527
- event,
3528
- isExpression = true
3529
- }) {
3530
- if (code.trim() === "") {
3531
- return void 0;
3532
- }
3533
- const getPath = getSimpleExpressionGetPath(code.trim());
3534
- if (getPath) {
3535
- return get({
3536
- ...rootState,
3537
- ...localState
3538
- }, getPath);
3539
- }
3540
- const args = {
3541
- code: parseCode(code, {
3542
- isExpression
3543
- }),
3544
- builder: getBuilderGlobals(),
3545
- context,
3546
- event,
3547
- rootSetState,
3548
- rootState,
3549
- localState
3550
- };
3551
- try {
3552
- const newEval = chooseBrowserOrServerEval(args);
3553
- return newEval;
3554
- } catch (e) {
3555
- logger.error("Failed code evaluation: " + e.message, {
3556
- code
3557
- });
3558
- return void 0;
3559
- }
3560
- }
3561
-
3562
- // src/functions/get-block-component-options.ts
3563
- function getBlockComponentOptions(block, context) {
3564
- return {
3565
- ...block.component?.options,
3566
- ...block.options,
3567
- ...evaluateTextComponentTextOption(block, context)
3568
- };
3569
- }
3570
- var evaluateTextComponentTextOption = (block, context) => {
3571
- if (block.component?.name === "Text" && block.component.options?.text && typeof block.component.options.text === "string") {
3572
- return {
3573
- ...block.component.options,
3574
- text: block.component.options.text.replace(/{{([^}]+)}}/g, (_match, group) => evaluate({
3575
- code: group,
3576
- context,
3577
- localState: context.localState,
3578
- rootState: context.rootState,
3579
- rootSetState: context.rootSetState
3580
- }))
3581
- };
3582
- }
3583
- };
3584
-
3585
- // src/helpers/omit.ts
3586
- function omit(obj, ...values) {
3587
- const newObject = Object.assign({}, obj);
3588
- for (const key of values) {
3589
- delete newObject[key];
3590
- }
3591
- return newObject;
3592
- }
3593
-
3594
- // src/functions/traverse.ts
3595
- function traverse(obj, callback, parent2 = null, key = null, visited = /* @__PURE__ */ new WeakSet()) {
3596
- if (obj == null || typeof obj !== "object") {
3597
- callback(obj, (newValue) => {
3598
- if (parent2 !== null && key !== null) {
3599
- parent2[key] = newValue;
3600
- }
3601
- });
3602
- return;
3603
- }
3604
- if (visited.has(obj)) {
3605
- return;
3606
- }
3607
- visited.add(obj);
3608
- if (Array.isArray(obj)) {
3609
- obj.forEach((item, index) => {
3610
- const update = (newValue) => {
3611
- obj[index] = newValue;
3612
- };
3613
- callback(item, update);
3614
- traverse(item, callback, obj, index, visited);
3615
- });
3616
- } else {
3617
- Object.entries(obj).forEach(([key2, value]) => {
3618
- const update = (newValue) => {
3619
- obj[key2] = newValue;
3620
- };
3621
- callback(value, update);
3622
- traverse(value, callback, obj, key2, visited);
3623
- });
3624
- }
3625
- }
3626
-
3627
- // src/functions/extract-localized-values.ts
3628
- function isLocalizedField(value) {
3629
- return value && typeof value === "object" && value["@type"] === "@builder.io/core:LocalizedValue";
3630
- }
3631
- function containsLocalizedValues(data) {
3632
- if (!data || !Object.getOwnPropertyNames(data).length) {
3633
- return false;
3634
- }
3635
- let hasLocalizedValues = false;
3636
- traverse(data, (value) => {
3637
- if (isLocalizedField(value)) {
3638
- hasLocalizedValues = true;
3639
- return;
3640
- }
3641
- });
3642
- return hasLocalizedValues;
3643
- }
3644
- function extractLocalizedValues(data, locale) {
3645
- if (!data || !Object.getOwnPropertyNames(data).length) {
3646
- return {};
3647
- }
3648
- traverse(data, (value, update) => {
3649
- if (isLocalizedField(value)) {
3650
- update(value[locale] ?? void 0);
3651
- }
3652
- });
3653
- return data;
3654
- }
3655
- function resolveLocalizedValues(block, locale) {
3656
- if (block.component?.options && containsLocalizedValues(block.component?.options)) {
3657
- if (!locale) {
3658
- }
3659
- block.component.options = extractLocalizedValues(block.component.options, locale ?? "Default");
3660
- }
3661
- return block;
3662
- }
3663
-
3664
- // src/functions/fast-clone.ts
3665
- var fastClone = (obj) => JSON.parse(JSON.stringify(obj));
3666
-
3667
- // src/functions/set.ts
3668
- var set = (obj, _path, value) => {
3669
- if (Object(obj) !== obj) {
3670
- return obj;
3671
- }
3672
- const path = Array.isArray(_path) ? _path : _path.toString().match(/[^.[\]]+/g);
3673
- path.slice(0, -1).reduce((a, c, i) => Object(a[c]) === a[c] ? a[c] : a[c] = Math.abs(Number(path[i + 1])) >> 0 === +path[i + 1] ? [] : {}, obj)[path[path.length - 1]] = value;
3674
- return obj;
3675
- };
3676
-
3677
- // src/functions/transform-block.ts
3678
- function transformBlock(block) {
3679
- return block;
3680
- }
3681
-
3682
- // src/functions/get-processed-block.ts
3683
- function deepCloneWithConditions(obj) {
3684
- if (obj === null || typeof obj !== "object") {
3685
- return obj;
3686
- }
3687
- if (Array.isArray(obj)) {
3688
- return obj.map((item) => deepCloneWithConditions(item));
3689
- }
3690
- if (obj["@type"] === "@builder.io/sdk:Element") {
3691
- return obj;
3692
- }
3693
- const clonedObj = {};
3694
- for (const key in obj) {
3695
- if (key !== "meta" && Object.prototype.hasOwnProperty.call(obj, key)) {
3696
- clonedObj[key] = deepCloneWithConditions(obj[key]);
3697
- }
3698
- }
3699
- return clonedObj;
3700
- }
3701
- var IS_SDK_WITHOUT_CACHED_PROCESSED_BLOCK = ["svelte", "vue", "angular", "qwik", "solid"].includes(TARGET);
3702
- var getCopy = (block) => {
3703
- if (IS_SDK_WITHOUT_CACHED_PROCESSED_BLOCK) {
3704
- const copy = fastClone(block);
3705
- const copied = {
3706
- ...copy,
3707
- properties: {
3708
- ...copy.properties
3709
- },
3710
- actions: {
3711
- ...copy.actions
3712
- }
3713
- };
3714
- return copied;
3715
- } else {
3716
- const copy = deepCloneWithConditions(omit(block, "children", "meta"));
3717
- return {
3718
- ...copy,
3719
- properties: {
3720
- ...copy.properties
3721
- },
3722
- actions: {
3723
- ...copy.actions
3724
- },
3725
- children: block.children,
3726
- meta: block.meta
3727
- };
3728
- }
3729
- };
3730
- var evaluateBindings = ({
3731
- block,
3732
- context,
3733
- localState,
3734
- rootState,
3735
- rootSetState
3736
- }) => {
3737
- if (!block.bindings) {
3738
- return block;
3739
- }
3740
- const copied = getCopy(block);
3741
- for (const binding in block.bindings) {
3742
- const expression = block.bindings[binding];
3743
- const value = evaluate({
3744
- code: expression,
3745
- localState,
3746
- rootState,
3747
- rootSetState,
3748
- context
3749
- });
3750
- set(copied, binding, value);
3751
- }
3752
- return copied;
3753
- };
3754
- function getProcessedBlock({
3755
- block,
3756
- context,
3757
- localState,
3758
- rootState,
3759
- rootSetState
3760
- }) {
3761
- let transformedBlock = transformBlock(block);
3762
- transformedBlock = evaluateBindings({
3763
- block: transformedBlock,
3764
- localState,
3765
- rootState,
3766
- rootSetState,
3767
- context
3768
- });
3769
- transformedBlock = resolveLocalizedValues(transformedBlock, rootState.locale);
3770
- return transformedBlock;
3771
- }
3772
-
3773
- // src/functions/camel-to-kebab-case.ts
3774
- var camelToKebabCase = (str) => str ? str.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, "$1-$2").toLowerCase() : "";
3775
-
3776
- // src/components/block/animator.ts
3777
- function throttle(func, wait, options = {}) {
3778
- let context;
3779
- let args;
3780
- let result;
3781
- let timeout = null;
3782
- let previous = 0;
3783
- const later = function() {
3784
- previous = options.leading === false ? 0 : Date.now();
3785
- timeout = null;
3786
- result = func.apply(context, args);
3787
- if (!timeout)
3788
- context = args = null;
3789
- };
3790
- return function() {
3791
- const now = Date.now();
3792
- if (!previous && options.leading === false)
3793
- previous = now;
3794
- const remaining = wait - (now - previous);
3795
- context = this;
3796
- args = arguments;
3797
- if (remaining <= 0 || remaining > wait) {
3798
- if (timeout) {
3799
- clearTimeout(timeout);
3800
- timeout = null;
3801
- }
3802
- previous = now;
3803
- result = func.apply(context, args);
3804
- if (!timeout)
3805
- context = args = null;
3806
- } else if (!timeout && options.trailing !== false) {
3807
- timeout = setTimeout(later, remaining);
3808
- }
3809
- return result;
3810
- };
3811
- }
3812
- function assign(target, ..._args) {
3813
- const to = Object(target);
3814
- for (let index = 1; index < arguments.length; index++) {
3815
- const nextSource = arguments[index];
3816
- if (nextSource != null) {
3817
- for (const nextKey in nextSource) {
3818
- if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
3819
- to[nextKey] = nextSource[nextKey];
3820
- }
3821
- }
3822
- }
3823
- }
3824
- return to;
3825
- }
3826
- function bindAnimations(animations) {
3827
- if (TARGET === "reactNative") {
3828
- return;
3829
- }
3830
- for (const animation of animations) {
3831
- switch (animation.trigger) {
3832
- case "pageLoad":
3833
- triggerAnimation(animation);
3834
- break;
3835
- case "scrollInView":
3836
- bindScrollInViewAnimation(animation);
3837
- break;
3838
- }
3839
- }
3840
- }
3841
- function warnElementNotPresent(id2) {
3842
- }
3843
- function augmentAnimation(animation, element) {
3844
- const stylesUsed = getAllStylesUsed(animation);
3845
- const computedStyle = getComputedStyle(element);
3846
- const firstStyles = animation.steps[0].styles;
3847
- const lastStyles = animation.steps[animation.steps.length - 1].styles;
3848
- const bothStyles = [firstStyles, lastStyles];
3849
- for (const styles of bothStyles) {
3850
- for (const style of stylesUsed) {
3851
- if (!(style in styles)) {
3852
- styles[style] = computedStyle[style];
3853
- }
3854
- }
3855
- }
3856
- }
3857
- function getAllStylesUsed(animation) {
3858
- const properties = [];
3859
- for (const step of animation.steps) {
3860
- for (const key in step.styles) {
3861
- if (properties.indexOf(key) === -1) {
3862
- properties.push(key);
3863
- }
3864
- }
3865
- }
3866
- return properties;
3867
- }
3868
- function triggerAnimation(animation) {
3869
- const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
3870
- if (!elements.length) {
3871
- warnElementNotPresent(animation.elementId || animation.id || "");
3872
- return;
3873
- }
3874
- Array.from(elements).forEach((element) => {
3875
- augmentAnimation(animation, element);
3876
- element.style.transition = "none";
3877
- element.style.transitionDelay = "0";
3878
- assign(element.style, animation.steps[0].styles);
3879
- setTimeout(() => {
3880
- element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
3881
- if (animation.delay) {
3882
- element.style.transitionDelay = animation.delay + "s";
3883
- }
3884
- assign(element.style, animation.steps[1].styles);
3885
- setTimeout(() => {
3886
- element.style.transition = "";
3887
- element.style.transitionDelay = "";
3888
- }, (animation.delay || 0) * 1e3 + animation.duration * 1e3 + 100);
3889
- });
3890
- });
3891
- }
3892
- function bindScrollInViewAnimation(animation) {
3893
- const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
3894
- if (!elements.length) {
3895
- warnElementNotPresent(animation.elementId || animation.id || "");
3896
- return;
3897
- }
3898
- Array.from(elements).forEach((element) => {
3899
- augmentAnimation(animation, element);
3900
- let triggered = false;
3901
- let pendingAnimation = false;
3902
- function immediateOnScroll() {
3903
- if (!triggered && isScrolledIntoView(element)) {
3904
- triggered = true;
3905
- pendingAnimation = true;
3906
- setTimeout(() => {
3907
- assign(element.style, animation.steps[1].styles);
3908
- if (!animation.repeat) {
3909
- document.removeEventListener("scroll", onScroll);
3910
- }
3911
- setTimeout(() => {
3912
- pendingAnimation = false;
3913
- if (!animation.repeat) {
3914
- element.style.transition = "";
3915
- element.style.transitionDelay = "";
3916
- }
3917
- }, (animation.duration + (animation.delay || 0)) * 1e3 + 100);
3918
- });
3919
- } else if (animation.repeat && triggered && !pendingAnimation && !isScrolledIntoView(element)) {
3920
- triggered = false;
3921
- assign(element.style, animation.steps[0].styles);
3922
- }
3923
- }
3924
- const onScroll = throttle(immediateOnScroll, 200, {
3925
- leading: false
3926
- });
3927
- function isScrolledIntoView(elem) {
3928
- const rect = elem.getBoundingClientRect();
3929
- const windowHeight = window.innerHeight;
3930
- const thresholdPercent = (animation.thresholdPercent || 0) / 100;
3931
- const threshold = thresholdPercent * windowHeight;
3932
- return rect.bottom > threshold && rect.top < windowHeight - threshold;
3933
- }
3934
- const defaultState = animation.steps[0].styles;
3935
- function attachDefaultState() {
3936
- assign(element.style, defaultState);
3937
- }
3938
- attachDefaultState();
3939
- setTimeout(() => {
3940
- element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
3941
- if (animation.delay) {
3942
- element.style.transitionDelay = animation.delay + "s";
3943
- }
3944
- });
3945
- document.addEventListener("scroll", onScroll, {
3946
- capture: true,
3947
- passive: true
3948
- });
3949
- immediateOnScroll();
3950
- });
3951
- }
3952
-
3953
- // src/helpers/css.ts
3954
- var convertStyleMapToCSSArray = (style) => {
3955
- const cssProps = Object.entries(style).map(([key, value]) => {
3956
- if (typeof value === "string") {
3957
- return `${camelToKebabCase(key)}: ${value};`;
3958
- } else {
3959
- return void 0;
3960
- }
3961
- });
3962
- return cssProps.filter(checkIsDefined);
3963
- };
3964
- var convertStyleMapToCSS = (style) => convertStyleMapToCSSArray(style).join("\n");
3965
- var createCssClass = ({
3966
- mediaQuery,
3967
- className,
3968
- styles
3772
+ }
3773
+
3774
+ // src/functions/evaluate/should-force-browser-runtime-in-node.ts
3775
+ var shouldForceBrowserRuntimeInNode = ({
3776
+ shouldLogWarning
3969
3777
  }) => {
3970
- const cssClass = `.${className} {
3971
- ${convertStyleMapToCSS(styles)}
3972
- }`;
3973
- if (mediaQuery) {
3974
- return `${mediaQuery} {
3975
- ${cssClass}
3976
- }`;
3977
- } else {
3978
- return cssClass;
3778
+ if (!isNodeRuntime())
3779
+ return false;
3780
+ const isArm64 = process.arch === "arm64";
3781
+ const isNode20 = process.version.startsWith("v20");
3782
+ const hasNoNodeSnapshotNodeOption = process.env.NODE_OPTIONS?.includes("--no-node-snapshot");
3783
+ if (isArm64 && isNode20 && !hasNoNodeSnapshotNodeOption) {
3784
+ if (shouldLogWarning) {
3785
+ logger.log(`Skipping usage of \`isolated-vm\` to avoid crashes in Node v20 on an arm64 machine.
3786
+ If you would like to use the \`isolated-vm\` package on this machine, please provide the \`NODE_OPTIONS=--no-node-snapshot\` config to your Node process.
3787
+ See https://github.com/BuilderIO/builder/blob/main/packages/sdks/README.md#node-v20--m1-macs-apple-silicon-support for more information.
3788
+ `);
3789
+ }
3790
+ return true;
3979
3791
  }
3792
+ return false;
3980
3793
  };
3981
3794
 
3982
- // src/functions/transform-style-property.ts
3983
- function transformStyleProperty({
3984
- style
3795
+ // src/functions/evaluate/choose-eval.ts
3796
+ var chooseBrowserOrServerEval = (args) => isBrowser() || shouldForceBrowserRuntimeInNode({
3797
+ shouldLogWarning: true
3798
+ }) ? runInBrowser(args) : runInEdge(args);
3799
+
3800
+ // src/functions/evaluate/evaluate.ts
3801
+ var STATE_GETTER_REGEX = /^(return )?(\s*)?state(?<getPath>(\.\w+)+)(\s*);?$/;
3802
+ var VIRTUAL_INDEX_REGEX = /(\s)*var(\s)+_virtual_index(\s)*=(\s)*state(?<getPath>(\.\w+)+)(\s*);?(\s)*return(\s)*_virtual_index(\s)*/;
3803
+ var getSimpleExpressionGetPath = (code) => {
3804
+ return STATE_GETTER_REGEX.exec(code.trim())?.groups?.getPath?.slice(1) || VIRTUAL_INDEX_REGEX.exec(code.trim())?.groups?.getPath?.slice(1);
3805
+ };
3806
+ function evaluate({
3807
+ code,
3808
+ context,
3809
+ localState,
3810
+ rootState,
3811
+ rootSetState,
3812
+ event,
3813
+ isExpression = true,
3814
+ trackingContext
3985
3815
  }) {
3986
- return style;
3816
+ if (code.trim() === "") {
3817
+ return void 0;
3818
+ }
3819
+ const getPath = getSimpleExpressionGetPath(code.trim());
3820
+ if (getPath) {
3821
+ return get({
3822
+ ...rootState,
3823
+ ...localState
3824
+ }, getPath);
3825
+ }
3826
+ const args = {
3827
+ code: parseCode(code, {
3828
+ isExpression
3829
+ }),
3830
+ builder: getBuilderGlobals(trackingContext),
3831
+ context,
3832
+ event,
3833
+ rootSetState,
3834
+ rootState,
3835
+ localState
3836
+ };
3837
+ try {
3838
+ const newEval = chooseBrowserOrServerEval(args);
3839
+ return newEval;
3840
+ } catch (e) {
3841
+ logger.error("Failed code evaluation: " + e.message, {
3842
+ code
3843
+ });
3844
+ return void 0;
3845
+ }
3987
3846
  }
3988
3847
 
3989
- // src/functions/get-style.ts
3990
- var getStyle = ({
3991
- block,
3992
- context
3993
- }) => {
3994
- return mapStyleObjToStrIfNeeded(transformStyleProperty({
3995
- style: block.style || {},
3996
- context,
3997
- block
3998
- }));
3848
+ // src/functions/get-block-component-options.ts
3849
+ function getBlockComponentOptions(block, context) {
3850
+ return {
3851
+ ...block.component?.options,
3852
+ ...block.options,
3853
+ ...evaluateTextComponentTextOption(block, context)
3854
+ };
3855
+ }
3856
+ var evaluateTextComponentTextOption = (block, context) => {
3857
+ if (block.component?.name === "Text" && block.component.options?.text && typeof block.component.options.text === "string") {
3858
+ return {
3859
+ ...block.component.options,
3860
+ text: block.component.options.text.replace(/{{([^}]+)}}/g, (_match, group) => evaluate({
3861
+ code: group,
3862
+ context,
3863
+ localState: context.localState,
3864
+ rootState: context.rootState,
3865
+ rootSetState: context.rootSetState
3866
+ }))
3867
+ };
3868
+ }
3999
3869
  };
4000
- function mapStyleObjToStrIfNeeded(style) {
4001
- switch (TARGET) {
4002
- case "svelte":
4003
- case "vue":
4004
- case "solid":
4005
- case "angular":
4006
- return convertStyleMapToCSSArray(style).join(" ");
4007
- case "qwik":
4008
- case "reactNative":
4009
- case "react":
4010
- case "rsc":
4011
- return style;
3870
+
3871
+ // src/helpers/omit.ts
3872
+ function omit(obj, ...values) {
3873
+ const newObject = Object.assign({}, obj);
3874
+ for (const key of values) {
3875
+ delete newObject[key];
4012
3876
  }
3877
+ return newObject;
4013
3878
  }
4014
3879
 
4015
- // src/components/block/block.helpers.ts
4016
- var checkIsComponentRestricted = (component, model) => {
4017
- if (!component)
4018
- return true;
4019
- if (!model)
4020
- return false;
4021
- return component.models && component.models.length > 0 && !component.models.includes(model);
4022
- };
4023
- var getComponent = ({
4024
- block,
4025
- registeredComponents,
4026
- model
4027
- }) => {
4028
- const componentName = block.component?.name;
4029
- if (!componentName) {
4030
- return null;
3880
+ // src/functions/traverse.ts
3881
+ function traverse(obj, callback, parent2 = null, key = null, visited = /* @__PURE__ */ new WeakSet()) {
3882
+ if (obj == null || typeof obj !== "object") {
3883
+ callback(obj, (newValue) => {
3884
+ if (parent2 !== null && key !== null) {
3885
+ parent2[key] = newValue;
3886
+ }
3887
+ });
3888
+ return;
4031
3889
  }
4032
- const ref = registeredComponents[componentName];
4033
- if (!ref || checkIsComponentRestricted(ref, model)) {
4034
- return void 0;
3890
+ if (visited.has(obj)) {
3891
+ return;
3892
+ }
3893
+ visited.add(obj);
3894
+ if (Array.isArray(obj)) {
3895
+ obj.forEach((item, index) => {
3896
+ const update = (newValue) => {
3897
+ obj[index] = newValue;
3898
+ };
3899
+ callback(item, update);
3900
+ traverse(item, callback, obj, index, visited);
3901
+ });
4035
3902
  } else {
4036
- return ref;
3903
+ Object.entries(obj).forEach(([key2, value]) => {
3904
+ const update = (newValue) => {
3905
+ obj[key2] = newValue;
3906
+ };
3907
+ callback(value, update);
3908
+ traverse(value, callback, obj, key2, visited);
3909
+ });
4037
3910
  }
4038
- };
4039
- var getRepeatItemData = ({
4040
- block,
4041
- context
4042
- }) => {
4043
- const {
4044
- repeat,
4045
- ...blockWithoutRepeat
4046
- } = block;
4047
- if (!repeat?.collection) {
4048
- return void 0;
3911
+ }
3912
+
3913
+ // src/functions/extract-localized-values.ts
3914
+ function isLocalizedField(value) {
3915
+ return value && typeof value === "object" && value["@type"] === "@builder.io/core:LocalizedValue";
3916
+ }
3917
+ function containsLocalizedValues(data) {
3918
+ if (!data || !Object.getOwnPropertyNames(data).length) {
3919
+ return false;
4049
3920
  }
4050
- const itemsArray = evaluate({
4051
- code: repeat.collection,
4052
- localState: context.localState,
4053
- rootState: context.rootState,
4054
- rootSetState: context.rootSetState,
4055
- context: context.context
3921
+ let hasLocalizedValues = false;
3922
+ traverse(data, (value) => {
3923
+ if (isLocalizedField(value)) {
3924
+ hasLocalizedValues = true;
3925
+ return;
3926
+ }
4056
3927
  });
4057
- if (!Array.isArray(itemsArray)) {
4058
- return void 0;
3928
+ return hasLocalizedValues;
3929
+ }
3930
+ function extractLocalizedValues(data, locale) {
3931
+ if (!data || !Object.getOwnPropertyNames(data).length) {
3932
+ return {};
4059
3933
  }
4060
- const collectionName = repeat.collection.split(".").pop();
4061
- const itemNameToUse = repeat.itemName || (collectionName ? collectionName + "Item" : "item");
4062
- const repeatArray = itemsArray.map((item, index) => ({
4063
- context: {
4064
- ...context,
4065
- localState: {
4066
- ...context.localState,
4067
- $index: index,
4068
- $item: item,
4069
- [itemNameToUse]: item,
4070
- [`$${itemNameToUse}Index`]: index
4071
- }
4072
- },
4073
- block: blockWithoutRepeat
4074
- }));
4075
- return repeatArray;
4076
- };
4077
- var provideLinkComponent = (block, linkComponent) => {
4078
- if (block?.shouldReceiveBuilderProps?.builderLinkComponent)
4079
- return {
4080
- builderLinkComponent: linkComponent
4081
- };
4082
- return {};
4083
- };
4084
- var provideRegisteredComponents = (block, registeredComponents, model) => {
4085
- if (block?.shouldReceiveBuilderProps?.builderComponents) {
4086
- const filteredRegisteredComponents = Object.fromEntries(Object.entries(registeredComponents).filter(([_, component]) => {
4087
- return !checkIsComponentRestricted(component, model);
4088
- }));
4089
- return {
4090
- builderComponents: filteredRegisteredComponents
4091
- };
3934
+ traverse(data, (value, update) => {
3935
+ if (isLocalizedField(value)) {
3936
+ update(value[locale] ?? void 0);
3937
+ }
3938
+ });
3939
+ return data;
3940
+ }
3941
+ function resolveLocalizedValues(block, locale) {
3942
+ if (block.component?.options && containsLocalizedValues(block.component?.options)) {
3943
+ if (!locale) {
3944
+ }
3945
+ block.component.options = extractLocalizedValues(block.component.options, locale ?? "Default");
4092
3946
  }
4093
- return {};
4094
- };
4095
- var provideBuilderBlock = (block, builderBlock) => {
4096
- if (block?.shouldReceiveBuilderProps?.builderBlock)
4097
- return {
4098
- builderBlock
4099
- };
4100
- return {};
4101
- };
4102
- var provideBuilderContext = (block, context) => {
4103
- if (block?.shouldReceiveBuilderProps?.builderContext)
4104
- return {
4105
- builderContext: context
4106
- };
4107
- return {};
4108
- };
4109
- var generateKey = (index) => {
4110
- return index.toString();
4111
- };
4112
-
4113
- // src/functions/event-handler-name.ts
4114
- function capitalizeFirstLetter(string) {
4115
- return string.charAt(0).toUpperCase() + string.slice(1);
3947
+ return block;
4116
3948
  }
4117
- var getEventHandlerName = (key) => `on${capitalizeFirstLetter(key)}`;
4118
3949
 
4119
- // src/functions/get-block-actions-handler.ts
4120
- var createEventHandler = (value, options) => (event) => evaluate({
4121
- code: value,
4122
- context: options.context,
4123
- localState: options.localState,
4124
- rootState: options.rootState,
4125
- rootSetState: options.rootSetState,
4126
- event,
4127
- isExpression: false
4128
- });
3950
+ // src/functions/fast-clone.ts
3951
+ var fastClone = (obj) => JSON.parse(JSON.stringify(obj));
4129
3952
 
4130
- // src/functions/get-block-actions.ts
4131
- function getBlockActions(options) {
4132
- const obj = {};
4133
- const optionActions = options.block.actions ?? {};
4134
- for (const key in optionActions) {
4135
- if (!optionActions.hasOwnProperty(key)) {
4136
- continue;
4137
- }
4138
- const value = optionActions[key];
4139
- let eventHandlerName = getEventHandlerName(key);
4140
- if (options.stripPrefix) {
4141
- switch (TARGET) {
4142
- case "vue":
4143
- eventHandlerName = eventHandlerName.replace("v-on:", "");
4144
- break;
4145
- case "svelte":
4146
- eventHandlerName = eventHandlerName.replace("on:", "");
4147
- break;
4148
- }
4149
- }
4150
- obj[eventHandlerName] = createEventHandler(value, options);
3953
+ // src/functions/set.ts
3954
+ var set = (obj, _path, value) => {
3955
+ if (Object(obj) !== obj) {
3956
+ return obj;
4151
3957
  }
3958
+ const path = Array.isArray(_path) ? _path : _path.toString().match(/[^.[\]]+/g);
3959
+ path.slice(0, -1).reduce((a, c, i) => Object(a[c]) === a[c] ? a[c] : a[c] = Math.abs(Number(path[i + 1])) >> 0 === +path[i + 1] ? [] : {}, obj)[path[path.length - 1]] = value;
4152
3960
  return obj;
4153
- }
3961
+ };
4154
3962
 
4155
- // src/functions/transform-block-properties.ts
4156
- function transformBlockProperties({
4157
- properties
4158
- }) {
4159
- return properties;
3963
+ // src/functions/transform-block.ts
3964
+ function transformBlock(block) {
3965
+ return block;
4160
3966
  }
4161
3967
 
4162
- // src/functions/get-block-properties.ts
4163
- var extractRelevantRootBlockProperties = (block) => {
4164
- return {
4165
- href: block.href
4166
- };
3968
+ // src/functions/get-processed-block.ts
3969
+ function deepCloneWithConditions(obj) {
3970
+ if (obj === null || typeof obj !== "object") {
3971
+ return obj;
3972
+ }
3973
+ if (Array.isArray(obj)) {
3974
+ return obj.map((item) => deepCloneWithConditions(item));
3975
+ }
3976
+ if (obj["@type"] === "@builder.io/sdk:Element") {
3977
+ return obj;
3978
+ }
3979
+ const clonedObj = {};
3980
+ for (const key in obj) {
3981
+ if (key !== "meta" && Object.prototype.hasOwnProperty.call(obj, key)) {
3982
+ clonedObj[key] = deepCloneWithConditions(obj[key]);
3983
+ }
3984
+ }
3985
+ return clonedObj;
3986
+ }
3987
+ var IS_SDK_WITHOUT_CACHED_PROCESSED_BLOCK = ["svelte", "vue", "angular", "qwik", "solid"].includes(TARGET);
3988
+ var getCopy = (block) => {
3989
+ if (IS_SDK_WITHOUT_CACHED_PROCESSED_BLOCK) {
3990
+ const copy = fastClone(block);
3991
+ const copied = {
3992
+ ...copy,
3993
+ properties: {
3994
+ ...copy.properties
3995
+ },
3996
+ actions: {
3997
+ ...copy.actions
3998
+ }
3999
+ };
4000
+ return copied;
4001
+ } else {
4002
+ const copy = deepCloneWithConditions(omit(block, "children", "meta"));
4003
+ return {
4004
+ ...copy,
4005
+ properties: {
4006
+ ...copy.properties
4007
+ },
4008
+ actions: {
4009
+ ...copy.actions
4010
+ },
4011
+ children: block.children,
4012
+ meta: block.meta
4013
+ };
4014
+ }
4167
4015
  };
4168
- function getBlockProperties({
4016
+ var evaluateBindings = ({
4169
4017
  block,
4170
- context
4171
- }) {
4172
- const properties = {
4173
- ...extractRelevantRootBlockProperties(block),
4174
- ...block.properties,
4175
- "builder-id": block.id,
4176
- style: getStyle({
4177
- block,
4018
+ context,
4019
+ localState,
4020
+ rootState,
4021
+ rootSetState
4022
+ }) => {
4023
+ if (!block.bindings) {
4024
+ return block;
4025
+ }
4026
+ const copied = getCopy(block);
4027
+ for (const binding in block.bindings) {
4028
+ const expression = block.bindings[binding];
4029
+ const value = evaluate({
4030
+ code: expression,
4031
+ localState,
4032
+ rootState,
4033
+ rootSetState,
4178
4034
  context
4179
- }),
4180
- [getClassPropName()]: [block.id, "builder-block", block.class, block.properties?.class].filter(Boolean).join(" ")
4181
- };
4182
- return transformBlockProperties({
4183
- properties,
4184
- context,
4185
- block
4035
+ });
4036
+ set(copied, binding, value);
4037
+ }
4038
+ return copied;
4039
+ };
4040
+ function getProcessedBlock({
4041
+ block,
4042
+ context,
4043
+ localState,
4044
+ rootState,
4045
+ rootSetState
4046
+ }) {
4047
+ let transformedBlock = transformBlock(block);
4048
+ transformedBlock = evaluateBindings({
4049
+ block: transformedBlock,
4050
+ localState,
4051
+ rootState,
4052
+ rootSetState,
4053
+ context
4186
4054
  });
4055
+ transformedBlock = resolveLocalizedValues(transformedBlock, rootState.locale);
4056
+ return transformedBlock;
4187
4057
  }
4188
4058
 
4189
- // src/components/block/components/block-wrapper.tsx
4190
- function BlockWrapper(props) {
4191
- return <><Dynamic_renderer_default
4192
- TagName={props.Wrapper}
4193
- attributes={getBlockProperties({
4194
- block: props.block,
4195
- context: props.context
4196
- })}
4197
- actionAttributes={getBlockActions({
4198
- block: props.block,
4199
- rootState: props.context.rootState,
4200
- rootSetState: props.context.rootSetState,
4201
- localState: props.context.localState,
4202
- context: props.context.context,
4203
- stripPrefix: true
4204
- })}
4205
- >{props.children}</Dynamic_renderer_default></>;
4206
- }
4207
- var Block_wrapper_default = BlockWrapper;
4208
-
4209
- // src/components/block/components/component-ref/component-ref.tsx
4210
- import { Show as Show3, For, createSignal as createSignal3 } from "solid-js";
4211
- import { Dynamic as Dynamic4 } from "solid-js/web";
4212
-
4213
- // src/components/block/components/interactive-element.tsx
4214
- import { Show as Show2, on, createEffect, createMemo as createMemo2, createSignal as createSignal2 } from "solid-js";
4215
- import { Dynamic as Dynamic3 } from "solid-js/web";
4216
-
4217
- // src/functions/is-previewing.ts
4218
- function isPreviewing(search) {
4219
- const searchToUse = search || (isBrowser() ? window.location.search : void 0);
4220
- if (!searchToUse) {
4221
- return false;
4222
- }
4223
- const normalizedSearch = getSearchString(searchToUse);
4224
- return Boolean(normalizedSearch.indexOf("builder.preview=") !== -1);
4225
- }
4059
+ // src/functions/camel-to-kebab-case.ts
4060
+ var camelToKebabCase = (str) => str ? str.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, "$1-$2").toLowerCase() : "";
4226
4061
 
4227
- // src/functions/register-component.ts
4228
- var createRegisterComponentMessage = (info) => ({
4229
- type: "builder.registerComponent",
4230
- data: serializeIncludingFunctions(info)
4231
- });
4232
- var serializeFn = (fnValue) => {
4233
- const fnStr = fnValue.toString().trim();
4234
- const isArrowWithoutParens = /^[a-zA-Z0-9_]+\s*=>/i.test(fnStr);
4235
- const appendFunction = !fnStr.startsWith("function") && !fnStr.startsWith("async") && !fnStr.startsWith("(") && !isArrowWithoutParens;
4236
- return `return (${appendFunction ? "function " : ""}${fnStr}).apply(this, arguments)`;
4237
- };
4238
- function serializeIncludingFunctions(info) {
4239
- return JSON.parse(JSON.stringify(info, (key, value) => {
4240
- if (typeof value === "function") {
4241
- return serializeFn(value);
4062
+ // src/components/block/animator.ts
4063
+ function throttle(func, wait, options = {}) {
4064
+ let context;
4065
+ let args;
4066
+ let result;
4067
+ let timeout = null;
4068
+ let previous = 0;
4069
+ const later = function() {
4070
+ previous = options.leading === false ? 0 : Date.now();
4071
+ timeout = null;
4072
+ result = func.apply(context, args);
4073
+ if (!timeout)
4074
+ context = args = null;
4075
+ };
4076
+ return function() {
4077
+ const now = Date.now();
4078
+ if (!previous && options.leading === false)
4079
+ previous = now;
4080
+ const remaining = wait - (now - previous);
4081
+ context = this;
4082
+ args = arguments;
4083
+ if (remaining <= 0 || remaining > wait) {
4084
+ if (timeout) {
4085
+ clearTimeout(timeout);
4086
+ timeout = null;
4087
+ }
4088
+ previous = now;
4089
+ result = func.apply(context, args);
4090
+ if (!timeout)
4091
+ context = args = null;
4092
+ } else if (!timeout && options.trailing !== false) {
4093
+ timeout = setTimeout(later, remaining);
4242
4094
  }
4243
- return value;
4244
- }));
4095
+ return result;
4096
+ };
4245
4097
  }
4246
-
4247
- // src/functions/register.ts
4248
- var registry = {};
4249
- function register(type, info) {
4250
- if (type === "plugin") {
4251
- info = serializeIncludingFunctions(info);
4252
- }
4253
- let typeList = registry[type];
4254
- if (!typeList) {
4255
- typeList = registry[type] = [];
4256
- }
4257
- typeList.push(info);
4258
- if (isBrowser()) {
4259
- const message = {
4260
- type: "builder.register",
4261
- data: {
4262
- type,
4263
- info
4264
- }
4265
- };
4266
- try {
4267
- parent.postMessage(message, "*");
4268
- if (parent !== window) {
4269
- window.postMessage(message, "*");
4098
+ function assign(target, ..._args) {
4099
+ const to = Object(target);
4100
+ for (let index = 1; index < arguments.length; index++) {
4101
+ const nextSource = arguments[index];
4102
+ if (nextSource != null) {
4103
+ for (const nextKey in nextSource) {
4104
+ if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
4105
+ to[nextKey] = nextSource[nextKey];
4106
+ }
4270
4107
  }
4271
- } catch (err) {
4272
4108
  }
4273
4109
  }
4110
+ return to;
4274
4111
  }
4275
- function registerAction(action) {
4276
- if (isBrowser()) {
4277
- const actionClone = JSON.parse(JSON.stringify(action));
4278
- if (action.action) {
4279
- actionClone.action = action.action.toString();
4112
+ function bindAnimations(animations) {
4113
+ if (TARGET === "reactNative") {
4114
+ return;
4115
+ }
4116
+ for (const animation of animations) {
4117
+ switch (animation.trigger) {
4118
+ case "pageLoad":
4119
+ triggerAnimation(animation);
4120
+ break;
4121
+ case "scrollInView":
4122
+ bindScrollInViewAnimation(animation);
4123
+ break;
4280
4124
  }
4281
- window.parent?.postMessage({
4282
- type: "builder.registerAction",
4283
- data: actionClone
4284
- }, "*");
4285
4125
  }
4286
4126
  }
4287
-
4288
- // src/functions/set-editor-settings.ts
4289
- var settings = {};
4290
- function setEditorSettings(newSettings) {
4291
- if (isBrowser()) {
4292
- Object.assign(settings, newSettings);
4293
- const message = {
4294
- type: "builder.settingsChange",
4295
- data: settings
4296
- };
4297
- parent.postMessage(message, "*");
4298
- }
4127
+ function warnElementNotPresent(id2) {
4299
4128
  }
4300
-
4301
- // src/functions/get-builder-search-params/index.ts
4302
- var BUILDER_SEARCHPARAMS_PREFIX = "builder.";
4303
- var BUILDER_OPTIONS_PREFIX = "options.";
4304
- var getBuilderSearchParams = (_options) => {
4305
- if (!_options) {
4306
- return {};
4129
+ function augmentAnimation(animation, element) {
4130
+ const stylesUsed = getAllStylesUsed(animation);
4131
+ const computedStyle = getComputedStyle(element);
4132
+ const firstStyles = animation.steps[0].styles;
4133
+ const lastStyles = animation.steps[animation.steps.length - 1].styles;
4134
+ const bothStyles = [firstStyles, lastStyles];
4135
+ for (const styles of bothStyles) {
4136
+ for (const style of stylesUsed) {
4137
+ if (!(style in styles)) {
4138
+ styles[style] = computedStyle[style];
4139
+ }
4140
+ }
4307
4141
  }
4308
- const options = normalizeSearchParams(_options);
4309
- const newOptions = {};
4310
- Object.keys(options).forEach((key) => {
4311
- if (key.startsWith(BUILDER_SEARCHPARAMS_PREFIX)) {
4312
- const trimmedKey = key.replace(BUILDER_SEARCHPARAMS_PREFIX, "").replace(BUILDER_OPTIONS_PREFIX, "");
4313
- newOptions[trimmedKey] = options[key];
4142
+ }
4143
+ function getAllStylesUsed(animation) {
4144
+ const properties = [];
4145
+ for (const step of animation.steps) {
4146
+ for (const key in step.styles) {
4147
+ if (properties.indexOf(key) === -1) {
4148
+ properties.push(key);
4149
+ }
4314
4150
  }
4315
- });
4316
- return newOptions;
4317
- };
4318
- var getBuilderSearchParamsFromWindow = () => {
4319
- if (!isBrowser()) {
4320
- return {};
4321
4151
  }
4322
- const searchParams = new URLSearchParams(window.location.search);
4323
- return getBuilderSearchParams(searchParams);
4324
- };
4325
-
4326
- // src/constants/sdk-version.ts
4327
- var SDK_VERSION = "5.0.1";
4328
-
4329
- // src/helpers/sdk-headers.ts
4330
- var getSdkHeaders = () => ({
4331
- "X-Builder-SDK": TARGET,
4332
- "X-Builder-SDK-GEN": "2",
4333
- "X-Builder-SDK-Version": SDK_VERSION
4334
- });
4335
-
4336
- // src/helpers/url.ts
4337
- var getTopLevelDomain = (host) => {
4338
- if (host === "localhost" || host === "127.0.0.1") {
4339
- return host;
4152
+ return properties;
4153
+ }
4154
+ function triggerAnimation(animation) {
4155
+ const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
4156
+ if (!elements.length) {
4157
+ warnElementNotPresent(animation.elementId || animation.id || "");
4158
+ return;
4340
4159
  }
4341
- const parts = host.split(".");
4342
- if (parts.length > 2) {
4343
- return parts.slice(1).join(".");
4160
+ Array.from(elements).forEach((element) => {
4161
+ augmentAnimation(animation, element);
4162
+ element.style.transition = "none";
4163
+ element.style.transitionDelay = "0";
4164
+ assign(element.style, animation.steps[0].styles);
4165
+ setTimeout(() => {
4166
+ element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
4167
+ if (animation.delay) {
4168
+ element.style.transitionDelay = animation.delay + "s";
4169
+ }
4170
+ assign(element.style, animation.steps[1].styles);
4171
+ setTimeout(() => {
4172
+ element.style.transition = "";
4173
+ element.style.transitionDelay = "";
4174
+ }, (animation.delay || 0) * 1e3 + animation.duration * 1e3 + 100);
4175
+ });
4176
+ });
4177
+ }
4178
+ function bindScrollInViewAnimation(animation) {
4179
+ const elements = Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || ""));
4180
+ if (!elements.length) {
4181
+ warnElementNotPresent(animation.elementId || animation.id || "");
4182
+ return;
4344
4183
  }
4345
- return host;
4346
- };
4347
-
4348
- // src/helpers/cookie.ts
4349
- var getCookieSync = ({
4350
- name,
4351
- canTrack
4352
- }) => {
4353
- try {
4354
- if (!canTrack) {
4355
- return void 0;
4184
+ Array.from(elements).forEach((element) => {
4185
+ augmentAnimation(animation, element);
4186
+ let triggered = false;
4187
+ let pendingAnimation = false;
4188
+ function immediateOnScroll() {
4189
+ if (!triggered && isScrolledIntoView(element)) {
4190
+ triggered = true;
4191
+ pendingAnimation = true;
4192
+ setTimeout(() => {
4193
+ assign(element.style, animation.steps[1].styles);
4194
+ if (!animation.repeat) {
4195
+ document.removeEventListener("scroll", onScroll);
4196
+ }
4197
+ setTimeout(() => {
4198
+ pendingAnimation = false;
4199
+ if (!animation.repeat) {
4200
+ element.style.transition = "";
4201
+ element.style.transitionDelay = "";
4202
+ }
4203
+ }, (animation.duration + (animation.delay || 0)) * 1e3 + 100);
4204
+ });
4205
+ } else if (animation.repeat && triggered && !pendingAnimation && !isScrolledIntoView(element)) {
4206
+ triggered = false;
4207
+ assign(element.style, animation.steps[0].styles);
4208
+ }
4356
4209
  }
4357
- return document.cookie.split("; ").find((row) => row.startsWith(`${name}=`))?.split("=")[1];
4358
- } catch (err) {
4359
- logger.warn("[COOKIE] GET error: ", err?.message || err);
4360
- return void 0;
4361
- }
4362
- };
4363
- var getCookie = async (args) => getCookieSync(args);
4364
- var stringifyCookie = (cookie) => cookie.map(([key, value]) => value ? `${key}=${value}` : key).filter(checkIsDefined).join("; ");
4365
- var SECURE_CONFIG = [["secure", ""], ["SameSite", "None"]];
4366
- var createCookieString = ({
4367
- name,
4368
- value,
4369
- expires
4370
- }) => {
4371
- const secure = isBrowser() ? location.protocol === "https:" : true;
4372
- const secureObj = secure ? SECURE_CONFIG : [[]];
4373
- const expiresObj = expires ? [["expires", expires.toUTCString()]] : [[]];
4374
- const cookieValue = [[name, value], ...expiresObj, ["path", "/"], ["domain", getTopLevelDomain(window.location.hostname)], ...secureObj];
4375
- const cookie = stringifyCookie(cookieValue);
4376
- return cookie;
4377
- };
4378
- var setCookie = async ({
4379
- name,
4380
- value,
4381
- expires,
4382
- canTrack
4383
- }) => {
4384
- try {
4385
- if (!canTrack) {
4386
- return;
4210
+ const onScroll = throttle(immediateOnScroll, 200, {
4211
+ leading: false
4212
+ });
4213
+ function isScrolledIntoView(elem) {
4214
+ const rect = elem.getBoundingClientRect();
4215
+ const windowHeight = window.innerHeight;
4216
+ const thresholdPercent = (animation.thresholdPercent || 0) / 100;
4217
+ const threshold = thresholdPercent * windowHeight;
4218
+ return rect.bottom > threshold && rect.top < windowHeight - threshold;
4387
4219
  }
4388
- const cookie = createCookieString({
4389
- name,
4390
- value,
4391
- expires
4220
+ const defaultState = animation.steps[0].styles;
4221
+ function attachDefaultState() {
4222
+ assign(element.style, defaultState);
4223
+ }
4224
+ attachDefaultState();
4225
+ setTimeout(() => {
4226
+ element.style.transition = `all ${animation.duration}s ${camelToKebabCase(animation.easing)}`;
4227
+ if (animation.delay) {
4228
+ element.style.transitionDelay = animation.delay + "s";
4229
+ }
4392
4230
  });
4393
- document.cookie = cookie;
4394
- } catch (err) {
4395
- logger.warn("[COOKIE] SET error: ", err?.message || err);
4396
- }
4397
- };
4398
-
4399
- // src/helpers/uuid.ts
4400
- function uuidv4() {
4401
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
4402
- const r = Math.random() * 16 | 0, v2 = c == "x" ? r : r & 3 | 8;
4403
- return v2.toString(16);
4231
+ document.addEventListener("scroll", onScroll, {
4232
+ capture: true,
4233
+ passive: true
4234
+ });
4235
+ immediateOnScroll();
4404
4236
  });
4405
4237
  }
4406
- function uuid() {
4407
- return uuidv4().replace(/-/g, "");
4408
- }
4409
4238
 
4410
- // src/helpers/sessionId.ts
4411
- var SESSION_LOCAL_STORAGE_KEY = "builderSessionId";
4412
- var getSessionId = async ({
4413
- canTrack
4414
- }) => {
4415
- if (!canTrack) {
4416
- return void 0;
4417
- }
4418
- const sessionId = await getCookie({
4419
- name: SESSION_LOCAL_STORAGE_KEY,
4420
- canTrack
4239
+ // src/helpers/css.ts
4240
+ var convertStyleMapToCSSArray = (style) => {
4241
+ const cssProps = Object.entries(style).map(([key, value]) => {
4242
+ if (typeof value === "string") {
4243
+ return `${camelToKebabCase(key)}: ${value};`;
4244
+ } else {
4245
+ return void 0;
4246
+ }
4421
4247
  });
4422
- if (checkIsDefined(sessionId)) {
4423
- return sessionId;
4248
+ return cssProps.filter(checkIsDefined);
4249
+ };
4250
+ var convertStyleMapToCSS = (style) => convertStyleMapToCSSArray(style).join("\n");
4251
+ var createCssClass = ({
4252
+ mediaQuery,
4253
+ className,
4254
+ styles
4255
+ }) => {
4256
+ const cssClass = `.${className} {
4257
+ ${convertStyleMapToCSS(styles)}
4258
+ }`;
4259
+ if (mediaQuery) {
4260
+ return `${mediaQuery} {
4261
+ ${cssClass}
4262
+ }`;
4424
4263
  } else {
4425
- const newSessionId = createSessionId();
4426
- setSessionId({
4427
- id: newSessionId,
4428
- canTrack
4429
- });
4430
- return newSessionId;
4264
+ return cssClass;
4431
4265
  }
4432
4266
  };
4433
- var createSessionId = () => uuid();
4434
- var setSessionId = ({
4435
- id: id2,
4436
- canTrack
4437
- }) => setCookie({
4438
- name: SESSION_LOCAL_STORAGE_KEY,
4439
- value: id2,
4440
- canTrack
4441
- });
4442
4267
 
4443
- // src/helpers/localStorage.ts
4444
- var getLocalStorage = () => isBrowser() && typeof localStorage !== "undefined" ? localStorage : void 0;
4445
- var getLocalStorageItem = ({
4446
- key,
4447
- canTrack
4268
+ // src/functions/transform-style-property.ts
4269
+ function transformStyleProperty({
4270
+ style
4271
+ }) {
4272
+ return style;
4273
+ }
4274
+
4275
+ // src/functions/get-style.ts
4276
+ var getStyle = ({
4277
+ block,
4278
+ context
4448
4279
  }) => {
4449
- try {
4450
- if (canTrack) {
4451
- return getLocalStorage()?.getItem(key);
4452
- }
4453
- return void 0;
4454
- } catch (err) {
4455
- return void 0;
4280
+ return mapStyleObjToStrIfNeeded(transformStyleProperty({
4281
+ style: block.style || {},
4282
+ context,
4283
+ block
4284
+ }));
4285
+ };
4286
+ function mapStyleObjToStrIfNeeded(style) {
4287
+ switch (TARGET) {
4288
+ case "svelte":
4289
+ case "vue":
4290
+ case "solid":
4291
+ case "angular":
4292
+ return convertStyleMapToCSSArray(style).join(" ");
4293
+ case "qwik":
4294
+ case "reactNative":
4295
+ case "react":
4296
+ case "rsc":
4297
+ return style;
4456
4298
  }
4299
+ }
4300
+
4301
+ // src/components/block/block.helpers.ts
4302
+ var checkIsComponentRestricted = (component, model) => {
4303
+ if (!component)
4304
+ return true;
4305
+ if (!model)
4306
+ return false;
4307
+ return component.models && component.models.length > 0 && !component.models.includes(model);
4457
4308
  };
4458
- var setLocalStorageItem = ({
4459
- key,
4460
- canTrack,
4461
- value
4309
+ var getComponent = ({
4310
+ block,
4311
+ registeredComponents,
4312
+ model
4462
4313
  }) => {
4463
- try {
4464
- if (canTrack) {
4465
- getLocalStorage()?.setItem(key, value);
4466
- }
4467
- } catch (err) {
4314
+ const componentName = block.component?.name;
4315
+ if (!componentName) {
4316
+ return null;
4317
+ }
4318
+ const ref = registeredComponents[componentName];
4319
+ if (!ref || checkIsComponentRestricted(ref, model)) {
4320
+ return void 0;
4321
+ } else {
4322
+ return ref;
4468
4323
  }
4469
4324
  };
4470
-
4471
- // src/helpers/visitorId.ts
4472
- var VISITOR_LOCAL_STORAGE_KEY = "builderVisitorId";
4473
- var getVisitorId = ({
4474
- canTrack
4325
+ var getRepeatItemData = ({
4326
+ block,
4327
+ context
4475
4328
  }) => {
4476
- if (!canTrack) {
4329
+ const {
4330
+ repeat,
4331
+ ...blockWithoutRepeat
4332
+ } = block;
4333
+ if (!repeat?.collection) {
4477
4334
  return void 0;
4478
4335
  }
4479
- const visitorId = getLocalStorageItem({
4480
- key: VISITOR_LOCAL_STORAGE_KEY,
4481
- canTrack
4336
+ const itemsArray = evaluate({
4337
+ code: repeat.collection,
4338
+ localState: context.localState,
4339
+ rootState: context.rootState,
4340
+ rootSetState: context.rootSetState,
4341
+ context: context.context
4482
4342
  });
4483
- if (checkIsDefined(visitorId)) {
4484
- return visitorId;
4485
- } else {
4486
- const newVisitorId = createVisitorId();
4487
- setVisitorId({
4488
- id: newVisitorId,
4489
- canTrack
4490
- });
4491
- return newVisitorId;
4343
+ if (!Array.isArray(itemsArray)) {
4344
+ return void 0;
4345
+ }
4346
+ const collectionName = repeat.collection.split(".").pop();
4347
+ const itemNameToUse = repeat.itemName || (collectionName ? collectionName + "Item" : "item");
4348
+ const repeatArray = itemsArray.map((item, index) => ({
4349
+ context: {
4350
+ ...context,
4351
+ localState: {
4352
+ ...context.localState,
4353
+ $index: index,
4354
+ $item: item,
4355
+ [itemNameToUse]: item,
4356
+ [`$${itemNameToUse}Index`]: index
4357
+ }
4358
+ },
4359
+ block: blockWithoutRepeat
4360
+ }));
4361
+ return repeatArray;
4362
+ };
4363
+ var provideLinkComponent = (block, linkComponent) => {
4364
+ if (block?.shouldReceiveBuilderProps?.builderLinkComponent)
4365
+ return {
4366
+ builderLinkComponent: linkComponent
4367
+ };
4368
+ return {};
4369
+ };
4370
+ var provideRegisteredComponents = (block, registeredComponents, model) => {
4371
+ if (block?.shouldReceiveBuilderProps?.builderComponents) {
4372
+ const filteredRegisteredComponents = Object.fromEntries(Object.entries(registeredComponents).filter(([_, component]) => {
4373
+ return !checkIsComponentRestricted(component, model);
4374
+ }));
4375
+ return {
4376
+ builderComponents: filteredRegisteredComponents
4377
+ };
4492
4378
  }
4379
+ return {};
4493
4380
  };
4494
- var createVisitorId = () => uuid();
4495
- var setVisitorId = ({
4496
- id: id2,
4497
- canTrack
4498
- }) => setLocalStorageItem({
4499
- key: VISITOR_LOCAL_STORAGE_KEY,
4500
- value: id2,
4501
- canTrack
4381
+ var provideBuilderBlock = (block, builderBlock) => {
4382
+ if (block?.shouldReceiveBuilderProps?.builderBlock)
4383
+ return {
4384
+ builderBlock
4385
+ };
4386
+ return {};
4387
+ };
4388
+ var provideBuilderContext = (block, context) => {
4389
+ if (block?.shouldReceiveBuilderProps?.builderContext)
4390
+ return {
4391
+ builderContext: context
4392
+ };
4393
+ return {};
4394
+ };
4395
+ var generateKey = (index) => {
4396
+ return index.toString();
4397
+ };
4398
+
4399
+ // src/functions/event-handler-name.ts
4400
+ function capitalizeFirstLetter(string) {
4401
+ return string.charAt(0).toUpperCase() + string.slice(1);
4402
+ }
4403
+ var getEventHandlerName = (key) => `on${capitalizeFirstLetter(key)}`;
4404
+
4405
+ // src/functions/get-block-actions-handler.ts
4406
+ var createEventHandler = (value, options) => (event) => evaluate({
4407
+ code: value,
4408
+ context: options.context,
4409
+ localState: options.localState,
4410
+ rootState: options.rootState,
4411
+ rootSetState: options.rootSetState,
4412
+ event,
4413
+ isExpression: false,
4414
+ trackingContext: options.trackingContext
4502
4415
  });
4503
4416
 
4504
- // src/functions/log-fetch.ts
4505
- function logFetch(url) {
4506
- if (typeof process !== "undefined" && process.env?.DEBUG) {
4507
- if (String(process.env.DEBUG) == "true") {
4508
- logger.log(url);
4417
+ // src/functions/get-block-actions.ts
4418
+ function getBlockActions(options) {
4419
+ const obj = {};
4420
+ const optionActions = options.block.actions ?? {};
4421
+ for (const key in optionActions) {
4422
+ if (!optionActions.hasOwnProperty(key)) {
4423
+ continue;
4424
+ }
4425
+ const value = optionActions[key];
4426
+ let eventHandlerName = getEventHandlerName(key);
4427
+ if (options.stripPrefix) {
4428
+ switch (TARGET) {
4429
+ case "vue":
4430
+ eventHandlerName = eventHandlerName.replace("v-on:", "");
4431
+ break;
4432
+ case "svelte":
4433
+ eventHandlerName = eventHandlerName.replace("on:", "");
4434
+ break;
4435
+ }
4509
4436
  }
4437
+ obj[eventHandlerName] = createEventHandler(value, options);
4510
4438
  }
4439
+ return obj;
4511
4440
  }
4512
4441
 
4513
- // src/functions/track/index.ts
4514
- var getTrackingEventData = async ({
4515
- canTrack
4516
- }) => {
4517
- if (!canTrack) {
4518
- return {
4519
- visitorId: void 0,
4520
- sessionId: void 0
4521
- };
4522
- }
4523
- const sessionId = await getSessionId({
4524
- canTrack
4525
- });
4526
- const visitorId = getVisitorId({
4527
- canTrack
4528
- });
4442
+ // src/functions/transform-block-properties.ts
4443
+ function transformBlockProperties({
4444
+ properties
4445
+ }) {
4446
+ return properties;
4447
+ }
4448
+
4449
+ // src/functions/get-block-properties.ts
4450
+ var extractRelevantRootBlockProperties = (block) => {
4529
4451
  return {
4530
- sessionId,
4531
- visitorId
4452
+ href: block.href
4532
4453
  };
4533
4454
  };
4534
- var createEvent = async ({
4535
- type: eventType,
4536
- canTrack,
4537
- apiKey,
4538
- metadata,
4539
- ...properties
4540
- }) => ({
4541
- type: eventType,
4542
- data: {
4543
- ...properties,
4544
- metadata: {
4545
- url: location.href,
4546
- ...metadata
4547
- },
4548
- ...await getTrackingEventData({
4549
- canTrack
4455
+ function getBlockProperties({
4456
+ block,
4457
+ context
4458
+ }) {
4459
+ const properties = {
4460
+ ...extractRelevantRootBlockProperties(block),
4461
+ ...block.properties,
4462
+ "builder-id": block.id,
4463
+ style: getStyle({
4464
+ block,
4465
+ context
4550
4466
  }),
4551
- userAttributes: getUserAttributes(),
4552
- ownerId: apiKey
4467
+ [getClassPropName()]: [block.id, "builder-block", block.class, block.properties?.class].filter(Boolean).join(" ")
4468
+ };
4469
+ return transformBlockProperties({
4470
+ properties,
4471
+ context,
4472
+ block
4473
+ });
4474
+ }
4475
+
4476
+ // src/components/block/components/block-wrapper.tsx
4477
+ function BlockWrapper(props) {
4478
+ return <><Dynamic_renderer_default
4479
+ TagName={props.Wrapper}
4480
+ attributes={getBlockProperties({
4481
+ block: props.block,
4482
+ context: props.context
4483
+ })}
4484
+ actionAttributes={getBlockActions({
4485
+ block: props.block,
4486
+ rootState: props.context.rootState,
4487
+ rootSetState: props.context.rootSetState,
4488
+ localState: props.context.localState,
4489
+ context: props.context.context,
4490
+ stripPrefix: true,
4491
+ trackingContext: {
4492
+ apiKey: props.context.apiKey,
4493
+ canTrack: props.context.canTrack ?? true,
4494
+ contentId: props.context.content?.id,
4495
+ variationId: props.context.content?.testVariationId
4496
+ }
4497
+ })}
4498
+ >{props.children}</Dynamic_renderer_default></>;
4499
+ }
4500
+ var Block_wrapper_default = BlockWrapper;
4501
+
4502
+ // src/components/block/components/component-ref/component-ref.tsx
4503
+ import { Show as Show3, For, createSignal as createSignal3 } from "solid-js";
4504
+ import { Dynamic as Dynamic4 } from "solid-js/web";
4505
+
4506
+ // src/components/block/components/interactive-element.tsx
4507
+ import { Show as Show2, on, createEffect, createMemo as createMemo2, createSignal as createSignal2 } from "solid-js";
4508
+ import { Dynamic as Dynamic3 } from "solid-js/web";
4509
+
4510
+ // src/functions/is-previewing.ts
4511
+ function isPreviewing(search) {
4512
+ const searchToUse = search || (isBrowser() ? window.location.search : void 0);
4513
+ if (!searchToUse) {
4514
+ return false;
4553
4515
  }
4516
+ const normalizedSearch = getSearchString(searchToUse);
4517
+ return Boolean(normalizedSearch.indexOf("builder.preview=") !== -1);
4518
+ }
4519
+
4520
+ // src/functions/register-component.ts
4521
+ var createRegisterComponentMessage = (info) => ({
4522
+ type: "builder.registerComponent",
4523
+ data: serializeIncludingFunctions(info)
4554
4524
  });
4555
- async function _track({
4556
- apiHost,
4557
- ...eventProps
4558
- }) {
4559
- if (!eventProps.apiKey) {
4560
- logger.error("Missing API key for track call. Please provide your API key.");
4561
- return;
4525
+ var serializeFn = (fnValue) => {
4526
+ const fnStr = fnValue.toString().trim();
4527
+ const isArrowWithoutParens = /^[a-zA-Z0-9_]+\s*=>/i.test(fnStr);
4528
+ const appendFunction = !fnStr.startsWith("function") && !fnStr.startsWith("async") && !fnStr.startsWith("(") && !isArrowWithoutParens;
4529
+ return `return (${appendFunction ? "function " : ""}${fnStr}).apply(this, arguments)`;
4530
+ };
4531
+ function serializeIncludingFunctions(info) {
4532
+ return JSON.parse(JSON.stringify(info, (key, value) => {
4533
+ if (typeof value === "function") {
4534
+ return serializeFn(value);
4535
+ }
4536
+ return value;
4537
+ }));
4538
+ }
4539
+
4540
+ // src/functions/register.ts
4541
+ var registry = {};
4542
+ function register(type, info) {
4543
+ if (type === "plugin") {
4544
+ info = serializeIncludingFunctions(info);
4562
4545
  }
4563
- if (!eventProps.canTrack) {
4564
- return;
4546
+ let typeList = registry[type];
4547
+ if (!typeList) {
4548
+ typeList = registry[type] = [];
4565
4549
  }
4566
- if (isEditing()) {
4567
- return;
4550
+ typeList.push(info);
4551
+ if (isBrowser()) {
4552
+ const message = {
4553
+ type: "builder.register",
4554
+ data: {
4555
+ type,
4556
+ info
4557
+ }
4558
+ };
4559
+ try {
4560
+ parent.postMessage(message, "*");
4561
+ if (parent !== window) {
4562
+ window.postMessage(message, "*");
4563
+ }
4564
+ } catch (err) {
4565
+ }
4568
4566
  }
4569
- if (!(isBrowser() || TARGET === "reactNative")) {
4570
- return;
4567
+ }
4568
+ function registerAction(action) {
4569
+ if (isBrowser()) {
4570
+ const actionClone = JSON.parse(JSON.stringify(action));
4571
+ if (action.action) {
4572
+ actionClone.action = action.action.toString();
4573
+ }
4574
+ window.parent?.postMessage({
4575
+ type: "builder.registerAction",
4576
+ data: actionClone
4577
+ }, "*");
4571
4578
  }
4572
- const baseUrl = apiHost || "https://cdn.builder.io";
4573
- const url = `${baseUrl}/api/v1/track`;
4574
- logFetch(url);
4575
- return fetch(url, {
4576
- method: "POST",
4577
- body: JSON.stringify({
4578
- events: [await createEvent(eventProps)]
4579
- }),
4580
- headers: {
4581
- "content-type": "application/json",
4582
- ...getSdkHeaders()
4583
- },
4584
- mode: "cors"
4585
- }).catch((err) => {
4586
- });
4587
4579
  }
4588
- var track = (args) => _track({
4589
- ...args,
4590
- canTrack: true
4591
- });
4580
+
4581
+ // src/functions/set-editor-settings.ts
4582
+ var settings = {};
4583
+ function setEditorSettings(newSettings) {
4584
+ if (isBrowser()) {
4585
+ Object.assign(settings, newSettings);
4586
+ const message = {
4587
+ type: "builder.settingsChange",
4588
+ data: settings
4589
+ };
4590
+ parent.postMessage(message, "*");
4591
+ }
4592
+ }
4593
+
4594
+ // src/functions/get-builder-search-params/index.ts
4595
+ var BUILDER_SEARCHPARAMS_PREFIX = "builder.";
4596
+ var BUILDER_OPTIONS_PREFIX = "options.";
4597
+ var getBuilderSearchParams = (_options) => {
4598
+ if (!_options) {
4599
+ return {};
4600
+ }
4601
+ const options = normalizeSearchParams(_options);
4602
+ const newOptions = {};
4603
+ Object.keys(options).forEach((key) => {
4604
+ if (key.startsWith(BUILDER_SEARCHPARAMS_PREFIX)) {
4605
+ const trimmedKey = key.replace(BUILDER_SEARCHPARAMS_PREFIX, "").replace(BUILDER_OPTIONS_PREFIX, "");
4606
+ newOptions[trimmedKey] = options[key];
4607
+ }
4608
+ });
4609
+ return newOptions;
4610
+ };
4611
+ var getBuilderSearchParamsFromWindow = () => {
4612
+ if (!isBrowser()) {
4613
+ return {};
4614
+ }
4615
+ const searchParams = new URLSearchParams(window.location.search);
4616
+ return getBuilderSearchParams(searchParams);
4617
+ };
4592
4618
 
4593
4619
  // src/functions/is-from-trusted-host.ts
4594
4620
  var DEFAULT_TRUSTED_HOSTS = ["*.beta.builder.io", "beta.builder.io", "builder.io", "localhost", "qa.builder.io"];
@@ -5330,7 +5356,13 @@ function InteractiveElement(props) {
5330
5356
  rootState: props.context.rootState,
5331
5357
  rootSetState: props.context.rootSetState,
5332
5358
  localState: props.context.localState,
5333
- context: props.context.context
5359
+ context: props.context.context,
5360
+ trackingContext: {
5361
+ apiKey: props.context.apiKey,
5362
+ canTrack: props.context.canTrack ?? true,
5363
+ contentId: props.context.content?.id,
5364
+ variationId: props.context.content?.testVariationId
5365
+ }
5334
5366
  })
5335
5367
  } : {};
5336
5368
  });