@uniformdev/next-app-router 20.75.1-alpha.16 → 20.76.1-alpha.3

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/dist/index.js CHANGED
@@ -396,6 +396,195 @@ var require_retry2 = __commonJS({
396
396
  }
397
397
  });
398
398
 
399
+ // ../../node_modules/.pnpm/rfdc@1.4.1/node_modules/rfdc/index.js
400
+ var require_rfdc = __commonJS({
401
+ "../../node_modules/.pnpm/rfdc@1.4.1/node_modules/rfdc/index.js"(exports2, module2) {
402
+ "use strict";
403
+ module2.exports = rfdc4;
404
+ function copyBuffer(cur) {
405
+ if (cur instanceof Buffer) {
406
+ return Buffer.from(cur);
407
+ }
408
+ return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length);
409
+ }
410
+ function rfdc4(opts) {
411
+ opts = opts || {};
412
+ if (opts.circles) return rfdcCircles(opts);
413
+ const constructorHandlers = /* @__PURE__ */ new Map();
414
+ constructorHandlers.set(Date, (o) => new Date(o));
415
+ constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)));
416
+ constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)));
417
+ if (opts.constructorHandlers) {
418
+ for (const handler2 of opts.constructorHandlers) {
419
+ constructorHandlers.set(handler2[0], handler2[1]);
420
+ }
421
+ }
422
+ let handler = null;
423
+ return opts.proto ? cloneProto : clone2;
424
+ function cloneArray(a, fn) {
425
+ const keys = Object.keys(a);
426
+ const a2 = new Array(keys.length);
427
+ for (let i = 0; i < keys.length; i++) {
428
+ const k = keys[i];
429
+ const cur = a[k];
430
+ if (typeof cur !== "object" || cur === null) {
431
+ a2[k] = cur;
432
+ } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
433
+ a2[k] = handler(cur, fn);
434
+ } else if (ArrayBuffer.isView(cur)) {
435
+ a2[k] = copyBuffer(cur);
436
+ } else {
437
+ a2[k] = fn(cur);
438
+ }
439
+ }
440
+ return a2;
441
+ }
442
+ function clone2(o) {
443
+ if (typeof o !== "object" || o === null) return o;
444
+ if (Array.isArray(o)) return cloneArray(o, clone2);
445
+ if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {
446
+ return handler(o, clone2);
447
+ }
448
+ const o2 = {};
449
+ for (const k in o) {
450
+ if (Object.hasOwnProperty.call(o, k) === false) continue;
451
+ const cur = o[k];
452
+ if (typeof cur !== "object" || cur === null) {
453
+ o2[k] = cur;
454
+ } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
455
+ o2[k] = handler(cur, clone2);
456
+ } else if (ArrayBuffer.isView(cur)) {
457
+ o2[k] = copyBuffer(cur);
458
+ } else {
459
+ o2[k] = clone2(cur);
460
+ }
461
+ }
462
+ return o2;
463
+ }
464
+ function cloneProto(o) {
465
+ if (typeof o !== "object" || o === null) return o;
466
+ if (Array.isArray(o)) return cloneArray(o, cloneProto);
467
+ if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {
468
+ return handler(o, cloneProto);
469
+ }
470
+ const o2 = {};
471
+ for (const k in o) {
472
+ const cur = o[k];
473
+ if (typeof cur !== "object" || cur === null) {
474
+ o2[k] = cur;
475
+ } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
476
+ o2[k] = handler(cur, cloneProto);
477
+ } else if (ArrayBuffer.isView(cur)) {
478
+ o2[k] = copyBuffer(cur);
479
+ } else {
480
+ o2[k] = cloneProto(cur);
481
+ }
482
+ }
483
+ return o2;
484
+ }
485
+ }
486
+ function rfdcCircles(opts) {
487
+ const refs = [];
488
+ const refsNew = [];
489
+ const constructorHandlers = /* @__PURE__ */ new Map();
490
+ constructorHandlers.set(Date, (o) => new Date(o));
491
+ constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)));
492
+ constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)));
493
+ if (opts.constructorHandlers) {
494
+ for (const handler2 of opts.constructorHandlers) {
495
+ constructorHandlers.set(handler2[0], handler2[1]);
496
+ }
497
+ }
498
+ let handler = null;
499
+ return opts.proto ? cloneProto : clone2;
500
+ function cloneArray(a, fn) {
501
+ const keys = Object.keys(a);
502
+ const a2 = new Array(keys.length);
503
+ for (let i = 0; i < keys.length; i++) {
504
+ const k = keys[i];
505
+ const cur = a[k];
506
+ if (typeof cur !== "object" || cur === null) {
507
+ a2[k] = cur;
508
+ } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
509
+ a2[k] = handler(cur, fn);
510
+ } else if (ArrayBuffer.isView(cur)) {
511
+ a2[k] = copyBuffer(cur);
512
+ } else {
513
+ const index = refs.indexOf(cur);
514
+ if (index !== -1) {
515
+ a2[k] = refsNew[index];
516
+ } else {
517
+ a2[k] = fn(cur);
518
+ }
519
+ }
520
+ }
521
+ return a2;
522
+ }
523
+ function clone2(o) {
524
+ if (typeof o !== "object" || o === null) return o;
525
+ if (Array.isArray(o)) return cloneArray(o, clone2);
526
+ if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {
527
+ return handler(o, clone2);
528
+ }
529
+ const o2 = {};
530
+ refs.push(o);
531
+ refsNew.push(o2);
532
+ for (const k in o) {
533
+ if (Object.hasOwnProperty.call(o, k) === false) continue;
534
+ const cur = o[k];
535
+ if (typeof cur !== "object" || cur === null) {
536
+ o2[k] = cur;
537
+ } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
538
+ o2[k] = handler(cur, clone2);
539
+ } else if (ArrayBuffer.isView(cur)) {
540
+ o2[k] = copyBuffer(cur);
541
+ } else {
542
+ const i = refs.indexOf(cur);
543
+ if (i !== -1) {
544
+ o2[k] = refsNew[i];
545
+ } else {
546
+ o2[k] = clone2(cur);
547
+ }
548
+ }
549
+ }
550
+ refs.pop();
551
+ refsNew.pop();
552
+ return o2;
553
+ }
554
+ function cloneProto(o) {
555
+ if (typeof o !== "object" || o === null) return o;
556
+ if (Array.isArray(o)) return cloneArray(o, cloneProto);
557
+ if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {
558
+ return handler(o, cloneProto);
559
+ }
560
+ const o2 = {};
561
+ refs.push(o);
562
+ refsNew.push(o2);
563
+ for (const k in o) {
564
+ const cur = o[k];
565
+ if (typeof cur !== "object" || cur === null) {
566
+ o2[k] = cur;
567
+ } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {
568
+ o2[k] = handler(cur, cloneProto);
569
+ } else if (ArrayBuffer.isView(cur)) {
570
+ o2[k] = copyBuffer(cur);
571
+ } else {
572
+ const i = refs.indexOf(cur);
573
+ if (i !== -1) {
574
+ o2[k] = refsNew[i];
575
+ } else {
576
+ o2[k] = cloneProto(cur);
577
+ }
578
+ }
579
+ }
580
+ refs.pop();
581
+ refsNew.pop();
582
+ return o2;
583
+ }
584
+ }
585
+ }
586
+ });
587
+
399
588
  // src/index.ts
400
589
  var index_exports = {};
401
590
  __export(index_exports, {
@@ -1474,15 +1663,15 @@ var CanvasClient = class extends ApiClient {
1474
1663
  /** Updates or creates a Canvas component definition */
1475
1664
  async updateComposition(body, options) {
1476
1665
  const fetchUri = this.createUrl(CANVAS_URL2);
1477
- const headers = {};
1666
+ const headers2 = {};
1478
1667
  if (options == null ? void 0 : options.ifUnmodifiedSince) {
1479
- headers["x-if-unmodified-since"] = options.ifUnmodifiedSince;
1668
+ headers2["x-if-unmodified-since"] = options.ifUnmodifiedSince;
1480
1669
  }
1481
1670
  const { response } = await this.apiClientWithResponse(fetchUri, {
1482
1671
  method: "PUT",
1483
1672
  body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1484
1673
  expectNoContent: true,
1485
- headers
1674
+ headers: headers2
1486
1675
  });
1487
1676
  return { modified: response.headers.get("x-modified-at") };
1488
1677
  }
@@ -1580,15 +1769,15 @@ var _ContentClient = class _ContentClient2 extends ApiClient {
1580
1769
  }
1581
1770
  async upsertEntry(body, options) {
1582
1771
  const fetchUri = this.createUrl(__privateGet3(_ContentClient2, _entriesUrl));
1583
- const headers = {};
1772
+ const headers2 = {};
1584
1773
  if (options == null ? void 0 : options.ifUnmodifiedSince) {
1585
- headers["x-if-unmodified-since"] = options.ifUnmodifiedSince;
1774
+ headers2["x-if-unmodified-since"] = options.ifUnmodifiedSince;
1586
1775
  }
1587
1776
  const { response } = await this.apiClientWithResponse(fetchUri, {
1588
1777
  method: "PUT",
1589
1778
  body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1590
1779
  expectNoContent: true,
1591
- headers
1780
+ headers: headers2
1592
1781
  });
1593
1782
  return { modified: response.headers.get("x-modified-at") };
1594
1783
  }
@@ -2085,7 +2274,155 @@ var BlockFormatError = class _BlockFormatError extends Error {
2085
2274
  function createVariableReference(variableName) {
2086
2275
  return `\${${variableName.replace(/([${}])/g, "\\$1")}}`;
2087
2276
  }
2277
+ function evaluateVisibilityCriteriaGroup(options) {
2278
+ const { criteriaGroup, simplifyCriteria } = options;
2279
+ const earlyExitResult = criteriaGroup.op === "&" || !criteriaGroup.op ? false : true;
2280
+ let hasIndeterminateClauses = false;
2281
+ for (let index = criteriaGroup.clauses.length - 1; index >= 0; index--) {
2282
+ const clause = criteriaGroup.clauses[index];
2283
+ const criteriaResult = evaluateCriterion(clause, options);
2284
+ if (criteriaResult === null) {
2285
+ hasIndeterminateClauses = true;
2286
+ } else if (criteriaResult === earlyExitResult) {
2287
+ return earlyExitResult;
2288
+ } else if (criteriaResult !== null && simplifyCriteria) {
2289
+ criteriaGroup.clauses.splice(index, 1);
2290
+ }
2291
+ }
2292
+ return hasIndeterminateClauses ? null : !earlyExitResult;
2293
+ }
2294
+ function evaluateCriterion(clause, rootOptions) {
2295
+ var _a;
2296
+ if ("clauses" in clause) {
2297
+ return evaluateVisibilityCriteriaGroup({
2298
+ ...rootOptions,
2299
+ criteriaGroup: clause
2300
+ });
2301
+ }
2302
+ const lhs = (_a = clause.source) != null ? _a : clause.rule;
2303
+ const rhs = Array.isArray(clause.value) ? clause.value : clause.value !== void 0 ? [clause.value] : void 0;
2304
+ if (typeof lhs === "string" && hasReferencedVariables(lhs) > 0 || (rhs == null ? void 0 : rhs.some((rhv) => typeof rhv === "string" && hasReferencedVariables(rhv) > 0))) {
2305
+ return null;
2306
+ }
2307
+ const rule = rootOptions.rules[clause.rule];
2308
+ if (rule) {
2309
+ return rule(clause);
2310
+ }
2311
+ return null;
2312
+ }
2313
+ function evaluateNodeVisibilityParameter({
2314
+ parameter,
2315
+ ...evaluateGroupOptions
2316
+ }) {
2317
+ if (parameter == null ? void 0 : parameter.explicitlyHidden) {
2318
+ return false;
2319
+ }
2320
+ if (!(parameter == null ? void 0 : parameter.criteria)) {
2321
+ return true;
2322
+ }
2323
+ const result = evaluateVisibilityCriteriaGroup({
2324
+ ...evaluateGroupOptions,
2325
+ criteriaGroup: parameter.criteria
2326
+ });
2327
+ return result;
2328
+ }
2088
2329
  var CANVAS_VIZ_CONTROL_PARAM = "$viz";
2330
+ var isEvaluator = (criteria, matchValue) => {
2331
+ if (Array.isArray(criteria)) {
2332
+ return criteria.includes(matchValue);
2333
+ }
2334
+ return criteria === matchValue;
2335
+ };
2336
+ var containsEvaluator = (criteria, matchValue) => {
2337
+ if (Array.isArray(criteria)) {
2338
+ return criteria.some((criterion) => matchValue.includes(criterion));
2339
+ }
2340
+ return matchValue.includes(criteria);
2341
+ };
2342
+ var startsWithEvaluator = (criteria, matchValue) => {
2343
+ if (Array.isArray(criteria)) {
2344
+ return criteria.some((criterion) => matchValue.startsWith(criterion));
2345
+ }
2346
+ return matchValue.startsWith(criteria);
2347
+ };
2348
+ var endsWithEvaluator = (criteria, matchValue) => {
2349
+ if (Array.isArray(criteria)) {
2350
+ return criteria.some((criterion) => matchValue.endsWith(criterion));
2351
+ }
2352
+ return matchValue.endsWith(criteria);
2353
+ };
2354
+ var emptyEvaluator = (_, matchValue) => {
2355
+ return matchValue === "";
2356
+ };
2357
+ var stringOperatorEvaluators = {
2358
+ is: isEvaluator,
2359
+ has: containsEvaluator,
2360
+ startswith: startsWithEvaluator,
2361
+ endswith: endsWithEvaluator,
2362
+ empty: emptyEvaluator
2363
+ };
2364
+ var numericOperatorEvaluators = {
2365
+ gt: (left, right) => left > right,
2366
+ lt: (left, right) => left < right
2367
+ };
2368
+ function evaluateNumericOperator(criteria, matchValue) {
2369
+ const { op, value } = criteria;
2370
+ const evaluator = numericOperatorEvaluators[op];
2371
+ if (!evaluator) {
2372
+ return null;
2373
+ }
2374
+ if (typeof matchValue === "string" && matchValue.trim() === "" || typeof value === "string" && value.trim() === "") {
2375
+ return false;
2376
+ }
2377
+ const leftNum = Number(matchValue);
2378
+ const rightNum = Number(value);
2379
+ if (isNaN(leftNum) || isNaN(rightNum)) {
2380
+ return false;
2381
+ }
2382
+ return evaluator(leftNum, rightNum);
2383
+ }
2384
+ function evaluateStringMatch(criteria, matchValue, allow) {
2385
+ const { op, value } = criteria;
2386
+ if (allow && !allow.has(op)) {
2387
+ return null;
2388
+ }
2389
+ if (op in numericOperatorEvaluators) {
2390
+ return evaluateNumericOperator(criteria, matchValue);
2391
+ }
2392
+ let opMatch = op;
2393
+ const negation = op.startsWith("!");
2394
+ if (negation) {
2395
+ opMatch = opMatch.slice(1);
2396
+ }
2397
+ const evaluator = stringOperatorEvaluators[opMatch];
2398
+ if (!evaluator) {
2399
+ return null;
2400
+ }
2401
+ const result = evaluator(value, matchValue);
2402
+ return negation ? !result : result;
2403
+ }
2404
+ var quirksVisibilityOperators = /* @__PURE__ */ new Set([
2405
+ "is",
2406
+ "!is",
2407
+ "has",
2408
+ "!has",
2409
+ "startswith",
2410
+ "!startswith",
2411
+ "endswith",
2412
+ "!endswith",
2413
+ "empty",
2414
+ "!empty"
2415
+ ]);
2416
+ var CANVAS_VIZ_QUIRKS_RULE = "$qk";
2417
+ function createQuirksVisibilityRule(quirks) {
2418
+ return {
2419
+ [CANVAS_VIZ_QUIRKS_RULE]: (criterion) => {
2420
+ const { source } = criterion;
2421
+ const quirkValue = source ? quirks[source] : void 0;
2422
+ return evaluateStringMatch(criterion, quirkValue != null ? quirkValue : "", quirksVisibilityOperators);
2423
+ }
2424
+ };
2425
+ }
2089
2426
  var _baseUrl;
2090
2427
  var _IntegrationPropertyEditorsClient = class _IntegrationPropertyEditorsClient2 extends ApiClient {
2091
2428
  constructor(options) {
@@ -2529,7 +2866,7 @@ var buildCanvasClientOptions = (options) => {
2529
2866
  limitPolicy: createLimitPolicy2({
2530
2867
  limit: 6
2531
2868
  }),
2532
- fetch: (req, init) => {
2869
+ fetch: (req, init2) => {
2533
2870
  let requestedUrl;
2534
2871
  if (typeof req === "string") {
2535
2872
  requestedUrl = new URL(req);
@@ -2556,10 +2893,10 @@ var buildCanvasClientOptions = (options) => {
2556
2893
  }
2557
2894
  const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache2);
2558
2895
  return fetch(req, {
2559
- ...init,
2896
+ ...init2,
2560
2897
  cache: fetchCache,
2561
2898
  headers: {
2562
- ...init == null ? void 0 : init.headers,
2899
+ ...init2 == null ? void 0 : init2.headers,
2563
2900
  "x-bypass-cache": typeof cache2.bypassCache !== "undefined" ? cache2.bypassCache.toString() : "false"
2564
2901
  },
2565
2902
  next: {
@@ -2608,12 +2945,12 @@ var getManifestClient = (options) => {
2608
2945
  limitPolicy: createLimitPolicy2({
2609
2946
  limit: 6
2610
2947
  }),
2611
- fetch: (req, init) => {
2948
+ fetch: (req, init2) => {
2612
2949
  const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache2);
2613
2950
  return fetch(req, {
2614
- ...init,
2951
+ ...init2,
2615
2952
  headers: {
2616
- ...init == null ? void 0 : init.headers,
2953
+ ...init2 == null ? void 0 : init2.headers,
2617
2954
  "x-bypass-cache": typeof cache2.bypassCache !== "undefined" ? cache2.bypassCache.toString() : "false"
2618
2955
  },
2619
2956
  cache: fetchCache,
@@ -2950,12 +3287,12 @@ var getProjectMapClient = (options) => {
2950
3287
  limitPolicy: createLimitPolicy2({
2951
3288
  limit: 6
2952
3289
  }),
2953
- fetch: (req, init) => {
3290
+ fetch: (req, init2) => {
2954
3291
  const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache2);
2955
3292
  return fetch(req, {
2956
- ...init,
3293
+ ...init2,
2957
3294
  headers: {
2958
- ...init == null ? void 0 : init.headers,
3295
+ ...init2 == null ? void 0 : init2.headers,
2959
3296
  "x-bypass-cache": typeof cache2.bypassCache !== "undefined" ? cache2.bypassCache.toString() : "false"
2960
3297
  },
2961
3298
  cache: fetchCache,
@@ -2991,7 +3328,7 @@ var getRouteClient = (options) => {
2991
3328
  limitPolicy: createLimitPolicy2({
2992
3329
  limit: 6
2993
3330
  }),
2994
- fetch: (req, init) => {
3331
+ fetch: (req, init2) => {
2995
3332
  let requestedUrl;
2996
3333
  if (typeof req === "string") {
2997
3334
  requestedUrl = new URL(req);
@@ -3003,9 +3340,9 @@ var getRouteClient = (options) => {
3003
3340
  const tags = getRouteCacheTags(requestedUrl);
3004
3341
  const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache2);
3005
3342
  return fetch(req, {
3006
- ...init,
3343
+ ...init2,
3007
3344
  headers: {
3008
- ...init == null ? void 0 : init.headers,
3345
+ ...init2 == null ? void 0 : init2.headers,
3009
3346
  "x-bypass-cache": typeof cache2.bypassCache !== "undefined" ? cache2.bypassCache.toString() : "false"
3010
3347
  },
3011
3348
  cache: fetchCache,
@@ -3022,115 +3359,2831 @@ var getRouteClient = (options) => {
3022
3359
  // src/components/UniformComposition.tsx
3023
3360
  var import_core = require("@uniformdev/canvas-react/core");
3024
3361
  var import_next_app_router_client5 = require("@uniformdev/next-app-router-client");
3025
- var import_next_app_router_shared4 = require("@uniformdev/next-app-router-shared");
3362
+ var import_next_app_router_shared6 = require("@uniformdev/next-app-router-shared");
3026
3363
  var import_navigation = require("next/navigation");
3027
- var import_react6 = __toESM(require("react"));
3364
+ var import_react5 = __toESM(require("react"));
3028
3365
 
3029
- // src/data/extract/extractTest.ts
3030
- var import_next_app_router_shared = require("@uniformdev/next-app-router-shared");
3031
- var extractTest = ({ component }) => {
3032
- var _a;
3033
- const testName = (0, import_next_app_router_shared.extractTestName)({ component });
3034
- const slot = ((_a = component.slots) == null ? void 0 : _a[CANVAS_TEST_SLOT]) || [];
3035
- const componentVariations = mapSlotToTestVariations(slot).map((variation, index) => {
3036
- const slotComponent = slot[index];
3037
- if (!slotComponent) {
3038
- throw new Error(`Slot component not found for index ${index}`);
3366
+ // src/data/evaluate/evaluateDraftPageState.ts
3367
+ var import_headers = require("next/headers");
3368
+
3369
+ // ../../node_modules/.pnpm/dequal@2.0.3/node_modules/dequal/lite/index.mjs
3370
+ var has = Object.prototype.hasOwnProperty;
3371
+ function dequal(foo, bar) {
3372
+ var ctor, len;
3373
+ if (foo === bar) return true;
3374
+ if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
3375
+ if (ctor === Date) return foo.getTime() === bar.getTime();
3376
+ if (ctor === RegExp) return foo.toString() === bar.toString();
3377
+ if (ctor === Array) {
3378
+ if ((len = foo.length) === bar.length) {
3379
+ while (len-- && dequal(foo[len], bar[len])) ;
3380
+ }
3381
+ return len === -1;
3039
3382
  }
3040
- return {
3041
- ...variation,
3042
- index,
3043
- componentId: slotComponent._id
3044
- };
3045
- });
3046
- return {
3047
- name: testName,
3048
- variations: componentVariations
3049
- };
3050
- };
3383
+ if (!ctor || typeof foo === "object") {
3384
+ len = 0;
3385
+ for (ctor in foo) {
3386
+ if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;
3387
+ if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;
3388
+ }
3389
+ return Object.keys(bar).length === len;
3390
+ }
3391
+ }
3392
+ return foo !== foo && bar !== bar;
3393
+ }
3051
3394
 
3052
- // src/components/ComponentProps.ts
3053
- var import_next_app_router_shared2 = require("@uniformdev/next-app-router-shared");
3054
- var createComponentProps = ({
3055
- component,
3056
- parent,
3057
- isRoot,
3058
- slotName,
3059
- slotIndex,
3060
- slots,
3061
- pageState,
3062
- composition,
3063
- compositionContext
3064
- }) => {
3065
- var _a, _b;
3066
- const parameters = (_a = component.parameters) != null ? _a : {};
3067
- const componentProps = {
3068
- parameters: Object.keys(parameters).reduce((acc, cur) => {
3069
- acc[cur] = {
3070
- parameterId: cur,
3071
- ...parameters[cur]
3072
- };
3073
- return acc;
3074
- }, {}),
3075
- component: {
3076
- _id: component._id,
3077
- _parentId: (_b = parent == null ? void 0 : parent._id) != null ? _b : null,
3078
- slotName,
3079
- slotIndex: isRoot ? void 0 : slotIndex
3080
- },
3081
- type: component.type,
3082
- variant: component.variant,
3083
- slots,
3084
- context: {
3085
- isContextualEditing: pageState.compositionState === CANVAS_EDITOR_STATE,
3086
- _id: composition._id,
3087
- state: pageState.compositionState,
3088
- type: composition.type,
3089
- pageState,
3090
- matchedRoute: compositionContext.matchedRoute,
3091
- dynamicInputs: compositionContext.dynamicInputs
3395
+ // ../../node_modules/.pnpm/js-cookie@3.0.8/node_modules/js-cookie/dist/js.cookie.mjs
3396
+ function assign(target) {
3397
+ for (var i = 1; i < arguments.length; i++) {
3398
+ var source = arguments[i];
3399
+ for (var key in source) {
3400
+ if (key === "__proto__") continue;
3401
+ target[key] = source[key];
3092
3402
  }
3093
- };
3094
- return componentProps;
3403
+ }
3404
+ return target;
3405
+ }
3406
+ var defaultConverter = {
3407
+ read: function(value) {
3408
+ if (value[0] === '"') {
3409
+ value = value.slice(1, -1);
3410
+ }
3411
+ return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
3412
+ },
3413
+ write: function(value) {
3414
+ return encodeURIComponent(value).replace(
3415
+ /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
3416
+ decodeURIComponent
3417
+ );
3418
+ }
3095
3419
  };
3096
- var createPersonalizeComponentProps = ({
3097
- common,
3098
- componentId,
3099
- pageState
3100
- }) => {
3101
- var _a;
3102
- const component = (0, import_next_app_router_shared2.resolveComponentFromPageState)({
3103
- pageState,
3104
- componentId
3105
- });
3106
- return {
3107
- ...common,
3108
- indexes: (_a = component == null ? void 0 : component.indexes) != null ? _a : []
3109
- };
3420
+ function init(converter, defaultAttributes) {
3421
+ function set(name, value, attributes) {
3422
+ if (typeof document === "undefined") {
3423
+ return;
3424
+ }
3425
+ attributes = assign({}, defaultAttributes, attributes);
3426
+ if (typeof attributes.expires === "number") {
3427
+ attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
3428
+ }
3429
+ if (attributes.expires) {
3430
+ attributes.expires = attributes.expires.toUTCString();
3431
+ }
3432
+ name = encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
3433
+ var stringifiedAttributes = "";
3434
+ for (var attributeName in attributes) {
3435
+ if (!attributes[attributeName]) {
3436
+ continue;
3437
+ }
3438
+ stringifiedAttributes += "; " + attributeName;
3439
+ if (attributes[attributeName] === true) {
3440
+ continue;
3441
+ }
3442
+ stringifiedAttributes += "=" + attributes[attributeName].split(";")[0];
3443
+ }
3444
+ return document.cookie = name + "=" + converter.write(value, name) + stringifiedAttributes;
3445
+ }
3446
+ function get(name) {
3447
+ if (typeof document === "undefined" || arguments.length && !name) {
3448
+ return;
3449
+ }
3450
+ var cookies2 = document.cookie ? document.cookie.split("; ") : [];
3451
+ var jar = {};
3452
+ for (var i = 0; i < cookies2.length; i++) {
3453
+ var parts = cookies2[i].split("=");
3454
+ var value = parts.slice(1).join("=");
3455
+ try {
3456
+ var found = decodeURIComponent(parts[0]);
3457
+ if (!(found in jar)) jar[found] = converter.read(value, found);
3458
+ if (name === found) {
3459
+ break;
3460
+ }
3461
+ } catch (_e) {
3462
+ }
3463
+ }
3464
+ return name ? jar[name] : jar;
3465
+ }
3466
+ return Object.create(
3467
+ {
3468
+ set,
3469
+ get,
3470
+ remove: function(name, attributes) {
3471
+ set(
3472
+ name,
3473
+ "",
3474
+ assign({}, attributes, {
3475
+ expires: -1
3476
+ })
3477
+ );
3478
+ },
3479
+ withAttributes: function(attributes) {
3480
+ return init(this.converter, assign({}, this.attributes, attributes));
3481
+ },
3482
+ withConverter: function(converter2) {
3483
+ return init(assign({}, this.converter, converter2), this.attributes);
3484
+ }
3485
+ },
3486
+ {
3487
+ attributes: { value: Object.freeze(defaultAttributes) },
3488
+ converter: { value: Object.freeze(converter) }
3489
+ }
3490
+ );
3491
+ }
3492
+ var api = init(defaultConverter, { path: "/" });
3493
+
3494
+ // ../../node_modules/.pnpm/mitt@3.0.1/node_modules/mitt/dist/mitt.mjs
3495
+ function mitt_default(n) {
3496
+ return { all: n = n || /* @__PURE__ */ new Map(), on: function(t, e) {
3497
+ var i = n.get(t);
3498
+ i ? i.push(e) : n.set(t, [e]);
3499
+ }, off: function(t, e) {
3500
+ var i = n.get(t);
3501
+ i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
3502
+ }, emit: function(t, e) {
3503
+ var i = n.get(t);
3504
+ i && i.slice().map(function(n2) {
3505
+ n2(e);
3506
+ }), (i = n.get("*")) && i.slice().map(function(n2) {
3507
+ n2(t, e);
3508
+ });
3509
+ } };
3510
+ }
3511
+
3512
+ // ../context/dist/index.mjs
3513
+ var import_rfdc = __toESM(require_rfdc(), 1);
3514
+ var import_rfdc2 = __toESM(require_rfdc(), 1);
3515
+ var import_rfdc3 = __toESM(require_rfdc(), 1);
3516
+ var __defProp3 = Object.defineProperty;
3517
+ var __typeError5 = (msg) => {
3518
+ throw TypeError(msg);
3110
3519
  };
3111
- var createTestComponentProps = ({
3112
- common,
3113
- componentId,
3114
- pageState,
3115
- test
3116
- }) => {
3520
+ var __defNormalProp3 = (obj, key, value) => key in obj ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3521
+ var __publicField3 = (obj, key, value) => __defNormalProp3(obj, typeof key !== "symbol" ? key + "" : key, value);
3522
+ var __accessCheck5 = (obj, member, msg) => member.has(obj) || __typeError5("Cannot " + msg);
3523
+ var __privateGet5 = (obj, member, getter) => (__accessCheck5(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
3524
+ var __privateAdd5 = (obj, member, value) => member.has(obj) ? __typeError5("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3525
+ var __privateSet3 = (obj, member, value, setter) => (__accessCheck5(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
3526
+ var __privateMethod2 = (obj, member, method) => (__accessCheck5(obj, member, "access private method"), method);
3527
+ function computeAggregateDimensions(primitiveScores, aggregates) {
3528
+ const result = { ...primitiveScores };
3529
+ for (const aggregateDimension in aggregates) {
3530
+ const aggregateScore = computeAggregateDimension(
3531
+ primitiveScores,
3532
+ aggregateDimension,
3533
+ aggregates,
3534
+ /* @__PURE__ */ new Set([aggregateDimension])
3535
+ );
3536
+ if (aggregateScore !== 0) {
3537
+ result[aggregateDimension] = aggregateScore;
3538
+ }
3539
+ }
3540
+ return result;
3541
+ }
3542
+ function computeAggregateDimension(primitiveScores, aggregateDimension, allAggregates, visitedDimensions) {
3117
3543
  var _a;
3118
- if (pageState.isPrefetch) {
3544
+ let aggregateScore = 0;
3545
+ for (const input of allAggregates[aggregateDimension].inputs) {
3546
+ let currentScore = (_a = primitiveScores[input.dim]) != null ? _a : 0;
3547
+ if (!currentScore) {
3548
+ const aggRef = allAggregates[input.dim];
3549
+ if (aggRef) {
3550
+ if (visitedDimensions.has(input.dim)) {
3551
+ continue;
3552
+ }
3553
+ const newVisited = new Set(visitedDimensions);
3554
+ newVisited.add(input.dim);
3555
+ currentScore = computeAggregateDimension(primitiveScores, input.dim, allAggregates, newVisited);
3556
+ }
3557
+ }
3558
+ if (currentScore !== 0) {
3559
+ if (input.sign === "c") {
3560
+ aggregateScore = 0;
3561
+ break;
3562
+ } else if (input.sign === "-") {
3563
+ aggregateScore -= currentScore;
3564
+ } else {
3565
+ aggregateScore += currentScore;
3566
+ }
3567
+ }
3568
+ }
3569
+ return aggregateScore;
3570
+ }
3571
+ var ENR_SEPARATOR = "_";
3572
+ var _id;
3573
+ var SignalGoalEvaluator = class {
3574
+ constructor(options) {
3575
+ __privateAdd5(this, _id);
3576
+ __privateSet3(this, _id, options.id);
3577
+ }
3578
+ get id() {
3579
+ return __privateGet5(this, _id);
3580
+ }
3581
+ evaluate({ scores, quirks }) {
3582
+ const score = scores == null ? void 0 : scores[__privateGet5(this, _id)];
3583
+ const key = `goal_${__privateGet5(this, _id)}_triggered`;
3584
+ const hasGoalTriggered = (quirks == null ? void 0 : quirks[key]) === "1";
3119
3585
  return {
3120
- ...common,
3121
- index: void 0,
3122
- test
3586
+ key,
3587
+ triggered: typeof score === "number" && !hasGoalTriggered
3123
3588
  };
3124
3589
  }
3125
- const component = (0, import_next_app_router_shared2.resolveComponentFromPageState)({
3126
- pageState,
3127
- componentId
3128
- });
3129
- const [testIndex] = (_a = component == null ? void 0 : component.indexes) != null ? _a : [];
3130
- return {
3131
- ...common,
3132
- index: testIndex,
3133
- test
3590
+ };
3591
+ _id = /* @__PURE__ */ new WeakMap();
3592
+ var _evaluator;
3593
+ var _onLogMessage;
3594
+ var SignalInstance = class {
3595
+ constructor(data, evaluator, onLogMessage) {
3596
+ __privateAdd5(this, _evaluator);
3597
+ __privateAdd5(this, _onLogMessage);
3598
+ __publicField3(this, "signal");
3599
+ this.signal = data;
3600
+ __privateSet3(this, _evaluator, evaluator);
3601
+ __privateSet3(this, _onLogMessage, onLogMessage);
3602
+ }
3603
+ /** Computes storage update commands to take based on a state update and the signal's criteria */
3604
+ computeSignal(update, commands) {
3605
+ const isAtCap = update.scores[this.signal.id] >= this.signal.cap;
3606
+ if (isAtCap && this.signal.dur !== "t") {
3607
+ return;
3608
+ }
3609
+ const criteriaMatchUpdate = __privateGet5(this, _evaluator).evaluate(
3610
+ update,
3611
+ this.signal.crit,
3612
+ commands,
3613
+ this.signal,
3614
+ __privateGet5(this, _onLogMessage)
3615
+ );
3616
+ const scoreCommand = this.signal.dur === "s" || this.signal.dur === "t" ? "modscoreS" : "modscore";
3617
+ if (!criteriaMatchUpdate.changed) {
3618
+ return;
3619
+ }
3620
+ if (criteriaMatchUpdate.result) {
3621
+ commands.push({
3622
+ type: scoreCommand,
3623
+ data: { dimension: this.signal.id, delta: this.signal.str }
3624
+ });
3625
+ } else if (this.signal.dur === "t") {
3626
+ const sessionScore = update.visitor.sessionScores[this.signal.id];
3627
+ if (sessionScore) {
3628
+ commands.push({
3629
+ type: scoreCommand,
3630
+ data: { dimension: this.signal.id, delta: -sessionScore }
3631
+ });
3632
+ }
3633
+ }
3634
+ }
3635
+ };
3636
+ _evaluator = /* @__PURE__ */ new WeakMap();
3637
+ _onLogMessage = /* @__PURE__ */ new WeakMap();
3638
+ var rollForControlGroup = (value) => {
3639
+ let control = value;
3640
+ if (control >= 1) {
3641
+ control = control / 100;
3642
+ }
3643
+ return Math.random() < control;
3644
+ };
3645
+ var _mf;
3646
+ var _signalInstances;
3647
+ var _goalEvaluators;
3648
+ var _onLogMessage2;
3649
+ var ManifestInstance = class {
3650
+ constructor({
3651
+ manifest,
3652
+ evaluator = new GroupCriteriaEvaluator({}),
3653
+ onLogMessage = () => {
3654
+ }
3655
+ }) {
3656
+ __publicField3(this, "data");
3657
+ __privateAdd5(this, _mf);
3658
+ __privateAdd5(this, _signalInstances);
3659
+ __privateAdd5(this, _goalEvaluators, []);
3660
+ __privateAdd5(this, _onLogMessage2);
3661
+ var _a, _b, _c, _d, _e;
3662
+ __privateSet3(this, _mf, (_a = manifest.project) != null ? _a : {});
3663
+ this.data = manifest;
3664
+ __privateSet3(this, _signalInstances, Object.entries((_c = (_b = __privateGet5(this, _mf).pz) == null ? void 0 : _b.sig) != null ? _c : []).map(
3665
+ ([id, signal]) => new SignalInstance({ ...signal, id }, evaluator, onLogMessage)
3666
+ ));
3667
+ Object.entries((_e = (_d = __privateGet5(this, _mf).pz) == null ? void 0 : _d.sig) != null ? _e : []).forEach(([id, signal]) => {
3668
+ if (signal.conversion) {
3669
+ __privateGet5(this, _goalEvaluators).push(new SignalGoalEvaluator({ id, signal }));
3670
+ }
3671
+ });
3672
+ __privateSet3(this, _onLogMessage2, onLogMessage);
3673
+ }
3674
+ rollForControlGroup() {
3675
+ var _a;
3676
+ return rollForControlGroup(((_a = __privateGet5(this, _mf).pz) == null ? void 0 : _a.control) || 0);
3677
+ }
3678
+ getTest(name) {
3679
+ var _a;
3680
+ return (_a = __privateGet5(this, _mf).test) == null ? void 0 : _a[name];
3681
+ }
3682
+ computeSignals(update) {
3683
+ const commands = [];
3684
+ __privateGet5(this, _onLogMessage2).call(this, ["debug", 200, "GROUP"]);
3685
+ try {
3686
+ __privateGet5(this, _signalInstances).forEach((signal) => {
3687
+ __privateGet5(this, _onLogMessage2).call(this, ["debug", 201, "GROUP", signal.signal]);
3688
+ try {
3689
+ signal.computeSignal(update, commands);
3690
+ } finally {
3691
+ __privateGet5(this, _onLogMessage2).call(this, ["debug", 201, "ENDGROUP"]);
3692
+ }
3693
+ });
3694
+ } finally {
3695
+ __privateGet5(this, _onLogMessage2).call(this, ["debug", 200, "ENDGROUP"]);
3696
+ }
3697
+ return commands;
3698
+ }
3699
+ computeGoals(data) {
3700
+ const commands = [];
3701
+ __privateGet5(this, _goalEvaluators).forEach((evaluator) => {
3702
+ const { triggered, key } = evaluator.evaluate(data);
3703
+ if (triggered) {
3704
+ commands.push({
3705
+ type: "setgoal",
3706
+ data: {
3707
+ goal: evaluator.id
3708
+ }
3709
+ });
3710
+ commands.push({
3711
+ type: "setquirk",
3712
+ data: {
3713
+ key,
3714
+ value: "1"
3715
+ }
3716
+ });
3717
+ }
3718
+ });
3719
+ return commands;
3720
+ }
3721
+ /**
3722
+ * Computes aggregated scores based on other dimensions
3723
+ */
3724
+ computeAggregateDimensions(primitiveScores) {
3725
+ var _a, _b;
3726
+ return computeAggregateDimensions(primitiveScores, (_b = (_a = __privateGet5(this, _mf).pz) == null ? void 0 : _a.agg) != null ? _b : {});
3727
+ }
3728
+ getDimensionByKey(scoreKey) {
3729
+ var _a, _b, _c, _d;
3730
+ const enrichmentIndex = scoreKey.indexOf(ENR_SEPARATOR);
3731
+ if (enrichmentIndex <= 0) {
3732
+ return (_b = (_a = __privateGet5(this, _mf).pz) == null ? void 0 : _a.sig) == null ? void 0 : _b[scoreKey];
3733
+ }
3734
+ return (_d = (_c = __privateGet5(this, _mf).pz) == null ? void 0 : _c.enr) == null ? void 0 : _d[scoreKey.substring(0, enrichmentIndex)];
3735
+ }
3736
+ getAggregateDimensionByKey(scoreKey) {
3737
+ var _a, _b;
3738
+ return (_b = (_a = __privateGet5(this, _mf).pz) == null ? void 0 : _a.agg) == null ? void 0 : _b[scoreKey];
3739
+ }
3740
+ };
3741
+ _mf = /* @__PURE__ */ new WeakMap();
3742
+ _signalInstances = /* @__PURE__ */ new WeakMap();
3743
+ _goalEvaluators = /* @__PURE__ */ new WeakMap();
3744
+ _onLogMessage2 = /* @__PURE__ */ new WeakMap();
3745
+ function isStringMatch(lhs, match) {
3746
+ var _a, _b, _c, _d, _e, _f;
3747
+ const type = (_a = match == null ? void 0 : match.op) != null ? _a : "=";
3748
+ if (match.op === "*") {
3749
+ return lhs !== null && typeof lhs !== "undefined";
3750
+ }
3751
+ if (match.op === "!*") {
3752
+ return lhs === null || typeof lhs === "undefined";
3753
+ }
3754
+ if (!("rhs" in match)) {
3755
+ throw new Error(`Match expression is required for match type ${type}`);
3756
+ }
3757
+ const caseSensitive = (_b = match.cs) != null ? _b : false;
3758
+ const localRhs = (caseSensitive ? lhs != null ? lhs : "" : caseDesensitize(lhs)).toString();
3759
+ const localLhs = (caseSensitive ? match.rhs : caseDesensitize(match.rhs)).toString();
3760
+ switch (type) {
3761
+ case "=":
3762
+ return localRhs === localLhs;
3763
+ case "!=":
3764
+ return localRhs !== localLhs;
3765
+ case "~":
3766
+ return (_c = localRhs.includes(localLhs)) != null ? _c : false;
3767
+ case "!~":
3768
+ return !((_d = localRhs.includes(localLhs)) != null ? _d : true);
3769
+ case "//":
3770
+ return new RegExp(match.rhs.toString(), caseSensitive ? "" : "i").test((_e = lhs == null ? void 0 : lhs.toString()) != null ? _e : "");
3771
+ case "!//":
3772
+ return !new RegExp(match.rhs.toString(), caseSensitive ? "" : "i").test((_f = lhs == null ? void 0 : lhs.toString()) != null ? _f : "");
3773
+ default:
3774
+ throw new Error(`Unknown match type ${type}.`);
3775
+ }
3776
+ }
3777
+ function explainStringMatch(lhs, match) {
3778
+ const cs = "cs" in match ? match.cs : false;
3779
+ return `'${cs ? lhs : lhs == null ? void 0 : lhs.toString().toUpperCase()}' ${explainStringMatchCriteria(match)}`;
3780
+ }
3781
+ function explainStringMatchCriteria(match) {
3782
+ if ("rhs" in match) {
3783
+ return `${match.op} '${match.cs ? match.rhs : match.rhs.toString().toUpperCase()}'`;
3784
+ }
3785
+ return `${match.op === "*" ? "exists" : "does not exist"}`;
3786
+ }
3787
+ function caseDesensitize(value) {
3788
+ var _a, _b;
3789
+ return (_b = (_a = value == null ? void 0 : value.toString()) == null ? void 0 : _a.toUpperCase()) != null ? _b : "";
3790
+ }
3791
+ var cookieEvaluator = ({ update, criteria, onLogMessage }) => {
3792
+ var _a, _b;
3793
+ if (criteria.type !== "CK") {
3794
+ return { result: false, changed: false };
3795
+ }
3796
+ const changed = !dequal(cleanCookies(update.state.cookies), cleanCookies((_a = update.previousState) == null ? void 0 : _a.cookies));
3797
+ const value = (_b = update.state.cookies) == null ? void 0 : _b[criteria.cookieName];
3798
+ const result = isStringMatch(value, criteria.match);
3799
+ const finalResult = { result, changed };
3800
+ onLogMessage == null ? void 0 : onLogMessage([
3801
+ "debug",
3802
+ 203,
3803
+ { criteria, result: finalResult, explanation: explainStringMatch(value, criteria.match) }
3804
+ ]);
3805
+ return finalResult;
3806
+ };
3807
+ function cleanCookies(cookie) {
3808
+ if (!cookie) {
3809
+ return void 0;
3810
+ }
3811
+ if (!cookie.ufvd) {
3812
+ return cookie;
3813
+ }
3814
+ const { ufvd, ...rest } = cookie;
3815
+ return rest;
3816
+ }
3817
+ var currentPageEvaluator = ({ update, criteria, onLogMessage }) => {
3818
+ var _a, _b, _c;
3819
+ if (criteria.type !== "PV") {
3820
+ return { result: false, changed: false };
3821
+ }
3822
+ const value = (_a = update.state.url) == null ? void 0 : _a.pathname;
3823
+ const hasUrlChanged = !update.previousState || (value == null ? void 0 : value.toString()) !== ((_c = (_b = update.previousState.url) == null ? void 0 : _b.pathname) == null ? void 0 : _c.toString());
3824
+ const result = isStringMatch(value, criteria.path);
3825
+ const finalResult = { result, changed: hasUrlChanged };
3826
+ onLogMessage == null ? void 0 : onLogMessage([
3827
+ "debug",
3828
+ 203,
3829
+ { criteria, result: finalResult, explanation: explainStringMatch(value, criteria.path) }
3830
+ ]);
3831
+ return finalResult;
3832
+ };
3833
+ var eventEvaluator = ({ update, criteria, onLogMessage }) => {
3834
+ var _a, _b, _c;
3835
+ if (criteria.type !== "EVT") {
3836
+ return { result: false, changed: false };
3837
+ }
3838
+ const result = (_b = (_a = update.state.events) == null ? void 0 : _a.some((event) => isStringMatch(event.event, criteria.event))) != null ? _b : false;
3839
+ const finalResult = { result, changed: result };
3840
+ onLogMessage == null ? void 0 : onLogMessage([
3841
+ "debug",
3842
+ 203,
3843
+ {
3844
+ criteria,
3845
+ result: finalResult,
3846
+ explanation: `'${(_c = update.state.events) == null ? void 0 : _c.join("', '")}' ${explainStringMatchCriteria(criteria.event)}`
3847
+ }
3848
+ ]);
3849
+ return finalResult;
3850
+ };
3851
+ function getEnrichmentVectorKey(category, value) {
3852
+ return `${category}${ENR_SEPARATOR}${value}`;
3853
+ }
3854
+ function isNumberMatch(lhs, match) {
3855
+ var _a;
3856
+ if (typeof lhs === "undefined" || lhs === null) {
3857
+ return false;
3858
+ }
3859
+ const lhsValue = Number(lhs);
3860
+ if (isNaN(lhsValue)) {
3861
+ return false;
3862
+ }
3863
+ switch ((_a = match == null ? void 0 : match.op) != null ? _a : "=") {
3864
+ case "=":
3865
+ return lhsValue === match.rhs;
3866
+ case "!=":
3867
+ return lhsValue !== match.rhs;
3868
+ case ">":
3869
+ return lhsValue > match.rhs;
3870
+ case "<":
3871
+ return lhsValue < match.rhs;
3872
+ default:
3873
+ console.warn(`Unknown match type ${match.op} is false.`);
3874
+ return false;
3875
+ }
3876
+ }
3877
+ function explainNumberMatch(lhs, match) {
3878
+ return `${lhs} ${explainNumberMatchCriteria(match)}`;
3879
+ }
3880
+ function explainNumberMatchCriteria(match) {
3881
+ return `${match.op} ${match.rhs}`;
3882
+ }
3883
+ var pageViewCountDimension = getEnrichmentVectorKey("$pvc", "v");
3884
+ var pageViewCountEvaluator = ({ update, criteria, commands, onLogMessage }) => {
3885
+ var _a, _b;
3886
+ if (criteria.type !== "PVC") {
3887
+ return { result: false, changed: false };
3888
+ }
3889
+ const hasUrlChanged = Boolean(
3890
+ update.state.url && (!update.previousState || ((_a = update.state.url) == null ? void 0 : _a.toString()) !== ((_b = update.previousState.url) == null ? void 0 : _b.toString()))
3891
+ );
3892
+ const existingValueNumber = update.visitor.sessionScores[pageViewCountDimension] || 0;
3893
+ const updatedCount = existingValueNumber + 1;
3894
+ const finalResult = { result: false, changed: hasUrlChanged };
3895
+ const hasExistingPageViewIncrementCommand = commands.some(
3896
+ (c) => c.type === "modscoreS" && c.data.dimension === pageViewCountDimension
3897
+ );
3898
+ if (hasUrlChanged && !hasExistingPageViewIncrementCommand) {
3899
+ commands.push({
3900
+ type: "modscoreS",
3901
+ data: {
3902
+ dimension: pageViewCountDimension,
3903
+ delta: 1
3904
+ }
3905
+ });
3906
+ }
3907
+ if (isNumberMatch(updatedCount, criteria.match)) {
3908
+ finalResult.result = true;
3909
+ }
3910
+ onLogMessage == null ? void 0 : onLogMessage([
3911
+ "debug",
3912
+ 203,
3913
+ { criteria, result: finalResult, explanation: explainNumberMatch(updatedCount, criteria.match) }
3914
+ ]);
3915
+ return finalResult;
3916
+ };
3917
+ pageViewCountEvaluator.alwaysExecute = true;
3918
+ var queryStringEvaluator = ({ update, criteria, onLogMessage }) => {
3919
+ var _a, _b, _c, _d, _e;
3920
+ if (criteria.type !== "QS") {
3921
+ return { result: false, changed: false };
3922
+ }
3923
+ const hasQueryChanged = !update.previousState || ((_b = (_a = update.state.url) == null ? void 0 : _a.searchParams) == null ? void 0 : _b.toString()) !== ((_d = (_c = update.previousState.url) == null ? void 0 : _c.searchParams) == null ? void 0 : _d.toString());
3924
+ const value = (_e = update.state.url) == null ? void 0 : _e.searchParams.get(criteria.queryName);
3925
+ const result = isStringMatch(value, criteria.match);
3926
+ const finalResult = { result, changed: hasQueryChanged };
3927
+ onLogMessage == null ? void 0 : onLogMessage([
3928
+ "debug",
3929
+ 203,
3930
+ { criteria, result: finalResult, explanation: explainStringMatch(value, criteria.match) }
3931
+ ]);
3932
+ return finalResult;
3933
+ };
3934
+ var quirkEvaluator = ({ update, criteria, signal, onLogMessage }) => {
3935
+ var _a;
3936
+ if (criteria.type !== "QK") {
3937
+ return { result: false, changed: false };
3938
+ }
3939
+ if (typeof document === "undefined" && update.scores[signal.id] > 0) {
3940
+ return { result: true, changed: false };
3941
+ }
3942
+ const visitorValue = update.visitor.quirks[criteria.key];
3943
+ const updateValue = (_a = update.state.quirks) == null ? void 0 : _a[criteria.key];
3944
+ const value = updateValue != null ? updateValue : visitorValue;
3945
+ const changed = Boolean(updateValue !== void 0 && visitorValue !== updateValue);
3946
+ const result = isStringMatch(value, criteria.match);
3947
+ const finalResult = { result, changed };
3948
+ onLogMessage == null ? void 0 : onLogMessage([
3949
+ "debug",
3950
+ 203,
3951
+ { criteria, result: finalResult, explanation: explainStringMatch(value, criteria.match) }
3952
+ ]);
3953
+ return finalResult;
3954
+ };
3955
+ var _evaluators;
3956
+ var GroupCriteriaEvaluator = class {
3957
+ constructor(criteriaEvaluators) {
3958
+ __privateAdd5(this, _evaluators);
3959
+ __privateSet3(this, _evaluators, criteriaEvaluators);
3960
+ }
3961
+ evaluate(update, crit, commands, signal, onLogMessage) {
3962
+ const hasMultipleClauses = crit.clauses.length > 1;
3963
+ if (hasMultipleClauses) {
3964
+ onLogMessage == null ? void 0 : onLogMessage(["debug", 202, "GROUP", crit]);
3965
+ }
3966
+ try {
3967
+ const earlyExitEvaluatorResult = crit.op === "&" || !crit.op ? false : true;
3968
+ let earlyExitResult = null;
3969
+ let isAnyChanged = false;
3970
+ for (const criteria of crit.clauses) {
3971
+ let result;
3972
+ if (criteria.type === "G") {
3973
+ result = this.evaluate(update, criteria, commands, signal, onLogMessage);
3974
+ } else {
3975
+ const evaluator = __privateGet5(this, _evaluators)[criteria.type];
3976
+ if (earlyExitResult && !evaluator.alwaysExecute) {
3977
+ continue;
3978
+ }
3979
+ if (!evaluator) {
3980
+ throw new Error(`${criteria.type} signal criteria not registered`);
3981
+ }
3982
+ result = evaluator({ update, criteria, commands, signal, onLogMessage });
3983
+ }
3984
+ if (result.changed) {
3985
+ isAnyChanged = true;
3986
+ }
3987
+ if (!earlyExitResult && result.result === earlyExitEvaluatorResult) {
3988
+ earlyExitResult = { result: earlyExitEvaluatorResult, changed: isAnyChanged };
3989
+ }
3990
+ }
3991
+ const finalResult = earlyExitResult != null ? earlyExitResult : { result: !earlyExitEvaluatorResult, changed: isAnyChanged };
3992
+ if (hasMultipleClauses) {
3993
+ onLogMessage == null ? void 0 : onLogMessage(["debug", 204, finalResult]);
3994
+ }
3995
+ return finalResult;
3996
+ } finally {
3997
+ if (hasMultipleClauses) {
3998
+ onLogMessage == null ? void 0 : onLogMessage(["debug", 202, "ENDGROUP"]);
3999
+ }
4000
+ }
4001
+ }
4002
+ };
4003
+ _evaluators = /* @__PURE__ */ new WeakMap();
4004
+ function evaluateVariantMatch(variantId, match, vec, onLogMessage, quirks) {
4005
+ onLogMessage == null ? void 0 : onLogMessage(["info", 301, "GROUP", { id: variantId, op: match == null ? void 0 : match.op }]);
4006
+ let result;
4007
+ try {
4008
+ if (!(match == null ? void 0 : match.crit)) {
4009
+ onLogMessage == null ? void 0 : onLogMessage(["info", 302, { matched: true, description: "default variation" }]);
4010
+ result = true;
4011
+ } else if (!match.op || match.op === "&") {
4012
+ result = match.crit.every((c) => evaluateMatch(c, vec, quirks != null ? quirks : {}, onLogMessage));
4013
+ } else {
4014
+ result = match.crit.some((c) => evaluateMatch(c, vec, quirks != null ? quirks : {}, onLogMessage));
4015
+ }
4016
+ onLogMessage == null ? void 0 : onLogMessage(["info", 303, result]);
4017
+ } finally {
4018
+ onLogMessage == null ? void 0 : onLogMessage(["info", 301, "ENDGROUP"]);
4019
+ }
4020
+ return result;
4021
+ }
4022
+ function evaluateMatch(crit, vec, quirks, onLogMessage) {
4023
+ if ("t" in crit && crit.t === "q") {
4024
+ return evaluateQuirkMatch(crit, quirks, onLogMessage);
4025
+ } else {
4026
+ return evaluateDimensionMatch(crit, vec, onLogMessage);
4027
+ }
4028
+ }
4029
+ function evaluateDimensionMatch(crit, vec, onLogMessage) {
4030
+ var _a, _b;
4031
+ const { l: lhs, op } = crit;
4032
+ const lhsScore = (_a = vec[lhs]) != null ? _a : 0;
4033
+ if (op === "^") {
4034
+ const [cat] = lhs.split(ENR_SEPARATOR);
4035
+ let topVectorName = void 0;
4036
+ let topScore = 0;
4037
+ Object.keys(vec).forEach((vectorName) => {
4038
+ if (vectorName.startsWith(`${cat}${ENR_SEPARATOR}`)) {
4039
+ const score = vec[vectorName];
4040
+ if (score > topScore) {
4041
+ topVectorName = vectorName;
4042
+ topScore = score;
4043
+ }
4044
+ }
4045
+ });
4046
+ const result = topVectorName === lhs;
4047
+ onLogMessage == null ? void 0 : onLogMessage([
4048
+ "info",
4049
+ 302,
4050
+ {
4051
+ matched: result,
4052
+ description: `${crit.l} has the highest score in the category`
4053
+ }
4054
+ ]);
4055
+ return result;
4056
+ } else if (op === "+") {
4057
+ const result = Math.max(...Object.values(vec)) === lhsScore && lhsScore > 0;
4058
+ onLogMessage == null ? void 0 : onLogMessage([
4059
+ "info",
4060
+ 302,
4061
+ {
4062
+ matched: result,
4063
+ description: `${crit.l} has the highest score`
4064
+ }
4065
+ ]);
4066
+ return result;
4067
+ } else if (op === "-") {
4068
+ const result = Math.min(...Object.values(vec)) === lhsScore && lhsScore > 0;
4069
+ onLogMessage == null ? void 0 : onLogMessage([
4070
+ "info",
4071
+ 302,
4072
+ {
4073
+ matched: result,
4074
+ description: `${crit.l} has the lowest non-zero score`
4075
+ }
4076
+ ]);
4077
+ return result;
4078
+ }
4079
+ let rhsScore;
4080
+ if (crit.rDim) {
4081
+ rhsScore = vec[crit.rDim] || 0;
4082
+ } else {
4083
+ rhsScore = parseInt(crit.r, 10);
4084
+ }
4085
+ if (isNaN(rhsScore)) {
4086
+ onLogMessage == null ? void 0 : onLogMessage([
4087
+ "info",
4088
+ 302,
4089
+ {
4090
+ matched: false,
4091
+ description: `${(_b = crit.rDim) != null ? _b : crit.r} has no score value`
4092
+ }
4093
+ ]);
4094
+ return false;
4095
+ }
4096
+ if (op === ">") {
4097
+ const result = lhsScore > rhsScore;
4098
+ explainScore(onLogMessage, result, crit, lhsScore, rhsScore);
4099
+ return result;
4100
+ } else if (op === ">=") {
4101
+ const result = lhsScore >= rhsScore;
4102
+ explainScore(onLogMessage, result, crit, lhsScore, rhsScore);
4103
+ return result;
4104
+ } else if (op === "<") {
4105
+ const result = lhsScore < rhsScore;
4106
+ explainScore(onLogMessage, result, crit, lhsScore, rhsScore);
4107
+ return result;
4108
+ } else if (op === "<=") {
4109
+ const result = lhsScore <= rhsScore;
4110
+ explainScore(onLogMessage, result, crit, lhsScore, rhsScore);
4111
+ return result;
4112
+ } else if (op === "=") {
4113
+ const result = lhsScore === rhsScore;
4114
+ explainScore(onLogMessage, result, crit, lhsScore, rhsScore);
4115
+ return result;
4116
+ } else if (op === "!=") {
4117
+ const result = lhsScore !== rhsScore;
4118
+ explainScore(onLogMessage, result, crit, lhsScore, rhsScore);
4119
+ return result;
4120
+ } else {
4121
+ onLogMessage == null ? void 0 : onLogMessage([
4122
+ "error",
4123
+ 302,
4124
+ {
4125
+ matched: false,
4126
+ description: `${crit.l} ${crit.op} ${crit.rDim ? `${crit.rDim}` : crit.r}: Unknown op ${crit.op}.`
4127
+ }
4128
+ ]);
4129
+ return false;
4130
+ }
4131
+ }
4132
+ function evaluateQuirkMatch(crit, quirks, onLogMessage) {
4133
+ var _a;
4134
+ const { l: targetQuirk, op, r: targetValue } = crit;
4135
+ const targetQuirkValue = (_a = quirks[targetQuirk]) != null ? _a : "";
4136
+ if (op === "=") {
4137
+ const result = targetQuirkValue === targetValue;
4138
+ explainQuirk(onLogMessage, result, crit, targetQuirkValue);
4139
+ return result;
4140
+ } else if (op === "!=") {
4141
+ const result = targetQuirkValue !== targetValue;
4142
+ explainQuirk(onLogMessage, result, crit, targetQuirkValue);
4143
+ return result;
4144
+ } else {
4145
+ onLogMessage == null ? void 0 : onLogMessage([
4146
+ "error",
4147
+ 302,
4148
+ {
4149
+ matched: false,
4150
+ description: `Quirk ${crit.l} ${crit.op} ${crit.r}: Unknown quirk op ${crit.op}.`
4151
+ }
4152
+ ]);
4153
+ return false;
4154
+ }
4155
+ }
4156
+ function explainScore(onLogMessage, result, crit, lhsScore, rhsScore) {
4157
+ onLogMessage == null ? void 0 : onLogMessage([
4158
+ "info",
4159
+ 302,
4160
+ {
4161
+ matched: result,
4162
+ description: `${crit.l}[${lhsScore}] ${crit.op} ${crit.rDim ? `${crit.rDim}[${rhsScore}]` : crit.r}`
4163
+ }
4164
+ ]);
4165
+ }
4166
+ function explainQuirk(onLogMessage, result, crit, lhs) {
4167
+ onLogMessage == null ? void 0 : onLogMessage([
4168
+ "info",
4169
+ 302,
4170
+ {
4171
+ matched: result,
4172
+ description: `Quirk ${crit.l}[${lhs}] ${crit.op} ${crit.r}`
4173
+ }
4174
+ ]);
4175
+ }
4176
+ var TOP_DOWN_CRITERIA_PERSONALIZATION_ALGORITHM = "default";
4177
+ function topDownCriteriaPersonalizationSelectionAlgorithm({
4178
+ name,
4179
+ context,
4180
+ variations,
4181
+ take = 1,
4182
+ onLogMessage
4183
+ }) {
4184
+ var _a, _b, _c;
4185
+ onLogMessage == null ? void 0 : onLogMessage(["info", 300, "GROUP", { name, take }]);
4186
+ try {
4187
+ const variationMatches = [];
4188
+ const defaultVariations = [];
4189
+ const needsConsentToPersonalize = context.requireConsentForPersonalization;
4190
+ const personalizationAllowed = !needsConsentToPersonalize || context.storage.data.consent;
4191
+ for (const variation of variations) {
4192
+ const isInvalidFormat = variation.pz && (typeof variation.pz !== "object" || variation.pz === null || !("crit" in variation.pz && Array.isArray(variation.pz.crit)));
4193
+ let validVariation;
4194
+ if (isInvalidFormat) {
4195
+ const { pz, ...validParts } = variation;
4196
+ validVariation = validParts;
4197
+ } else {
4198
+ validVariation = variation;
4199
+ }
4200
+ if ((_a = validVariation.pz) == null ? void 0 : _a.crit.length) {
4201
+ if (personalizationAllowed && variationMatches.length !== take && evaluateVariantMatch(variation.id, validVariation.pz, context.scores, onLogMessage, context.quirks)) {
4202
+ variationMatches.push(validVariation);
4203
+ }
4204
+ } else {
4205
+ defaultVariations.push(validVariation);
4206
+ }
4207
+ }
4208
+ const result = [];
4209
+ for (let i = 0; i < variationMatches.length; i++) {
4210
+ let isControl = (_b = context.storage.data.controlGroup) != null ? _b : false;
4211
+ const variation = variationMatches[i];
4212
+ if (!isControl && typeof ((_c = variation.pz) == null ? void 0 : _c.control) === "number") {
4213
+ isControl = context.getPersonalizeVariantControl(name, i);
4214
+ if (typeof isControl === "undefined") {
4215
+ isControl = rollForControlGroup(variation.pz.control);
4216
+ context.storage.updateData([
4217
+ {
4218
+ type: "setpersonalizecontrol",
4219
+ data: {
4220
+ personlizationName: name,
4221
+ index: i,
4222
+ control: isControl
4223
+ }
4224
+ }
4225
+ ]);
4226
+ }
4227
+ }
4228
+ let variantToAdd = variation;
4229
+ if (isControl) {
4230
+ const defaultReplacement = defaultVariations.shift();
4231
+ if (defaultReplacement) {
4232
+ variantToAdd = {
4233
+ ...defaultReplacement,
4234
+ id: variation.id
4235
+ };
4236
+ } else {
4237
+ variantToAdd = void 0;
4238
+ }
4239
+ }
4240
+ if (variantToAdd) {
4241
+ result.push({ ...variantToAdd, control: isControl });
4242
+ }
4243
+ }
4244
+ while (result.length < take && defaultVariations.length) {
4245
+ result.push({ ...defaultVariations.shift(), control: false });
4246
+ }
4247
+ const personalized = result.some((v) => {
4248
+ var _a2;
4249
+ return (_a2 = v.pz) == null ? void 0 : _a2.crit.length;
4250
+ });
4251
+ return {
4252
+ personalized,
4253
+ variations: result
4254
+ };
4255
+ } finally {
4256
+ onLogMessage == null ? void 0 : onLogMessage(["info", 300, "ENDGROUP"]);
4257
+ }
4258
+ }
4259
+ var STRONGEST_SCORE_PERSONALIZATION_ALGORITHM = "ssc";
4260
+ function strongestScorePersonalizationSelectionAlgorithm({
4261
+ name,
4262
+ context,
4263
+ variations,
4264
+ take = 1,
4265
+ onLogMessage
4266
+ }) {
4267
+ var _a, _b;
4268
+ onLogMessage == null ? void 0 : onLogMessage(["info", 300, "GROUP", { name, take }]);
4269
+ try {
4270
+ const variationMatches = [];
4271
+ const defaultVariations = [];
4272
+ const needsConsentToPersonalize = context.requireConsentForPersonalization;
4273
+ const isInGlobalControlGroup = (_a = context.storage.data.controlGroup) != null ? _a : false;
4274
+ const personalizationAllowed = !needsConsentToPersonalize || context.storage.data.consent;
4275
+ let originalIndex = 0;
4276
+ for (const variation of variations) {
4277
+ const isInvalidFormat = variation.pz && typeof variation.pz !== "object";
4278
+ let validVariation;
4279
+ if (isInvalidFormat) {
4280
+ const { pz, ...validParts } = variation;
4281
+ validVariation = validParts;
4282
+ } else {
4283
+ validVariation = variation;
4284
+ }
4285
+ if ((_b = validVariation.pz) == null ? void 0 : _b.dim) {
4286
+ if (!personalizationAllowed) {
4287
+ continue;
4288
+ }
4289
+ const score = context.scores[validVariation.pz.dim];
4290
+ if (score === void 0 || score <= 0) {
4291
+ continue;
4292
+ }
4293
+ variationMatches.push({ variation: validVariation, score, originalIndex });
4294
+ originalIndex++;
4295
+ } else {
4296
+ defaultVariations.push(validVariation);
4297
+ }
4298
+ }
4299
+ variationMatches.sort((a, b) => {
4300
+ const scoreComparison = b.score - a.score;
4301
+ if (scoreComparison === 0) {
4302
+ return a.originalIndex - b.originalIndex;
4303
+ }
4304
+ return scoreComparison;
4305
+ });
4306
+ const result = [];
4307
+ for (let i = 0; i < variationMatches.length; i++) {
4308
+ const variationMatch = variationMatches[i];
4309
+ let variantToAdd = variationMatch.variation;
4310
+ if (i >= take) {
4311
+ continue;
4312
+ }
4313
+ if (isInGlobalControlGroup) {
4314
+ const defaultReplacement = defaultVariations.shift();
4315
+ if (defaultReplacement) {
4316
+ variantToAdd = {
4317
+ ...defaultReplacement,
4318
+ id: variationMatch.variation.id
4319
+ };
4320
+ } else {
4321
+ variantToAdd = void 0;
4322
+ }
4323
+ }
4324
+ if (variantToAdd) {
4325
+ result.push({ ...variantToAdd, control: isInGlobalControlGroup });
4326
+ }
4327
+ }
4328
+ while (result.length < take && defaultVariations.length) {
4329
+ result.push({ ...defaultVariations.shift(), control: false });
4330
+ }
4331
+ return {
4332
+ personalized: variationMatches.length > 0 && !isInGlobalControlGroup,
4333
+ variations: result
4334
+ };
4335
+ } finally {
4336
+ onLogMessage == null ? void 0 : onLogMessage(["info", 300, "ENDGROUP"]);
4337
+ }
4338
+ }
4339
+ var normalizeVariationDistributions = (variations) => {
4340
+ const { values, total, missingDistribution } = variations.reduce(
4341
+ (previous, current) => {
4342
+ if (current.testDistribution) {
4343
+ previous.total += current.testDistribution;
4344
+ } else {
4345
+ ++previous.missingDistribution;
4346
+ }
4347
+ previous.values.push(current.testDistribution);
4348
+ return previous;
4349
+ },
4350
+ {
4351
+ values: [],
4352
+ total: 0,
4353
+ missingDistribution: 0
4354
+ }
4355
+ );
4356
+ if (total > 100) {
4357
+ const autoScaleFactor = 100 / total;
4358
+ values.forEach((value, index) => {
4359
+ if (typeof value === "number") {
4360
+ values[index] = value * autoScaleFactor;
4361
+ }
4362
+ });
4363
+ } else if (total < 100) {
4364
+ const remainder = 100 - total;
4365
+ const missingSlice = remainder / missingDistribution;
4366
+ values.forEach((value, index) => {
4367
+ if (typeof value === "undefined") {
4368
+ values[index] = missingSlice;
4369
+ }
4370
+ });
4371
+ }
4372
+ return values;
4373
+ };
4374
+ var testVariations = ({
4375
+ name,
4376
+ context,
4377
+ variations,
4378
+ onLogMessage
4379
+ }) => {
4380
+ onLogMessage == null ? void 0 : onLogMessage(["info", 400, "GROUP", name]);
4381
+ try {
4382
+ let selectedVariant;
4383
+ const selectedVariantId = context.getTestVariantId(name);
4384
+ if (selectedVariantId === null) {
4385
+ onLogMessage == null ? void 0 : onLogMessage(["error", 401, name]);
4386
+ return { result: void 0, variantAssigned: false };
4387
+ }
4388
+ if (selectedVariantId) {
4389
+ selectedVariant = variations.find((variation) => variation.id === selectedVariantId);
4390
+ if (!selectedVariant) {
4391
+ onLogMessage == null ? void 0 : onLogMessage([
4392
+ "warn",
4393
+ 402,
4394
+ { missingVariant: selectedVariantId, variants: variations.map((v) => v.id) }
4395
+ ]);
4396
+ }
4397
+ }
4398
+ if (!selectedVariant) {
4399
+ const distributions = normalizeVariationDistributions(variations);
4400
+ const random = Math.random() * 100;
4401
+ let distributionOffset = 0;
4402
+ selectedVariant = variations.find((variant, index) => {
4403
+ const distribution = distributions[index];
4404
+ if (random >= distributionOffset && random < distributionOffset + distribution) {
4405
+ return variant;
4406
+ }
4407
+ distributionOffset += distribution;
4408
+ });
4409
+ if (selectedVariant) {
4410
+ onLogMessage == null ? void 0 : onLogMessage(["info", 403, selectedVariant.id]);
4411
+ context.setTestVariantId(name, selectedVariant.id);
4412
+ }
4413
+ }
4414
+ if (selectedVariant) {
4415
+ onLogMessage == null ? void 0 : onLogMessage(["info", 404, selectedVariant.id]);
4416
+ if (selectedVariant.control === void 0) {
4417
+ selectedVariant.control = variations.findIndex((variation) => variation.id === selectedVariantId) === 0;
4418
+ }
4419
+ }
4420
+ return {
4421
+ result: selectedVariant,
4422
+ variantAssigned: !selectedVariantId
4423
+ };
4424
+ } finally {
4425
+ onLogMessage == null ? void 0 : onLogMessage(["info", 400, "ENDGROUP"]);
4426
+ }
4427
+ };
4428
+ var areCommandsEqual = (a, b) => {
4429
+ if (a.type !== b.type) {
4430
+ return false;
4431
+ }
4432
+ return dequal(a, b);
4433
+ };
4434
+ var SERVER_STATE_ID = "__UNIFORM_DATA__";
4435
+ var _data;
4436
+ var _initialData;
4437
+ var _mitt;
4438
+ var TransitionDataStore = class {
4439
+ constructor({ initialData }) {
4440
+ __privateAdd5(this, _data);
4441
+ __privateAdd5(this, _initialData);
4442
+ __privateAdd5(this, _mitt, mitt_default());
4443
+ __publicField3(this, "events", {
4444
+ on: __privateGet5(this, _mitt).on,
4445
+ off: __privateGet5(this, _mitt).off
4446
+ });
4447
+ if (initialData) {
4448
+ __privateSet3(this, _data, initialData);
4449
+ __privateSet3(this, _initialData, initialData);
4450
+ }
4451
+ }
4452
+ get data() {
4453
+ return __privateGet5(this, _data);
4454
+ }
4455
+ get initialData() {
4456
+ return __privateGet5(this, _initialData);
4457
+ }
4458
+ /**
4459
+ * Updates data in the transition storage.
4460
+ * @param commands - Commands to execute against existing stored value (event based stores)
4461
+ * @param computedValue - Pre-computed new value against existing value (object based stores)
4462
+ * @returns Resolved promise when the data has been updated
4463
+ */
4464
+ updateData(commands, computedValue) {
4465
+ __privateSet3(this, _data, computedValue);
4466
+ return this.handleUpdateData(commands, computedValue);
4467
+ }
4468
+ /**
4469
+ * Deletes a visitor's stored data, forgetting them.
4470
+ * @param fromAllDevices - false: logout from this device ID. true: forget all data about the visitor and their identity.
4471
+ */
4472
+ async delete(fromAllDevices) {
4473
+ __privateSet3(this, _data, void 0);
4474
+ await this.handleDelete(fromAllDevices);
4475
+ }
4476
+ signalAsyncDataUpdate(newScores) {
4477
+ if (dequal(this.data, newScores)) {
4478
+ return;
4479
+ }
4480
+ __privateSet3(this, _data, newScores);
4481
+ __privateGet5(this, _mitt).emit("dataUpdatedAsync", newScores);
4482
+ }
4483
+ /**
4484
+ * When we load on the client side after a server side rendering has occurred (server to client transition),
4485
+ * we can have a page script (ID: __UNIFORM_DATA__) that contains the computed visitor data from the SSR/edge render.
4486
+ * This data is injected into the first render to allow score syncing and the server to request commands be applied
4487
+ * to the client side data store.
4488
+ */
4489
+ getClientTransitionState() {
4490
+ if (typeof document === "undefined") {
4491
+ return;
4492
+ }
4493
+ const matchesElement = document.getElementById(SERVER_STATE_ID);
4494
+ return (matchesElement == null ? void 0 : matchesElement.textContent) ? JSON.parse(matchesElement.textContent) : void 0;
4495
+ }
4496
+ };
4497
+ _data = /* @__PURE__ */ new WeakMap();
4498
+ _initialData = /* @__PURE__ */ new WeakMap();
4499
+ _mitt = /* @__PURE__ */ new WeakMap();
4500
+ var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4501
+ var b2s = alphabet.split("");
4502
+ var s2b = new Array(123);
4503
+ for (let i = 0; i < alphabet.length; i++) {
4504
+ s2b[alphabet.charCodeAt(i)] = i;
4505
+ }
4506
+ var ntob = (number) => {
4507
+ if (number < 0) return `-${ntob(-number)}`;
4508
+ let lo = number >>> 0;
4509
+ let hi = number / 4294967296 >>> 0;
4510
+ let right = "";
4511
+ while (hi > 0) {
4512
+ right = b2s[63 & lo] + right;
4513
+ lo >>>= 6;
4514
+ lo |= (63 & hi) << 26;
4515
+ hi >>>= 6;
4516
+ }
4517
+ let left = "";
4518
+ do {
4519
+ left = b2s[63 & lo] + left;
4520
+ lo >>>= 6;
4521
+ } while (lo > 0);
4522
+ return left + right;
4523
+ };
4524
+ var bton = (base64) => {
4525
+ let number = 0;
4526
+ const sign = base64.charAt(0) === "-" ? 1 : 0;
4527
+ for (let i = sign; i < base64.length; i++) {
4528
+ number = number * 64 + s2b[base64.charCodeAt(i)];
4529
+ }
4530
+ return sign ? -number : number;
4531
+ };
4532
+ var ssr = typeof document === "undefined";
4533
+ var UNIFORM_DEFAULT_COOKIE_NAME = "ufvd";
4534
+ var UNIFORM_DEFAULT_QUIRK_COOKIE_NAME = `ufvdqk`;
4535
+ var _cookieName;
4536
+ var _quirkCookieName;
4537
+ var _cookieAttributes;
4538
+ var _quirksEnabled;
4539
+ var CookieTransitionDataStore = class extends TransitionDataStore {
4540
+ constructor({
4541
+ serverCookieValue,
4542
+ experimental_quirksEnabled,
4543
+ quirkCookieValue,
4544
+ quirkCookieName = UNIFORM_DEFAULT_QUIRK_COOKIE_NAME,
4545
+ cookieName = UNIFORM_DEFAULT_COOKIE_NAME,
4546
+ cookieAttributes = { sameSite: "lax" }
4547
+ }) {
4548
+ super({
4549
+ initialData: ssr ? parseScoreCookie(serverCookieValue, experimental_quirksEnabled ? quirkCookieValue : void 0) : void 0
4550
+ });
4551
+ __privateAdd5(this, _cookieName);
4552
+ __privateAdd5(this, _quirkCookieName);
4553
+ __privateAdd5(this, _cookieAttributes);
4554
+ __privateAdd5(this, _quirksEnabled);
4555
+ __privateSet3(this, _cookieName, cookieName);
4556
+ __privateSet3(this, _cookieAttributes, cookieAttributes);
4557
+ __privateSet3(this, _quirkCookieName, quirkCookieName);
4558
+ __privateSet3(this, _quirksEnabled, experimental_quirksEnabled || false);
4559
+ }
4560
+ handleDelete() {
4561
+ if (ssr) return Promise.resolve();
4562
+ api.remove(__privateGet5(this, _cookieName));
4563
+ return Promise.resolve();
4564
+ }
4565
+ async handleUpdateData(_, computedValue) {
4566
+ if (ssr) return;
4567
+ if (computedValue.consent) {
4568
+ api.set(__privateGet5(this, _cookieName), serializeCookie(computedValue), __privateGet5(this, _cookieAttributes));
4569
+ if (__privateGet5(this, _quirksEnabled) && Object.keys(computedValue.quirks || {}).length) {
4570
+ const quirkCookieValue = serializeQuirks(computedValue.quirks || {});
4571
+ api.set(__privateGet5(this, _quirkCookieName), quirkCookieValue, __privateGet5(this, _cookieAttributes));
4572
+ }
4573
+ } else {
4574
+ api.remove(__privateGet5(this, _cookieName));
4575
+ if (__privateGet5(this, _quirksEnabled)) {
4576
+ api.remove(__privateGet5(this, _quirkCookieName));
4577
+ }
4578
+ }
4579
+ }
4580
+ };
4581
+ _cookieName = /* @__PURE__ */ new WeakMap();
4582
+ _quirkCookieName = /* @__PURE__ */ new WeakMap();
4583
+ _cookieAttributes = /* @__PURE__ */ new WeakMap();
4584
+ _quirksEnabled = /* @__PURE__ */ new WeakMap();
4585
+ var TYPE_SEP = "~";
4586
+ var PAIR_SEP = "!";
4587
+ var KV_SEP = "-";
4588
+ var QUIRK_SEP = "!!";
4589
+ function parseScoreCookie(cookieValue, quirkCookieValue) {
4590
+ if (!cookieValue) return;
4591
+ const types = cookieValue.split(TYPE_SEP);
4592
+ if (types.length > 5) return;
4593
+ const [abTestData, sessionScores, visitorScores, controlGroup, personalizeVariants] = types;
4594
+ const data = {
4595
+ // this is true since we're reading a cookie, which wouldn't exist if consent wasn't given
4596
+ consent: true,
4597
+ sessionScores: decodeCookieType(parseCookieScores(sessionScores)),
4598
+ scores: decodeCookieType(parseCookieScores(visitorScores)),
4599
+ tests: parseCookieType(abTestData),
4600
+ controlGroup: controlGroup === "1",
4601
+ personalizeVariants: decodePersonalizeVariants(personalizeVariants)
4602
+ };
4603
+ if (quirkCookieValue) {
4604
+ data.quirks = parseQuirkCookie(quirkCookieValue);
4605
+ }
4606
+ return data;
4607
+ }
4608
+ function parseQuirkCookie(quirkCookieValue) {
4609
+ const pairs = quirkCookieValue.split(QUIRK_SEP);
4610
+ const splitPairs = pairs.map((pair) => {
4611
+ const sep = pair.indexOf(KV_SEP);
4612
+ if (sep === -1) {
4613
+ return void 0;
4614
+ }
4615
+ return [pair.slice(0, sep), pair.slice(sep + 1)];
4616
+ });
4617
+ const areAllPairsValid = splitPairs.every((pair) => pair !== void 0);
4618
+ if (!areAllPairsValid) {
4619
+ return {};
4620
+ }
4621
+ return splitPairs.reduce((acc, cur) => {
4622
+ const [key, value] = cur;
4623
+ acc[key] = value;
4624
+ return acc;
4625
+ }, {});
4626
+ }
4627
+ function parseCookieScores(type) {
4628
+ if (!type) {
4629
+ return {};
4630
+ }
4631
+ const pairs = type.split(PAIR_SEP).map((pair) => pair.split(KV_SEP));
4632
+ return pairs.reduce((acc, cur) => {
4633
+ if (cur.length < 2) return acc;
4634
+ const key = cur.slice(0, -1).join(KV_SEP);
4635
+ acc[key] = cur[cur.length - 1];
4636
+ return acc;
4637
+ }, {});
4638
+ }
4639
+ function parseCookieType(type) {
4640
+ if (!type) {
4641
+ return {};
4642
+ }
4643
+ const pairs = type.split(PAIR_SEP).map((pair) => pair.split(KV_SEP));
4644
+ return pairs.reduce((acc, cur) => {
4645
+ if (cur.length < 2) return acc;
4646
+ acc[cur[0]] = cur.slice(1).join("-");
4647
+ return acc;
4648
+ }, {});
4649
+ }
4650
+ function decodeCookieType(type) {
4651
+ return Object.entries(type).reduce((acc, [key, value]) => {
4652
+ acc[key] = bton(value);
4653
+ return acc;
4654
+ }, {});
4655
+ }
4656
+ function serializeCookie(data) {
4657
+ return [
4658
+ serializeCookieType(data.tests),
4659
+ serializeCookieType(encodeCookieType(data.sessionScores)),
4660
+ serializeCookieType(encodeCookieType(data.scores)),
4661
+ data.controlGroup ? "1" : "0",
4662
+ serializePersonalizeVariants(data)
4663
+ ].join(TYPE_SEP);
4664
+ }
4665
+ function serializePersonalizeVariants({
4666
+ personalizeVariants
4667
+ }) {
4668
+ const data = {};
4669
+ if (typeof personalizeVariants === "object") {
4670
+ Object.keys(personalizeVariants).forEach((personalizationName) => {
4671
+ const results = [];
4672
+ const variants = personalizeVariants[personalizationName];
4673
+ variants.forEach((variant) => {
4674
+ results.push(`${variant.index}:${variant.control ? "1" : "0"}`);
4675
+ });
4676
+ data[personalizationName] = results.join(",");
4677
+ });
4678
+ }
4679
+ const serialized = serializeCookieType(data);
4680
+ return serialized;
4681
+ }
4682
+ function decodePersonalizeVariants(data) {
4683
+ const parsed = parseCookieType(data);
4684
+ const keys = Object.keys(parsed);
4685
+ if (!keys.length) {
4686
+ return void 0;
4687
+ }
4688
+ const results = {};
4689
+ Object.keys(parsed).forEach((k) => {
4690
+ const variants = parsed[k].split(",");
4691
+ const key = decodeURIComponent(k);
4692
+ results[key] = variants.map((variant) => {
4693
+ const [index, control] = variant.split(":");
4694
+ return {
4695
+ index: parseInt(index, 10),
4696
+ control: control === "1"
4697
+ };
4698
+ });
4699
+ });
4700
+ return results;
4701
+ }
4702
+ function encodeCookieType(type) {
4703
+ return Object.entries(type).reduce((acc, [key, value]) => {
4704
+ acc[key] = ntob(value);
4705
+ return acc;
4706
+ }, {});
4707
+ }
4708
+ function serializeCookieType(type) {
4709
+ return Object.entries(type).map((kv) => kv.join(KV_SEP)).join(PAIR_SEP);
4710
+ }
4711
+ function serializeQuirks(quirks) {
4712
+ return Object.entries(quirks).map((kv) => kv.join(KV_SEP)).join(QUIRK_SEP);
4713
+ }
4714
+ var _EdgeTransitionDataStore_instances;
4715
+ var fetchData_fn;
4716
+ _EdgeTransitionDataStore_instances = /* @__PURE__ */ new WeakSet();
4717
+ fetchData_fn = async function() {
4718
+ const serviceData = await new Promise((resolve) => {
4719
+ setTimeout(() => {
4720
+ resolve(void 0);
4721
+ }, 2e3);
4722
+ });
4723
+ if (serviceData) {
4724
+ this.signalAsyncDataUpdate(serviceData);
4725
+ }
4726
+ };
4727
+ var emptyVisitorData = () => ({
4728
+ quirks: {},
4729
+ scores: {},
4730
+ sessionScores: {},
4731
+ tests: {},
4732
+ goals: {},
4733
+ consent: false,
4734
+ controlGroup: false,
4735
+ personalizeVariants: {}
4736
+ });
4737
+ var clone = (0, import_rfdc.default)();
4738
+ function applyCommandsToData(commands, state) {
4739
+ const newData = state ? clone(state) : emptyVisitorData();
4740
+ commands.forEach((command) => {
4741
+ var _a, _b, _c;
4742
+ switch (command.type) {
4743
+ case "consent":
4744
+ newData.consent = command.data;
4745
+ break;
4746
+ case "setquirk":
4747
+ newData.quirks[command.data.key] = command.data.value;
4748
+ break;
4749
+ case "settest":
4750
+ newData.tests[command.data.test] = command.data.variant;
4751
+ break;
4752
+ case "modscore":
4753
+ const delta = Number(command.data.delta);
4754
+ if (isNaN(delta)) {
4755
+ throw new Error("Non-number delta received");
4756
+ }
4757
+ const existing = (_a = newData.scores[command.data.dimension]) != null ? _a : 0;
4758
+ newData.scores[command.data.dimension] = existing + delta;
4759
+ break;
4760
+ case "modscoreS":
4761
+ const deltaS = Number(command.data.delta);
4762
+ if (isNaN(deltaS)) {
4763
+ throw new Error("Non-number delta received");
4764
+ }
4765
+ const existingS = (_b = newData.sessionScores[command.data.dimension]) != null ? _b : 0;
4766
+ newData.sessionScores[command.data.dimension] = existingS + deltaS;
4767
+ break;
4768
+ case "identify":
4769
+ break;
4770
+ case "setcontrol":
4771
+ newData.controlGroup = command.data;
4772
+ break;
4773
+ case "setpersonalizecontrol":
4774
+ if (!newData.personalizeVariants) {
4775
+ newData.personalizeVariants = {};
4776
+ }
4777
+ if (!newData.personalizeVariants[command.data.personlizationName]) {
4778
+ newData.personalizeVariants[command.data.personlizationName] = [];
4779
+ }
4780
+ const existingDef = newData.personalizeVariants[command.data.personlizationName].find(
4781
+ (i) => i.index === command.data.index
4782
+ );
4783
+ if (!existingDef) {
4784
+ newData.personalizeVariants[command.data.personlizationName].push({
4785
+ index: command.data.index,
4786
+ control: command.data.control
4787
+ });
4788
+ } else {
4789
+ console.warn("Overwriting existing control group definition is not allowed");
4790
+ }
4791
+ break;
4792
+ case "setgoal":
4793
+ newData.goals = (_c = newData.goals) != null ? _c : {};
4794
+ newData.goals[command.data.goal] = true;
4795
+ break;
4796
+ default:
4797
+ throw new Error(`Unknown command`);
4798
+ }
4799
+ });
4800
+ return newData;
4801
+ }
4802
+ var _LocalStorage_instances;
4803
+ var key_fn;
4804
+ var LocalStorage = class {
4805
+ constructor(partitionKey) {
4806
+ __publicField3(this, "partitionKey", partitionKey);
4807
+ __privateAdd5(this, _LocalStorage_instances);
4808
+ __publicField3(this, "inMemoryFallback", {});
4809
+ __publicField3(this, "hasLocalStorageObject", typeof document !== "undefined" && typeof localStorage !== "undefined");
4810
+ }
4811
+ get(key) {
4812
+ const keyValue = __privateMethod2(this, _LocalStorage_instances, key_fn).call(this, key);
4813
+ const fallbackValue = this.inMemoryFallback[keyValue];
4814
+ if (!this.hasLocalStorageObject || fallbackValue) {
4815
+ return fallbackValue;
4816
+ }
4817
+ try {
4818
+ const value = localStorage.getItem(keyValue);
4819
+ return value ? JSON.parse(value) : void 0;
4820
+ } catch (e) {
4821
+ return fallbackValue;
4822
+ }
4823
+ }
4824
+ set(key, value, storageConsent) {
4825
+ const keyValue = __privateMethod2(this, _LocalStorage_instances, key_fn).call(this, key);
4826
+ this.inMemoryFallback[keyValue] = value;
4827
+ if (!this.hasLocalStorageObject || !storageConsent) {
4828
+ return;
4829
+ }
4830
+ try {
4831
+ localStorage.setItem(keyValue, JSON.stringify(value));
4832
+ } catch (e) {
4833
+ console.warn(e);
4834
+ }
4835
+ }
4836
+ delete(key, leaveInMemory) {
4837
+ const keyValue = __privateMethod2(this, _LocalStorage_instances, key_fn).call(this, key);
4838
+ if (!leaveInMemory) {
4839
+ delete this.inMemoryFallback[keyValue];
4840
+ }
4841
+ try {
4842
+ localStorage.removeItem(keyValue);
4843
+ } catch (e) {
4844
+ }
4845
+ }
4846
+ };
4847
+ _LocalStorage_instances = /* @__PURE__ */ new WeakSet();
4848
+ key_fn = function(key) {
4849
+ return this.partitionKey ? `${this.partitionKey}.${key}` : key;
4850
+ };
4851
+ var STORAGE_KEY = "ufvisitor";
4852
+ var _mitt2;
4853
+ var _persist;
4854
+ var _visitTimeout;
4855
+ var _options;
4856
+ var _VisitorDataStore_instances;
4857
+ var currentData_get;
4858
+ var replaceData_fn;
4859
+ var setVisitTimeout_fn;
4860
+ var isExpired_fn;
4861
+ var handleCaps_fn;
4862
+ var defaultData_fn;
4863
+ var VisitorDataStore = class {
4864
+ constructor(options) {
4865
+ __privateAdd5(this, _VisitorDataStore_instances);
4866
+ __privateAdd5(this, _mitt2, mitt_default());
4867
+ __privateAdd5(this, _persist);
4868
+ __privateAdd5(this, _visitTimeout);
4869
+ __privateAdd5(this, _options);
4870
+ __publicField3(this, "events", {
4871
+ on: __privateGet5(this, _mitt2).on,
4872
+ off: __privateGet5(this, _mitt2).off
4873
+ });
4874
+ __privateSet3(this, _options, options);
4875
+ __privateSet3(this, _persist, new LocalStorage(options.partitionKey));
4876
+ if (!__privateGet5(this, _VisitorDataStore_instances, currentData_get)) {
4877
+ __privateMethod2(this, _VisitorDataStore_instances, replaceData_fn).call(this, __privateMethod2(this, _VisitorDataStore_instances, defaultData_fn).call(this), true);
4878
+ }
4879
+ if (options.transitionStore) {
4880
+ const serverToClientTransitionState = options.transitionStore.getClientTransitionState();
4881
+ if (serverToClientTransitionState && options.onServerTransitionReceived) {
4882
+ options.onServerTransitionReceived(serverToClientTransitionState);
4883
+ }
4884
+ options.transitionStore.events.on("dataUpdatedAsync", (data) => {
4885
+ __privateMethod2(this, _VisitorDataStore_instances, replaceData_fn).call(this, {
4886
+ ...__privateGet5(this, _VisitorDataStore_instances, currentData_get).visitorData,
4887
+ ...data
4888
+ });
4889
+ });
4890
+ const transitionData = options.transitionStore.data;
4891
+ if (transitionData) {
4892
+ __privateMethod2(this, _VisitorDataStore_instances, replaceData_fn).call(
4893
+ this,
4894
+ // we know _currentData is not empty because we inited it above if it was
4895
+ { ...__privateGet5(this, _VisitorDataStore_instances, currentData_get).visitorData, ...transitionData },
4896
+ true
4897
+ );
4898
+ }
4899
+ }
4900
+ }
4901
+ /** Gets the current visitor data. This property is always up to date. */
4902
+ get data() {
4903
+ var _a, _b, _c;
4904
+ const data = (_a = __privateGet5(this, _VisitorDataStore_instances, currentData_get)) != null ? _a : { visitorData: __privateMethod2(this, _VisitorDataStore_instances, defaultData_fn).call(this), updated: (/* @__PURE__ */ new Date()).getTime() };
4905
+ if (__privateMethod2(this, _VisitorDataStore_instances, isExpired_fn).call(this, data)) {
4906
+ const { sessionScores, ...newData } = data.visitorData;
4907
+ __privateMethod2(this, _VisitorDataStore_instances, replaceData_fn).call(this, { ...newData, sessionScores: {} });
4908
+ (_c = (_b = __privateGet5(this, _options)).onLogMessage) == null ? void 0 : _c.call(_b, ["info", 120]);
4909
+ return __privateGet5(this, _VisitorDataStore_instances, currentData_get).visitorData;
4910
+ }
4911
+ return data.visitorData;
4912
+ }
4913
+ get decayEnabled() {
4914
+ return !!__privateGet5(this, _options).decay;
4915
+ }
4916
+ get options() {
4917
+ return __privateGet5(this, _options);
4918
+ }
4919
+ /** Push data update command(s) into the visitor data */
4920
+ async updateData(commands) {
4921
+ var _a, _b, _c;
4922
+ if (commands.length === 0) {
4923
+ return;
4924
+ }
4925
+ (_b = (_a = __privateGet5(this, _options)).onLogMessage) == null ? void 0 : _b.call(_a, ["debug", 101, commands]);
4926
+ const newData = applyCommandsToData(commands, this.data);
4927
+ if (commands.some((c) => c.type === "consent" && !c.data)) {
4928
+ __privateGet5(this, _persist).delete(STORAGE_KEY, true);
4929
+ }
4930
+ __privateMethod2(this, _VisitorDataStore_instances, replaceData_fn).call(this, newData);
4931
+ await ((_c = __privateGet5(this, _options).transitionStore) == null ? void 0 : _c.updateData(commands, __privateGet5(this, _VisitorDataStore_instances, currentData_get).visitorData));
4932
+ __privateGet5(this, _mitt2).emit("commandsExecuted", commands);
4933
+ }
4934
+ /**
4935
+ * Deletes visitor data (forgetting them)
4936
+ * In most cases you should use forget() on the Context instead of this function, which also clears the Context state.
4937
+ * @param fromAllDevices - for an identified user, whether to delete all their data (for the entire account) - true, or data for this device (sign out) - false
4938
+ */
4939
+ async delete(fromAllDevices) {
4940
+ var _a, _b, _c, _d, _e;
4941
+ (_b = (_a = __privateGet5(this, _options)).onLogMessage) == null ? void 0 : _b.call(_a, ["info", 103, "GROUP", fromAllDevices]);
4942
+ try {
4943
+ __privateGet5(this, _persist).delete(STORAGE_KEY, false);
4944
+ await ((_c = __privateGet5(this, _options).transitionStore) == null ? void 0 : _c.delete(fromAllDevices));
4945
+ __privateMethod2(this, _VisitorDataStore_instances, replaceData_fn).call(this, __privateMethod2(this, _VisitorDataStore_instances, defaultData_fn).call(this));
4946
+ } finally {
4947
+ (_e = (_d = __privateGet5(this, _options)).onLogMessage) == null ? void 0 : _e.call(_d, ["info", 103, "ENDGROUP"]);
4948
+ }
4949
+ }
4950
+ };
4951
+ _mitt2 = /* @__PURE__ */ new WeakMap();
4952
+ _persist = /* @__PURE__ */ new WeakMap();
4953
+ _visitTimeout = /* @__PURE__ */ new WeakMap();
4954
+ _options = /* @__PURE__ */ new WeakMap();
4955
+ _VisitorDataStore_instances = /* @__PURE__ */ new WeakSet();
4956
+ currentData_get = function() {
4957
+ return __privateGet5(this, _persist).get(STORAGE_KEY);
4958
+ };
4959
+ replaceData_fn = function(data, quiet = false) {
4960
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
4961
+ const oldData = __privateGet5(this, _VisitorDataStore_instances, currentData_get);
4962
+ const now = Date.now();
4963
+ __privateMethod2(this, _VisitorDataStore_instances, handleCaps_fn).call(this, data.scores);
4964
+ __privateMethod2(this, _VisitorDataStore_instances, handleCaps_fn).call(this, data.sessionScores);
4965
+ (_b = (_a = __privateGet5(this, _options)).decay) == null ? void 0 : _b.call(_a, {
4966
+ now,
4967
+ lastUpd: oldData == null ? void 0 : oldData.updated,
4968
+ scores: data.scores,
4969
+ sessionScores: data.sessionScores,
4970
+ onLogMessage: __privateGet5(this, _options).onLogMessage
4971
+ });
4972
+ const haveScoresChanged = !dequal(oldData == null ? void 0 : oldData.visitorData.scores, data.scores);
4973
+ const haveSessionScoresChanged = !dequal(oldData == null ? void 0 : oldData.visitorData.sessionScores, data.sessionScores);
4974
+ const haveQuirksChanged = !dequal(oldData == null ? void 0 : oldData.visitorData.quirks, data.quirks);
4975
+ const haveTestsChanged = !dequal(oldData == null ? void 0 : oldData.visitorData.tests, data.tests);
4976
+ const haveGoalsChanged = !dequal(oldData == null ? void 0 : oldData.visitorData.goals, data.goals);
4977
+ const updatedData = {
4978
+ updated: now,
4979
+ visitorData: data
4980
+ };
4981
+ __privateMethod2(this, _VisitorDataStore_instances, setVisitTimeout_fn).call(this);
4982
+ __privateGet5(this, _persist).set(STORAGE_KEY, updatedData, !!data.consent);
4983
+ (_d = (_c = __privateGet5(this, _options)).onLogMessage) == null ? void 0 : _d.call(_c, ["debug", 102, data]);
4984
+ if (!quiet) {
4985
+ if (haveScoresChanged || haveSessionScoresChanged) {
4986
+ __privateGet5(this, _mitt2).emit("scoresUpdated", data);
4987
+ }
4988
+ if (haveQuirksChanged) {
4989
+ __privateGet5(this, _mitt2).emit("quirksUpdated", data);
4990
+ }
4991
+ if (haveTestsChanged) {
4992
+ __privateGet5(this, _mitt2).emit("testsUpdated", data);
4993
+ }
4994
+ if (((_e = oldData == null ? void 0 : oldData.visitorData) == null ? void 0 : _e.consent) !== data.consent) {
4995
+ __privateGet5(this, _mitt2).emit("consentUpdated", data);
4996
+ }
4997
+ if (((_f = oldData == null ? void 0 : oldData.visitorData) == null ? void 0 : _f.controlGroup) !== data.controlGroup) {
4998
+ __privateGet5(this, _mitt2).emit("controlGroupUpdated", data);
4999
+ (_i = (_h = __privateGet5(this, _options)).onLogMessage) == null ? void 0 : _i.call(_h, ["debug", 104, (_g = data.controlGroup) != null ? _g : false]);
5000
+ }
5001
+ if (haveGoalsChanged) {
5002
+ const newGoalKeys = Object.keys((_j = data.goals) != null ? _j : {});
5003
+ for (let i = 0; i < newGoalKeys.length; i++) {
5004
+ const key = newGoalKeys[i];
5005
+ if (!((_k = oldData == null ? void 0 : oldData.visitorData.goals) == null ? void 0 : _k[key])) {
5006
+ __privateGet5(this, _mitt2).emit("goalConverted", { goalId: key });
5007
+ }
5008
+ }
5009
+ }
5010
+ }
5011
+ };
5012
+ setVisitTimeout_fn = function() {
5013
+ if (typeof document === "undefined" || !__privateGet5(this, _options).visitLifespan) {
5014
+ return;
5015
+ }
5016
+ if (__privateGet5(this, _visitTimeout)) {
5017
+ window.clearTimeout(__privateGet5(this, _visitTimeout));
5018
+ }
5019
+ __privateSet3(this, _visitTimeout, window.setTimeout(() => {
5020
+ this.data;
5021
+ }, __privateGet5(this, _options).visitLifespan + 50));
5022
+ };
5023
+ isExpired_fn = function(data) {
5024
+ const expires = __privateGet5(this, _options).visitLifespan;
5025
+ return expires ? data.updated + expires < Date.now() : false;
5026
+ };
5027
+ handleCaps_fn = function(scores) {
5028
+ var _a, _b;
5029
+ if (!__privateGet5(this, _options).manifest) {
5030
+ return;
5031
+ }
5032
+ for (const dim in scores) {
5033
+ const score = scores[dim];
5034
+ const dimDef = __privateGet5(this, _options).manifest.getDimensionByKey(dim);
5035
+ if (!dimDef) {
5036
+ continue;
5037
+ }
5038
+ if (score > dimDef.cap) {
5039
+ (_b = (_a = __privateGet5(this, _options)).onLogMessage) == null ? void 0 : _b.call(_a, ["debug", 110, { dim, score, cap: dimDef.cap }]);
5040
+ scores[dim] = dimDef.cap;
5041
+ }
5042
+ }
5043
+ };
5044
+ defaultData_fn = function() {
5045
+ var _a, _b, _c;
5046
+ return {
5047
+ ...emptyVisitorData(),
5048
+ consent: (_a = __privateGet5(this, _options).defaultConsent) != null ? _a : false,
5049
+ controlGroup: (_c = (_b = __privateGet5(this, _options).manifest) == null ? void 0 : _b.rollForControlGroup()) != null ? _c : false
5050
+ };
5051
+ };
5052
+ var CONTEXTUAL_EDITING_TEST_NAME = "contextual_editing_test";
5053
+ var CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID = "contextual_editing_test_selected_variant";
5054
+ var _personalizationSelectionAlgorithms;
5055
+ var _serverTransitionState;
5056
+ var _scores;
5057
+ var _state;
5058
+ var _pzCache;
5059
+ var _plugins;
5060
+ var _commands;
5061
+ var _requireConsentForPersonalization;
5062
+ var _mitt3;
5063
+ var _Context_instances;
5064
+ var emitTest_fn;
5065
+ var updateGoals_fn;
5066
+ var updateComputedScores_fn;
5067
+ var calculateScores_fn;
5068
+ var Context = class {
5069
+ constructor(options) {
5070
+ __privateAdd5(this, _Context_instances);
5071
+ __publicField3(this, "manifest");
5072
+ __privateAdd5(this, _personalizationSelectionAlgorithms);
5073
+ __privateAdd5(this, _serverTransitionState);
5074
+ __privateAdd5(this, _scores, {});
5075
+ __privateAdd5(this, _state);
5076
+ __privateAdd5(this, _pzCache, {});
5077
+ __privateAdd5(this, _plugins);
5078
+ __privateAdd5(this, _commands);
5079
+ __privateAdd5(this, _requireConsentForPersonalization);
5080
+ __privateAdd5(this, _mitt3, mitt_default());
5081
+ __publicField3(this, "events", {
5082
+ on: __privateGet5(this, _mitt3).on,
5083
+ off: __privateGet5(this, _mitt3).off
5084
+ });
5085
+ __publicField3(this, "storage");
5086
+ var _a, _b, _c;
5087
+ const { manifest, ...storageOptions } = options;
5088
+ __privateSet3(this, _state, {});
5089
+ __privateSet3(this, _plugins, options.plugins);
5090
+ __privateSet3(this, _requireConsentForPersonalization, options.requireConsentForPersonalization);
5091
+ if (typeof options.transitionStore !== "undefined") {
5092
+ __privateSet3(this, _commands, []);
5093
+ }
5094
+ __privateSet3(this, _personalizationSelectionAlgorithms, {
5095
+ [TOP_DOWN_CRITERIA_PERSONALIZATION_ALGORITHM]: topDownCriteriaPersonalizationSelectionAlgorithm,
5096
+ [STRONGEST_SCORE_PERSONALIZATION_ALGORITHM]: strongestScorePersonalizationSelectionAlgorithm
5097
+ });
5098
+ (_a = __privateGet5(this, _plugins)) == null ? void 0 : _a.forEach((plugin) => {
5099
+ if (!plugin.personalizationSelectionAlgorithms) {
5100
+ return;
5101
+ }
5102
+ __privateSet3(this, _personalizationSelectionAlgorithms, {
5103
+ ...__privateGet5(this, _personalizationSelectionAlgorithms),
5104
+ ...plugin.personalizationSelectionAlgorithms
5105
+ });
5106
+ });
5107
+ (_b = __privateGet5(this, _plugins)) == null ? void 0 : _b.forEach((plugin) => {
5108
+ if (!plugin.logDrain) {
5109
+ return;
5110
+ }
5111
+ __privateGet5(this, _mitt3).on("log", plugin.logDrain);
5112
+ });
5113
+ __privateGet5(this, _mitt3).emit("log", ["info", 1, "GROUP"]);
5114
+ try {
5115
+ this.manifest = new ManifestInstance({
5116
+ onLogMessage: (message) => __privateGet5(this, _mitt3).emit("log", message),
5117
+ manifest,
5118
+ evaluator: new GroupCriteriaEvaluator({
5119
+ CK: cookieEvaluator,
5120
+ QS: queryStringEvaluator,
5121
+ QK: quirkEvaluator,
5122
+ PVC: pageViewCountEvaluator,
5123
+ EVT: eventEvaluator,
5124
+ PV: currentPageEvaluator
5125
+ })
5126
+ });
5127
+ this.storage = new VisitorDataStore({
5128
+ ...storageOptions,
5129
+ manifest: this.manifest,
5130
+ onServerTransitionReceived: (state) => {
5131
+ __privateSet3(this, _serverTransitionState, state);
5132
+ if (state.ssv) {
5133
+ __privateSet3(this, _scores, state.ssv);
5134
+ __privateGet5(this, _mitt3).emit("log", ["debug", 130, state]);
5135
+ }
5136
+ if (state.compositionMetadata) {
5137
+ __privateGet5(this, _state).compositionMetadata = state.compositionMetadata;
5138
+ }
5139
+ },
5140
+ onLogMessage: (message) => __privateGet5(this, _mitt3).emit("log", message)
5141
+ });
5142
+ this.storage.events.on("scoresUpdated", __privateMethod2(this, _Context_instances, updateComputedScores_fn).bind(this));
5143
+ if (!__privateGet5(this, _serverTransitionState)) {
5144
+ __privateMethod2(this, _Context_instances, updateComputedScores_fn).call(this, this.storage.data);
5145
+ }
5146
+ this.storage.events.on("quirksUpdated", (quirks) => {
5147
+ const updates = this.manifest.computeSignals({
5148
+ scores: __privateGet5(this, _scores),
5149
+ state: __privateGet5(this, _state),
5150
+ previousState: __privateGet5(this, _state),
5151
+ visitor: this.storage.data
5152
+ });
5153
+ __privateMethod2(this, _Context_instances, updateGoals_fn).call(this, {
5154
+ quirks: quirks.quirks,
5155
+ scores: void 0
5156
+ });
5157
+ this.storage.updateData(updates);
5158
+ __privateGet5(this, _mitt3).emit("quirksUpdated", quirks.quirks);
5159
+ __privateGet5(this, _mitt3).emit("log", ["info", 4, quirks.quirks]);
5160
+ });
5161
+ (_c = __privateGet5(this, _plugins)) == null ? void 0 : _c.forEach((plugin) => {
5162
+ if (!plugin.init) {
5163
+ return;
5164
+ }
5165
+ plugin.init(this);
5166
+ });
5167
+ } finally {
5168
+ __privateGet5(this, _mitt3).emit("log", ["info", 1, "ENDGROUP"]);
5169
+ }
5170
+ if (typeof window !== "undefined") {
5171
+ window.__UNIFORM_CONTEXTUAL_EDITING_CONTEXT__ = this;
5172
+ }
5173
+ }
5174
+ /** Gets the current visitor's dimension score vector. */
5175
+ get scores() {
5176
+ return __privateGet5(this, _scores);
5177
+ }
5178
+ /** Gets the current visitor's quirks values. */
5179
+ get quirks() {
5180
+ var _a, _b;
5181
+ return (_b = (_a = __privateGet5(this, _serverTransitionState)) == null ? void 0 : _a.quirks) != null ? _b : this.storage.data.quirks;
5182
+ }
5183
+ get requireConsentForPersonalization() {
5184
+ return __privateGet5(this, _requireConsentForPersonalization);
5185
+ }
5186
+ /**
5187
+ * Updates the Context with new data of any sort, such as
5188
+ * new URLs, cookies, quirks, and enrichments.
5189
+ *
5190
+ * Only properties that are set in the data parameter will be updated,
5191
+ * for example if passing `url` but not `cookies`, the last known state of cookies will be preserved.
5192
+ *
5193
+ * Properties that do not result in a changed state,
5194
+ * i.e. pushing the same URL or cookies as before,
5195
+ * will NOT result in a recomputation of signal state.
5196
+ */
5197
+ async update(newData) {
5198
+ var _a, _b, _c, _d, _e;
5199
+ const commands = [];
5200
+ const newServerSideTests = {};
5201
+ if ((_a = __privateGet5(this, _serverTransitionState)) == null ? void 0 : _a.quirks) {
5202
+ newData = {
5203
+ ...newData,
5204
+ quirks: {
5205
+ ...__privateGet5(this, _serverTransitionState).quirks,
5206
+ ...newData.quirks || {}
5207
+ }
5208
+ };
5209
+ }
5210
+ if ((_b = __privateGet5(this, _serverTransitionState)) == null ? void 0 : _b.tests) {
5211
+ const testEntries = Object.entries(__privateGet5(this, _serverTransitionState).tests);
5212
+ if (testEntries.length > 0) {
5213
+ const validTests = [];
5214
+ testEntries.forEach(([testName, testVariantId]) => {
5215
+ if (!this.storage.data.tests[testName]) {
5216
+ validTests.push([testName, testVariantId]);
5217
+ newServerSideTests[testName] = testVariantId;
5218
+ }
5219
+ });
5220
+ commands.push(
5221
+ ...validTests.map(([key, value]) => ({
5222
+ type: "settest",
5223
+ data: { test: key, variant: value }
5224
+ }))
5225
+ );
5226
+ }
5227
+ }
5228
+ if ((_c = __privateGet5(this, _serverTransitionState)) == null ? void 0 : _c.personalizeVariants) {
5229
+ Object.keys(__privateGet5(this, _serverTransitionState).personalizeVariants).forEach((personalizationName) => {
5230
+ const variants = __privateGet5(this, _serverTransitionState).personalizeVariants[personalizationName];
5231
+ variants.forEach((e) => {
5232
+ commands.push({
5233
+ type: "setpersonalizecontrol",
5234
+ data: { personlizationName: personalizationName, index: e.index, control: e.control }
5235
+ });
5236
+ });
5237
+ });
5238
+ }
5239
+ try {
5240
+ __privateGet5(this, _mitt3).emit("log", [
5241
+ "info",
5242
+ 2,
5243
+ "GROUP",
5244
+ {
5245
+ ...newData,
5246
+ // need to convert url to string so it can be json serialized
5247
+ // to go over postMessage to chrome extension
5248
+ url: (_d = newData.url) == null ? void 0 : _d.toString()
5249
+ }
5250
+ ]);
5251
+ if (newData.quirks) {
5252
+ commands.push(
5253
+ ...Object.entries(newData.quirks).map(([key, value]) => ({
5254
+ type: "setquirk",
5255
+ data: { key, value }
5256
+ }))
5257
+ );
5258
+ }
5259
+ if (newData.enrichments) {
5260
+ newData.enrichments.forEach((enrichment) => {
5261
+ const dimension = getEnrichmentVectorKey(enrichment.cat, enrichment.key);
5262
+ const dimData = this.manifest.getDimensionByKey(dimension);
5263
+ if (dimData) {
5264
+ commands.push({
5265
+ type: "modscore",
5266
+ data: {
5267
+ dimension,
5268
+ delta: enrichment.str
5269
+ }
5270
+ });
5271
+ } else {
5272
+ __privateGet5(this, _mitt3).emit("log", ["warn", 5, enrichment]);
5273
+ }
5274
+ });
5275
+ }
5276
+ const effectiveNewStateForSignalComputation = {
5277
+ ...__privateGet5(this, _state),
5278
+ ...newData
5279
+ };
5280
+ commands.push(
5281
+ ...this.manifest.computeSignals({
5282
+ state: effectiveNewStateForSignalComputation,
5283
+ previousState: __privateGet5(this, _state),
5284
+ visitor: this.storage.data,
5285
+ // re-compute using scores from storage instead of the current scores since
5286
+ // server transition scores might have adjusted values already integrated into them,
5287
+ // which causes issues when you are near limits.
5288
+ scores: __privateGet5(this, _serverTransitionState) ? __privateMethod2(this, _Context_instances, calculateScores_fn).call(this, this.storage.data) : __privateGet5(this, _scores)
5289
+ })
5290
+ );
5291
+ const previousCompositionMetadata = __privateGet5(this, _state).compositionMetadata;
5292
+ __privateSet3(this, _state, {
5293
+ ...__privateGet5(this, _state),
5294
+ ...newData
5295
+ });
5296
+ if (newData.compositionMetadata && // deep equal is not too bad, as we only have 1 level of depth in dynamic inputs
5297
+ !dequal(previousCompositionMetadata, __privateGet5(this, _state).compositionMetadata)) {
5298
+ __privateGet5(this, _mitt3).emit("canvasDataUpdated", __privateGet5(this, _state).compositionMetadata);
5299
+ __privateGet5(this, _state).compositionMetadata = newData.compositionMetadata;
5300
+ }
5301
+ await this.storage.updateData(commands);
5302
+ if (__privateGet5(this, _serverTransitionState)) {
5303
+ await this.processServerCommands({
5304
+ serverCommands: __privateGet5(this, _serverTransitionState).commands,
5305
+ commands
5306
+ });
5307
+ __privateMethod2(this, _Context_instances, updateComputedScores_fn).call(this, this.storage.data);
5308
+ Object.entries(newServerSideTests).forEach(([testName, testVariantId]) => {
5309
+ __privateMethod2(this, _Context_instances, emitTest_fn).call(this, {
5310
+ name: testName,
5311
+ variantId: testVariantId,
5312
+ variantAssigned: true,
5313
+ control: false,
5314
+ compositionMetadata: void 0
5315
+ });
5316
+ });
5317
+ const haveQuirksChanged = __privateGet5(this, _serverTransitionState) && !dequal(__privateGet5(this, _serverTransitionState).quirks, this.storage.data.quirks);
5318
+ __privateSet3(this, _serverTransitionState, void 0);
5319
+ if (haveQuirksChanged) {
5320
+ __privateGet5(this, _mitt3).emit("quirksUpdated", this.storage.data.quirks);
5321
+ }
5322
+ __privateGet5(this, _mitt3).emit("log", ["debug", 131]);
5323
+ }
5324
+ if (__privateGet5(this, _plugins)) {
5325
+ for (let i = 0; i < __privateGet5(this, _plugins).length; i++) {
5326
+ const plugin = __privateGet5(this, _plugins)[i];
5327
+ if (!plugin.update) {
5328
+ continue;
5329
+ }
5330
+ await plugin.update(newData, __privateGet5(this, _scores));
5331
+ }
5332
+ }
5333
+ (_e = __privateGet5(this, _commands)) == null ? void 0 : _e.push(...commands);
5334
+ } finally {
5335
+ __privateGet5(this, _mitt3).emit("log", ["info", 2, "ENDGROUP"]);
5336
+ }
5337
+ }
5338
+ async processServerCommands({
5339
+ serverCommands,
5340
+ commands
5341
+ }) {
5342
+ if (!(serverCommands == null ? void 0 : serverCommands.length)) {
5343
+ return;
5344
+ }
5345
+ const notExecutedCommands = [];
5346
+ serverCommands.forEach((serverCommand) => {
5347
+ const found = commands.find((command) => {
5348
+ return areCommandsEqual(command, serverCommand);
5349
+ });
5350
+ if (!found) {
5351
+ notExecutedCommands.push(serverCommand);
5352
+ }
5353
+ });
5354
+ if (notExecutedCommands.length > 0) {
5355
+ await this.storage.updateData(notExecutedCommands);
5356
+ }
5357
+ }
5358
+ /** use test() instead */
5359
+ getTestVariantId(testName) {
5360
+ var _a, _b, _c, _d;
5361
+ const definition = this.manifest.getTest(testName);
5362
+ if (!definition) {
5363
+ __privateGet5(this, _mitt3).emit("log", ["warn", 401, testName]);
5364
+ return null;
5365
+ }
5366
+ return (_d = (_c = definition.wv) != null ? _c : (_b = (_a = __privateGet5(this, _serverTransitionState)) == null ? void 0 : _a.tests) == null ? void 0 : _b[testName]) != null ? _d : this.storage.data.tests[testName];
5367
+ }
5368
+ /** use test() instead */
5369
+ setTestVariantId(testName, variantId) {
5370
+ this.storage.updateData([
5371
+ {
5372
+ type: "settest",
5373
+ data: {
5374
+ test: testName,
5375
+ variant: variantId
5376
+ }
5377
+ }
5378
+ ]);
5379
+ }
5380
+ getPersonalizeVariantControl(name, index) {
5381
+ var _a, _b, _c;
5382
+ const source = (_b = (_a = __privateGet5(this, _serverTransitionState)) == null ? void 0 : _a.personalizeVariants) != null ? _b : this.storage.data.personalizeVariants;
5383
+ const variants = (_c = source == null ? void 0 : source[name]) != null ? _c : [];
5384
+ const variant = variants.find((v) => v.index === index);
5385
+ return variant == null ? void 0 : variant.control;
5386
+ }
5387
+ /**
5388
+ * Writes a message to the Context log sink.
5389
+ * Used by Uniform internal SDK; not intended for public use.
5390
+ */
5391
+ log(...message) {
5392
+ __privateGet5(this, _mitt3).emit("log", message);
5393
+ }
5394
+ /** Executes an A/B test with a given set of variants, showing the visitor's assigned variant (or selecting one to assign, if none is set yet) */
5395
+ test(options) {
5396
+ var _a, _b, _c, _d, _e;
5397
+ if (options.name === CONTEXTUAL_EDITING_TEST_NAME) {
5398
+ const selectedVariant = (_a = options.variations.find((variant) => variant.id === CONTEXTUAL_EDITING_TEST_SELECTED_VARIANT_ID)) != null ? _a : options.variations.at(-1);
5399
+ const value2 = {
5400
+ result: selectedVariant,
5401
+ variantAssigned: false
5402
+ };
5403
+ return value2;
5404
+ }
5405
+ const value = testVariations({
5406
+ ...options,
5407
+ context: this,
5408
+ onLogMessage: (message) => __privateGet5(this, _mitt3).emit("log", message)
5409
+ });
5410
+ __privateMethod2(this, _Context_instances, emitTest_fn).call(this, {
5411
+ name: options.name,
5412
+ variantId: (_c = (_b = value.result) == null ? void 0 : _b.id) != null ? _c : void 0,
5413
+ variantAssigned: value.variantAssigned,
5414
+ control: (_e = (_d = value.result) == null ? void 0 : _d.control) != null ? _e : false,
5415
+ compositionMetadata: options.compositionMetadata
5416
+ });
5417
+ return value;
5418
+ }
5419
+ /** Executes a personalized placement with a given set of variants */
5420
+ personalize(options) {
5421
+ var _a;
5422
+ const algorithmName = (_a = options.algorithm) != null ? _a : TOP_DOWN_CRITERIA_PERSONALIZATION_ALGORITHM;
5423
+ const algorithm = __privateGet5(this, _personalizationSelectionAlgorithms)[algorithmName];
5424
+ if (!algorithm) {
5425
+ __privateGet5(this, _mitt3).emit("log", ["warn", 304, { algorithm: algorithmName }]);
5426
+ return {
5427
+ personalized: false,
5428
+ variations: []
5429
+ };
5430
+ }
5431
+ const value = algorithm({
5432
+ ...options,
5433
+ context: this,
5434
+ onLogMessage: (message) => __privateGet5(this, _mitt3).emit("log", message)
5435
+ });
5436
+ const previousPlacement = __privateGet5(this, _pzCache)[options.name];
5437
+ const eventData = {
5438
+ name: options.name,
5439
+ variantIds: value.variations.map((variation) => ({
5440
+ id: variation.id || "Unknown",
5441
+ control: variation.control
5442
+ })),
5443
+ control: this.storage.data.controlGroup,
5444
+ changed: true,
5445
+ compositionMetadata: options.compositionMetadata
5446
+ };
5447
+ if (previousPlacement && dequal(eventData.variantIds, previousPlacement)) {
5448
+ eventData.changed = false;
5449
+ }
5450
+ __privateGet5(this, _mitt3).emit("personalizationResult", eventData);
5451
+ __privateGet5(this, _pzCache)[options.name] = eventData.variantIds;
5452
+ return value;
5453
+ }
5454
+ /**
5455
+ * Forgets the visitor's data and resets the Context to its initial state.
5456
+ * @param fromAllDevices - for an identified user, whether to delete all their data (for the entire account) - true, or data for this device (sign out) - false
5457
+ */
5458
+ async forget(fromAllDevices) {
5459
+ const previousCompositionMetadata = __privateGet5(this, _state).compositionMetadata;
5460
+ __privateSet3(this, _state, {
5461
+ compositionMetadata: previousCompositionMetadata
5462
+ });
5463
+ if (__privateGet5(this, _plugins)) {
5464
+ for (let i = 0; i < __privateGet5(this, _plugins).length; i++) {
5465
+ const plugin = __privateGet5(this, _plugins)[i];
5466
+ if (!plugin.forget) {
5467
+ continue;
5468
+ }
5469
+ await plugin.forget();
5470
+ }
5471
+ }
5472
+ await this.storage.delete(fromAllDevices);
5473
+ }
5474
+ /**
5475
+ * Computes server to client transition state.
5476
+ *
5477
+ * Removes state from server-to-client if it came in initial state (cookies) to avoid double tracking on the client.
5478
+ */
5479
+ getServerToClientTransitionState() {
5480
+ const transitionState = {
5481
+ quirks: this.storage.data.quirks,
5482
+ ssv: __privateGet5(this, _scores),
5483
+ tests: {},
5484
+ personalizeVariants: this.storage.data.personalizeVariants,
5485
+ commands: __privateGet5(this, _commands),
5486
+ compositionMetadata: __privateGet5(this, _state).compositionMetadata
5487
+ };
5488
+ const allTests = this.storage.data.tests;
5489
+ Object.entries(allTests).map(([testName, testValue]) => {
5490
+ var _a, _b, _c;
5491
+ if (((_c = (_b = (_a = this.storage.options.transitionStore) == null ? void 0 : _a.initialData) == null ? void 0 : _b.tests) == null ? void 0 : _c[testName]) !== allTests[testName] && transitionState.tests) {
5492
+ transitionState.tests[testName] = testValue;
5493
+ }
5494
+ });
5495
+ return transitionState;
5496
+ }
5497
+ /** @deprecated Internal API for test event processing; not for public use. */
5498
+ internal_processTestEvent(event) {
5499
+ if (event.variantId) {
5500
+ this.setTestVariantId(event.name, event.variantId);
5501
+ __privateMethod2(this, _Context_instances, emitTest_fn).call(this, event);
5502
+ }
5503
+ }
5504
+ /** @deprecated Internal API for personalization event processing; not for public use. */
5505
+ internal_processPersonalizationEvent(event) {
5506
+ __privateGet5(this, _pzCache)[event.name] = event.variantIds;
5507
+ __privateGet5(this, _mitt3).emit("personalizationResult", event);
5508
+ }
5509
+ /**
5510
+ * Gets the current canvas data
5511
+ */
5512
+ getCompositionMetadata() {
5513
+ return __privateGet5(this, _state).compositionMetadata;
5514
+ }
5515
+ /**
5516
+ * Updates the canvas data and emits a canvasDataUpdated event
5517
+ */
5518
+ async updateCompositionMetadata(newData) {
5519
+ const currentCanvas = __privateGet5(this, _state).compositionMetadata || {};
5520
+ const updatedCanvas = { ...currentCanvas, ...newData };
5521
+ if (!dequal(currentCanvas, updatedCanvas)) {
5522
+ __privateSet3(this, _state, {
5523
+ ...__privateGet5(this, _state),
5524
+ compositionMetadata: updatedCanvas
5525
+ });
5526
+ __privateGet5(this, _mitt3).emit("canvasDataUpdated", updatedCanvas);
5527
+ __privateGet5(this, _mitt3).emit("log", ["info", 4, "Canvas data updated"]);
5528
+ }
5529
+ }
5530
+ };
5531
+ _personalizationSelectionAlgorithms = /* @__PURE__ */ new WeakMap();
5532
+ _serverTransitionState = /* @__PURE__ */ new WeakMap();
5533
+ _scores = /* @__PURE__ */ new WeakMap();
5534
+ _state = /* @__PURE__ */ new WeakMap();
5535
+ _pzCache = /* @__PURE__ */ new WeakMap();
5536
+ _plugins = /* @__PURE__ */ new WeakMap();
5537
+ _commands = /* @__PURE__ */ new WeakMap();
5538
+ _requireConsentForPersonalization = /* @__PURE__ */ new WeakMap();
5539
+ _mitt3 = /* @__PURE__ */ new WeakMap();
5540
+ _Context_instances = /* @__PURE__ */ new WeakSet();
5541
+ emitTest_fn = function(event) {
5542
+ __privateGet5(this, _mitt3).emit("testResult", event);
5543
+ };
5544
+ updateGoals_fn = async function(data) {
5545
+ const goalCommands = this.manifest.computeGoals(data);
5546
+ if (goalCommands.length !== 0) {
5547
+ await this.storage.updateData(goalCommands);
5548
+ }
5549
+ };
5550
+ updateComputedScores_fn = function(newData) {
5551
+ const newScores = __privateMethod2(this, _Context_instances, calculateScores_fn).call(this, newData);
5552
+ const newScoresHaveChanged = !dequal(newScores, __privateGet5(this, _scores));
5553
+ if (newScoresHaveChanged) {
5554
+ __privateSet3(this, _scores, newScores);
5555
+ __privateMethod2(this, _Context_instances, updateGoals_fn).call(this, {
5556
+ scores: __privateGet5(this, _scores),
5557
+ quirks: void 0
5558
+ });
5559
+ __privateGet5(this, _mitt3).emit("scoresUpdated", newScores);
5560
+ __privateGet5(this, _mitt3).emit("log", ["info", 3, newScores]);
5561
+ }
5562
+ };
5563
+ calculateScores_fn = function(newData) {
5564
+ var _a;
5565
+ let newScores = { ...newData.scores };
5566
+ for (const session in newData.sessionScores) {
5567
+ newScores[session] = ((_a = newScores[session]) != null ? _a : 0) + newData.sessionScores[session];
5568
+ }
5569
+ newScores = this.manifest.computeAggregateDimensions(newScores);
5570
+ return newScores;
5571
+ };
5572
+ var dc = (0, import_rfdc2.default)();
5573
+ var dc2 = (0, import_rfdc3.default)();
5574
+
5575
+ // src/config/helpers.ts
5576
+ var import_resolved = __toESM(require("@uniformdev/next-app-router/config/resolved"));
5577
+ var getDisabledDevTools = () => {
5578
+ var _a;
5579
+ if (typeof ((_a = import_resolved.default.context) == null ? void 0 : _a.disableDevTools) === "boolean") {
5580
+ return import_resolved.default.context.disableDevTools;
5581
+ }
5582
+ return false;
5583
+ };
5584
+ var getDefaultConsent = () => {
5585
+ if (typeof import_resolved.default.defaultConsent === "boolean") {
5586
+ return import_resolved.default.defaultConsent;
5587
+ }
5588
+ return false;
5589
+ };
5590
+ var getQuirkSerialization = () => {
5591
+ if (typeof import_resolved.default.quirkSerialization === "boolean") {
5592
+ return import_resolved.default.quirkSerialization;
5593
+ }
5594
+ return true;
5595
+ };
5596
+ var getMiddlewareRuntimeCache = () => {
5597
+ if (process.env.NODE_ENV === "development" && !process.env.RUNTIME_CACHE_ENDPOINT) {
5598
+ return false;
5599
+ }
5600
+ if (typeof import_resolved.default.middlewareRuntimeCache === "boolean") {
5601
+ return import_resolved.default.middlewareRuntimeCache;
5602
+ }
5603
+ return true;
5604
+ };
5605
+ var getDisableSwrMiddlewareCache = () => {
5606
+ var _a;
5607
+ if (typeof ((_a = import_resolved.default.experimental) == null ? void 0 : _a.disableSwrMiddlewareCache) === "boolean") {
5608
+ return import_resolved.default.experimental.disableSwrMiddlewareCache;
5609
+ }
5610
+ return false;
5611
+ };
5612
+
5613
+ // src/middleware/context/index.ts
5614
+ var createOnDemandContext = async (options) => {
5615
+ var _a;
5616
+ const manifest = await options.dataClient.getManifest({ source: (_a = options.source) != null ? _a : "middleware" });
5617
+ if (!manifest) {
5618
+ console.error("Uniform manifest not found, falling back to empty manifest");
5619
+ }
5620
+ return new OnDemandContext({
5621
+ ...options,
5622
+ manifest: manifest != null ? manifest : { project: {} },
5623
+ defaultConsent: options.defaultConsent
5624
+ });
5625
+ };
5626
+ var _options2;
5627
+ var OnDemandContext = class {
5628
+ constructor(options) {
5629
+ __privateAdd(this, _options2);
5630
+ __privateSet(this, _options2, options);
5631
+ }
5632
+ async getContext() {
5633
+ var _a, _b, _c;
5634
+ if (!this._context) {
5635
+ const uniformCookie = __privateGet(this, _options2).cookies.get(UNIFORM_DEFAULT_COOKIE_NAME);
5636
+ const quirkCookie = __privateGet(this, _options2).cookies.get(UNIFORM_DEFAULT_QUIRK_COOKIE_NAME);
5637
+ this._context = new Context({
5638
+ manifest: __privateGet(this, _options2).manifest,
5639
+ defaultConsent: (_a = __privateGet(this, _options2).defaultConsent) != null ? _a : getDefaultConsent(),
5640
+ transitionStore: new CookieTransitionDataStore({
5641
+ serverCookieValue: (_b = uniformCookie == null ? void 0 : uniformCookie.value) != null ? _b : "",
5642
+ experimental_quirksEnabled: getQuirkSerialization(),
5643
+ quirkCookieValue: (_c = quirkCookie == null ? void 0 : quirkCookie.value) != null ? _c : ""
5644
+ })
5645
+ });
5646
+ }
5647
+ return this._context;
5648
+ }
5649
+ };
5650
+ _options2 = new WeakMap();
5651
+
5652
+ // src/utils/quirks.ts
5653
+ var buildQuirksFromHeaders = (headers2) => {
5654
+ const headerToQuirkKey = {
5655
+ "x-vercel-ip-country": "vc-country",
5656
+ "x-vercel-ip-country-region": "vc-region",
5657
+ "x-vercel-ip-city": "vc-city"
5658
+ };
5659
+ return Object.entries(headerToQuirkKey).reduce((acc, [headerName, quirkKey]) => {
5660
+ const value = headers2.get(headerName);
5661
+ if (value) {
5662
+ acc[quirkKey] = value;
5663
+ }
5664
+ return acc;
5665
+ }, {});
5666
+ };
5667
+
5668
+ // src/data/client.ts
5669
+ var import_functions = require("@vercel/functions");
5670
+ var MANIFEST_CACHE_KEY = "uniform-manifest";
5671
+ var DefaultDataClient = class {
5672
+ async getManifest(options) {
5673
+ const cache2 = options.source === "middleware" && getMiddlewareRuntimeCache() ? (0, import_functions.getCache)() : null;
5674
+ if (cache2) {
5675
+ const cachedManifest = await cache2.get(MANIFEST_CACHE_KEY);
5676
+ if (cachedManifest) {
5677
+ return cachedManifest;
5678
+ }
5679
+ }
5680
+ const manifest = await getManifest({
5681
+ cache: isDevelopmentEnvironment() ? {
5682
+ type: "no-cache",
5683
+ bypassCache: true
5684
+ } : {
5685
+ type: "force-cache"
5686
+ }
5687
+ });
5688
+ if (cache2) {
5689
+ (0, import_functions.waitUntil)(
5690
+ (async () => {
5691
+ await cache2.set(MANIFEST_CACHE_KEY, manifest, {
5692
+ tags: generateManifestCacheTags()
5693
+ });
5694
+ })()
5695
+ );
5696
+ }
5697
+ return manifest;
5698
+ }
5699
+ async getRouteFromApi({
5700
+ route,
5701
+ routeClient,
5702
+ enableRuntimeCache,
5703
+ disableSwrCache
5704
+ }) {
5705
+ const newCacheKey = `uniform-route-${route.state}-${route.releaseId}-${route.path}`;
5706
+ const oldCacheKey = `uniform-route-old-${route.state}-${route.releaseId}-${route.path}`;
5707
+ const cache2 = enableRuntimeCache ? (0, import_functions.getCache)() : null;
5708
+ const cacheNewRoute = async (result2) => {
5709
+ if (cache2 && result2.type === "composition") {
5710
+ const tags = generateRouteCacheTags({ path: route.path });
5711
+ await cache2.set(newCacheKey, result2, {
5712
+ tags
5713
+ });
5714
+ }
5715
+ };
5716
+ const cacheOldRoute = async (result2) => {
5717
+ if (cache2 && result2.type === "composition" && !disableSwrCache) {
5718
+ const tags = generateRouteCacheTags({ path: route.path, old: true });
5719
+ await cache2.set(oldCacheKey, result2, {
5720
+ tags
5721
+ });
5722
+ }
5723
+ };
5724
+ if (cache2) {
5725
+ const [cachedRoute, oldCachedRoute] = await Promise.all([
5726
+ cache2.get(newCacheKey),
5727
+ disableSwrCache ? null : cache2.get(oldCacheKey)
5728
+ ]);
5729
+ if (cachedRoute) {
5730
+ return cachedRoute;
5731
+ }
5732
+ if (oldCachedRoute) {
5733
+ (0, import_functions.waitUntil)(
5734
+ (async () => {
5735
+ const result2 = await routeClient.get(route);
5736
+ await cacheNewRoute(result2);
5737
+ })()
5738
+ );
5739
+ return oldCachedRoute;
5740
+ }
5741
+ }
5742
+ const result = await routeClient.get(route);
5743
+ (0, import_functions.waitUntil)(
5744
+ (async () => {
5745
+ await Promise.all([
5746
+ cacheNewRoute(result),
5747
+ disableSwrCache ? Promise.resolve() : cacheOldRoute(result)
5748
+ ]);
5749
+ })()
5750
+ );
5751
+ return result;
5752
+ }
5753
+ async getRoute(options) {
5754
+ if (options.source === "middleware") {
5755
+ return this.getRouteMiddleware(options);
5756
+ }
5757
+ return this.getRoutePageState(options);
5758
+ }
5759
+ async enhanceRoute(_options3) {
5760
+ }
5761
+ async getRouteMiddleware(options) {
5762
+ const routeClient = getRouteClient({
5763
+ searchParams: options.searchParams,
5764
+ draftModeEnabled: options.draftModeEnabled
5765
+ });
5766
+ const resolvedRoute = await this.getRouteFromApi({
5767
+ source: "middleware",
5768
+ route: options.route,
5769
+ routeClient,
5770
+ // The runtime cache is keyed on the route path. Development bypasses it so an author sees
5771
+ // an edit right away, the same way the fetch cache is bypassed for development.
5772
+ enableRuntimeCache: options.route.state === CANVAS_PUBLISHED_STATE && getMiddlewareRuntimeCache() && !isDevelopmentEnvironment(),
5773
+ disableSwrCache: getDisableSwrMiddlewareCache()
5774
+ });
5775
+ if (resolvedRoute.type === "composition") {
5776
+ await this.enhanceRoute({
5777
+ source: "middleware",
5778
+ parameters: options.route,
5779
+ route: resolvedRoute,
5780
+ routeClient,
5781
+ keys: void 0
5782
+ });
5783
+ }
5784
+ return {
5785
+ route: resolvedRoute
5786
+ };
5787
+ }
5788
+ async getRoutePageState(options) {
5789
+ const shouldBypassCache = options.pageState.compositionState !== CANVAS_PUBLISHED_STATE || isDevelopmentEnvironment();
5790
+ const routeClient = getRouteClient({
5791
+ cache: shouldBypassCache ? {
5792
+ type: "no-cache",
5793
+ bypassCache: true
5794
+ } : {
5795
+ type: "force-cache"
5796
+ }
5797
+ });
5798
+ const originalRoute = {
5799
+ path: options.pageState.routePath,
5800
+ state: options.pageState.compositionState,
5801
+ dataSourceVariant: getDataSourceVariantFromRouteGetParams({}, options.pageState.compositionState),
5802
+ withComponentIDs: true,
5803
+ releaseId: options.pageState.releaseId,
5804
+ locale: options.pageState.locale,
5805
+ ignoreRedirects: shouldIgnoreRedirects({ state: options.pageState.compositionState })
5806
+ };
5807
+ const resolvedRoute = await this.getRouteFromApi({
5808
+ source: "pageState",
5809
+ route: originalRoute,
5810
+ routeClient,
5811
+ enableRuntimeCache: false,
5812
+ disableSwrCache: false
5813
+ });
5814
+ if (resolvedRoute.type === "composition") {
5815
+ await this.enhanceRoute({
5816
+ source: "pageState",
5817
+ parameters: originalRoute,
5818
+ route: resolvedRoute,
5819
+ routeClient,
5820
+ keys: options.pageState.keys
5821
+ });
5822
+ }
5823
+ return {
5824
+ route: resolvedRoute
5825
+ };
5826
+ }
5827
+ };
5828
+ var expireMiddlewareCacheTag = async (tag) => {
5829
+ const cache2 = getMiddlewareRuntimeCache() ? (0, import_functions.getCache)() : null;
5830
+ if (cache2) {
5831
+ await cache2.expireTag(tag);
5832
+ } else {
5833
+ console.warn("Middleware cache is not enabled, cannot clear cache tag", tag);
5834
+ }
5835
+ };
5836
+
5837
+ // src/middleware/composition/evaluate/evaluateRunnables.ts
5838
+ var import_next_app_router_shared = require("@uniformdev/next-app-router-shared");
5839
+ var evaluateRunnables = async ({
5840
+ runnables,
5841
+ context,
5842
+ compositionContext,
5843
+ isPrefetch
5844
+ }) => {
5845
+ var _a;
5846
+ const result = {
5847
+ components: {},
5848
+ rules: void 0
5849
+ };
5850
+ const runnablesToProcess = runnables.filter((item2) => item2.variantId === void 0);
5851
+ let item;
5852
+ while (item = runnablesToProcess.shift()) {
5853
+ if (item.type === "test" && isPrefetch) {
5854
+ continue;
5855
+ }
5856
+ if (item.type === "test") {
5857
+ const testResult = (0, import_next_app_router_shared.evaluateTest)({
5858
+ context,
5859
+ test: item.result,
5860
+ compositionContext
5861
+ });
5862
+ if (testResult.index !== null) {
5863
+ result.components[item._id] = {
5864
+ indexes: [testResult.index]
5865
+ };
5866
+ if (testResult.componentId) {
5867
+ const dependentRunnables = runnables.filter((r) => r.variantId === testResult.componentId);
5868
+ runnablesToProcess.push(...dependentRunnables);
5869
+ }
5870
+ }
5871
+ } else if (item.type === "personalization") {
5872
+ const personalizationResult = (0, import_next_app_router_shared.evaluatePersonalization)({
5873
+ context,
5874
+ personalization: item.result,
5875
+ compositionContext
5876
+ });
5877
+ if (personalizationResult.indexes.length) {
5878
+ result.components[item._id] = {
5879
+ indexes: personalizationResult.indexes
5880
+ };
5881
+ }
5882
+ if (personalizationResult.componentIds.length) {
5883
+ const dependentRunnables = runnables.filter(
5884
+ (r) => r.variantId && personalizationResult.componentIds.includes(r.variantId)
5885
+ );
5886
+ runnablesToProcess.push(...dependentRunnables);
5887
+ }
5888
+ } else if (item.type === "visibility") {
5889
+ const rules = createQuirksVisibilityRule(context.quirks);
5890
+ const isVisible = evaluateNodeVisibilityParameter({
5891
+ rules,
5892
+ parameter: item.rules
5893
+ });
5894
+ if (isVisible !== null) {
5895
+ result.rules = (_a = result.rules) != null ? _a : {};
5896
+ result.rules[item._id] = isVisible;
5897
+ }
5898
+ }
5899
+ }
5900
+ return result;
5901
+ };
5902
+
5903
+ // src/data/extract/extractRunnables.ts
5904
+ var import_next_app_router_shared4 = require("@uniformdev/next-app-router-shared");
5905
+
5906
+ // src/data/extract/extractPersonalization.ts
5907
+ var import_next_app_router_shared2 = require("@uniformdev/next-app-router-shared");
5908
+ var extractPersonalization = ({
5909
+ component
5910
+ }) => {
5911
+ var _a, _b, _c;
5912
+ const trackingEventName = (0, import_next_app_router_shared2.extractPersonalizationName)({ component });
5913
+ const countParameter = (_a = component.parameters) == null ? void 0 : _a.count;
5914
+ const algorithmParameter = (_b = component.parameters) == null ? void 0 : _b.algorithm;
5915
+ const count = countParameter == null ? void 0 : countParameter.value;
5916
+ const algorithm = algorithmParameter == null ? void 0 : algorithmParameter.value;
5917
+ let parsedCount;
5918
+ if (typeof count === "string") {
5919
+ parsedCount = parseInt(count, 10);
5920
+ } else if (typeof count !== "number") {
5921
+ parsedCount = void 0;
5922
+ } else {
5923
+ parsedCount = count || 1;
5924
+ }
5925
+ const slot = ((_c = component.slots) == null ? void 0 : _c[CANVAS_PERSONALIZE_SLOT]) || [];
5926
+ const componentVariations = mapSlotToPersonalizedVariations(
5927
+ slot
5928
+ ).map((variant, index) => {
5929
+ const slotComponent = slot[index];
5930
+ if (!slotComponent) {
5931
+ throw new Error(`Slot component not found for index ${index}`);
5932
+ }
5933
+ return {
5934
+ ...variant,
5935
+ index,
5936
+ componentId: slotComponent._id
5937
+ };
5938
+ });
5939
+ return {
5940
+ name: trackingEventName,
5941
+ take: parsedCount,
5942
+ variations: componentVariations,
5943
+ algorithm
5944
+ };
5945
+ };
5946
+
5947
+ // src/data/extract/extractTest.ts
5948
+ var import_next_app_router_shared3 = require("@uniformdev/next-app-router-shared");
5949
+ var extractTest = ({ component }) => {
5950
+ var _a;
5951
+ const testName = (0, import_next_app_router_shared3.extractTestName)({ component });
5952
+ const slot = ((_a = component.slots) == null ? void 0 : _a[CANVAS_TEST_SLOT]) || [];
5953
+ const componentVariations = mapSlotToTestVariations(slot).map((variation, index) => {
5954
+ const slotComponent = slot[index];
5955
+ if (!slotComponent) {
5956
+ throw new Error(`Slot component not found for index ${index}`);
5957
+ }
5958
+ return {
5959
+ ...variation,
5960
+ index,
5961
+ componentId: slotComponent._id
5962
+ };
5963
+ });
5964
+ return {
5965
+ name: testName,
5966
+ variations: componentVariations
5967
+ };
5968
+ };
5969
+
5970
+ // src/data/extract/extractRunnables.ts
5971
+ var findAncestorVariant = (ancestorsAndSelf) => {
5972
+ for (let i = 0; i < ancestorsAndSelf.length; i++) {
5973
+ const node = ancestorsAndSelf[i];
5974
+ if (node.type === "slot" && (node.parentSlot === CANVAS_PERSONALIZE_SLOT || node.parentSlot === CANVAS_TEST_SLOT)) {
5975
+ return node.node._id;
5976
+ }
5977
+ }
5978
+ return void 0;
5979
+ };
5980
+ var extractRunnables = (composition) => {
5981
+ const runnable = [];
5982
+ walkNodeTree(composition, (node) => {
5983
+ var _a, _b;
5984
+ if (node.type === "component") {
5985
+ const component = node.node;
5986
+ const visibilityRules = (_b = (_a = component.parameters) == null ? void 0 : _a[CANVAS_VIZ_CONTROL_PARAM]) == null ? void 0 : _b.value;
5987
+ if (component.type === CANVAS_TEST_TYPE) {
5988
+ const test = extractTest({ component });
5989
+ runnable.push({
5990
+ _id: component._id,
5991
+ variantId: findAncestorVariant(node.ancestorsAndSelf),
5992
+ type: "test",
5993
+ result: test
5994
+ });
5995
+ } else if (component.type === CANVAS_PERSONALIZE_TYPE) {
5996
+ const personalize = extractPersonalization({ component });
5997
+ runnable.push({
5998
+ type: "personalization",
5999
+ variantId: findAncestorVariant(node.ancestorsAndSelf),
6000
+ _id: component._id,
6001
+ result: personalize
6002
+ });
6003
+ }
6004
+ if (visibilityRules) {
6005
+ runnable.push({
6006
+ type: "visibility",
6007
+ _id: (0, import_next_app_router_shared4.getRuleId)(visibilityRules),
6008
+ variantId: findAncestorVariant(node.ancestorsAndSelf),
6009
+ rules: visibilityRules
6010
+ });
6011
+ }
6012
+ }
6013
+ });
6014
+ return runnable;
6015
+ };
6016
+
6017
+ // src/data/evaluate/evaluatePageState.ts
6018
+ var evaluatePageState = async ({
6019
+ composition,
6020
+ matchedRoute,
6021
+ dynamicInputs,
6022
+ pageState,
6023
+ context
6024
+ }) => {
6025
+ const extracted = extractRunnables(composition);
6026
+ const result = await evaluateRunnables({
6027
+ runnables: extracted,
6028
+ context,
6029
+ isPrefetch: pageState.isPrefetch,
6030
+ compositionContext: {
6031
+ _id: composition._id,
6032
+ type: composition.type,
6033
+ state: pageState.compositionState,
6034
+ isContextualEditing: pageState.compositionState === CANVAS_EDITOR_STATE,
6035
+ matchedRoute,
6036
+ dynamicInputs,
6037
+ pageState: {
6038
+ ...pageState,
6039
+ // empty for now, we need to pass composition metadata down to evaluateRunnables for Context events enrichment
6040
+ components: {},
6041
+ rules: void 0
6042
+ }
6043
+ }
6044
+ });
6045
+ const allComponentIds = extracted.filter((r) => r.type === "test" || r.type === "personalization").map((r) => r._id);
6046
+ return {
6047
+ ...result,
6048
+ allComponentIds
6049
+ };
6050
+ };
6051
+
6052
+ // src/data/evaluate/evaluateDraftPageState.ts
6053
+ var REQUEST_ORIGIN_PLACEHOLDER = "http://uniform.local";
6054
+ var evaluateDraftPageState = async ({
6055
+ pageState,
6056
+ composition,
6057
+ matchedRoute,
6058
+ dynamicInputs,
6059
+ dataClient
6060
+ }) => {
6061
+ var _a;
6062
+ const isPublished = pageState.compositionState === CANVAS_PUBLISHED_STATE;
6063
+ const isAlreadyEvaluated = Object.keys(pageState.components).length > 0 || Boolean(pageState.rules);
6064
+ if (isPublished || isAlreadyEvaluated) {
6065
+ return pageState;
6066
+ }
6067
+ const [requestCookies, requestHeaders] = await Promise.all([(0, import_headers.cookies)(), (0, import_headers.headers)()]);
6068
+ const onDemandContext = await createOnDemandContext({
6069
+ source: "pageState",
6070
+ cookies: requestCookies,
6071
+ dataClient: dataClient != null ? dataClient : new DefaultDataClient(),
6072
+ defaultConsent: pageState.defaultConsent
6073
+ });
6074
+ const context = await onDemandContext.getContext();
6075
+ await context.update({
6076
+ url: new URL((_a = pageState.requestPath) != null ? _a : pageState.routePath, REQUEST_ORIGIN_PLACEHOLDER),
6077
+ cookies: requestCookies.getAll().reduce(
6078
+ (acc, cookie) => {
6079
+ acc[cookie.name] = cookie.value;
6080
+ return acc;
6081
+ },
6082
+ {}
6083
+ ),
6084
+ // Same precedence as the middleware: header-derived quirks first, then the custom quirks
6085
+ // the consumer passed to `handleUniformRoute`, which win on conflict.
6086
+ quirks: {
6087
+ ...buildQuirksFromHeaders(requestHeaders),
6088
+ ...pageState.quirks
6089
+ }
6090
+ });
6091
+ const { components, rules } = await evaluatePageState({
6092
+ composition,
6093
+ matchedRoute,
6094
+ dynamicInputs,
6095
+ pageState,
6096
+ context
6097
+ });
6098
+ return {
6099
+ ...pageState,
6100
+ components,
6101
+ rules
6102
+ };
6103
+ };
6104
+
6105
+ // src/components/ComponentProps.ts
6106
+ var import_next_app_router_shared5 = require("@uniformdev/next-app-router-shared");
6107
+ var createComponentProps = ({
6108
+ component,
6109
+ parent,
6110
+ isRoot,
6111
+ slotName,
6112
+ slotIndex,
6113
+ slots,
6114
+ pageState,
6115
+ composition,
6116
+ compositionContext
6117
+ }) => {
6118
+ var _a, _b;
6119
+ const parameters = (_a = component.parameters) != null ? _a : {};
6120
+ const componentProps = {
6121
+ parameters: Object.keys(parameters).reduce((acc, cur) => {
6122
+ acc[cur] = {
6123
+ parameterId: cur,
6124
+ ...parameters[cur]
6125
+ };
6126
+ return acc;
6127
+ }, {}),
6128
+ component: {
6129
+ _id: component._id,
6130
+ _parentId: (_b = parent == null ? void 0 : parent._id) != null ? _b : null,
6131
+ slotName,
6132
+ slotIndex: isRoot ? void 0 : slotIndex
6133
+ },
6134
+ type: component.type,
6135
+ variant: component.variant,
6136
+ slots,
6137
+ context: {
6138
+ isContextualEditing: pageState.compositionState === CANVAS_EDITOR_STATE,
6139
+ _id: composition._id,
6140
+ state: pageState.compositionState,
6141
+ type: composition.type,
6142
+ pageState,
6143
+ matchedRoute: compositionContext.matchedRoute,
6144
+ dynamicInputs: compositionContext.dynamicInputs
6145
+ }
6146
+ };
6147
+ return componentProps;
6148
+ };
6149
+ var createPersonalizeComponentProps = ({
6150
+ common,
6151
+ componentId,
6152
+ pageState
6153
+ }) => {
6154
+ var _a;
6155
+ const component = (0, import_next_app_router_shared5.resolveComponentFromPageState)({
6156
+ pageState,
6157
+ componentId
6158
+ });
6159
+ return {
6160
+ ...common,
6161
+ indexes: (_a = component == null ? void 0 : component.indexes) != null ? _a : []
6162
+ };
6163
+ };
6164
+ var createTestComponentProps = ({
6165
+ common,
6166
+ componentId,
6167
+ pageState,
6168
+ test
6169
+ }) => {
6170
+ var _a;
6171
+ if (pageState.isPrefetch) {
6172
+ return {
6173
+ ...common,
6174
+ index: void 0,
6175
+ test
6176
+ };
6177
+ }
6178
+ const component = (0, import_next_app_router_shared5.resolveComponentFromPageState)({
6179
+ pageState,
6180
+ componentId
6181
+ });
6182
+ const [testIndex] = (_a = component == null ? void 0 : component.indexes) != null ? _a : [];
6183
+ return {
6184
+ ...common,
6185
+ index: testIndex,
6186
+ test
3134
6187
  };
3135
6188
  };
3136
6189
 
@@ -3199,61 +6252,9 @@ var Test = ({ index, slots, test, component, context: compositionContext }) => {
3199
6252
  return (0, import_react2.createElement)(import_react2.Fragment, void 0, [indexToShow == null ? void 0 : indexToShow.component, eventElement]);
3200
6253
  };
3201
6254
 
3202
- // src/components/UniformCompositionWrapper.tsx
3203
- var import_next_app_router_shared3 = require("@uniformdev/next-app-router-shared");
3204
- var import_react3 = __toESM(require("react"));
3205
- var UniformCompositionWrapper = ({
3206
- code,
3207
- children
3208
- }) => {
3209
- const data = (0, import_next_app_router_shared3.deserializeEvaluationResult)({ input: code });
3210
- const WrapperComponent = data.compositionState === CANVAS_EDITOR_STATE || data.compositionState === CANVAS_DRAFT_STATE ? import_react3.Suspense : import_react3.Fragment;
3211
- return /* @__PURE__ */ import_react3.default.createElement(WrapperComponent, null, children);
3212
- };
3213
-
3214
6255
  // src/components/UniformContext.tsx
3215
6256
  var import_next_app_router_client3 = require("@uniformdev/next-app-router-client");
3216
- var import_react4 = __toESM(require("react"));
3217
-
3218
- // src/config/helpers.ts
3219
- var import_resolved = __toESM(require("@uniformdev/next-app-router/config/resolved"));
3220
- var getDisabledDevTools = () => {
3221
- var _a;
3222
- if (typeof ((_a = import_resolved.default.context) == null ? void 0 : _a.disableDevTools) === "boolean") {
3223
- return import_resolved.default.context.disableDevTools;
3224
- }
3225
- return false;
3226
- };
3227
- var getDefaultConsent = () => {
3228
- if (typeof import_resolved.default.defaultConsent === "boolean") {
3229
- return import_resolved.default.defaultConsent;
3230
- }
3231
- return false;
3232
- };
3233
- var getQuirkSerialization = () => {
3234
- if (typeof import_resolved.default.quirkSerialization === "boolean") {
3235
- return import_resolved.default.quirkSerialization;
3236
- }
3237
- return true;
3238
- };
3239
- var getMiddlewareRuntimeCache = () => {
3240
- if (process.env.NODE_ENV === "development" && !process.env.RUNTIME_CACHE_ENDPOINT) {
3241
- return false;
3242
- }
3243
- if (typeof import_resolved.default.middlewareRuntimeCache === "boolean") {
3244
- return import_resolved.default.middlewareRuntimeCache;
3245
- }
3246
- return true;
3247
- };
3248
- var getDisableSwrMiddlewareCache = () => {
3249
- var _a;
3250
- if (typeof ((_a = import_resolved.default.experimental) == null ? void 0 : _a.disableSwrMiddlewareCache) === "boolean") {
3251
- return import_resolved.default.experimental.disableSwrMiddlewareCache;
3252
- }
3253
- return false;
3254
- };
3255
-
3256
- // src/components/UniformContext.tsx
6257
+ var import_react3 = __toESM(require("react"));
3257
6258
  var UniformContext = async ({ clientContextComponent, result }) => {
3258
6259
  var _a;
3259
6260
  const manifest = await getManifest({
@@ -3269,7 +6270,7 @@ var UniformContext = async ({ clientContextComponent, result }) => {
3269
6270
  const disableDevTools = getDisabledDevTools();
3270
6271
  const defaultConsent = (_a = result == null ? void 0 : result.pageState.defaultConsent) != null ? _a : getDefaultConsent();
3271
6272
  const experimentalQuirkSerialization = getQuirkSerialization();
3272
- return /* @__PURE__ */ import_react4.default.createElement(import_react4.default.Fragment, null, /* @__PURE__ */ import_react4.default.createElement(
6273
+ return /* @__PURE__ */ import_react3.default.createElement(import_react3.default.Fragment, null, /* @__PURE__ */ import_react3.default.createElement(
3273
6274
  ContextComponent,
3274
6275
  {
3275
6276
  manifest,
@@ -3283,18 +6284,18 @@ var UniformContext = async ({ clientContextComponent, result }) => {
3283
6284
 
3284
6285
  // src/components/VisibilityRulesWrapper.tsx
3285
6286
  var import_next_app_router_client4 = require("@uniformdev/next-app-router-client");
3286
- var import_react5 = __toESM(require("react"));
6287
+ var import_react4 = __toESM(require("react"));
3287
6288
  var VisibilityRulesWrapper = ({
3288
6289
  parameter,
3289
6290
  initialIsVisible,
3290
6291
  children
3291
6292
  }) => {
3292
- return /* @__PURE__ */ import_react5.default.createElement(import_next_app_router_client4.VisibilityRulesWrapperClient, { parameter, initialIsVisible }, children);
6293
+ return /* @__PURE__ */ import_react4.default.createElement(import_next_app_router_client4.VisibilityRulesWrapperClient, { parameter, initialIsVisible }, children);
3293
6294
  };
3294
6295
 
3295
6296
  // src/components/UniformComposition.tsx
3296
6297
  function UniformComposition({ code, ...props }) {
3297
- return /* @__PURE__ */ import_react6.default.createElement(UniformCompositionWrapper, { code }, /* @__PURE__ */ import_react6.default.createElement(UniformCompositionInner, { code, ...props }));
6298
+ return /* @__PURE__ */ import_react5.default.createElement(UniformCompositionInner, { code, ...props });
3298
6299
  }
3299
6300
  async function UniformCompositionInner({
3300
6301
  code,
@@ -3305,7 +6306,7 @@ async function UniformCompositionInner({
3305
6306
  clientContextComponent,
3306
6307
  dataClient
3307
6308
  }) {
3308
- var _a, _b;
6309
+ var _a, _b, _c;
3309
6310
  const result = await resolveRoute({
3310
6311
  code,
3311
6312
  dataClient
@@ -3313,8 +6314,15 @@ async function UniformCompositionInner({
3313
6314
  if (!(result == null ? void 0 : result.route) || ((_a = result == null ? void 0 : result.route) == null ? void 0 : _a.type) !== "composition") {
3314
6315
  (0, import_navigation.notFound)();
3315
6316
  }
3316
- const { pageState, route } = result;
6317
+ const { route } = result;
3317
6318
  const composition = result.route.compositionApiResponse.composition;
6319
+ const pageState = await evaluateDraftPageState({
6320
+ pageState: result.pageState,
6321
+ composition,
6322
+ matchedRoute: route.matchedRoute,
6323
+ dynamicInputs: (_b = route.dynamicInputs) != null ? _b : {},
6324
+ dataClient
6325
+ });
3318
6326
  applyEditableParameters({
3319
6327
  composition,
3320
6328
  state: route.compositionApiResponse.state
@@ -3326,7 +6334,7 @@ async function UniformCompositionInner({
3326
6334
  state: pageState.compositionState,
3327
6335
  isContextualEditing: pageState.compositionState === CANVAS_EDITOR_STATE,
3328
6336
  matchedRoute: route.matchedRoute,
3329
- dynamicInputs: (_b = route.dynamicInputs) != null ? _b : {},
6337
+ dynamicInputs: (_c = route.dynamicInputs) != null ? _c : {},
3330
6338
  pageState
3331
6339
  };
3332
6340
  const [resolved] = resolveComponents({
@@ -3342,7 +6350,7 @@ async function UniformCompositionInner({
3342
6350
  composition,
3343
6351
  compositionContext
3344
6352
  });
3345
- return /* @__PURE__ */ import_react6.default.createElement(import_react6.default.Fragment, null, resolved, /* @__PURE__ */ import_react6.default.createElement(import_react6.Suspense, null, /* @__PURE__ */ import_react6.default.createElement(
6353
+ return /* @__PURE__ */ import_react5.default.createElement(import_react5.default.Fragment, null, resolved, /* @__PURE__ */ import_react5.default.createElement(import_react5.Suspense, null, /* @__PURE__ */ import_react5.default.createElement(
3346
6354
  UniformContext,
3347
6355
  {
3348
6356
  clientContextComponent,
@@ -3352,7 +6360,7 @@ async function UniformCompositionInner({
3352
6360
  route
3353
6361
  }
3354
6362
  }
3355
- )), (pageState.compositionState === CANVAS_EDITOR_STATE || pageState.compositionState === CANVAS_DRAFT_STATE) && /* @__PURE__ */ import_react6.default.createElement(import_next_app_router_client5.UniformScript, null));
6363
+ )), (pageState.compositionState === CANVAS_EDITOR_STATE || pageState.compositionState === CANVAS_DRAFT_STATE) && /* @__PURE__ */ import_react5.default.createElement(import_next_app_router_client5.UniformScript, null));
3356
6364
  }
3357
6365
  var resolveComponents = ({
3358
6366
  target,
@@ -3429,11 +6437,11 @@ var resolveComponents = ({
3429
6437
  });
3430
6438
  let element = null;
3431
6439
  if (wrapInSuspense) {
3432
- element = (0, import_react6.createElement)(
3433
- import_react6.Suspense,
6440
+ element = (0, import_react5.createElement)(
6441
+ import_react5.Suspense,
3434
6442
  {
3435
6443
  key,
3436
- fallback: typeof wrapInSuspense === "boolean" || typeof (wrapInSuspense == null ? void 0 : wrapInSuspense.fallback) === "undefined" ? void 0 : (0, import_react6.createElement)(wrapInSuspense.fallback)
6444
+ fallback: typeof wrapInSuspense === "boolean" || typeof (wrapInSuspense == null ? void 0 : wrapInSuspense.fallback) === "undefined" ? void 0 : (0, import_react5.createElement)(wrapInSuspense.fallback)
3437
6445
  },
3438
6446
  createResolvedComponent({ component, props: componentProps, resolvedComponent, pageState })
3439
6447
  );
@@ -3448,7 +6456,7 @@ var resolveComponents = ({
3448
6456
  }
3449
6457
  let tagElement = null;
3450
6458
  if (enrichmentTags == null ? void 0 : enrichmentTags.length) {
3451
- tagElement = (0, import_react6.createElement)(import_next_app_router_client5.ContextUpdateTransfer, {
6459
+ tagElement = (0, import_react5.createElement)(import_next_app_router_client5.ContextUpdateTransfer, {
3452
6460
  key: `${slotName}-${componentIndex}-tags`,
3453
6461
  update: {
3454
6462
  enrichments: enrichmentTags
@@ -3463,7 +6471,7 @@ var resolveComponents = ({
3463
6471
  }
3464
6472
  const isPlaceholder2 = isComponentPlaceholderId(component == null ? void 0 : component._id);
3465
6473
  if (!isPlaceholder2 || pageState.compositionState === CANVAS_EDITOR_STATE) {
3466
- childNode = (0, import_react6.createElement)(
6474
+ childNode = (0, import_react5.createElement)(
3467
6475
  import_core.PureContextualEditingComponentWrapper,
3468
6476
  {
3469
6477
  key: `${slotName}-${componentIndex}-wrapper`,
@@ -3486,11 +6494,11 @@ var resolveComponents = ({
3486
6494
  childNode = elements;
3487
6495
  }
3488
6496
  if (visibilityRules) {
3489
- const isVisible = (0, import_next_app_router_shared4.resolveRuleFromPageState)({
6497
+ const isVisible = (0, import_next_app_router_shared6.resolveRuleFromPageState)({
3490
6498
  pageState,
3491
6499
  rule: visibilityRules
3492
6500
  });
3493
- childNode = (0, import_react6.createElement)(
6501
+ childNode = (0, import_react5.createElement)(
3494
6502
  VisibilityRulesWrapper,
3495
6503
  {
3496
6504
  key: `${slotName}-${componentIndex}-visibility`,
@@ -3500,8 +6508,8 @@ var resolveComponents = ({
3500
6508
  childNode
3501
6509
  );
3502
6510
  }
3503
- return (0, import_react6.createElement)(
3504
- import_react6.Fragment,
6511
+ return (0, import_react5.createElement)(
6512
+ import_react5.Fragment,
3505
6513
  {
3506
6514
  key: !isRoot ? `${slotName}-${componentIndex}` : void 0
3507
6515
  },
@@ -3523,7 +6531,7 @@ var createResolvedComponent = ({
3523
6531
  componentId: component._id,
3524
6532
  pageState
3525
6533
  });
3526
- return (0, import_react6.createElement)(import_next_app_router_client5.Personalize, { ...personalizeProps, key });
6534
+ return (0, import_react5.createElement)(import_next_app_router_client5.Personalize, { ...personalizeProps, key });
3527
6535
  }
3528
6536
  if (component.type === CANVAS_TEST_TYPE) {
3529
6537
  const extractedTest = extractTest({
@@ -3535,12 +6543,12 @@ var createResolvedComponent = ({
3535
6543
  pageState,
3536
6544
  test: extractedTest
3537
6545
  });
3538
- return (0, import_react6.createElement)(Test, { ...testProps, key });
6546
+ return (0, import_react5.createElement)(Test, { ...testProps, key });
3539
6547
  }
3540
6548
  if (!resolvedComponent) {
3541
6549
  return null;
3542
6550
  }
3543
- return (0, import_react6.createElement)(resolvedComponent, { ...props, key });
6551
+ return (0, import_react5.createElement)(resolvedComponent, { ...props, key });
3544
6552
  };
3545
6553
  var resolveSlots = ({
3546
6554
  component,
@@ -3600,154 +6608,61 @@ var resolveSlots = ({
3600
6608
  return slots;
3601
6609
  };
3602
6610
 
3603
- // src/components/UniformPlayground.tsx
3604
- var import_headers = require("next/headers");
3605
- var import_react7 = __toESM(require("react"));
3606
-
3607
- // src/data/resolvePlaygroundRoute.ts
3608
- var import_next_app_router_shared5 = require("@uniformdev/next-app-router-shared");
3609
- var resolvePlaygroundRoute = async ({ code }) => {
3610
- const pageState = (0, import_next_app_router_shared5.deserializeEvaluationResult)({ input: code });
3611
- const canvasClient = getCompositionDeliveryClient({
3612
- cache: {
3613
- type: "no-cache"
3614
- }
3615
- });
3616
- let composition = void 0;
3617
- try {
3618
- composition = await canvasClient.get({
3619
- compositionId: pageState.routePath,
3620
- state: pageState.compositionState,
3621
- withComponentIDs: true
3622
- });
3623
- } catch (e) {
3624
- console.warn(
3625
- `Failed to get composition ${pageState.routePath} with state ${pageState.compositionState}`,
3626
- e
3627
- );
3628
- }
3629
- if (!composition) {
3630
- return {
3631
- code,
3632
- pageState,
3633
- route: void 0
3634
- };
3635
- }
3636
- return {
3637
- code,
3638
- pageState,
3639
- route: {
3640
- type: "composition",
3641
- compositionApiResponse: composition,
3642
- matchedRoute: "composition"
3643
- }
3644
- };
3645
- };
3646
-
3647
- // src/components/UniformPlayground.tsx
3648
- var UniformPlayground = async ({ resolveRoute, ...rest }) => {
3649
- const isDraftMode = (await (0, import_headers.draftMode)()).isEnabled;
3650
- if (!isDraftMode) {
3651
- return /* @__PURE__ */ import_react7.default.createElement("div", null, /* @__PURE__ */ import_react7.default.createElement("h1", null, "Playground is only available in draft mode"));
3652
- }
3653
- return /* @__PURE__ */ import_react7.default.createElement(UniformComposition, { ...rest, resolveRoute: resolvePlaygroundRoute });
3654
- };
3655
-
3656
- // src/components/generateStaticParams.ts
3657
- var import_next_app_router_shared8 = require("@uniformdev/next-app-router-shared");
3658
-
3659
- // src/data/extract/extractRunnables.ts
3660
- var import_next_app_router_shared7 = require("@uniformdev/next-app-router-shared");
3661
-
3662
- // src/data/extract/extractPersonalization.ts
3663
- var import_next_app_router_shared6 = require("@uniformdev/next-app-router-shared");
3664
- var extractPersonalization = ({
3665
- component
3666
- }) => {
3667
- var _a, _b, _c;
3668
- const trackingEventName = (0, import_next_app_router_shared6.extractPersonalizationName)({ component });
3669
- const countParameter = (_a = component.parameters) == null ? void 0 : _a.count;
3670
- const algorithmParameter = (_b = component.parameters) == null ? void 0 : _b.algorithm;
3671
- const count = countParameter == null ? void 0 : countParameter.value;
3672
- const algorithm = algorithmParameter == null ? void 0 : algorithmParameter.value;
3673
- let parsedCount;
3674
- if (typeof count === "string") {
3675
- parsedCount = parseInt(count, 10);
3676
- } else if (typeof count !== "number") {
3677
- parsedCount = void 0;
3678
- } else {
3679
- parsedCount = count || 1;
3680
- }
3681
- const slot = ((_c = component.slots) == null ? void 0 : _c[CANVAS_PERSONALIZE_SLOT]) || [];
3682
- const componentVariations = mapSlotToPersonalizedVariations(
3683
- slot
3684
- ).map((variant, index) => {
3685
- const slotComponent = slot[index];
3686
- if (!slotComponent) {
3687
- throw new Error(`Slot component not found for index ${index}`);
6611
+ // src/components/UniformPlayground.tsx
6612
+ var import_headers2 = require("next/headers");
6613
+ var import_react6 = __toESM(require("react"));
6614
+
6615
+ // src/data/resolvePlaygroundRoute.ts
6616
+ var import_next_app_router_shared7 = require("@uniformdev/next-app-router-shared");
6617
+ var resolvePlaygroundRoute = async ({ code }) => {
6618
+ const pageState = (0, import_next_app_router_shared7.deserializeEvaluationResult)({ input: code });
6619
+ const canvasClient = getCompositionDeliveryClient({
6620
+ cache: {
6621
+ type: "no-cache"
3688
6622
  }
6623
+ });
6624
+ let composition = void 0;
6625
+ try {
6626
+ composition = await canvasClient.get({
6627
+ compositionId: pageState.routePath,
6628
+ state: pageState.compositionState,
6629
+ withComponentIDs: true
6630
+ });
6631
+ } catch (e) {
6632
+ console.warn(
6633
+ `Failed to get composition ${pageState.routePath} with state ${pageState.compositionState}`,
6634
+ e
6635
+ );
6636
+ }
6637
+ if (!composition) {
3689
6638
  return {
3690
- ...variant,
3691
- index,
3692
- componentId: slotComponent._id
6639
+ code,
6640
+ pageState,
6641
+ route: void 0
3693
6642
  };
3694
- });
6643
+ }
3695
6644
  return {
3696
- name: trackingEventName,
3697
- take: parsedCount,
3698
- variations: componentVariations,
3699
- algorithm
6645
+ code,
6646
+ pageState,
6647
+ route: {
6648
+ type: "composition",
6649
+ compositionApiResponse: composition,
6650
+ matchedRoute: "composition"
6651
+ }
3700
6652
  };
3701
6653
  };
3702
6654
 
3703
- // src/data/extract/extractRunnables.ts
3704
- var findAncestorVariant = (ancestorsAndSelf) => {
3705
- for (let i = 0; i < ancestorsAndSelf.length; i++) {
3706
- const node = ancestorsAndSelf[i];
3707
- if (node.type === "slot" && (node.parentSlot === CANVAS_PERSONALIZE_SLOT || node.parentSlot === CANVAS_TEST_SLOT)) {
3708
- return node.node._id;
3709
- }
6655
+ // src/components/UniformPlayground.tsx
6656
+ var UniformPlayground = async ({ resolveRoute, ...rest }) => {
6657
+ const isDraftMode = (await (0, import_headers2.draftMode)()).isEnabled;
6658
+ if (!isDraftMode) {
6659
+ return /* @__PURE__ */ import_react6.default.createElement("div", null, /* @__PURE__ */ import_react6.default.createElement("h1", null, "Playground is only available in draft mode"));
3710
6660
  }
3711
- return void 0;
3712
- };
3713
- var extractRunnables = (composition) => {
3714
- const runnable = [];
3715
- walkNodeTree(composition, (node) => {
3716
- var _a, _b;
3717
- if (node.type === "component") {
3718
- const component = node.node;
3719
- const visibilityRules = (_b = (_a = component.parameters) == null ? void 0 : _a[CANVAS_VIZ_CONTROL_PARAM]) == null ? void 0 : _b.value;
3720
- if (component.type === CANVAS_TEST_TYPE) {
3721
- const test = extractTest({ component });
3722
- runnable.push({
3723
- _id: component._id,
3724
- variantId: findAncestorVariant(node.ancestorsAndSelf),
3725
- type: "test",
3726
- result: test
3727
- });
3728
- } else if (component.type === CANVAS_PERSONALIZE_TYPE) {
3729
- const personalize = extractPersonalization({ component });
3730
- runnable.push({
3731
- type: "personalization",
3732
- variantId: findAncestorVariant(node.ancestorsAndSelf),
3733
- _id: component._id,
3734
- result: personalize
3735
- });
3736
- }
3737
- if (visibilityRules) {
3738
- runnable.push({
3739
- type: "visibility",
3740
- _id: (0, import_next_app_router_shared7.getRuleId)(visibilityRules),
3741
- variantId: findAncestorVariant(node.ancestorsAndSelf),
3742
- rules: visibilityRules
3743
- });
3744
- }
3745
- }
3746
- });
3747
- return runnable;
6661
+ return /* @__PURE__ */ import_react6.default.createElement(UniformComposition, { ...rest, resolveRoute: resolvePlaygroundRoute });
3748
6662
  };
3749
6663
 
3750
6664
  // src/components/generateStaticParams.ts
6665
+ var import_next_app_router_shared8 = require("@uniformdev/next-app-router-shared");
3751
6666
  var createUniformPlaygroundStaticParams = async (options) => {
3752
6667
  var _a;
3753
6668
  const { paths } = options;
@@ -4000,173 +6915,6 @@ function generateAllGroupPermutations(groups) {
4000
6915
  return combineAcrossGroups(perGroupSelections);
4001
6916
  }
4002
6917
 
4003
- // src/data/client.ts
4004
- var import_functions = require("@vercel/functions");
4005
- var MANIFEST_CACHE_KEY = "uniform-manifest";
4006
- var DefaultDataClient = class {
4007
- async getManifest(options) {
4008
- const cache2 = options.source === "middleware" && getMiddlewareRuntimeCache() ? (0, import_functions.getCache)() : null;
4009
- if (cache2) {
4010
- const cachedManifest = await cache2.get(MANIFEST_CACHE_KEY);
4011
- if (cachedManifest) {
4012
- return cachedManifest;
4013
- }
4014
- }
4015
- const manifest = await getManifest({
4016
- cache: isDevelopmentEnvironment() ? {
4017
- type: "no-cache",
4018
- bypassCache: true
4019
- } : {
4020
- type: "force-cache"
4021
- }
4022
- });
4023
- if (cache2) {
4024
- (0, import_functions.waitUntil)(
4025
- (async () => {
4026
- await cache2.set(MANIFEST_CACHE_KEY, manifest, {
4027
- tags: generateManifestCacheTags()
4028
- });
4029
- })()
4030
- );
4031
- }
4032
- return manifest;
4033
- }
4034
- async getRouteFromApi({
4035
- route,
4036
- routeClient,
4037
- enableRuntimeCache,
4038
- disableSwrCache
4039
- }) {
4040
- const newCacheKey = `uniform-route-${route.state}-${route.releaseId}-${route.path}`;
4041
- const oldCacheKey = `uniform-route-old-${route.state}-${route.releaseId}-${route.path}`;
4042
- const cache2 = enableRuntimeCache ? (0, import_functions.getCache)() : null;
4043
- const cacheNewRoute = async (result2) => {
4044
- if (cache2 && result2.type === "composition") {
4045
- const tags = generateRouteCacheTags({ path: route.path });
4046
- await cache2.set(newCacheKey, result2, {
4047
- tags
4048
- });
4049
- }
4050
- };
4051
- const cacheOldRoute = async (result2) => {
4052
- if (cache2 && result2.type === "composition" && !disableSwrCache) {
4053
- const tags = generateRouteCacheTags({ path: route.path, old: true });
4054
- await cache2.set(oldCacheKey, result2, {
4055
- tags
4056
- });
4057
- }
4058
- };
4059
- if (cache2) {
4060
- const [cachedRoute, oldCachedRoute] = await Promise.all([
4061
- cache2.get(newCacheKey),
4062
- disableSwrCache ? null : cache2.get(oldCacheKey)
4063
- ]);
4064
- if (cachedRoute) {
4065
- return cachedRoute;
4066
- }
4067
- if (oldCachedRoute) {
4068
- (0, import_functions.waitUntil)(
4069
- (async () => {
4070
- const result2 = await routeClient.get(route);
4071
- await cacheNewRoute(result2);
4072
- })()
4073
- );
4074
- return oldCachedRoute;
4075
- }
4076
- }
4077
- const result = await routeClient.get(route);
4078
- (0, import_functions.waitUntil)(
4079
- (async () => {
4080
- await Promise.all([
4081
- cacheNewRoute(result),
4082
- disableSwrCache ? Promise.resolve() : cacheOldRoute(result)
4083
- ]);
4084
- })()
4085
- );
4086
- return result;
4087
- }
4088
- async getRoute(options) {
4089
- if (options.source === "middleware") {
4090
- return this.getRouteMiddleware(options);
4091
- }
4092
- return this.getRoutePageState(options);
4093
- }
4094
- async enhanceRoute(_options) {
4095
- }
4096
- async getRouteMiddleware(options) {
4097
- const routeClient = getRouteClient({
4098
- searchParams: options.searchParams,
4099
- draftModeEnabled: options.draftModeEnabled
4100
- });
4101
- const resolvedRoute = await this.getRouteFromApi({
4102
- source: "middleware",
4103
- route: options.route,
4104
- routeClient,
4105
- enableRuntimeCache: options.route.state === CANVAS_PUBLISHED_STATE && getMiddlewareRuntimeCache(),
4106
- disableSwrCache: getDisableSwrMiddlewareCache()
4107
- });
4108
- if (resolvedRoute.type === "composition") {
4109
- await this.enhanceRoute({
4110
- source: "middleware",
4111
- parameters: options.route,
4112
- route: resolvedRoute,
4113
- routeClient,
4114
- keys: void 0
4115
- });
4116
- }
4117
- return {
4118
- route: resolvedRoute
4119
- };
4120
- }
4121
- async getRoutePageState(options) {
4122
- const shouldBypassCache = options.pageState.compositionState !== CANVAS_PUBLISHED_STATE || isDevelopmentEnvironment();
4123
- const routeClient = getRouteClient({
4124
- cache: shouldBypassCache ? {
4125
- type: "no-cache",
4126
- bypassCache: true
4127
- } : {
4128
- type: "force-cache"
4129
- }
4130
- });
4131
- const originalRoute = {
4132
- path: options.pageState.routePath,
4133
- state: options.pageState.compositionState,
4134
- dataSourceVariant: getDataSourceVariantFromRouteGetParams({}, options.pageState.compositionState),
4135
- withComponentIDs: true,
4136
- releaseId: options.pageState.releaseId,
4137
- locale: options.pageState.locale,
4138
- ignoreRedirects: shouldIgnoreRedirects({ state: options.pageState.compositionState })
4139
- };
4140
- const resolvedRoute = await this.getRouteFromApi({
4141
- source: "pageState",
4142
- route: originalRoute,
4143
- routeClient,
4144
- enableRuntimeCache: false,
4145
- disableSwrCache: false
4146
- });
4147
- if (resolvedRoute.type === "composition") {
4148
- await this.enhanceRoute({
4149
- source: "pageState",
4150
- parameters: originalRoute,
4151
- route: resolvedRoute,
4152
- routeClient,
4153
- keys: options.pageState.keys
4154
- });
4155
- }
4156
- return {
4157
- route: resolvedRoute
4158
- };
4159
- }
4160
- };
4161
- var expireMiddlewareCacheTag = async (tag) => {
4162
- const cache2 = getMiddlewareRuntimeCache() ? (0, import_functions.getCache)() : null;
4163
- if (cache2) {
4164
- await cache2.expireTag(tag);
4165
- } else {
4166
- console.warn("Middleware cache is not enabled, cannot clear cache tag", tag);
4167
- }
4168
- };
4169
-
4170
6918
  // src/data/precomputeComposition.ts
4171
6919
  var import_next_app_router_shared9 = require("@uniformdev/next-app-router-shared");
4172
6920
  var shouldEvaluateTest = (test, evaluateTests) => {
@@ -4288,9 +7036,9 @@ var findRouteMatch = (routes, path) => {
4288
7036
  };
4289
7037
 
4290
7038
  // src/cache/helpers.ts
4291
- var import_react8 = require("react");
7039
+ var import_react7 = require("react");
4292
7040
  var serverContext = (defaultValue) => {
4293
- const getRef = (0, import_react8.cache)(() => ({ current: defaultValue }));
7041
+ const getRef = (0, import_react7.cache)(() => ({ current: defaultValue }));
4294
7042
  const getValue = () => getRef().current;
4295
7043
  const setValue = (value) => {
4296
7044
  getRef().current = value;
@@ -4354,3 +7102,8 @@ var createCompositionCache = () => {
4354
7102
  resolveRouteFromCode,
4355
7103
  serverContext
4356
7104
  });
7105
+ /*! Bundled license information:
7106
+
7107
+ js-cookie/dist/js.cookie.mjs:
7108
+ (*! js-cookie v3.0.8 | MIT *)
7109
+ */