@adhese/sdk 0.6.1 → 0.6.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.cjs ADDED
@@ -0,0 +1,2311 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const sdkDevtools = require("@adhese/sdk-devtools");
4
+ const runtimeCore = require("@vue/runtime-core");
5
+ const zod = require("zod");
6
+ async function waitForDomLoad() {
7
+ return new Promise((resolve) => {
8
+ function onDomLoad() {
9
+ resolve();
10
+ window.removeEventListener("DOMContentLoaded", onDomLoad);
11
+ }
12
+ if (document.readyState === "loading")
13
+ document.addEventListener("DOMContentLoaded", onDomLoad);
14
+ else
15
+ resolve();
16
+ });
17
+ }
18
+ function createEventManager() {
19
+ const disposables = /* @__PURE__ */ new Set();
20
+ function dispose() {
21
+ for (const disposable of disposables)
22
+ disposable();
23
+ }
24
+ return new Proxy({
25
+ dispose
26
+ }, {
27
+ // eslint-disable-next-line ts/explicit-function-return-type
28
+ get(target, key, receiver) {
29
+ if (!(key in target) && typeof key === "string") {
30
+ const event = createEvent();
31
+ disposables.add(() => {
32
+ event.listeners.clear();
33
+ });
34
+ Reflect.set(target, key, event, receiver);
35
+ }
36
+ return Reflect.get(target, key, receiver);
37
+ }
38
+ });
39
+ }
40
+ function createEvent() {
41
+ const listeners = /* @__PURE__ */ new Set();
42
+ function dispatch(data) {
43
+ for (const listener of listeners)
44
+ void listener(data);
45
+ }
46
+ async function dispatchAsync(data) {
47
+ await Promise.allSettled(
48
+ Array.from(listeners).map((listener) => listener(data))
49
+ );
50
+ }
51
+ function addListener(listener) {
52
+ listeners.add(listener);
53
+ }
54
+ function removeListener(listener) {
55
+ listeners.delete(listener);
56
+ }
57
+ return {
58
+ listeners,
59
+ dispatch,
60
+ dispatchAsync,
61
+ addListener,
62
+ removeListener
63
+ };
64
+ }
65
+ var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
66
+ function getDefaultExportFromCjs(x) {
67
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
68
+ }
69
+ var freeGlobal$1 = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
70
+ var _freeGlobal = freeGlobal$1;
71
+ var freeGlobal = _freeGlobal;
72
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
73
+ var root$a = freeGlobal || freeSelf || Function("return this")();
74
+ var _root = root$a;
75
+ var root$9 = _root;
76
+ var Symbol$5 = root$9.Symbol;
77
+ var _Symbol = Symbol$5;
78
+ function arrayMap$1(array, iteratee) {
79
+ var index = -1, length = array == null ? 0 : array.length, result = Array(length);
80
+ while (++index < length) {
81
+ result[index] = iteratee(array[index], index, array);
82
+ }
83
+ return result;
84
+ }
85
+ var _arrayMap = arrayMap$1;
86
+ var isArray$4 = Array.isArray;
87
+ var isArray_1 = isArray$4;
88
+ var Symbol$4 = _Symbol;
89
+ var objectProto$b = Object.prototype;
90
+ var hasOwnProperty$8 = objectProto$b.hasOwnProperty;
91
+ var nativeObjectToString$1 = objectProto$b.toString;
92
+ var symToStringTag$1 = Symbol$4 ? Symbol$4.toStringTag : void 0;
93
+ function getRawTag$1(value) {
94
+ var isOwn = hasOwnProperty$8.call(value, symToStringTag$1), tag = value[symToStringTag$1];
95
+ try {
96
+ value[symToStringTag$1] = void 0;
97
+ var unmasked = true;
98
+ } catch (e) {
99
+ }
100
+ var result = nativeObjectToString$1.call(value);
101
+ if (unmasked) {
102
+ if (isOwn) {
103
+ value[symToStringTag$1] = tag;
104
+ } else {
105
+ delete value[symToStringTag$1];
106
+ }
107
+ }
108
+ return result;
109
+ }
110
+ var _getRawTag = getRawTag$1;
111
+ var objectProto$a = Object.prototype;
112
+ var nativeObjectToString = objectProto$a.toString;
113
+ function objectToString$1(value) {
114
+ return nativeObjectToString.call(value);
115
+ }
116
+ var _objectToString = objectToString$1;
117
+ var Symbol$3 = _Symbol, getRawTag = _getRawTag, objectToString = _objectToString;
118
+ var nullTag = "[object Null]", undefinedTag = "[object Undefined]";
119
+ var symToStringTag = Symbol$3 ? Symbol$3.toStringTag : void 0;
120
+ function baseGetTag$5(value) {
121
+ if (value == null) {
122
+ return value === void 0 ? undefinedTag : nullTag;
123
+ }
124
+ return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
125
+ }
126
+ var _baseGetTag = baseGetTag$5;
127
+ function isObjectLike$5(value) {
128
+ return value != null && typeof value == "object";
129
+ }
130
+ var isObjectLike_1 = isObjectLike$5;
131
+ var baseGetTag$4 = _baseGetTag, isObjectLike$4 = isObjectLike_1;
132
+ var symbolTag$1 = "[object Symbol]";
133
+ function isSymbol$2(value) {
134
+ return typeof value == "symbol" || isObjectLike$4(value) && baseGetTag$4(value) == symbolTag$1;
135
+ }
136
+ var isSymbol_1 = isSymbol$2;
137
+ var Symbol$2 = _Symbol, arrayMap = _arrayMap, isArray$3 = isArray_1, isSymbol$1 = isSymbol_1;
138
+ var INFINITY$1 = 1 / 0;
139
+ var symbolProto$1 = Symbol$2 ? Symbol$2.prototype : void 0, symbolToString = symbolProto$1 ? symbolProto$1.toString : void 0;
140
+ function baseToString$1(value) {
141
+ if (typeof value == "string") {
142
+ return value;
143
+ }
144
+ if (isArray$3(value)) {
145
+ return arrayMap(value, baseToString$1) + "";
146
+ }
147
+ if (isSymbol$1(value)) {
148
+ return symbolToString ? symbolToString.call(value) : "";
149
+ }
150
+ var result = value + "";
151
+ return result == "0" && 1 / value == -INFINITY$1 ? "-0" : result;
152
+ }
153
+ var _baseToString = baseToString$1;
154
+ var baseToString = _baseToString;
155
+ function toString$2(value) {
156
+ return value == null ? "" : baseToString(value);
157
+ }
158
+ var toString_1 = toString$2;
159
+ var toString$1 = toString_1;
160
+ var idCounter = 0;
161
+ function uniqueId(prefix) {
162
+ var id = ++idCounter;
163
+ return toString$1(prefix) + id;
164
+ }
165
+ var uniqueId_1 = uniqueId;
166
+ const uniqueId$1 = /* @__PURE__ */ getDefaultExportFromCjs(uniqueId_1);
167
+ function createSafeFrame({
168
+ renderFile,
169
+ context
170
+ }) {
171
+ const safeFrame = window.$sf;
172
+ if (!safeFrame)
173
+ throw new Error("SafeFrame not found");
174
+ const adhesePositions = /* @__PURE__ */ new Set();
175
+ const config = new safeFrame.host.Config({
176
+ auto: false,
177
+ debug: context.debug,
178
+ renderFile
179
+ });
180
+ function addPosition(ad, element) {
181
+ var _a;
182
+ if (!safeFrame)
183
+ throw new Error("SafeFrame not found");
184
+ const html = ad.ext === "js" && ad.body ? ad.body : ad.tag;
185
+ if (typeof html !== "string")
186
+ throw new Error("Ad tag is not a string");
187
+ const elementId = element.id || `ad-${ad.id}-${uniqueId$1()}`;
188
+ element.id = elementId;
189
+ const position = new safeFrame.host.Position({
190
+ id: elementId,
191
+ html,
192
+ src: ad.ext === "js" ? (_a = ad.swfSrc) == null ? void 0 : _a.href : void 0,
193
+ config: new safeFrame.host.PosConfig({
194
+ id: elementId,
195
+ w: Number(ad.width),
196
+ h: Number(ad.height),
197
+ size: `${Number(ad.width)}x${Number(ad.height)}`,
198
+ tgt: html.includes('target="_self"') ? "_self" : "_blank",
199
+ dest: elementId
200
+ })
201
+ });
202
+ adhesePositions.add(position);
203
+ return position;
204
+ }
205
+ async function render(position) {
206
+ if (!safeFrame)
207
+ throw new Error("SafeFrame not found");
208
+ safeFrame.host.render(position);
209
+ }
210
+ function dispose() {
211
+ }
212
+ return {
213
+ config,
214
+ addPosition,
215
+ render,
216
+ dispose
217
+ };
218
+ }
219
+ function renderIframe(ad, element) {
220
+ const iframe = document.createElement("iframe");
221
+ iframe.srcdoc = `
222
+ <!DOCTYPE html>
223
+ <html>
224
+ <head>
225
+ <style>
226
+ body {
227
+ margin: 0;
228
+ padding: 0;
229
+ overflow: hidden;
230
+ }
231
+ </style>
232
+ </head>
233
+ <body>
234
+ ${String(ad.tag)}
235
+ </body>
236
+ `.replaceAll(/\s+/g, " ").trim();
237
+ iframe.style.border = "none";
238
+ iframe.style.width = ad.width ? `${ad.width}px` : "auto";
239
+ iframe.style.height = ad.height ? `${ad.height}px` : "auto";
240
+ element.replaceChildren(iframe);
241
+ }
242
+ function renderInline(ad, element) {
243
+ element.innerHTML = String(ad.tag);
244
+ }
245
+ function generateName(location, format, slot) {
246
+ return `${location}${slot ? `${slot}` : ""}-${format}`;
247
+ }
248
+ async function findDomSlots(context) {
249
+ await waitForDomLoad();
250
+ return Array.from(document.querySelectorAll(".adunit")).filter((element) => {
251
+ var _a;
252
+ if (!element.dataset.format)
253
+ return false;
254
+ const name = generateName(
255
+ context.location,
256
+ element.dataset.format,
257
+ element.dataset.slot
258
+ );
259
+ return !((_a = context.getAll) == null ? void 0 : _a.call(context).some((activeSlot) => activeSlot.name.value === name));
260
+ }).map((element) => createSlot({
261
+ format: element.dataset.format,
262
+ containingElement: element,
263
+ slot: element.dataset.slot,
264
+ context
265
+ })).filter((slot) => {
266
+ var _a;
267
+ return !((_a = context.getAll) == null ? void 0 : _a.call(context).some((activeSlot) => activeSlot.name.value === slot.name.value));
268
+ });
269
+ }
270
+ function createSlotManager({
271
+ initialSlots = [],
272
+ context
273
+ }) {
274
+ const scope = runtimeCore.effectScope();
275
+ return scope.run(() => {
276
+ const slots = runtimeCore.shallowReactive(/* @__PURE__ */ new Map());
277
+ runtimeCore.watchEffect(() => {
278
+ var _a;
279
+ (_a = context.events) == null ? void 0 : _a.changeSlots.dispatch(Array.from(slots.values()));
280
+ });
281
+ function getAll() {
282
+ return Array.from(slots).map(([, slot]) => slot);
283
+ }
284
+ function add(options) {
285
+ var _a;
286
+ const slot = createSlot({
287
+ ...options,
288
+ onDispose,
289
+ context
290
+ });
291
+ function onDispose() {
292
+ var _a2;
293
+ slots.delete(slot.name.value);
294
+ logger.debug("Slot removed", {
295
+ slot,
296
+ slots: Array.from(slots)
297
+ });
298
+ (_a2 = context.events) == null ? void 0 : _a2.removeSlot.dispatch(slot);
299
+ }
300
+ slots.set(slot.name.value, slot);
301
+ runtimeCore.watch(slot.name, (newName, previousName) => {
302
+ slots.set(newName, slot);
303
+ slots.delete(previousName);
304
+ });
305
+ logger.debug("Slot added", {
306
+ slot,
307
+ slots: Array.from(slots.values())
308
+ });
309
+ (_a = context.events) == null ? void 0 : _a.addSlot.dispatch(slot);
310
+ return slot;
311
+ }
312
+ async function findDomSlots$1() {
313
+ const domSlots = await findDomSlots(
314
+ context
315
+ );
316
+ for (const slot of domSlots)
317
+ slots.set(slot.name.value, slot);
318
+ return domSlots;
319
+ }
320
+ function get(name) {
321
+ return slots.get(name);
322
+ }
323
+ function dispose() {
324
+ for (const slot of slots.values())
325
+ slot.dispose();
326
+ slots.clear();
327
+ scope.stop();
328
+ }
329
+ for (const options of initialSlots) {
330
+ add({
331
+ ...options,
332
+ lazyLoading: false
333
+ });
334
+ }
335
+ return {
336
+ getAll,
337
+ add,
338
+ findDomSlots: findDomSlots$1,
339
+ get,
340
+ dispose
341
+ };
342
+ });
343
+ }
344
+ function onTcfConsentChange(callback) {
345
+ var _a;
346
+ (_a = window.__tcfapi) == null ? void 0 : _a.call(window, "addEventListener", 2, callback);
347
+ return () => {
348
+ var _a2;
349
+ return (_a2 = window.__tcfapi) == null ? void 0 : _a2.call(window, "removeEventListener", 2, callback);
350
+ };
351
+ }
352
+ function isObject$5(value) {
353
+ var type = typeof value;
354
+ return value != null && (type == "object" || type == "function");
355
+ }
356
+ var isObject_1 = isObject$5;
357
+ var root$8 = _root;
358
+ var now$1 = function() {
359
+ return root$8.Date.now();
360
+ };
361
+ var now_1 = now$1;
362
+ var reWhitespace = /\s/;
363
+ function trimmedEndIndex$1(string) {
364
+ var index = string.length;
365
+ while (index-- && reWhitespace.test(string.charAt(index))) {
366
+ }
367
+ return index;
368
+ }
369
+ var _trimmedEndIndex = trimmedEndIndex$1;
370
+ var trimmedEndIndex = _trimmedEndIndex;
371
+ var reTrimStart = /^\s+/;
372
+ function baseTrim$1(string) {
373
+ return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string;
374
+ }
375
+ var _baseTrim = baseTrim$1;
376
+ var baseTrim = _baseTrim, isObject$4 = isObject_1, isSymbol = isSymbol_1;
377
+ var NAN = 0 / 0;
378
+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
379
+ var reIsBinary = /^0b[01]+$/i;
380
+ var reIsOctal = /^0o[0-7]+$/i;
381
+ var freeParseInt = parseInt;
382
+ function toNumber$3(value) {
383
+ if (typeof value == "number") {
384
+ return value;
385
+ }
386
+ if (isSymbol(value)) {
387
+ return NAN;
388
+ }
389
+ if (isObject$4(value)) {
390
+ var other = typeof value.valueOf == "function" ? value.valueOf() : value;
391
+ value = isObject$4(other) ? other + "" : other;
392
+ }
393
+ if (typeof value != "string") {
394
+ return value === 0 ? value : +value;
395
+ }
396
+ value = baseTrim(value);
397
+ var isBinary = reIsBinary.test(value);
398
+ return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
399
+ }
400
+ var toNumber_1 = toNumber$3;
401
+ var isObject$3 = isObject_1, now = now_1, toNumber$2 = toNumber_1;
402
+ var FUNC_ERROR_TEXT = "Expected a function";
403
+ var nativeMax = Math.max, nativeMin$2 = Math.min;
404
+ function debounce(func, wait, options) {
405
+ var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
406
+ if (typeof func != "function") {
407
+ throw new TypeError(FUNC_ERROR_TEXT);
408
+ }
409
+ wait = toNumber$2(wait) || 0;
410
+ if (isObject$3(options)) {
411
+ leading = !!options.leading;
412
+ maxing = "maxWait" in options;
413
+ maxWait = maxing ? nativeMax(toNumber$2(options.maxWait) || 0, wait) : maxWait;
414
+ trailing = "trailing" in options ? !!options.trailing : trailing;
415
+ }
416
+ function invokeFunc(time) {
417
+ var args = lastArgs, thisArg = lastThis;
418
+ lastArgs = lastThis = void 0;
419
+ lastInvokeTime = time;
420
+ result = func.apply(thisArg, args);
421
+ return result;
422
+ }
423
+ function leadingEdge(time) {
424
+ lastInvokeTime = time;
425
+ timerId = setTimeout(timerExpired, wait);
426
+ return leading ? invokeFunc(time) : result;
427
+ }
428
+ function remainingWait(time) {
429
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
430
+ return maxing ? nativeMin$2(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
431
+ }
432
+ function shouldInvoke(time) {
433
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
434
+ return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
435
+ }
436
+ function timerExpired() {
437
+ var time = now();
438
+ if (shouldInvoke(time)) {
439
+ return trailingEdge(time);
440
+ }
441
+ timerId = setTimeout(timerExpired, remainingWait(time));
442
+ }
443
+ function trailingEdge(time) {
444
+ timerId = void 0;
445
+ if (trailing && lastArgs) {
446
+ return invokeFunc(time);
447
+ }
448
+ lastArgs = lastThis = void 0;
449
+ return result;
450
+ }
451
+ function cancel() {
452
+ if (timerId !== void 0) {
453
+ clearTimeout(timerId);
454
+ }
455
+ lastInvokeTime = 0;
456
+ lastArgs = lastCallTime = lastThis = timerId = void 0;
457
+ }
458
+ function flush() {
459
+ return timerId === void 0 ? result : trailingEdge(now());
460
+ }
461
+ function debounced() {
462
+ var time = now(), isInvoking = shouldInvoke(time);
463
+ lastArgs = arguments;
464
+ lastThis = this;
465
+ lastCallTime = time;
466
+ if (isInvoking) {
467
+ if (timerId === void 0) {
468
+ return leadingEdge(lastCallTime);
469
+ }
470
+ if (maxing) {
471
+ clearTimeout(timerId);
472
+ timerId = setTimeout(timerExpired, wait);
473
+ return invokeFunc(lastCallTime);
474
+ }
475
+ }
476
+ if (timerId === void 0) {
477
+ timerId = setTimeout(timerExpired, wait);
478
+ }
479
+ return result;
480
+ }
481
+ debounced.cancel = cancel;
482
+ debounced.flush = flush;
483
+ return debounced;
484
+ }
485
+ var debounce_1 = debounce;
486
+ const debounce$1 = /* @__PURE__ */ getDefaultExportFromCjs(debounce_1);
487
+ function createQueryDetector({
488
+ onChange,
489
+ queries = {
490
+ mobile: "(max-width: 768px) and (pointer: coarse)",
491
+ tablet: "(min-width: 769px) and (max-width: 1024px) and (pointer: coarse)",
492
+ desktop: "(min-width: 1025px) and (pointer: fine)"
493
+ }
494
+ } = {}) {
495
+ const mediaMap = new Map(
496
+ Object.entries(queries).map(([key, query]) => [key, window.matchMedia(query)])
497
+ );
498
+ function getQuery() {
499
+ for (const [device, query] of Object.entries(queries)) {
500
+ if (window.matchMedia(query).matches)
501
+ return device;
502
+ }
503
+ return "unknown";
504
+ }
505
+ const handleOnChange = debounce$1(() => {
506
+ void (onChange == null ? void 0 : onChange(getQuery()));
507
+ logger.debug(`Change device ${getQuery()}`);
508
+ }, 50);
509
+ if (onChange) {
510
+ for (const query of mediaMap.values())
511
+ query.addEventListener("change", handleOnChange);
512
+ }
513
+ function dispose() {
514
+ for (const query of mediaMap.values())
515
+ query.removeEventListener("change", handleOnChange);
516
+ }
517
+ return {
518
+ queries: mediaMap,
519
+ getQuery,
520
+ dispose
521
+ };
522
+ }
523
+ var nativeFloor = Math.floor, nativeRandom$1 = Math.random;
524
+ function baseRandom$1(lower, upper) {
525
+ return lower + nativeFloor(nativeRandom$1() * (upper - lower + 1));
526
+ }
527
+ var _baseRandom = baseRandom$1;
528
+ function eq$3(value, other) {
529
+ return value === other || value !== value && other !== other;
530
+ }
531
+ var eq_1 = eq$3;
532
+ var baseGetTag$3 = _baseGetTag, isObject$2 = isObject_1;
533
+ var asyncTag = "[object AsyncFunction]", funcTag$1 = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
534
+ function isFunction$2(value) {
535
+ if (!isObject$2(value)) {
536
+ return false;
537
+ }
538
+ var tag = baseGetTag$3(value);
539
+ return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
540
+ }
541
+ var isFunction_1 = isFunction$2;
542
+ var MAX_SAFE_INTEGER$1 = 9007199254740991;
543
+ function isLength$2(value) {
544
+ return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
545
+ }
546
+ var isLength_1 = isLength$2;
547
+ var isFunction$1 = isFunction_1, isLength$1 = isLength_1;
548
+ function isArrayLike$2(value) {
549
+ return value != null && isLength$1(value.length) && !isFunction$1(value);
550
+ }
551
+ var isArrayLike_1 = isArrayLike$2;
552
+ var MAX_SAFE_INTEGER = 9007199254740991;
553
+ var reIsUint = /^(?:0|[1-9]\d*)$/;
554
+ function isIndex$2(value, length) {
555
+ var type = typeof value;
556
+ length = length == null ? MAX_SAFE_INTEGER : length;
557
+ return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
558
+ }
559
+ var _isIndex = isIndex$2;
560
+ var eq$2 = eq_1, isArrayLike$1 = isArrayLike_1, isIndex$1 = _isIndex, isObject$1 = isObject_1;
561
+ function isIterateeCall$1(value, index, object) {
562
+ if (!isObject$1(object)) {
563
+ return false;
564
+ }
565
+ var type = typeof index;
566
+ if (type == "number" ? isArrayLike$1(object) && isIndex$1(index, object.length) : type == "string" && index in object) {
567
+ return eq$2(object[index], value);
568
+ }
569
+ return false;
570
+ }
571
+ var _isIterateeCall = isIterateeCall$1;
572
+ var toNumber$1 = toNumber_1;
573
+ var INFINITY = 1 / 0, MAX_INTEGER = 17976931348623157e292;
574
+ function toFinite$2(value) {
575
+ if (!value) {
576
+ return value === 0 ? value : 0;
577
+ }
578
+ value = toNumber$1(value);
579
+ if (value === INFINITY || value === -INFINITY) {
580
+ var sign = value < 0 ? -1 : 1;
581
+ return sign * MAX_INTEGER;
582
+ }
583
+ return value === value ? value : 0;
584
+ }
585
+ var toFinite_1 = toFinite$2;
586
+ var baseRandom = _baseRandom, isIterateeCall = _isIterateeCall, toFinite$1 = toFinite_1;
587
+ var freeParseFloat = parseFloat;
588
+ var nativeMin$1 = Math.min, nativeRandom = Math.random;
589
+ function random(lower, upper, floating) {
590
+ if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) {
591
+ upper = floating = void 0;
592
+ }
593
+ if (floating === void 0) {
594
+ if (typeof upper == "boolean") {
595
+ floating = upper;
596
+ upper = void 0;
597
+ } else if (typeof lower == "boolean") {
598
+ floating = lower;
599
+ lower = void 0;
600
+ }
601
+ }
602
+ if (lower === void 0 && upper === void 0) {
603
+ lower = 0;
604
+ upper = 1;
605
+ } else {
606
+ lower = toFinite$1(lower);
607
+ if (upper === void 0) {
608
+ upper = lower;
609
+ lower = 0;
610
+ } else {
611
+ upper = toFinite$1(upper);
612
+ }
613
+ }
614
+ if (lower > upper) {
615
+ var temp = lower;
616
+ lower = upper;
617
+ upper = temp;
618
+ }
619
+ if (floating || lower % 1 || upper % 1) {
620
+ var rand = nativeRandom();
621
+ return nativeMin$1(lower + rand * (upper - lower + freeParseFloat("1e-" + ((rand + "").length - 1))), upper);
622
+ }
623
+ return baseRandom(lower, upper);
624
+ }
625
+ var random_1 = random;
626
+ const random$1 = /* @__PURE__ */ getDefaultExportFromCjs(random_1);
627
+ const defaultLogLevels = ["trace", "debug", "info", "warn", "error"];
628
+ function createLogger({
629
+ scope,
630
+ logLevels = defaultLogLevels,
631
+ minLogLevelThreshold = logLevels[2]
632
+ }) {
633
+ const logs = /* @__PURE__ */ new Set();
634
+ let currentMinLogLevelThreshold = minLogLevelThreshold;
635
+ const events = createEventManager();
636
+ const logFunctions = Object.fromEntries(logLevels.map((level, index) => {
637
+ const logFunction = (message, attributes) => {
638
+ logs.add({
639
+ scope,
640
+ level,
641
+ message,
642
+ attributes,
643
+ timestamp: Date.now(),
644
+ id: uniqueId$1()
645
+ });
646
+ events.log.dispatch({
647
+ scope,
648
+ level,
649
+ message,
650
+ attributes,
651
+ timestamp: Date.now(),
652
+ id: uniqueId$1()
653
+ });
654
+ if (index >= logLevels.indexOf(currentMinLogLevelThreshold)) {
655
+ if (["warn", "error", "trace"].includes(level)) {
656
+ console[level](...[
657
+ `%c${scope}`,
658
+ "color: red; font-weight: bold;",
659
+ message,
660
+ attributes
661
+ ].filter(Boolean));
662
+ } else {
663
+ console.log(...[
664
+ `%c${scope} %c${level.toUpperCase()}`,
665
+ "color: red; font-weight: bold;",
666
+ "font-weight: bold;",
667
+ message,
668
+ attributes
669
+ ].filter(Boolean));
670
+ }
671
+ }
672
+ };
673
+ return [level, logFunction];
674
+ }));
675
+ return {
676
+ ...logFunctions,
677
+ scope,
678
+ events,
679
+ setMinLogLevelThreshold(level) {
680
+ currentMinLogLevelThreshold = level;
681
+ },
682
+ resetMinLogLevelThreshold() {
683
+ currentMinLogLevelThreshold = minLogLevelThreshold;
684
+ },
685
+ getMinLogLevelThreshold() {
686
+ return currentMinLogLevelThreshold;
687
+ },
688
+ getLogs() {
689
+ return Array.from(logs);
690
+ },
691
+ resetLogs() {
692
+ events.reset.dispatch();
693
+ logs.clear();
694
+ }
695
+ };
696
+ }
697
+ const logger = createLogger({
698
+ scope: "Adhese SDK"
699
+ });
700
+ function createParameters(options, queryDetector) {
701
+ const parameters = /* @__PURE__ */ new Map();
702
+ if (options.logReferrer)
703
+ parameters.set("re", btoa(document.referrer));
704
+ if (options.logUrl)
705
+ parameters.set("ur", btoa(window.location.href));
706
+ for (const [key, value] of Object.entries({
707
+ ...options.parameters ?? {},
708
+ tl: options.consent ? "all" : "none",
709
+ dt: queryDetector.getQuery(),
710
+ br: queryDetector.getQuery(),
711
+ rn: random$1(1e4).toString()
712
+ }))
713
+ parameters.set(key, value);
714
+ return parameters;
715
+ }
716
+ function setupLogging(mergedOptions) {
717
+ if (mergedOptions.debug || window.location.search.includes("adhese_debug=true")) {
718
+ logger.setMinLogLevelThreshold("debug");
719
+ logger.debug("Debug logging enabled");
720
+ }
721
+ logger.debug("Created Adhese SDK instance", {
722
+ mergedOptions
723
+ });
724
+ }
725
+ function isPreviewMode() {
726
+ return window.location.search.includes("adhesePreviewCreativeId");
727
+ }
728
+ function createHook({
729
+ onRun,
730
+ onAdd
731
+ }) {
732
+ const callbacks = /* @__PURE__ */ new Set();
733
+ function run() {
734
+ for (const callback of callbacks)
735
+ callback();
736
+ onRun == null ? void 0 : onRun(callbacks);
737
+ }
738
+ function add(callback) {
739
+ callbacks.add(callback);
740
+ onAdd == null ? void 0 : onAdd(callbacks);
741
+ }
742
+ return [run, add];
743
+ }
744
+ let resolveOnInitPromise = () => {
745
+ };
746
+ let isInit = false;
747
+ const waitOnInit = new Promise((resolve) => {
748
+ resolveOnInitPromise = resolve;
749
+ });
750
+ const [runOnInit, onInit] = createHook({
751
+ onRun(callbacks) {
752
+ isInit = true;
753
+ resolveOnInitPromise();
754
+ logger.debug("Initialization completed");
755
+ callbacks.clear();
756
+ },
757
+ onAdd() {
758
+ if (isInit)
759
+ runOnInit();
760
+ }
761
+ });
762
+ function createAdhese(options) {
763
+ const scope = runtimeCore.effectScope();
764
+ return scope.run(() => {
765
+ const mergedOptions = {
766
+ host: `https://ads-${options.account}.adhese.com`,
767
+ poolHost: `https://pool-${options.account}.adhese.com`,
768
+ location: "homepage",
769
+ requestType: "POST",
770
+ debug: false,
771
+ initialSlots: [],
772
+ findDomSlotsOnLoad: false,
773
+ consent: false,
774
+ logReferrer: true,
775
+ logUrl: true,
776
+ safeFrame: false,
777
+ eagerRendering: false,
778
+ viewabilityTracking: true,
779
+ ...options
780
+ };
781
+ setupLogging(mergedOptions);
782
+ const context = runtimeCore.reactive({
783
+ location: mergedOptions.location,
784
+ consent: mergedOptions.consent,
785
+ debug: mergedOptions.debug,
786
+ getAll,
787
+ get,
788
+ options: mergedOptions,
789
+ logger
790
+ });
791
+ context.events = createEventManager();
792
+ context.safeFrame = options.safeFrame ? createSafeFrame({
793
+ renderFile: `${mergedOptions.poolHost}/sf/r.html`,
794
+ context
795
+ }) : void 0;
796
+ function getLocation() {
797
+ return context.location;
798
+ }
799
+ function setLocation(newLocation) {
800
+ var _a;
801
+ context.location = newLocation;
802
+ (_a = context.events) == null ? void 0 : _a.locationChange.dispatch(newLocation);
803
+ }
804
+ const queryDetector = createQueryDetector({
805
+ onChange: onQueryChange,
806
+ queries: mergedOptions.queries
807
+ });
808
+ context.parameters = createParameters(mergedOptions, queryDetector);
809
+ runtimeCore.watch(
810
+ context.parameters,
811
+ onParametersChange,
812
+ {
813
+ deep: true,
814
+ immediate: true
815
+ }
816
+ );
817
+ function onParametersChange() {
818
+ var _a;
819
+ if (context.parameters)
820
+ (_a = context.events) == null ? void 0 : _a.parametersChange.dispatch(context.parameters);
821
+ }
822
+ async function onQueryChange() {
823
+ var _a, _b;
824
+ const query = queryDetector.getQuery();
825
+ (_a = context.parameters) == null ? void 0 : _a.set("dt", query);
826
+ (_b = context.parameters) == null ? void 0 : _b.set("br", query);
827
+ await fetchAndRenderAllSlots();
828
+ }
829
+ function getConsent() {
830
+ return context.consent;
831
+ }
832
+ function setConsent(newConsent) {
833
+ var _a, _b;
834
+ (_a = context.parameters) == null ? void 0 : _a.set("tl", newConsent ? "all" : "none");
835
+ context.consent = newConsent;
836
+ (_b = context.events) == null ? void 0 : _b.consentChange.dispatch(newConsent);
837
+ }
838
+ const slotManager = createSlotManager({
839
+ initialSlots: mergedOptions.initialSlots,
840
+ context
841
+ });
842
+ function getAll() {
843
+ return slotManager.getAll() ?? [];
844
+ }
845
+ function get(name) {
846
+ return slotManager.get(name);
847
+ }
848
+ async function addSlot(slotOptions) {
849
+ if (!slotManager)
850
+ throw new Error("Slot manager not initialized");
851
+ const slot = slotManager.add(slotOptions);
852
+ if (!slot.lazyLoading) {
853
+ slot.ad.value = await requestAd({
854
+ slot,
855
+ context
856
+ });
857
+ }
858
+ return slot;
859
+ }
860
+ async function findDomSlots2() {
861
+ const domSlots = (await slotManager.findDomSlots() ?? []).filter((slot) => !slot.lazyLoading);
862
+ if (domSlots.length <= 0)
863
+ return [];
864
+ const ads = await requestAds({
865
+ slots: domSlots,
866
+ context
867
+ });
868
+ for (const ad of ads) {
869
+ const slot = slotManager.get(ad.slotName);
870
+ if (slot)
871
+ slot.ad.value = ad;
872
+ }
873
+ return domSlots;
874
+ }
875
+ let unmountDevtools;
876
+ async function toggleDebug() {
877
+ var _a, _b;
878
+ context.debug = !context.debug;
879
+ if (context.debug && !unmountDevtools) {
880
+ unmountDevtools = await sdkDevtools.createDevtools(context);
881
+ logger.setMinLogLevelThreshold("debug");
882
+ logger.debug("Debug mode enabled");
883
+ (_a = context.events) == null ? void 0 : _a.debugChange.dispatch(true);
884
+ } else {
885
+ logger.debug("Debug mode disabled");
886
+ unmountDevtools == null ? void 0 : unmountDevtools();
887
+ unmountDevtools = void 0;
888
+ logger.setMinLogLevelThreshold("info");
889
+ (_b = context.events) == null ? void 0 : _b.debugChange.dispatch(false);
890
+ }
891
+ return context.debug;
892
+ }
893
+ async function fetchAndRenderAllSlots() {
894
+ const slots = (slotManager.getAll() ?? []).filter((slot) => !slot.lazyLoading);
895
+ if (slots.length === 0)
896
+ return;
897
+ const ads = await requestAds({
898
+ slots,
899
+ context
900
+ });
901
+ for (const ad of ads) {
902
+ const slot = slotManager.get(ad.slotName);
903
+ if (slot)
904
+ slot.ad.value = ad;
905
+ }
906
+ }
907
+ const disposeOnTcfConsentChange = onTcfConsentChange(async (data) => {
908
+ var _a, _b;
909
+ if (!data.tcString)
910
+ return;
911
+ logger.debug("TCF v2 consent data received", {
912
+ data
913
+ });
914
+ (_a = context.parameters) == null ? void 0 : _a.set("xt", data.tcString);
915
+ (_b = context.parameters) == null ? void 0 : _b.delete("tl");
916
+ await fetchAndRenderAllSlots();
917
+ });
918
+ function dispose() {
919
+ var _a, _b;
920
+ unmountDevtools == null ? void 0 : unmountDevtools();
921
+ queryDetector.dispose();
922
+ slotManager.dispose();
923
+ queryDetector.dispose();
924
+ disposeOnTcfConsentChange();
925
+ (_a = context.parameters) == null ? void 0 : _a.clear();
926
+ logger.resetLogs();
927
+ (_b = context.events) == null ? void 0 : _b.dispose();
928
+ logger.info("Adhese instance disposed");
929
+ scope.stop();
930
+ }
931
+ onInit(async () => {
932
+ var _a;
933
+ if ((slotManager.getAll().length ?? 0) > 0)
934
+ await fetchAndRenderAllSlots().catch(logger.error);
935
+ if (mergedOptions.findDomSlotsOnLoad)
936
+ await findDomSlots2();
937
+ if (mergedOptions.debug || window.location.search.includes("adhese_debug=true") || isPreviewMode()) {
938
+ unmountDevtools = await sdkDevtools.createDevtools(context);
939
+ (_a = context.events) == null ? void 0 : _a.debugChange.dispatch(true);
940
+ }
941
+ if (!scope.active)
942
+ dispose();
943
+ });
944
+ runOnInit();
945
+ return {
946
+ ...mergedOptions,
947
+ ...slotManager,
948
+ parameters: context.parameters,
949
+ events: context.events,
950
+ getLocation,
951
+ setLocation,
952
+ getConsent,
953
+ setConsent,
954
+ addSlot,
955
+ findDomSlots: findDomSlots2,
956
+ dispose,
957
+ toggleDebug,
958
+ context
959
+ };
960
+ });
961
+ }
962
+ function listCacheClear$1() {
963
+ this.__data__ = [];
964
+ this.size = 0;
965
+ }
966
+ var _listCacheClear = listCacheClear$1;
967
+ var eq$1 = eq_1;
968
+ function assocIndexOf$4(array, key) {
969
+ var length = array.length;
970
+ while (length--) {
971
+ if (eq$1(array[length][0], key)) {
972
+ return length;
973
+ }
974
+ }
975
+ return -1;
976
+ }
977
+ var _assocIndexOf = assocIndexOf$4;
978
+ var assocIndexOf$3 = _assocIndexOf;
979
+ var arrayProto = Array.prototype;
980
+ var splice = arrayProto.splice;
981
+ function listCacheDelete$1(key) {
982
+ var data = this.__data__, index = assocIndexOf$3(data, key);
983
+ if (index < 0) {
984
+ return false;
985
+ }
986
+ var lastIndex = data.length - 1;
987
+ if (index == lastIndex) {
988
+ data.pop();
989
+ } else {
990
+ splice.call(data, index, 1);
991
+ }
992
+ --this.size;
993
+ return true;
994
+ }
995
+ var _listCacheDelete = listCacheDelete$1;
996
+ var assocIndexOf$2 = _assocIndexOf;
997
+ function listCacheGet$1(key) {
998
+ var data = this.__data__, index = assocIndexOf$2(data, key);
999
+ return index < 0 ? void 0 : data[index][1];
1000
+ }
1001
+ var _listCacheGet = listCacheGet$1;
1002
+ var assocIndexOf$1 = _assocIndexOf;
1003
+ function listCacheHas$1(key) {
1004
+ return assocIndexOf$1(this.__data__, key) > -1;
1005
+ }
1006
+ var _listCacheHas = listCacheHas$1;
1007
+ var assocIndexOf = _assocIndexOf;
1008
+ function listCacheSet$1(key, value) {
1009
+ var data = this.__data__, index = assocIndexOf(data, key);
1010
+ if (index < 0) {
1011
+ ++this.size;
1012
+ data.push([key, value]);
1013
+ } else {
1014
+ data[index][1] = value;
1015
+ }
1016
+ return this;
1017
+ }
1018
+ var _listCacheSet = listCacheSet$1;
1019
+ var listCacheClear = _listCacheClear, listCacheDelete = _listCacheDelete, listCacheGet = _listCacheGet, listCacheHas = _listCacheHas, listCacheSet = _listCacheSet;
1020
+ function ListCache$4(entries) {
1021
+ var index = -1, length = entries == null ? 0 : entries.length;
1022
+ this.clear();
1023
+ while (++index < length) {
1024
+ var entry = entries[index];
1025
+ this.set(entry[0], entry[1]);
1026
+ }
1027
+ }
1028
+ ListCache$4.prototype.clear = listCacheClear;
1029
+ ListCache$4.prototype["delete"] = listCacheDelete;
1030
+ ListCache$4.prototype.get = listCacheGet;
1031
+ ListCache$4.prototype.has = listCacheHas;
1032
+ ListCache$4.prototype.set = listCacheSet;
1033
+ var _ListCache = ListCache$4;
1034
+ var ListCache$3 = _ListCache;
1035
+ function stackClear$1() {
1036
+ this.__data__ = new ListCache$3();
1037
+ this.size = 0;
1038
+ }
1039
+ var _stackClear = stackClear$1;
1040
+ function stackDelete$1(key) {
1041
+ var data = this.__data__, result = data["delete"](key);
1042
+ this.size = data.size;
1043
+ return result;
1044
+ }
1045
+ var _stackDelete = stackDelete$1;
1046
+ function stackGet$1(key) {
1047
+ return this.__data__.get(key);
1048
+ }
1049
+ var _stackGet = stackGet$1;
1050
+ function stackHas$1(key) {
1051
+ return this.__data__.has(key);
1052
+ }
1053
+ var _stackHas = stackHas$1;
1054
+ var root$7 = _root;
1055
+ var coreJsData$1 = root$7["__core-js_shared__"];
1056
+ var _coreJsData = coreJsData$1;
1057
+ var coreJsData = _coreJsData;
1058
+ var maskSrcKey = function() {
1059
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
1060
+ return uid ? "Symbol(src)_1." + uid : "";
1061
+ }();
1062
+ function isMasked$1(func) {
1063
+ return !!maskSrcKey && maskSrcKey in func;
1064
+ }
1065
+ var _isMasked = isMasked$1;
1066
+ var funcProto$1 = Function.prototype;
1067
+ var funcToString$1 = funcProto$1.toString;
1068
+ function toSource$2(func) {
1069
+ if (func != null) {
1070
+ try {
1071
+ return funcToString$1.call(func);
1072
+ } catch (e) {
1073
+ }
1074
+ try {
1075
+ return func + "";
1076
+ } catch (e) {
1077
+ }
1078
+ }
1079
+ return "";
1080
+ }
1081
+ var _toSource = toSource$2;
1082
+ var isFunction = isFunction_1, isMasked = _isMasked, isObject = isObject_1, toSource$1 = _toSource;
1083
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
1084
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
1085
+ var funcProto = Function.prototype, objectProto$9 = Object.prototype;
1086
+ var funcToString = funcProto.toString;
1087
+ var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
1088
+ var reIsNative = RegExp(
1089
+ "^" + funcToString.call(hasOwnProperty$7).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
1090
+ );
1091
+ function baseIsNative$1(value) {
1092
+ if (!isObject(value) || isMasked(value)) {
1093
+ return false;
1094
+ }
1095
+ var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
1096
+ return pattern.test(toSource$1(value));
1097
+ }
1098
+ var _baseIsNative = baseIsNative$1;
1099
+ function getValue$1(object, key) {
1100
+ return object == null ? void 0 : object[key];
1101
+ }
1102
+ var _getValue = getValue$1;
1103
+ var baseIsNative = _baseIsNative, getValue = _getValue;
1104
+ function getNative$6(object, key) {
1105
+ var value = getValue(object, key);
1106
+ return baseIsNative(value) ? value : void 0;
1107
+ }
1108
+ var _getNative = getNative$6;
1109
+ var getNative$5 = _getNative, root$6 = _root;
1110
+ var Map$4 = getNative$5(root$6, "Map");
1111
+ var _Map = Map$4;
1112
+ var getNative$4 = _getNative;
1113
+ var nativeCreate$4 = getNative$4(Object, "create");
1114
+ var _nativeCreate = nativeCreate$4;
1115
+ var nativeCreate$3 = _nativeCreate;
1116
+ function hashClear$1() {
1117
+ this.__data__ = nativeCreate$3 ? nativeCreate$3(null) : {};
1118
+ this.size = 0;
1119
+ }
1120
+ var _hashClear = hashClear$1;
1121
+ function hashDelete$1(key) {
1122
+ var result = this.has(key) && delete this.__data__[key];
1123
+ this.size -= result ? 1 : 0;
1124
+ return result;
1125
+ }
1126
+ var _hashDelete = hashDelete$1;
1127
+ var nativeCreate$2 = _nativeCreate;
1128
+ var HASH_UNDEFINED$2 = "__lodash_hash_undefined__";
1129
+ var objectProto$8 = Object.prototype;
1130
+ var hasOwnProperty$6 = objectProto$8.hasOwnProperty;
1131
+ function hashGet$1(key) {
1132
+ var data = this.__data__;
1133
+ if (nativeCreate$2) {
1134
+ var result = data[key];
1135
+ return result === HASH_UNDEFINED$2 ? void 0 : result;
1136
+ }
1137
+ return hasOwnProperty$6.call(data, key) ? data[key] : void 0;
1138
+ }
1139
+ var _hashGet = hashGet$1;
1140
+ var nativeCreate$1 = _nativeCreate;
1141
+ var objectProto$7 = Object.prototype;
1142
+ var hasOwnProperty$5 = objectProto$7.hasOwnProperty;
1143
+ function hashHas$1(key) {
1144
+ var data = this.__data__;
1145
+ return nativeCreate$1 ? data[key] !== void 0 : hasOwnProperty$5.call(data, key);
1146
+ }
1147
+ var _hashHas = hashHas$1;
1148
+ var nativeCreate = _nativeCreate;
1149
+ var HASH_UNDEFINED$1 = "__lodash_hash_undefined__";
1150
+ function hashSet$1(key, value) {
1151
+ var data = this.__data__;
1152
+ this.size += this.has(key) ? 0 : 1;
1153
+ data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED$1 : value;
1154
+ return this;
1155
+ }
1156
+ var _hashSet = hashSet$1;
1157
+ var hashClear = _hashClear, hashDelete = _hashDelete, hashGet = _hashGet, hashHas = _hashHas, hashSet = _hashSet;
1158
+ function Hash$1(entries) {
1159
+ var index = -1, length = entries == null ? 0 : entries.length;
1160
+ this.clear();
1161
+ while (++index < length) {
1162
+ var entry = entries[index];
1163
+ this.set(entry[0], entry[1]);
1164
+ }
1165
+ }
1166
+ Hash$1.prototype.clear = hashClear;
1167
+ Hash$1.prototype["delete"] = hashDelete;
1168
+ Hash$1.prototype.get = hashGet;
1169
+ Hash$1.prototype.has = hashHas;
1170
+ Hash$1.prototype.set = hashSet;
1171
+ var _Hash = Hash$1;
1172
+ var Hash = _Hash, ListCache$2 = _ListCache, Map$3 = _Map;
1173
+ function mapCacheClear$1() {
1174
+ this.size = 0;
1175
+ this.__data__ = {
1176
+ "hash": new Hash(),
1177
+ "map": new (Map$3 || ListCache$2)(),
1178
+ "string": new Hash()
1179
+ };
1180
+ }
1181
+ var _mapCacheClear = mapCacheClear$1;
1182
+ function isKeyable$1(value) {
1183
+ var type = typeof value;
1184
+ return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
1185
+ }
1186
+ var _isKeyable = isKeyable$1;
1187
+ var isKeyable = _isKeyable;
1188
+ function getMapData$4(map, key) {
1189
+ var data = map.__data__;
1190
+ return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
1191
+ }
1192
+ var _getMapData = getMapData$4;
1193
+ var getMapData$3 = _getMapData;
1194
+ function mapCacheDelete$1(key) {
1195
+ var result = getMapData$3(this, key)["delete"](key);
1196
+ this.size -= result ? 1 : 0;
1197
+ return result;
1198
+ }
1199
+ var _mapCacheDelete = mapCacheDelete$1;
1200
+ var getMapData$2 = _getMapData;
1201
+ function mapCacheGet$1(key) {
1202
+ return getMapData$2(this, key).get(key);
1203
+ }
1204
+ var _mapCacheGet = mapCacheGet$1;
1205
+ var getMapData$1 = _getMapData;
1206
+ function mapCacheHas$1(key) {
1207
+ return getMapData$1(this, key).has(key);
1208
+ }
1209
+ var _mapCacheHas = mapCacheHas$1;
1210
+ var getMapData = _getMapData;
1211
+ function mapCacheSet$1(key, value) {
1212
+ var data = getMapData(this, key), size = data.size;
1213
+ data.set(key, value);
1214
+ this.size += data.size == size ? 0 : 1;
1215
+ return this;
1216
+ }
1217
+ var _mapCacheSet = mapCacheSet$1;
1218
+ var mapCacheClear = _mapCacheClear, mapCacheDelete = _mapCacheDelete, mapCacheGet = _mapCacheGet, mapCacheHas = _mapCacheHas, mapCacheSet = _mapCacheSet;
1219
+ function MapCache$2(entries) {
1220
+ var index = -1, length = entries == null ? 0 : entries.length;
1221
+ this.clear();
1222
+ while (++index < length) {
1223
+ var entry = entries[index];
1224
+ this.set(entry[0], entry[1]);
1225
+ }
1226
+ }
1227
+ MapCache$2.prototype.clear = mapCacheClear;
1228
+ MapCache$2.prototype["delete"] = mapCacheDelete;
1229
+ MapCache$2.prototype.get = mapCacheGet;
1230
+ MapCache$2.prototype.has = mapCacheHas;
1231
+ MapCache$2.prototype.set = mapCacheSet;
1232
+ var _MapCache = MapCache$2;
1233
+ var ListCache$1 = _ListCache, Map$2 = _Map, MapCache$1 = _MapCache;
1234
+ var LARGE_ARRAY_SIZE = 200;
1235
+ function stackSet$1(key, value) {
1236
+ var data = this.__data__;
1237
+ if (data instanceof ListCache$1) {
1238
+ var pairs = data.__data__;
1239
+ if (!Map$2 || pairs.length < LARGE_ARRAY_SIZE - 1) {
1240
+ pairs.push([key, value]);
1241
+ this.size = ++data.size;
1242
+ return this;
1243
+ }
1244
+ data = this.__data__ = new MapCache$1(pairs);
1245
+ }
1246
+ data.set(key, value);
1247
+ this.size = data.size;
1248
+ return this;
1249
+ }
1250
+ var _stackSet = stackSet$1;
1251
+ var ListCache = _ListCache, stackClear = _stackClear, stackDelete = _stackDelete, stackGet = _stackGet, stackHas = _stackHas, stackSet = _stackSet;
1252
+ function Stack$1(entries) {
1253
+ var data = this.__data__ = new ListCache(entries);
1254
+ this.size = data.size;
1255
+ }
1256
+ Stack$1.prototype.clear = stackClear;
1257
+ Stack$1.prototype["delete"] = stackDelete;
1258
+ Stack$1.prototype.get = stackGet;
1259
+ Stack$1.prototype.has = stackHas;
1260
+ Stack$1.prototype.set = stackSet;
1261
+ var _Stack = Stack$1;
1262
+ var HASH_UNDEFINED = "__lodash_hash_undefined__";
1263
+ function setCacheAdd$1(value) {
1264
+ this.__data__.set(value, HASH_UNDEFINED);
1265
+ return this;
1266
+ }
1267
+ var _setCacheAdd = setCacheAdd$1;
1268
+ function setCacheHas$1(value) {
1269
+ return this.__data__.has(value);
1270
+ }
1271
+ var _setCacheHas = setCacheHas$1;
1272
+ var MapCache = _MapCache, setCacheAdd = _setCacheAdd, setCacheHas = _setCacheHas;
1273
+ function SetCache$1(values) {
1274
+ var index = -1, length = values == null ? 0 : values.length;
1275
+ this.__data__ = new MapCache();
1276
+ while (++index < length) {
1277
+ this.add(values[index]);
1278
+ }
1279
+ }
1280
+ SetCache$1.prototype.add = SetCache$1.prototype.push = setCacheAdd;
1281
+ SetCache$1.prototype.has = setCacheHas;
1282
+ var _SetCache = SetCache$1;
1283
+ function arraySome$1(array, predicate) {
1284
+ var index = -1, length = array == null ? 0 : array.length;
1285
+ while (++index < length) {
1286
+ if (predicate(array[index], index, array)) {
1287
+ return true;
1288
+ }
1289
+ }
1290
+ return false;
1291
+ }
1292
+ var _arraySome = arraySome$1;
1293
+ function cacheHas$1(cache, key) {
1294
+ return cache.has(key);
1295
+ }
1296
+ var _cacheHas = cacheHas$1;
1297
+ var SetCache = _SetCache, arraySome = _arraySome, cacheHas = _cacheHas;
1298
+ var COMPARE_PARTIAL_FLAG$3 = 1, COMPARE_UNORDERED_FLAG$1 = 2;
1299
+ function equalArrays$2(array, other, bitmask, customizer, equalFunc, stack) {
1300
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3, arrLength = array.length, othLength = other.length;
1301
+ if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
1302
+ return false;
1303
+ }
1304
+ var arrStacked = stack.get(array);
1305
+ var othStacked = stack.get(other);
1306
+ if (arrStacked && othStacked) {
1307
+ return arrStacked == other && othStacked == array;
1308
+ }
1309
+ var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG$1 ? new SetCache() : void 0;
1310
+ stack.set(array, other);
1311
+ stack.set(other, array);
1312
+ while (++index < arrLength) {
1313
+ var arrValue = array[index], othValue = other[index];
1314
+ if (customizer) {
1315
+ var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
1316
+ }
1317
+ if (compared !== void 0) {
1318
+ if (compared) {
1319
+ continue;
1320
+ }
1321
+ result = false;
1322
+ break;
1323
+ }
1324
+ if (seen) {
1325
+ if (!arraySome(other, function(othValue2, othIndex) {
1326
+ if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
1327
+ return seen.push(othIndex);
1328
+ }
1329
+ })) {
1330
+ result = false;
1331
+ break;
1332
+ }
1333
+ } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
1334
+ result = false;
1335
+ break;
1336
+ }
1337
+ }
1338
+ stack["delete"](array);
1339
+ stack["delete"](other);
1340
+ return result;
1341
+ }
1342
+ var _equalArrays = equalArrays$2;
1343
+ var root$5 = _root;
1344
+ var Uint8Array$1 = root$5.Uint8Array;
1345
+ var _Uint8Array = Uint8Array$1;
1346
+ function mapToArray$1(map) {
1347
+ var index = -1, result = Array(map.size);
1348
+ map.forEach(function(value, key) {
1349
+ result[++index] = [key, value];
1350
+ });
1351
+ return result;
1352
+ }
1353
+ var _mapToArray = mapToArray$1;
1354
+ function setToArray$1(set) {
1355
+ var index = -1, result = Array(set.size);
1356
+ set.forEach(function(value) {
1357
+ result[++index] = value;
1358
+ });
1359
+ return result;
1360
+ }
1361
+ var _setToArray = setToArray$1;
1362
+ var Symbol$1 = _Symbol, Uint8Array = _Uint8Array, eq = eq_1, equalArrays$1 = _equalArrays, mapToArray = _mapToArray, setToArray = _setToArray;
1363
+ var COMPARE_PARTIAL_FLAG$2 = 1, COMPARE_UNORDERED_FLAG = 2;
1364
+ var boolTag$1 = "[object Boolean]", dateTag$1 = "[object Date]", errorTag$1 = "[object Error]", mapTag$2 = "[object Map]", numberTag$1 = "[object Number]", regexpTag$1 = "[object RegExp]", setTag$2 = "[object Set]", stringTag$1 = "[object String]", symbolTag = "[object Symbol]";
1365
+ var arrayBufferTag$1 = "[object ArrayBuffer]", dataViewTag$2 = "[object DataView]";
1366
+ var symbolProto = Symbol$1 ? Symbol$1.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
1367
+ function equalByTag$1(object, other, tag, bitmask, customizer, equalFunc, stack) {
1368
+ switch (tag) {
1369
+ case dataViewTag$2:
1370
+ if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
1371
+ return false;
1372
+ }
1373
+ object = object.buffer;
1374
+ other = other.buffer;
1375
+ case arrayBufferTag$1:
1376
+ if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
1377
+ return false;
1378
+ }
1379
+ return true;
1380
+ case boolTag$1:
1381
+ case dateTag$1:
1382
+ case numberTag$1:
1383
+ return eq(+object, +other);
1384
+ case errorTag$1:
1385
+ return object.name == other.name && object.message == other.message;
1386
+ case regexpTag$1:
1387
+ case stringTag$1:
1388
+ return object == other + "";
1389
+ case mapTag$2:
1390
+ var convert = mapToArray;
1391
+ case setTag$2:
1392
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2;
1393
+ convert || (convert = setToArray);
1394
+ if (object.size != other.size && !isPartial) {
1395
+ return false;
1396
+ }
1397
+ var stacked = stack.get(object);
1398
+ if (stacked) {
1399
+ return stacked == other;
1400
+ }
1401
+ bitmask |= COMPARE_UNORDERED_FLAG;
1402
+ stack.set(object, other);
1403
+ var result = equalArrays$1(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
1404
+ stack["delete"](object);
1405
+ return result;
1406
+ case symbolTag:
1407
+ if (symbolValueOf) {
1408
+ return symbolValueOf.call(object) == symbolValueOf.call(other);
1409
+ }
1410
+ }
1411
+ return false;
1412
+ }
1413
+ var _equalByTag = equalByTag$1;
1414
+ function arrayPush$1(array, values) {
1415
+ var index = -1, length = values.length, offset = array.length;
1416
+ while (++index < length) {
1417
+ array[offset + index] = values[index];
1418
+ }
1419
+ return array;
1420
+ }
1421
+ var _arrayPush = arrayPush$1;
1422
+ var arrayPush = _arrayPush, isArray$2 = isArray_1;
1423
+ function baseGetAllKeys$1(object, keysFunc, symbolsFunc) {
1424
+ var result = keysFunc(object);
1425
+ return isArray$2(object) ? result : arrayPush(result, symbolsFunc(object));
1426
+ }
1427
+ var _baseGetAllKeys = baseGetAllKeys$1;
1428
+ function arrayFilter$1(array, predicate) {
1429
+ var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
1430
+ while (++index < length) {
1431
+ var value = array[index];
1432
+ if (predicate(value, index, array)) {
1433
+ result[resIndex++] = value;
1434
+ }
1435
+ }
1436
+ return result;
1437
+ }
1438
+ var _arrayFilter = arrayFilter$1;
1439
+ function stubArray$1() {
1440
+ return [];
1441
+ }
1442
+ var stubArray_1 = stubArray$1;
1443
+ var arrayFilter = _arrayFilter, stubArray = stubArray_1;
1444
+ var objectProto$6 = Object.prototype;
1445
+ var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable;
1446
+ var nativeGetSymbols = Object.getOwnPropertySymbols;
1447
+ var getSymbols$1 = !nativeGetSymbols ? stubArray : function(object) {
1448
+ if (object == null) {
1449
+ return [];
1450
+ }
1451
+ object = Object(object);
1452
+ return arrayFilter(nativeGetSymbols(object), function(symbol) {
1453
+ return propertyIsEnumerable$1.call(object, symbol);
1454
+ });
1455
+ };
1456
+ var _getSymbols = getSymbols$1;
1457
+ function baseTimes$1(n, iteratee) {
1458
+ var index = -1, result = Array(n);
1459
+ while (++index < n) {
1460
+ result[index] = iteratee(index);
1461
+ }
1462
+ return result;
1463
+ }
1464
+ var _baseTimes = baseTimes$1;
1465
+ var baseGetTag$2 = _baseGetTag, isObjectLike$3 = isObjectLike_1;
1466
+ var argsTag$2 = "[object Arguments]";
1467
+ function baseIsArguments$1(value) {
1468
+ return isObjectLike$3(value) && baseGetTag$2(value) == argsTag$2;
1469
+ }
1470
+ var _baseIsArguments = baseIsArguments$1;
1471
+ var baseIsArguments = _baseIsArguments, isObjectLike$2 = isObjectLike_1;
1472
+ var objectProto$5 = Object.prototype;
1473
+ var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
1474
+ var propertyIsEnumerable = objectProto$5.propertyIsEnumerable;
1475
+ var isArguments$1 = baseIsArguments(/* @__PURE__ */ function() {
1476
+ return arguments;
1477
+ }()) ? baseIsArguments : function(value) {
1478
+ return isObjectLike$2(value) && hasOwnProperty$4.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
1479
+ };
1480
+ var isArguments_1 = isArguments$1;
1481
+ var isBuffer$2 = { exports: {} };
1482
+ function stubFalse() {
1483
+ return false;
1484
+ }
1485
+ var stubFalse_1 = stubFalse;
1486
+ isBuffer$2.exports;
1487
+ (function(module2, exports2) {
1488
+ var root2 = _root, stubFalse2 = stubFalse_1;
1489
+ var freeExports = exports2 && !exports2.nodeType && exports2;
1490
+ var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
1491
+ var moduleExports = freeModule && freeModule.exports === freeExports;
1492
+ var Buffer = moduleExports ? root2.Buffer : void 0;
1493
+ var nativeIsBuffer = Buffer ? Buffer.isBuffer : void 0;
1494
+ var isBuffer2 = nativeIsBuffer || stubFalse2;
1495
+ module2.exports = isBuffer2;
1496
+ })(isBuffer$2, isBuffer$2.exports);
1497
+ var isBufferExports = isBuffer$2.exports;
1498
+ var baseGetTag$1 = _baseGetTag, isLength = isLength_1, isObjectLike$1 = isObjectLike_1;
1499
+ var argsTag$1 = "[object Arguments]", arrayTag$1 = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", mapTag$1 = "[object Map]", numberTag = "[object Number]", objectTag$2 = "[object Object]", regexpTag = "[object RegExp]", setTag$1 = "[object Set]", stringTag = "[object String]", weakMapTag$1 = "[object WeakMap]";
1500
+ var arrayBufferTag = "[object ArrayBuffer]", dataViewTag$1 = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]";
1501
+ var typedArrayTags = {};
1502
+ typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
1503
+ typedArrayTags[argsTag$1] = typedArrayTags[arrayTag$1] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag] = typedArrayTags[objectTag$2] = typedArrayTags[regexpTag] = typedArrayTags[setTag$1] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag$1] = false;
1504
+ function baseIsTypedArray$1(value) {
1505
+ return isObjectLike$1(value) && isLength(value.length) && !!typedArrayTags[baseGetTag$1(value)];
1506
+ }
1507
+ var _baseIsTypedArray = baseIsTypedArray$1;
1508
+ function baseUnary$1(func) {
1509
+ return function(value) {
1510
+ return func(value);
1511
+ };
1512
+ }
1513
+ var _baseUnary = baseUnary$1;
1514
+ var _nodeUtil = { exports: {} };
1515
+ _nodeUtil.exports;
1516
+ (function(module2, exports2) {
1517
+ var freeGlobal2 = _freeGlobal;
1518
+ var freeExports = exports2 && !exports2.nodeType && exports2;
1519
+ var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
1520
+ var moduleExports = freeModule && freeModule.exports === freeExports;
1521
+ var freeProcess = moduleExports && freeGlobal2.process;
1522
+ var nodeUtil2 = function() {
1523
+ try {
1524
+ var types = freeModule && freeModule.require && freeModule.require("util").types;
1525
+ if (types) {
1526
+ return types;
1527
+ }
1528
+ return freeProcess && freeProcess.binding && freeProcess.binding("util");
1529
+ } catch (e) {
1530
+ }
1531
+ }();
1532
+ module2.exports = nodeUtil2;
1533
+ })(_nodeUtil, _nodeUtil.exports);
1534
+ var _nodeUtilExports = _nodeUtil.exports;
1535
+ var baseIsTypedArray = _baseIsTypedArray, baseUnary = _baseUnary, nodeUtil = _nodeUtilExports;
1536
+ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
1537
+ var isTypedArray$2 = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
1538
+ var isTypedArray_1 = isTypedArray$2;
1539
+ var baseTimes = _baseTimes, isArguments = isArguments_1, isArray$1 = isArray_1, isBuffer$1 = isBufferExports, isIndex = _isIndex, isTypedArray$1 = isTypedArray_1;
1540
+ var objectProto$4 = Object.prototype;
1541
+ var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
1542
+ function arrayLikeKeys$1(value, inherited) {
1543
+ var isArr = isArray$1(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer$1(value), isType = !isArr && !isArg && !isBuff && isTypedArray$1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length;
1544
+ for (var key in value) {
1545
+ if ((inherited || hasOwnProperty$3.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
1546
+ (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
1547
+ isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
1548
+ isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
1549
+ isIndex(key, length)))) {
1550
+ result.push(key);
1551
+ }
1552
+ }
1553
+ return result;
1554
+ }
1555
+ var _arrayLikeKeys = arrayLikeKeys$1;
1556
+ var objectProto$3 = Object.prototype;
1557
+ function isPrototype$1(value) {
1558
+ var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto$3;
1559
+ return value === proto;
1560
+ }
1561
+ var _isPrototype = isPrototype$1;
1562
+ function overArg$1(func, transform) {
1563
+ return function(arg) {
1564
+ return func(transform(arg));
1565
+ };
1566
+ }
1567
+ var _overArg = overArg$1;
1568
+ var overArg = _overArg;
1569
+ var nativeKeys$1 = overArg(Object.keys, Object);
1570
+ var _nativeKeys = nativeKeys$1;
1571
+ var isPrototype = _isPrototype, nativeKeys = _nativeKeys;
1572
+ var objectProto$2 = Object.prototype;
1573
+ var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
1574
+ function baseKeys$1(object) {
1575
+ if (!isPrototype(object)) {
1576
+ return nativeKeys(object);
1577
+ }
1578
+ var result = [];
1579
+ for (var key in Object(object)) {
1580
+ if (hasOwnProperty$2.call(object, key) && key != "constructor") {
1581
+ result.push(key);
1582
+ }
1583
+ }
1584
+ return result;
1585
+ }
1586
+ var _baseKeys = baseKeys$1;
1587
+ var arrayLikeKeys = _arrayLikeKeys, baseKeys = _baseKeys, isArrayLike = isArrayLike_1;
1588
+ function keys$1(object) {
1589
+ return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
1590
+ }
1591
+ var keys_1 = keys$1;
1592
+ var baseGetAllKeys = _baseGetAllKeys, getSymbols = _getSymbols, keys = keys_1;
1593
+ function getAllKeys$1(object) {
1594
+ return baseGetAllKeys(object, keys, getSymbols);
1595
+ }
1596
+ var _getAllKeys = getAllKeys$1;
1597
+ var getAllKeys = _getAllKeys;
1598
+ var COMPARE_PARTIAL_FLAG$1 = 1;
1599
+ var objectProto$1 = Object.prototype;
1600
+ var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
1601
+ function equalObjects$1(object, other, bitmask, customizer, equalFunc, stack) {
1602
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length;
1603
+ if (objLength != othLength && !isPartial) {
1604
+ return false;
1605
+ }
1606
+ var index = objLength;
1607
+ while (index--) {
1608
+ var key = objProps[index];
1609
+ if (!(isPartial ? key in other : hasOwnProperty$1.call(other, key))) {
1610
+ return false;
1611
+ }
1612
+ }
1613
+ var objStacked = stack.get(object);
1614
+ var othStacked = stack.get(other);
1615
+ if (objStacked && othStacked) {
1616
+ return objStacked == other && othStacked == object;
1617
+ }
1618
+ var result = true;
1619
+ stack.set(object, other);
1620
+ stack.set(other, object);
1621
+ var skipCtor = isPartial;
1622
+ while (++index < objLength) {
1623
+ key = objProps[index];
1624
+ var objValue = object[key], othValue = other[key];
1625
+ if (customizer) {
1626
+ var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
1627
+ }
1628
+ if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
1629
+ result = false;
1630
+ break;
1631
+ }
1632
+ skipCtor || (skipCtor = key == "constructor");
1633
+ }
1634
+ if (result && !skipCtor) {
1635
+ var objCtor = object.constructor, othCtor = other.constructor;
1636
+ if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
1637
+ result = false;
1638
+ }
1639
+ }
1640
+ stack["delete"](object);
1641
+ stack["delete"](other);
1642
+ return result;
1643
+ }
1644
+ var _equalObjects = equalObjects$1;
1645
+ var getNative$3 = _getNative, root$4 = _root;
1646
+ var DataView$1 = getNative$3(root$4, "DataView");
1647
+ var _DataView = DataView$1;
1648
+ var getNative$2 = _getNative, root$3 = _root;
1649
+ var Promise$2 = getNative$2(root$3, "Promise");
1650
+ var _Promise = Promise$2;
1651
+ var getNative$1 = _getNative, root$2 = _root;
1652
+ var Set$2 = getNative$1(root$2, "Set");
1653
+ var _Set = Set$2;
1654
+ var getNative = _getNative, root$1 = _root;
1655
+ var WeakMap$1 = getNative(root$1, "WeakMap");
1656
+ var _WeakMap = WeakMap$1;
1657
+ var DataView = _DataView, Map$1 = _Map, Promise$1 = _Promise, Set$1 = _Set, WeakMap = _WeakMap, baseGetTag = _baseGetTag, toSource = _toSource;
1658
+ var mapTag = "[object Map]", objectTag$1 = "[object Object]", promiseTag = "[object Promise]", setTag = "[object Set]", weakMapTag = "[object WeakMap]";
1659
+ var dataViewTag = "[object DataView]";
1660
+ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map$1), promiseCtorString = toSource(Promise$1), setCtorString = toSource(Set$1), weakMapCtorString = toSource(WeakMap);
1661
+ var getTag$1 = baseGetTag;
1662
+ if (DataView && getTag$1(new DataView(new ArrayBuffer(1))) != dataViewTag || Map$1 && getTag$1(new Map$1()) != mapTag || Promise$1 && getTag$1(Promise$1.resolve()) != promiseTag || Set$1 && getTag$1(new Set$1()) != setTag || WeakMap && getTag$1(new WeakMap()) != weakMapTag) {
1663
+ getTag$1 = function(value) {
1664
+ var result = baseGetTag(value), Ctor = result == objectTag$1 ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : "";
1665
+ if (ctorString) {
1666
+ switch (ctorString) {
1667
+ case dataViewCtorString:
1668
+ return dataViewTag;
1669
+ case mapCtorString:
1670
+ return mapTag;
1671
+ case promiseCtorString:
1672
+ return promiseTag;
1673
+ case setCtorString:
1674
+ return setTag;
1675
+ case weakMapCtorString:
1676
+ return weakMapTag;
1677
+ }
1678
+ }
1679
+ return result;
1680
+ };
1681
+ }
1682
+ var _getTag = getTag$1;
1683
+ var Stack = _Stack, equalArrays = _equalArrays, equalByTag = _equalByTag, equalObjects = _equalObjects, getTag = _getTag, isArray = isArray_1, isBuffer = isBufferExports, isTypedArray = isTypedArray_1;
1684
+ var COMPARE_PARTIAL_FLAG = 1;
1685
+ var argsTag = "[object Arguments]", arrayTag = "[object Array]", objectTag = "[object Object]";
1686
+ var objectProto = Object.prototype;
1687
+ var hasOwnProperty = objectProto.hasOwnProperty;
1688
+ function baseIsEqualDeep$1(object, other, bitmask, customizer, equalFunc, stack) {
1689
+ var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other);
1690
+ objTag = objTag == argsTag ? objectTag : objTag;
1691
+ othTag = othTag == argsTag ? objectTag : othTag;
1692
+ var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
1693
+ if (isSameTag && isBuffer(object)) {
1694
+ if (!isBuffer(other)) {
1695
+ return false;
1696
+ }
1697
+ objIsArr = true;
1698
+ objIsObj = false;
1699
+ }
1700
+ if (isSameTag && !objIsObj) {
1701
+ stack || (stack = new Stack());
1702
+ return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
1703
+ }
1704
+ if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
1705
+ var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__");
1706
+ if (objIsWrapped || othIsWrapped) {
1707
+ var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
1708
+ stack || (stack = new Stack());
1709
+ return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
1710
+ }
1711
+ }
1712
+ if (!isSameTag) {
1713
+ return false;
1714
+ }
1715
+ stack || (stack = new Stack());
1716
+ return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
1717
+ }
1718
+ var _baseIsEqualDeep = baseIsEqualDeep$1;
1719
+ var baseIsEqualDeep = _baseIsEqualDeep, isObjectLike = isObjectLike_1;
1720
+ function baseIsEqual$1(value, other, bitmask, customizer, stack) {
1721
+ if (value === other) {
1722
+ return true;
1723
+ }
1724
+ if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
1725
+ return value !== value && other !== other;
1726
+ }
1727
+ return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual$1, stack);
1728
+ }
1729
+ var _baseIsEqual = baseIsEqual$1;
1730
+ var baseIsEqual = _baseIsEqual;
1731
+ function isEqual(value, other) {
1732
+ return baseIsEqual(value, other);
1733
+ }
1734
+ var isEqual_1 = isEqual;
1735
+ const isEqual$1 = /* @__PURE__ */ getDefaultExportFromCjs(isEqual_1);
1736
+ function addTrackingPixel(url) {
1737
+ const img = document.createElement("img");
1738
+ img.src = url.toString();
1739
+ img.style.height = "1px";
1740
+ img.style.width = "1px";
1741
+ img.style.margin = "-1px";
1742
+ img.style.border = "0";
1743
+ img.style.position = "absolute";
1744
+ img.style.top = "0";
1745
+ return document.body.appendChild(img);
1746
+ }
1747
+ var toFinite = toFinite_1;
1748
+ function toInteger$1(value) {
1749
+ var result = toFinite(value), remainder = result % 1;
1750
+ return result === result ? remainder ? result - remainder : result : 0;
1751
+ }
1752
+ var toInteger_1 = toInteger$1;
1753
+ var root = _root, toInteger = toInteger_1, toNumber = toNumber_1, toString = toString_1;
1754
+ var nativeIsFinite = root.isFinite, nativeMin = Math.min;
1755
+ function createRound$1(methodName) {
1756
+ var func = Math[methodName];
1757
+ return function(number, precision) {
1758
+ number = toNumber(number);
1759
+ precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
1760
+ if (precision && nativeIsFinite(number)) {
1761
+ var pair = (toString(number) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision));
1762
+ pair = (toString(value) + "e").split("e");
1763
+ return +(pair[0] + "e" + (+pair[1] - precision));
1764
+ }
1765
+ return func(number);
1766
+ };
1767
+ }
1768
+ var _createRound = createRound$1;
1769
+ var createRound = _createRound;
1770
+ var round = createRound("round");
1771
+ var round_1 = round;
1772
+ const round$1 = /* @__PURE__ */ getDefaultExportFromCjs(round_1);
1773
+ function useViewabilityObserver({ context, ad, name, element }) {
1774
+ let timeoutId = null;
1775
+ const {
1776
+ threshold,
1777
+ duration,
1778
+ rootMargin
1779
+ } = {
1780
+ threshold: 0.2,
1781
+ duration: 1e3,
1782
+ rootMargin: "0px",
1783
+ ...context.options.viewabilityTrackingOptions
1784
+ };
1785
+ const trackingPixel = runtimeCore.ref(null);
1786
+ const isTracked = runtimeCore.computed(() => Boolean(trackingPixel.value));
1787
+ const viewabilityObserver = new IntersectionObserver(([entry]) => {
1788
+ if (context.options.viewabilityTracking && !trackingPixel.value && ad) {
1789
+ const ratio = round$1(entry.intersectionRatio, 1);
1790
+ if (ratio >= threshold && !timeoutId) {
1791
+ timeoutId = setTimeout(() => {
1792
+ var _a, _b, _c;
1793
+ timeoutId = null;
1794
+ if ((_a = ad.value) == null ? void 0 : _a.viewableImpressionCounter) {
1795
+ trackingPixel.value = addTrackingPixel(ad.value.viewableImpressionCounter);
1796
+ logger.debug(`Viewability tracking pixel fired for ${name.value}`);
1797
+ (_c = context.events) == null ? void 0 : _c.changeSlots.dispatch(Array.from(((_b = context.getAll) == null ? void 0 : _b.call(context)) ?? []));
1798
+ }
1799
+ }, duration);
1800
+ } else if (ratio < threshold && timeoutId) {
1801
+ clearTimeout(timeoutId);
1802
+ timeoutId = null;
1803
+ }
1804
+ }
1805
+ }, {
1806
+ rootMargin,
1807
+ threshold: Array.from({ length: 11 }, (_, i) => i * 0.1)
1808
+ });
1809
+ function observe(newElement, oldElement) {
1810
+ if (oldElement)
1811
+ viewabilityObserver.unobserve(oldElement);
1812
+ if (newElement && context.options.viewabilityTracking)
1813
+ viewabilityObserver.observe(newElement);
1814
+ return () => {
1815
+ if (newElement)
1816
+ viewabilityObserver.unobserve(newElement);
1817
+ };
1818
+ }
1819
+ runtimeCore.watch(element, observe);
1820
+ observe(element.value);
1821
+ return [isTracked, () => {
1822
+ var _a;
1823
+ (_a = trackingPixel.value) == null ? void 0 : _a.remove();
1824
+ viewabilityObserver.disconnect();
1825
+ }];
1826
+ }
1827
+ function useRenderIntersectionObserver({ ad, options, element, render }) {
1828
+ var _a;
1829
+ const isInViewport = runtimeCore.ref(false);
1830
+ const renderIntersectionObserver = new IntersectionObserver((entries) => {
1831
+ isInViewport.value = entries.some((entry) => entry.isIntersecting);
1832
+ if (isInViewport.value) {
1833
+ (async () => {
1834
+ if (!ad.value && options.lazyLoading)
1835
+ await render();
1836
+ await render(ad.value ?? void 0);
1837
+ })().catch(logger.error);
1838
+ }
1839
+ }, {
1840
+ rootMargin: ((_a = options.lazyLoadingOptions) == null ? void 0 : _a.rootMargin) ?? "200px",
1841
+ threshold: 0
1842
+ });
1843
+ function observe(newElement, oldElement) {
1844
+ if (oldElement)
1845
+ renderIntersectionObserver.unobserve(oldElement);
1846
+ if (newElement)
1847
+ renderIntersectionObserver.observe(newElement);
1848
+ return () => {
1849
+ if (newElement)
1850
+ renderIntersectionObserver.unobserve(newElement);
1851
+ };
1852
+ }
1853
+ runtimeCore.watch(element, observe);
1854
+ observe(element.value);
1855
+ return [isInViewport, () => {
1856
+ renderIntersectionObserver.disconnect();
1857
+ }];
1858
+ }
1859
+ const renderFunctions = {
1860
+ iframe: renderIframe,
1861
+ inline: renderInline
1862
+ };
1863
+ function createSlot(options) {
1864
+ const scope = runtimeCore.effectScope();
1865
+ return scope.run(() => {
1866
+ const {
1867
+ containingElement,
1868
+ slot,
1869
+ context,
1870
+ renderMode = "iframe"
1871
+ } = options;
1872
+ const parameters = runtimeCore.reactive(new Map(Object.entries(options.parameters ?? {})));
1873
+ let queryDetector = null;
1874
+ if (typeof options.format !== "string") {
1875
+ queryDetector = createQueryDetector({
1876
+ onChange: onQueryChange,
1877
+ queries: Object.fromEntries(options.format.map((item) => [item.format, item.query]))
1878
+ });
1879
+ }
1880
+ const format = runtimeCore.ref(queryDetector ? queryDetector.getQuery() : options.format);
1881
+ function onQueryChange(newFormat) {
1882
+ format.value = newFormat;
1883
+ }
1884
+ const ad = runtimeCore.ref(null);
1885
+ const originalAd = runtimeCore.ref(ad.value);
1886
+ const name = runtimeCore.computed(() => generateName(context.location, format.value, slot));
1887
+ runtimeCore.watch(name, async (newName, oldName) => {
1888
+ var _a;
1889
+ if (newName === oldName)
1890
+ return;
1891
+ (_a = options.onNameChange) == null ? void 0 : _a.call(options, newName, oldName);
1892
+ const newAd = await requestAd$1();
1893
+ cleanElement();
1894
+ ad.value = newAd;
1895
+ originalAd.value = newAd;
1896
+ });
1897
+ const isDomLoaded = useDomLoaded();
1898
+ const element = runtimeCore.computed(
1899
+ () => {
1900
+ if (!(typeof containingElement === "string" || !containingElement))
1901
+ return containingElement;
1902
+ if (!isDomLoaded.value)
1903
+ return null;
1904
+ return document.querySelector(`.adunit[data-format="${format.value}"]#${containingElement}${slot ? `[data-slot="${slot}"]` : ""}`);
1905
+ }
1906
+ );
1907
+ function getElement() {
1908
+ var _a, _b;
1909
+ if (renderMode === "iframe")
1910
+ return ((_a = element.value) == null ? void 0 : _a.querySelector("iframe")) ?? null;
1911
+ return ((_b = element.value) == null ? void 0 : _b.innerHTML) ? element.value.firstElementChild : null;
1912
+ }
1913
+ const [isInViewport, disposeRenderIntersectionObserver] = useRenderIntersectionObserver({
1914
+ ad,
1915
+ options,
1916
+ element,
1917
+ render
1918
+ });
1919
+ runtimeCore.watch([ad, isInViewport], async ([newAd, newIsInViewport], [oldAd]) => {
1920
+ var _a, _b;
1921
+ if (!newAd || isEqual$1(newAd, oldAd))
1922
+ return;
1923
+ if (newIsInViewport || context.options.eagerRendering)
1924
+ await render(newAd);
1925
+ (_b = context.events) == null ? void 0 : _b.changeSlots.dispatch(Array.from(((_a = context.getAll) == null ? void 0 : _a.call(context)) ?? []));
1926
+ });
1927
+ const [
1928
+ isViewabilityTracked,
1929
+ disposeViewabilityObserver
1930
+ ] = useViewabilityObserver({
1931
+ context,
1932
+ ad,
1933
+ name,
1934
+ element
1935
+ });
1936
+ const impressionTrackingPixelElement = runtimeCore.ref(null);
1937
+ const isImpressionTracked = runtimeCore.computed(() => Boolean(impressionTrackingPixelElement.value));
1938
+ async function requestAd$1() {
1939
+ const response = await requestAd({
1940
+ slot: {
1941
+ name: name.value,
1942
+ parameters
1943
+ },
1944
+ context
1945
+ });
1946
+ originalAd.value = response;
1947
+ return response;
1948
+ }
1949
+ async function render(adToRender) {
1950
+ var _a, _b;
1951
+ await waitForDomLoad();
1952
+ await waitOnInit;
1953
+ const renderAd = adToRender ?? ad.value ?? await requestAd$1();
1954
+ if (originalAd.value) {
1955
+ ad.value = ((_a = options.onBeforeRender) == null ? void 0 : _a.call(options, adToRender ?? originalAd.value)) ?? renderAd;
1956
+ }
1957
+ if (!element.value) {
1958
+ const error = `Could not create slot for format ${format.value}. No element found.`;
1959
+ logger.error(error, options);
1960
+ throw new Error(error);
1961
+ }
1962
+ if (context.debug)
1963
+ element.value.style.position = "relative";
1964
+ if (context.safeFrame && ad.value && renderMode === "iframe") {
1965
+ const position = context.safeFrame.addPosition(ad.value, element.value);
1966
+ await context.safeFrame.render(position);
1967
+ } else {
1968
+ renderFunctions[renderMode](renderAd, element.value);
1969
+ }
1970
+ if (renderAd.impressionCounter && !impressionTrackingPixelElement.value) {
1971
+ impressionTrackingPixelElement.value = addTrackingPixel(renderAd.impressionCounter);
1972
+ logger.debug(`Impression tracking pixel fired for ${name.value}`);
1973
+ }
1974
+ logger.debug("Slot rendered", {
1975
+ renderedElement: element,
1976
+ location: context.location,
1977
+ format,
1978
+ containingElement
1979
+ });
1980
+ (_b = options.onRender) == null ? void 0 : _b.call(options, element.value);
1981
+ disposeRenderIntersectionObserver();
1982
+ return element.value;
1983
+ }
1984
+ function cleanElement() {
1985
+ if (!element.value)
1986
+ return;
1987
+ element.value.innerHTML = "";
1988
+ element.value.style.position = "";
1989
+ element.value.style.width = "";
1990
+ element.value.style.height = "";
1991
+ }
1992
+ function dispose() {
1993
+ var _a, _b;
1994
+ cleanElement();
1995
+ (_a = impressionTrackingPixelElement.value) == null ? void 0 : _a.remove();
1996
+ ad.value = null;
1997
+ disposeRenderIntersectionObserver();
1998
+ disposeViewabilityObserver();
1999
+ (_b = options.onDispose) == null ? void 0 : _b.call(options);
2000
+ queryDetector == null ? void 0 : queryDetector.dispose();
2001
+ scope.stop();
2002
+ }
2003
+ return {
2004
+ location: context.location,
2005
+ lazyLoading: options.lazyLoading ?? false,
2006
+ slot,
2007
+ parameters,
2008
+ format,
2009
+ name,
2010
+ ad,
2011
+ isViewabilityTracked,
2012
+ isImpressionTracked,
2013
+ render,
2014
+ getElement,
2015
+ dispose
2016
+ };
2017
+ });
2018
+ }
2019
+ function useDomLoaded() {
2020
+ const isDomLoaded = runtimeCore.ref(false);
2021
+ onInit(async () => {
2022
+ await waitForDomLoad();
2023
+ isDomLoaded.value = true;
2024
+ });
2025
+ return isDomLoaded;
2026
+ }
2027
+ const numberLike = zod.union([zod.coerce.string().regex(/^\d+$/), zod.literal("")]).transform((value) => value === "" ? void 0 : Number(value));
2028
+ const booleanLike = zod.union([zod.coerce.boolean(), zod.literal("")]);
2029
+ const urlLike = zod.union([zod.coerce.string(), zod.literal("")]).transform((value) => {
2030
+ try {
2031
+ return new URL(value);
2032
+ } catch {
2033
+ return void 0;
2034
+ }
2035
+ });
2036
+ const dateLike = zod.union([zod.coerce.string(), zod.literal("")]).transform((value) => {
2037
+ if (value === "")
2038
+ return void 0;
2039
+ const date = new Date(numberLike.safeParse(value).success ? Number(value) : value);
2040
+ if (Number.isNaN(date.getTime()))
2041
+ return void 0;
2042
+ return date;
2043
+ });
2044
+ const cssValueLike = zod.union([zod.coerce.string(), zod.literal(""), zod.number()]).transform((value) => {
2045
+ if (value === "" || value === 0 || value === "0")
2046
+ return void 0;
2047
+ if (numberLike.parse(value))
2048
+ return `${numberLike.parse(value)}px`;
2049
+ return String(value);
2050
+ });
2051
+ const isJson = zod.string().transform((value, { addIssue }) => {
2052
+ try {
2053
+ return JSON.parse(value.replaceAll("'", '"'));
2054
+ } catch (error) {
2055
+ addIssue({
2056
+ code: zod.ZodIssueCode.custom,
2057
+ message: `Invalid JSON: ${error.message}`
2058
+ });
2059
+ return zod.NEVER;
2060
+ }
2061
+ });
2062
+ const isHtmlString = zod.string().transform((value, { addIssue }) => {
2063
+ var _a;
2064
+ const htmlParser = new DOMParser();
2065
+ try {
2066
+ const html = htmlParser.parseFromString(value, "text/html");
2067
+ if (((_a = html.body) == null ? void 0 : _a.children.length) === 0)
2068
+ throw new Error("Invalid HTML");
2069
+ return value;
2070
+ } catch (error) {
2071
+ addIssue({
2072
+ code: zod.ZodIssueCode.custom,
2073
+ message: error.message
2074
+ });
2075
+ return zod.NEVER;
2076
+ }
2077
+ });
2078
+ const isJsonOrHtmlString = zod.union([isJson, isHtmlString]);
2079
+ const isJsonOrHtmlOptionalString = zod.union([zod.coerce.string(), isJsonOrHtmlString]).transform((value) => {
2080
+ if (value === "")
2081
+ return void 0;
2082
+ return value;
2083
+ }).optional();
2084
+ const baseSchema = zod.object({
2085
+ adDuration: numberLike.optional(),
2086
+ adFormat: zod.string().optional(),
2087
+ adType: zod.string(),
2088
+ additionalCreativeTracker: urlLike.optional(),
2089
+ additionalViewableTracker: zod.string().optional(),
2090
+ adspaceEnd: dateLike.optional(),
2091
+ adspaceId: zod.string().optional(),
2092
+ adspaceKey: zod.string().optional(),
2093
+ adspaceStart: dateLike.optional(),
2094
+ advertiserId: zod.string().optional(),
2095
+ altText: zod.string().optional(),
2096
+ auctionable: booleanLike.optional(),
2097
+ body: isJsonOrHtmlOptionalString,
2098
+ clickTag: urlLike.optional(),
2099
+ comment: zod.string().optional(),
2100
+ creativeName: zod.string().optional(),
2101
+ deliveryGroupId: zod.string().optional(),
2102
+ deliveryMultiples: zod.string().optional(),
2103
+ ext: zod.string().optional(),
2104
+ extension: zod.object({
2105
+ mediaType: zod.string(),
2106
+ prebid: zod.unknown().optional()
2107
+ }).optional(),
2108
+ height: numberLike.optional(),
2109
+ id: zod.string(),
2110
+ impressionCounter: urlLike.optional(),
2111
+ libId: zod.string().optional(),
2112
+ orderId: zod.string().optional(),
2113
+ orderName: zod.string().optional(),
2114
+ orderProperty: zod.string().optional(),
2115
+ origin: zod.union([zod.literal("JERLICIA"), zod.literal("DALE")]),
2116
+ originData: zod.unknown().optional(),
2117
+ originInstance: zod.string().optional(),
2118
+ poolPath: urlLike.optional(),
2119
+ preview: booleanLike.optional(),
2120
+ priority: numberLike.optional(),
2121
+ sfSrc: urlLike.optional(),
2122
+ share: zod.string().optional(),
2123
+ // eslint-disable-next-line ts/naming-convention
2124
+ slotID: zod.string(),
2125
+ slotName: zod.string(),
2126
+ swfSrc: urlLike.optional(),
2127
+ tag: isJsonOrHtmlOptionalString,
2128
+ tagUrl: urlLike.optional(),
2129
+ timeStamp: dateLike.optional(),
2130
+ trackedImpressionCounter: urlLike.optional(),
2131
+ tracker: urlLike.optional(),
2132
+ trackingUrl: urlLike.optional(),
2133
+ url: urlLike.optional(),
2134
+ viewableImpressionCounter: urlLike.optional(),
2135
+ width: numberLike.optional(),
2136
+ widthLarge: cssValueLike.optional()
2137
+ });
2138
+ const jerliciaSchema = zod.object({
2139
+ origin: zod.literal("JERLICIA"),
2140
+ tag: isJsonOrHtmlString
2141
+ }).passthrough();
2142
+ const daleSchema = zod.object({
2143
+ origin: zod.literal("DALE"),
2144
+ body: isJsonOrHtmlString
2145
+ }).passthrough().transform(({ body, ...data }) => ({
2146
+ ...data,
2147
+ tag: body
2148
+ }));
2149
+ const adResponseSchema = baseSchema.extend({
2150
+ additionalCreatives: zod.lazy(() => zod.union([adResponseSchema.array(), zod.string()]).optional())
2151
+ });
2152
+ const adSchema = adResponseSchema.transform(({
2153
+ additionalCreatives,
2154
+ ...data
2155
+ }) => {
2156
+ const filteredValue = Object.fromEntries(
2157
+ Object.entries(data).filter(([, value]) => Boolean(value) && JSON.stringify(value) !== "{}" && JSON.stringify(value) !== "[]")
2158
+ );
2159
+ return {
2160
+ ...filteredValue,
2161
+ additionalCreatives: Array.isArray(additionalCreatives) ? additionalCreatives.map((creative) => adSchema.parse(creative)) : additionalCreatives
2162
+ };
2163
+ });
2164
+ function parseResponse(response) {
2165
+ const schemaMap = {
2166
+ /* eslint-disable ts/naming-convention */
2167
+ JERLICIA: jerliciaSchema,
2168
+ DALE: daleSchema
2169
+ /* eslint-enable ts/naming-convention */
2170
+ };
2171
+ const preParsed = adResponseSchema.array().parse(response);
2172
+ return preParsed.map((item) => {
2173
+ const schema = schemaMap[item.origin];
2174
+ if (!schema)
2175
+ return adSchema.parse(item);
2176
+ return schema.parse(item);
2177
+ });
2178
+ }
2179
+ async function requestPreviews(account) {
2180
+ const previewObjects = getPreviewObjects();
2181
+ const list = (await Promise.allSettled(previewObjects.filter((previewObject) => "adhesePreviewCreativeId" in previewObject).map(async (previewObject) => {
2182
+ const endpoint = new URL(`https://${account}-preview.adhese.org/creatives/preview/json/tag.do`);
2183
+ endpoint.searchParams.set(
2184
+ "id",
2185
+ previewObject.adhesePreviewCreativeId
2186
+ );
2187
+ const response = await fetch(endpoint.href, {
2188
+ method: "GET",
2189
+ headers: {
2190
+ accept: "application/json"
2191
+ }
2192
+ });
2193
+ if (!response.ok)
2194
+ return Promise.reject(new Error(`Failed to request preview ad with ID: ${previewObject.adhesePreviewCreativeId}`));
2195
+ return await response.json();
2196
+ }))).filter((response) => {
2197
+ if (response.status === "rejected") {
2198
+ logger.error(response.reason);
2199
+ return false;
2200
+ }
2201
+ return response.status === "fulfilled";
2202
+ }).map((response) => response.value.map((item) => ({
2203
+ ...item,
2204
+ preview: true
2205
+ })));
2206
+ return adSchema.array().parse(list.flat());
2207
+ }
2208
+ function getPreviewObjects() {
2209
+ const currentUrl = new URL(window.location.href);
2210
+ const previewObjects = [];
2211
+ let currentObject = {};
2212
+ for (const [key, value] of currentUrl.searchParams.entries()) {
2213
+ if (key === "adhesePreviewCreativeId" && Object.keys(currentObject).length > 0) {
2214
+ previewObjects.push(currentObject);
2215
+ currentObject = {};
2216
+ }
2217
+ currentObject[key] = value;
2218
+ }
2219
+ if (Object.keys(currentObject).length > 0)
2220
+ previewObjects.push(currentObject);
2221
+ return previewObjects;
2222
+ }
2223
+ function requestWithPost({
2224
+ context: { options: { host }, parameters },
2225
+ ...options
2226
+ }) {
2227
+ const payload = {
2228
+ ...options,
2229
+ slots: options.slots.map((slot) => ({
2230
+ slotname: runtimeCore.toValue(slot.name),
2231
+ parameters: parseParameters(slot.parameters)
2232
+ })),
2233
+ parameters: parameters && parseParameters(parameters)
2234
+ };
2235
+ return fetch(`${new URL(host).href}json`, {
2236
+ method: "POST",
2237
+ body: JSON.stringify(payload),
2238
+ headers: {
2239
+ // eslint-disable-next-line ts/naming-convention
2240
+ "Content-Type": "application/json"
2241
+ }
2242
+ });
2243
+ }
2244
+ async function requestWithGet({ context, slots }) {
2245
+ return fetch(new URL(`${context.options.host}/json/sl${slots.map((slot) => runtimeCore.toValue(slot.name)).join("/sl")}`), {
2246
+ method: "GET",
2247
+ headers: {
2248
+ // eslint-disable-next-line ts/naming-convention
2249
+ "Content-Type": "application/json"
2250
+ }
2251
+ });
2252
+ }
2253
+ function parseParameters(parameters) {
2254
+ return Object.fromEntries(Array.from(parameters.entries()).filter(([key]) => {
2255
+ if (key.length === 2)
2256
+ return true;
2257
+ logger.warn(`Invalid parameter key: ${key}. Key should be exactly 2 characters long. Key will be ignored.`);
2258
+ return false;
2259
+ }));
2260
+ }
2261
+ async function requestAds(options) {
2262
+ var _a, _b, _c, _d, _e;
2263
+ const { context } = options;
2264
+ try {
2265
+ (_a = context.events) == null ? void 0 : _a.requestAd.dispatch({
2266
+ ...options,
2267
+ context
2268
+ });
2269
+ const [response, previews] = await Promise.all([((_b = context.options.requestType) == null ? void 0 : _b.toUpperCase()) === "POST" ? requestWithPost(options) : requestWithGet(options), requestPreviews(context.options.account)]);
2270
+ logger.debug("Received response", response);
2271
+ if (!response.ok)
2272
+ throw new Error(`Failed to request ad: ${response.status} ${response.statusText}`);
2273
+ const result = parseResponse(await response.json());
2274
+ logger.debug("Parsed ad", result);
2275
+ if (previews.length > 0)
2276
+ logger.info(`Found ${previews.length} ${previews.length === 1 ? "preview" : "previews"}. Replacing ads in response with preview items`, previews);
2277
+ const matchedPreviews = previews.map(({ slotName, ...preview }) => {
2278
+ const partnerAd = result.find((ad) => ad.libId === preview.libId);
2279
+ return {
2280
+ slotName: `${(partnerAd == null ? void 0 : partnerAd.slotName) ?? slotName}`,
2281
+ ...preview
2282
+ };
2283
+ });
2284
+ if (matchedPreviews.length > 0)
2285
+ (_c = context.events) == null ? void 0 : _c.previewReceived.dispatch(matchedPreviews);
2286
+ const mergedResult = [
2287
+ ...result.filter((ad) => !previews.some((preview) => preview.libId === ad.libId)),
2288
+ ...matchedPreviews
2289
+ ];
2290
+ if (mergedResult.length === 0)
2291
+ throw new Error("No ads found");
2292
+ (_d = context.events) == null ? void 0 : _d.responseReceived.dispatch(mergedResult);
2293
+ return mergedResult;
2294
+ } catch (error) {
2295
+ logger.error(String(error));
2296
+ (_e = context.events) == null ? void 0 : _e.requestError.dispatch(error);
2297
+ throw error;
2298
+ }
2299
+ }
2300
+ async function requestAd({
2301
+ slot,
2302
+ ...options
2303
+ }) {
2304
+ const [ad] = await requestAds({
2305
+ slots: [slot],
2306
+ ...options
2307
+ });
2308
+ return ad;
2309
+ }
2310
+ exports.createAdhese = createAdhese;
2311
+ //# sourceMappingURL=index.cjs.map