@datarangers/sdk-javascript 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es/plugin/ab.js CHANGED
@@ -1,928 +1 @@
1
- /******************************************************************************
2
- Copyright (c) Microsoft Corporation.
3
-
4
- Permission to use, copy, modify, and/or distribute this software for any
5
- purpose with or without fee is hereby granted.
6
-
7
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
- PERFORMANCE OF THIS SOFTWARE.
14
- ***************************************************************************** */
15
-
16
- var __assign = function() {
17
- __assign = Object.assign || function __assign(t) {
18
- for (var s, i = 1, n = arguments.length; i < n; i++) {
19
- s = arguments[i];
20
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
21
- }
22
- return t;
23
- };
24
- return __assign.apply(this, arguments);
25
- };
26
-
27
- // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
28
- var STYLE_ID = '__rangers_ab_style__';
29
-
30
- function openOverlayer() {
31
- if (document.getElementById(STYLE_ID)) {
32
- return;
33
- }
34
-
35
- var css = 'body { opacity: 0 !important; }';
36
- var head = document.head || document.getElementsByTagName('head')[0];
37
- var style = document.createElement('style');
38
- style.id = STYLE_ID;
39
- style.type = 'text/css';
40
-
41
- if (style.styleSheet) {
42
- style.styleSheet.cssText = css;
43
- } else {
44
- style.appendChild(document.createTextNode(css));
45
- }
46
-
47
- head.appendChild(style);
48
- }
49
-
50
- function closeOverlayer() {
51
- var style = document.getElementById(STYLE_ID);
52
-
53
- if (style) {
54
- style.parentElement.removeChild(style);
55
- }
56
- }
57
-
58
- // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
59
- var AB_DOMAINS = {
60
- cn: '1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k',
61
- va: '1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k',
62
- sg: '1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k'
63
- };
64
-
65
- // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
66
- var Types;
67
-
68
- (function (Types) {
69
- Types["Init"] = "init";
70
- Types["Config"] = "config";
71
- Types["Start"] = "start";
72
- Types["Ready"] = "ready";
73
- Types["TokenComplete"] = "token-complete";
74
- Types["TokenStorage"] = "token-storage";
75
- Types["TokenFetch"] = "token-fetch";
76
- Types["TokenError"] = "token-error";
77
- Types["ConfigUuid"] = "config-uuid";
78
- Types["ConfigWebId"] = "config-webid";
79
- Types["ConfigDomain"] = "config-domain";
80
- Types["CustomWebId"] = "custom-webid";
81
- Types["AnonymousId"] = "anonymous-id";
82
- Types["TokenChange"] = "token-change";
83
- Types["TokenReset"] = "token-reset";
84
- Types["ConfigTransform"] = "config-transform";
85
- Types["EnvTransform"] = "env-transform";
86
- Types["SessionReset"] = "session-reset";
87
- Types["SessionResetTime"] = "session-reset-time";
88
- Types["Event"] = "event";
89
- Types["Events"] = "events";
90
- Types["EventNow"] = "event-now";
91
- Types["CleanEvents"] = "clean-events";
92
- Types["BeconEvent"] = "becon-event";
93
- Types["SubmitBefore"] = "submit-before";
94
- Types["SubmitScuess"] = "submit-scuess";
95
- Types["SubmitAfter"] = "submit-after";
96
- Types["SubmitError"] = "submit-error";
97
- Types["SubmitVerifyH"] = "submit-verify-h5";
98
- Types["Stay"] = "stay";
99
- Types["ResetStay"] = "reset-stay";
100
- Types["StayReady"] = "stay-ready";
101
- Types["SetStay"] = "set-stay";
102
- Types["RouteChange"] = "route-change";
103
- Types["RouteReady"] = "route-ready";
104
- Types["Ab"] = "ab";
105
- Types["AbVar"] = "ab-var";
106
- Types["AbAllVars"] = "ab-all-vars";
107
- Types["AbConfig"] = "ab-config";
108
- Types["AbExternalVersion"] = "ab-external-version";
109
- Types["AbVersionChangeOn"] = "ab-version-change-on";
110
- Types["AbVersionChangeOff"] = "ab-version-change-off";
111
- Types["AbOpenLayer"] = "ab-open-layer";
112
- Types["AbCloseLayer"] = "ab-close-layer";
113
- Types["AbReady"] = "ab-ready";
114
- Types["AbComplete"] = "ab-complete";
115
- Types["AbTimeout"] = "ab-timeout";
116
- Types["Profile"] = "profile";
117
- Types["ProfileSet"] = "profile-set";
118
- Types["ProfileSetOnce"] = "profile-set-once";
119
- Types["ProfileUnset"] = "profile-unset";
120
- Types["ProfileIncrement"] = "profile-increment";
121
- Types["ProfileAppend"] = "profile-append";
122
- Types["ProfileClear"] = "profile-clear";
123
- Types["TrackDuration"] = "track-duration";
124
- Types["TrackDurationStart"] = "track-duration-start";
125
- Types["TrackDurationEnd"] = "track-duration-end";
126
- Types["TrackDurationPause"] = "track-duration-pause";
127
- Types["TrackDurationResume"] = "tracl-duration-resume";
128
- Types["Autotrack"] = "autotrack";
129
- Types["AutotrackReady"] = "autotrack-ready";
130
- Types["CepReady"] = "cep-ready";
131
- Types["TracerReady"] = "tracer-ready";
132
- })(Types || (Types = {}));
133
-
134
- var DebuggerMesssge;
135
-
136
- (function (DebuggerMesssge) {
137
- DebuggerMesssge["DEBUGGER_MESSAGE"] = "debugger-message";
138
- DebuggerMesssge["DEBUGGER_MESSAGE_SDK"] = "debugger-message-sdk";
139
- DebuggerMesssge["DEBUGGER_MESSAGE_FETCH"] = "debugger-message-fetch";
140
- DebuggerMesssge["DEBUGGER_MESSAGE_FETCH_RESULT"] = "debugger-message-fetch-result";
141
- DebuggerMesssge["DEBUGGER_MESSAGE_EVENT"] = "debugger-message-event";
142
- DebuggerMesssge["DEVTOOL_WEB_READY"] = "devtool-web-ready";
143
- })(DebuggerMesssge || (DebuggerMesssge = {}));
144
-
145
- // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
146
- // @ts-nocheck
147
- // @ts-nocheck
148
- var isObject = function isObject(obj) {
149
- return obj != null && Object.prototype.toString.call(obj) == '[object Object]';
150
- };
151
- (function () {
152
- var lastEventId = +Date.now() + Number(("" + Math.random()).slice(2, 8));
153
- return function () {
154
- lastEventId += 1;
155
- return lastEventId;
156
- };
157
- })();
158
- /* eslint-disable no-param-reassign */
159
-
160
- var decrypto = function decrypto(str, xor, hex) {
161
- if (typeof str !== 'string' || typeof xor !== 'number' || typeof hex !== 'number') {
162
- return;
163
- }
164
-
165
- var strCharList = [];
166
- var resultList = [];
167
- hex = hex <= 25 ? hex : hex % 25;
168
- var splitStr = String.fromCharCode(hex + 97);
169
- strCharList = str.split(splitStr);
170
-
171
- for (var i = 0; i < strCharList.length; i++) {
172
- var charCode = parseInt(strCharList[i], hex);
173
- charCode = charCode * 1 ^ xor;
174
- var strChar = String.fromCharCode(charCode);
175
- resultList.push(strChar);
176
- }
177
-
178
- var resultStr = resultList.join('');
179
- return resultStr;
180
- };
181
- var decodeUrl = function decodeUrl(string) {
182
- return decrypto(string, 64, 25);
183
- };
184
- var parseURL = function parseURL(url) {
185
- var a = document.createElement('a');
186
- a.href = url;
187
- return a;
188
- };
189
- var parseUrlQuery = function parseUrlQuery(url) {
190
- var queryObj = {};
191
-
192
- try {
193
- var queryString = parseURL(url).search;
194
- queryString = queryString.slice(1);
195
- queryString.split('&').forEach(function (keyValue) {
196
- var _keyValue = keyValue.split('=');
197
-
198
- var key;
199
- var value;
200
-
201
- if (_keyValue.length) {
202
- key = _keyValue[0];
203
- value = _keyValue[1];
204
- }
205
-
206
- try {
207
- queryObj[key] = decodeURIComponent(typeof value === 'undefined' ? '' : value);
208
- } catch (e) {
209
- queryObj[key] = value;
210
- }
211
- });
212
- } catch (e) {}
213
-
214
- return queryObj;
215
- };
216
-
217
- var CallbackType;
218
-
219
- (function (CallbackType) {
220
- CallbackType[CallbackType["Var"] = 0] = "Var";
221
- CallbackType[CallbackType["All"] = 1] = "All";
222
- })(CallbackType || (CallbackType = {}));
223
-
224
- var STORAGE_EXPRIRE = 1 * 30 * 24 * 60 * 60 * 1000;
225
- var API = '/service/2/abtest_config/';
226
-
227
- var Ab =
228
- /** @class */
229
- function () {
230
- function Ab() {
231
- this.fetchStatus = 'no';
232
- this.refreshFetchStatus = 'complete';
233
- this.versions = [];
234
- this.extVersions = [];
235
- this.mulilinkVersions = [];
236
- this.enable_multilink = false;
237
- this.enable_ab_visual = false;
238
- this.editMode = false;
239
- this.callbacks = [];
240
- this.data = null;
241
- this.changeListener = new Map();
242
- this.readyStatus = false;
243
- this.exposureCache = [];
244
- }
245
-
246
- Ab.prototype.apply = function (collect, config) {
247
- var _this = this;
248
-
249
- this.collect = collect;
250
- this.config = config;
251
- if (!this.config.enable_ab_test) return;
252
- var enable_multilink = config.enable_multilink,
253
- ab_channel_domain = config.ab_channel_domain,
254
- enable_ab_visual = config.enable_ab_visual,
255
- ab_cross = config.ab_cross,
256
- ab_cookie_domain = config.ab_cookie_domain,
257
- disable_ab_reset = config.disable_ab_reset;
258
- var abDomain = ab_channel_domain || decodeUrl(AB_DOMAINS[config.channel || 'cn']);
259
- var _a = collect.adapters,
260
- storage = _a.storage,
261
- fetch = _a.fetch;
262
- this.cacheStorgae = new storage(false);
263
- this.fetch = fetch;
264
- this.enable_multilink = enable_multilink;
265
- this.enable_ab_visual = enable_ab_visual;
266
- this.abKey = "__tea_sdk_ab_version_" + config.app_id;
267
- this.ab_cross = ab_cross;
268
- this.ab_cookie_domain = ab_cookie_domain || '';
269
- this.fetchUrl = "" + abDomain + API;
270
- this.reportUrl = "" + collect.configManager.getUrl('event');
271
- this.exposureLimit = config.exposure_limit || 20;
272
- this.ab_batch_time = config.ab_batch_time || 500;
273
- var Types = this.collect.Types;
274
- this.types = Types;
275
- this.collect.on(Types.TokenChange, function (tokenInfo) {
276
- if (disable_ab_reset) return;
277
- if (tokenInfo.type !== 'uuid') return;
278
- if (!_this.readyStatus) return;
279
-
280
- _this.clearCache();
281
-
282
- _this.fetchAB();
283
- });
284
- this.collect.on(Types.TokenReset, function () {
285
- if (disable_ab_reset) return;
286
- if (!_this.readyStatus) return;
287
-
288
- _this.clearCache();
289
-
290
- _this.fetchAB();
291
- });
292
- this.collect.on(Types.AbVar, function (_a) {
293
- var name = _a.name,
294
- defaultValue = _a.defaultValue,
295
- callback = _a.callback;
296
-
297
- _this.getVar(name, defaultValue, callback);
298
- });
299
- this.collect.on(Types.AbAllVars, function (callback) {
300
- _this.getAllVars(callback);
301
- });
302
- this.collect.on(Types.AbConfig, function (_a) {
303
- var params = _a.params,
304
- callback = _a.callback;
305
-
306
- _this.getABconfig(params, callback);
307
- });
308
- this.collect.on(Types.AbExternalVersion, function (vids) {
309
- _this.setExternalAbVersion(vids);
310
- });
311
- this.collect.on(Types.AbOpenLayer, function () {
312
- _this.openOverlayer();
313
- });
314
- this.collect.on(Types.AbCloseLayer, function () {
315
- _this.closeOverlayer();
316
- });
317
- this.collect.on(Types.AbVersionChangeOn, function (cb) {
318
- _this.changeListener.set(cb, cb);
319
- });
320
- this.collect.on(Types.AbVersionChangeOff, function (cb) {
321
- if (_this.changeListener.get(cb)) {
322
- _this.changeListener["delete"](cb);
323
- }
324
- });
325
- this.loadMode();
326
- (this.enable_ab_visual || this.enable_multilink) && this.openOverlayer(this.config.multilink_timeout_ms || 500);
327
- this.checkLocal();
328
- this.ready('ab');
329
-
330
- if (!this.readyStatus) {
331
- this.fetchAB();
332
- this.readyStatus = true;
333
- }
334
-
335
- this.collect.emit(Types.AbReady);
336
- };
337
-
338
- Ab.prototype.ready = function (name) {
339
- var _this = this;
340
-
341
- this.collect.set(name);
342
-
343
- if (this.collect.hook._hooksCache.hasOwnProperty(name)) {
344
- var emits = this.collect.hook._hooksCache[name];
345
- if (!Object.keys(emits).length) return;
346
-
347
- var _loop_1 = function _loop_1(key) {
348
- if (emits[key].length) {
349
- emits[key].forEach(function (item) {
350
- _this.collect.hook.emit(key, item);
351
- });
352
- }
353
- };
354
-
355
- for (var key in emits) {
356
- _loop_1(key);
357
- }
358
- }
359
- };
360
-
361
- Ab.prototype.loadMode = function () {// const name = getIframeUrl();
362
- // let editMode = '';
363
- // if (name) {
364
- // const { scenario, href } = name;
365
- // if (scenario) {
366
- // this.editMode = true;
367
- // editMode = scenario;
368
- // } else if (
369
- // href &&
370
- // (href.indexOf('datatester') !== -1 ||
371
- // href.indexOf('visual-editor') !== -1)
372
- // ) {
373
- // this.editMode = true;
374
- // editMode = 'visual-editor';
375
- // }
376
- // }
377
- // if (this.enable_ab_visual) {
378
- // readyToLoadEditor(this.collect, this.config);
379
- // if (editMode === 'visual-editor') {
380
- // this.collect.destoryInstace();
381
- // return;
382
- // }
383
- // }
384
- // if (this.enable_multilink) {
385
- // loadMuiltlink(this.collect, this.config);
386
- // }
387
- };
388
-
389
- Ab.prototype.checkLocal = function () {
390
- var _a = this.getABCache(),
391
- ab_version = _a.ab_version,
392
- ab_ext_version = _a.ab_ext_version,
393
- ab_version_multilink = _a.ab_version_multilink,
394
- data = _a.data;
395
-
396
- var mulilinkUrlVid = this.checkFromUrl();
397
-
398
- if (mulilinkUrlVid) {
399
- this.mulilinkVersions.push(mulilinkUrlVid);
400
- } else {
401
- this.mulilinkVersions = ab_version_multilink || [];
402
- }
403
-
404
- this.extVersions = ab_ext_version || [];
405
- this.versions = ab_version || [];
406
- this.data = data;
407
- var vids = this.versions.concat(this.extVersions);
408
-
409
- if (this.enable_multilink) {
410
- vids = vids.concat(this.mulilinkVersions);
411
- }
412
-
413
- this.configVersions(vids.join(','));
414
- };
415
-
416
- Ab.prototype.checkFromUrl = function () {
417
- var urlQueryObj = parseUrlQuery(window.location.href);
418
-
419
- if (urlQueryObj && urlQueryObj['vid']) {
420
- return urlQueryObj['vid'];
421
- }
422
-
423
- return '';
424
- };
425
-
426
- Ab.prototype.updateVersions = function () {
427
- var versions = this.extVersions.length ? this.versions.concat(this.extVersions) : this.versions;
428
-
429
- if (this.enable_multilink) {
430
- versions = versions.concat(this.mulilinkVersions);
431
- }
432
-
433
- this.configVersions(versions.join(','));
434
- this.updateABCache();
435
- this.changeListener.size > 0 && this.changeListener.forEach(function (listener) {
436
- if (typeof listener === 'function') {
437
- listener(versions);
438
- }
439
- });
440
- };
441
-
442
- Ab.prototype.configVersions = function (vids) {
443
- this.collect.configManager.setAbVersion(vids);
444
- };
445
-
446
- Ab.prototype.getVar = function (name, defaultValue, callback) {
447
- if (!name) {
448
- throw new Error('variable must not be empty');
449
- }
450
-
451
- if (defaultValue === undefined) {
452
- throw new Error('variable no default value');
453
- }
454
-
455
- if (typeof callback !== 'function') {
456
- throw new Error('callback must be a function');
457
- }
458
-
459
- var callbackObj = {
460
- name: name,
461
- defaultValue: defaultValue,
462
- callback: callback,
463
- type: CallbackType.Var
464
- };
465
-
466
- if (this.fetchStatus === 'complete' && this.refreshFetchStatus === 'complete') {
467
- this.getRealVar(callbackObj, name);
468
- } else {
469
- this.callbacks.push(callbackObj);
470
- }
471
- };
472
-
473
- Ab.prototype.getRealVar = function (item, key) {
474
- var name = item.name,
475
- defaultValue = item.defaultValue,
476
- callback = item.callback;
477
- var data = this.data;
478
-
479
- if (!data) {
480
- callback(defaultValue);
481
- return;
482
- }
483
-
484
- if (isObject(data[name])) {
485
- var vid = data[name].vid;
486
-
487
- if (key === '$ab_url') {
488
- if (!this.mulilinkVersions.includes(vid)) {
489
- this.mulilinkVersions.push(vid);
490
- }
491
- } else {
492
- if (!this.versions.includes(vid)) {
493
- this.versions.push(vid);
494
- }
495
- }
496
-
497
- this.updateVersions();
498
- this.fechEvent(vid, key, defaultValue);
499
- callback(data[name].val);
500
- this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
501
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
502
- secType: 'AB',
503
- info: "SDK \u66DD\u5149\u4E86\u5B9E\u9A8C" + name,
504
- level: 'info',
505
- time: Date.now(),
506
- data: data[name]
507
- });
508
- return;
509
- }
510
-
511
- this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
512
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
513
- secType: 'AB',
514
- info: 'SDK 调用getVar',
515
- level: 'info',
516
- time: Date.now(),
517
- data: defaultValue
518
- });
519
- callback(defaultValue);
520
- };
521
-
522
- Ab.prototype.getAllVars = function (callback) {
523
- if (typeof callback !== 'function') {
524
- throw new Error('callback must be a function');
525
- }
526
-
527
- var callbackObj = {
528
- callback: callback,
529
- type: CallbackType.All
530
- };
531
-
532
- if (this.fetchStatus === 'complete' && this.refreshFetchStatus === 'complete') {
533
- this.getRealAllVars(callbackObj);
534
- } else {
535
- this.callbacks.push(callbackObj);
536
- }
537
- };
538
-
539
- Ab.prototype.getRealAllVars = function (item) {
540
- var callback = item.callback;
541
- callback(this.data ? JSON.parse(JSON.stringify(this.data)) : {});
542
- this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
543
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
544
- secType: 'AB',
545
- info: 'SDK 调用getAllVars',
546
- level: 'info',
547
- time: Date.now(),
548
- data: this.data
549
- });
550
- };
551
-
552
- Ab.prototype.fechEvent = function (vid, key, ab_url) {
553
- try {
554
- if (this.config.disable_track_event) return;
555
- if (!vid) return;
556
-
557
- var _a = this.collect.configManager.get(),
558
- header = _a.header,
559
- user = _a.user;
560
-
561
- var cache = this.getABCache();
562
- if (cache && cache.uuid && cache.uuid !== user.user_unique_id) return;
563
- var event_1 = {
564
- event: 'abtest_exposure',
565
- ab_sdk_version: "" + vid,
566
- params: JSON.stringify({
567
- app_id: this.config.appId,
568
- ab_url: key === '$ab_url' ? ab_url : window.location.href
569
- }),
570
- local_time_ms: Date.now()
571
- };
572
- header['custom'] = JSON.stringify(header['custom']);
573
- var abData = {
574
- events: [event_1],
575
- user: user,
576
- header: header
577
- };
578
-
579
- if (key === '$ab_url') {
580
- if (window.navigator.sendBeacon) {
581
- window.navigator.sendBeacon(this.reportUrl, JSON.stringify([abData]));
582
- } else {
583
- this.reportExposure(abData);
584
- }
585
- } else {
586
- this.reportExposure(abData);
587
- }
588
- } catch (e) {
589
- this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
590
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
591
- info: '发生了异常',
592
- level: 'error',
593
- time: Date.now(),
594
- data: e.message
595
- });
596
- }
597
- };
598
-
599
- Ab.prototype.reportExposure = function (abData) {
600
- var _this = this;
601
-
602
- this.exposureCache.push(abData);
603
-
604
- if (this.reportTimeout) {
605
- clearTimeout(this.reportTimeout);
606
- }
607
-
608
- if (this.exposureCache.length >= this.exposureLimit) {
609
- this.report();
610
- } else {
611
- this.reportTimeout = setTimeout(function () {
612
- _this.report();
613
-
614
- clearTimeout(_this.reportTimeout);
615
- }, this.ab_batch_time);
616
- }
617
- };
618
-
619
- Ab.prototype.report = function () {
620
- var _this = this;
621
-
622
- var encodeData = this.collect.cryptoData(this.exposureCache);
623
- this.fetch(this.reportUrl, encodeData, 100000, false, function () {}, function () {}, '', 'POST', this.config.enable_encryption, this.config.encryption_header);
624
- this.exposureCache.forEach(function (item) {
625
- _this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
626
- type: DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,
627
- info: '埋点上报成功',
628
- time: Date.now(),
629
- data: [item],
630
- code: 200,
631
- status: 'success'
632
- });
633
- });
634
- this.exposureCache = [];
635
- };
636
-
637
- Ab.prototype.setExternalAbVersion = function (vid) {
638
- this.extVersions = [vid];
639
- this.updateVersions();
640
- };
641
-
642
- Ab.prototype.getABconfig = function (params, callback) {
643
- var keys = Object.keys(params);
644
-
645
- if (keys && keys.length) {
646
- this.collect.configManager.set(params);
647
- }
648
-
649
- this.fetchAB(callback);
650
- };
651
-
652
- Ab.prototype.get = function (key) {
653
- if (this.ab_cross) {
654
- var ab_cookie = this.cacheStorgae.getCookie(key, this.ab_cookie_domain);
655
- return ab_cookie ? JSON.parse(ab_cookie) : null;
656
- } else {
657
- return this.cacheStorgae.getItem(key);
658
- }
659
- };
660
-
661
- Ab.prototype.set = function (key, data) {
662
- if (this.ab_cross) {
663
- this.cacheStorgae.setCookie(key, data, STORAGE_EXPRIRE, this.ab_cookie_domain);
664
- } else {
665
- this.cacheStorgae.setItem(key, data);
666
- }
667
-
668
- this.collect.configManager.setAbCache(data);
669
- };
670
-
671
- Ab.prototype.getABCache = function (key) {
672
- var data = {
673
- ab_version: [],
674
- ab_ext_version: [],
675
- ab_version_multilink: [],
676
- data: null,
677
- timestamp: +new Date(),
678
- uuid: ''
679
- };
680
- data = this.get(this.abKey) || data;
681
-
682
- if (Date.now() - data.timestamp >= STORAGE_EXPRIRE) {
683
- this.cacheStorgae.removeItem(this.abKey);
684
- return null;
685
- }
686
-
687
- if (key) {
688
- return data[key];
689
- }
690
-
691
- return data;
692
- };
693
-
694
- Ab.prototype.updateABCache = function () {
695
- var cache = this.getABCache();
696
- cache.ab_version_multilink = this.mulilinkVersions;
697
- cache.ab_ext_version = this.extVersions;
698
- cache.ab_version = this.versions;
699
- cache.timestamp = Date.now();
700
- this.set(this.abKey, cache);
701
- };
702
-
703
- Ab.prototype.setAbCache = function (uuid) {
704
- var cache = this.getABCache();
705
- cache.data = this.data;
706
- cache.uuid = uuid;
707
- cache.timestamp = Date.now();
708
- this.set(this.abKey, cache);
709
- };
710
-
711
- Ab.prototype.clearCache = function () {
712
- this.refreshFetchStatus = 'ing';
713
- this.data = {};
714
- this.extVersions = [];
715
- this.mulilinkVersions = [];
716
- this.versions = [];
717
- this.collect.configManager.clearAbCache();
718
- };
719
-
720
- Ab.prototype.openOverlayer = function (timeout) {
721
- var _this = this;
722
-
723
- openOverlayer();
724
-
725
- if (timeout) {
726
- var layer_1 = setTimeout(function () {
727
- _this.closeOverlayer();
728
-
729
- clearTimeout(layer_1);
730
- }, timeout);
731
- }
732
- };
733
-
734
- Ab.prototype.closeOverlayer = function () {
735
- closeOverlayer();
736
- };
737
-
738
- Ab.prototype.fetchComplete = function (abData, uuid) {
739
- var _this = this;
740
-
741
- if (abData && Object.prototype.toString.call(abData) == '[object Object]') {
742
- this.data = abData;
743
- this.setAbCache(uuid);
744
- var versions_1 = [];
745
- Object.keys(abData).forEach(function (key) {
746
- var vid = abData[key].vid;
747
-
748
- if (vid) {
749
- versions_1.push(vid);
750
- }
751
- });
752
- this.versions = this.versions.filter(function (vid) {
753
- return versions_1.includes(vid);
754
- });
755
- var $ab_url = abData.$ab_url,
756
- $ab_modification = abData.$ab_modification;
757
-
758
- if ($ab_modification && $ab_modification.val && this.enable_ab_visual) {
759
- if (this.collect.destroyInstance) return;
760
- this.getVar('$ab_modification', window.location.href, function () {
761
- // loadVisual($ab_modification.val);
762
- _this.closeOverlayer();
763
- });
764
- } else if ($ab_url && this.enable_multilink) {
765
- this.mulilinkVersions = this.mulilinkVersions.filter(function (vid) {
766
- return versions_1.includes(vid);
767
- });
768
- var val_1 = $ab_url.val,
769
- vid_1 = $ab_url.vid;
770
-
771
- if (val_1 && vid_1) {
772
- this.getVar('$ab_url', val_1, function () {
773
- if (_this.editMode) return;
774
-
775
- if (val_1 !== window.location.href) {
776
- setTimeout(function () {
777
- if (_this.collect.destroyInstance) return;
778
- var jump = "" + val_1;
779
- jump = jump.indexOf('http') === -1 ? "https://" + jump : jump;
780
- var newhost = parseURL(jump).host;
781
-
782
- try {
783
- var urlObj = new URL(jump);
784
-
785
- if (newhost !== location.host) {
786
- // 跳转的是一个新域名
787
- urlObj.searchParams.append('vid', vid_1);
788
- } else {
789
- // 不同的域名不能replace
790
- window.history.replaceState('', '', jump);
791
- }
792
-
793
- window.location.href = urlObj.href;
794
- } catch (e) {
795
- window.location.href = jump;
796
- }
797
- }, 100);
798
- } else {
799
- _this.closeOverlayer();
800
- }
801
- });
802
- }
803
- }
804
-
805
- this.updateVersions();
806
- } else {
807
- this.closeOverlayer();
808
- }
809
-
810
- this.callbacks.forEach(function (item) {
811
- return _this[item.type === CallbackType.Var ? 'getRealVar' : 'getRealAllVars'](item, '');
812
- });
813
- this.callbacks = [];
814
- };
815
-
816
- Ab.prototype.fetchAB = function (callback) {
817
- var _this = this;
818
-
819
- var env = this.collect.configManager.get();
820
- var header = env.header,
821
- user = env.user;
822
-
823
- if (this.config.enable_anonymousid) {
824
- delete user.web_id;
825
- }
826
-
827
- var fetchUuid = user.user_unique_id;
828
- var requestBody = {
829
- header: __assign({
830
- aid: this.config.app_id
831
- }, user || {}, header || {}, {
832
- ab_sdk_version: this.collect.configManager.getAbVersion(),
833
- ab_url: window.location.href
834
- })
835
- };
836
- this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
837
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
838
- info: 'SDK 发起AB实验请求',
839
- level: 'info',
840
- logType: 'fetch',
841
- time: Date.now(),
842
- data: requestBody
843
- });
844
- var cryptoData = this.collect.cryptoData(requestBody);
845
- this.fetch(this.fetchUrl, cryptoData, this.config.ab_timeout || 3000, false, function (response) {
846
- _this.fetchStatus = 'complete';
847
- _this.refreshFetchStatus = 'complete'; // let aa = {
848
- // message: "success",
849
- // data: {
850
- // abcdefg: { val: "gss", vid: "11407" },
851
- // erf: { val: 'name', vid: "22" },
852
- // hhhhh: { val: 'age', vid: "33" },
853
- // juuioh: { val: 'sex', vid: "44" },
854
- // $ab_url: { val: 'http://0.0.0.0:8898/index_cdn_5.html?s=2', vid: '0000' }
855
- // }
856
- // }
857
- // if (env.user.user_unique_id === 'bbbb') {
858
- // aa.data.abcdefg.vid = '11408'
859
- // } else if (env.user.user_unique_id === 'cccc') {
860
- // aa.data.abcdefg.vid = '11409'
861
- // }
862
-
863
- var data = response.data,
864
- message = response.message; // 解析出code
865
-
866
- if (message === 'success') {
867
- _this.fetchComplete(data, fetchUuid);
868
-
869
- callback && callback(data);
870
- } else {
871
- _this.fetchComplete(null, fetchUuid);
872
-
873
- callback && callback(null);
874
- }
875
-
876
- _this.collect.emit(_this.types.AbComplete, data);
877
-
878
- _this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
879
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
880
- secType: 'AB',
881
- info: 'AB实验请求成功',
882
- level: 'info',
883
- logType: 'fetch',
884
- time: Date.now(),
885
- data: data
886
- });
887
- }, function () {
888
- _this.fetchStatus = 'complete';
889
- _this.refreshFetchStatus = 'complete';
890
-
891
- _this.fetchComplete(null, fetchUuid);
892
-
893
- callback && callback(null);
894
-
895
- _this.collect.emit(_this.types.AbTimeout);
896
-
897
- _this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
898
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
899
- secType: 'AB',
900
- info: 'AB实验请求网络异常',
901
- level: 'error',
902
- logType: 'fetch',
903
- time: Date.now()
904
- });
905
- }, '', '', this.config.enable_encryption, this.config.encryption_header);
906
- };
907
-
908
- Ab.prototype.filterUrl = function (url) {
909
- try {
910
- var _reg = '';
911
-
912
- if (url.indexOf('&multilink=true') !== -1) {
913
- _reg = '&multilink=true[\x00-\xff]*';
914
- } else if (url.indexOf('?multilink=true') !== -1) {
915
- _reg = '\\?multilink=true[\x00-\xff]*';
916
- }
917
-
918
- var reg = new RegExp(_reg, 'g');
919
- url = url.replace(reg, '');
920
- } catch (e) {}
921
-
922
- return url;
923
- };
924
-
925
- return Ab;
926
- }();
927
-
928
- export { Ab as default };
1
+ var e=function(){return e=Object.assign||function(e){for(var t,o=1,i=arguments.length;o<i;o++)for(var n in t=arguments[o])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},e.apply(this,arguments)},t="__rangers_ab_style__";var o,i,n={cn:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"};!function(e){e.Init="init",e.Config="config",e.Start="start",e.Ready="ready",e.TokenComplete="token-complete",e.TokenStorage="token-storage",e.TokenFetch="token-fetch",e.TokenError="token-error",e.ConfigUuid="config-uuid",e.ConfigWebId="config-webid",e.ConfigDomain="config-domain",e.CustomWebId="custom-webid",e.AnonymousId="anonymous-id",e.TokenChange="token-change",e.TokenReset="token-reset",e.ConfigTransform="config-transform",e.EnvTransform="env-transform",e.SessionReset="session-reset",e.SessionResetTime="session-reset-time",e.Event="event",e.Events="events",e.EventNow="event-now",e.CleanEvents="clean-events",e.BeconEvent="becon-event",e.SubmitBefore="submit-before",e.SubmitScuess="submit-scuess",e.SubmitSuccess="submit-success",e.SubmitAfter="submit-after",e.SubmitError="submit-error",e.SubmitVerifyH="submit-verify-h5",e.Stay="stay",e.ResetStay="reset-stay",e.StayReady="stay-ready",e.SetStay="set-stay",e.RouteChange="route-change",e.RouteReady="route-ready",e.Ab="ab",e.AbVar="ab-var",e.AbAllVars="ab-all-vars",e.AbConfig="ab-config",e.AbExternalVersion="ab-external-version",e.AbVersionChangeOn="ab-version-change-on",e.AbVersionChangeOff="ab-version-change-off",e.AbOpenLayer="ab-open-layer",e.AbCloseLayer="ab-close-layer",e.AbReady="ab-ready",e.AbComplete="ab-complete",e.AbTimeout="ab-timeout",e.Profile="profile",e.ProfileSet="profile-set",e.ProfileSetOnce="profile-set-once",e.ProfileUnset="profile-unset",e.ProfileIncrement="profile-increment",e.ProfileAppend="profile-append",e.ProfileClear="profile-clear",e.TrackDuration="track-duration",e.TrackDurationStart="track-duration-start",e.TrackDurationEnd="track-duration-end",e.TrackDurationPause="track-duration-pause",e.TrackDurationResume="tracl-duration-resume",e.Autotrack="autotrack",e.AutotrackReady="autotrack-ready",e.CustomHeader="custom-request-header",e.TracerReady="tracer-ready"}(o||(o={})),function(e){e.DEBUGGER_MESSAGE="debugger-message",e.DEBUGGER_MESSAGE_SDK="debugger-message-sdk",e.DEBUGGER_MESSAGE_FETCH="debugger-message-fetch",e.DEBUGGER_MESSAGE_FETCH_RESULT="debugger-message-fetch-result",e.DEBUGGER_MESSAGE_EVENT="debugger-message-event",e.DEVTOOL_WEB_READY="devtool-web-ready"}(i||(i={}));Date.now(),Number((""+Math.random()).slice(2,8));var r=function(e){return function(e,t,o){if("string"==typeof e&&"number"==typeof t&&"number"==typeof o){var i,n=[];o=o<=25?o:o%25;var r=String.fromCharCode(o+97);i=e.split(r);for(var a=0;a<i.length;a++){var s=parseInt(i[a],o);s=1*s^t;var c=String.fromCharCode(s);n.push(c)}return n.join("")}}(e,64,25)},a=function(e){var t=document.createElement("a");return t.href=e,t};var s,c,l,h=(s=function(e,t){var o;o=function(){function e(){for(var e=0,t={};e<arguments.length;e++){var o=arguments[e];for(var i in o)t[i]=o[i]}return t}function t(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function o(i){function n(){}function r(t,o,r){if("undefined"!=typeof document){"number"==typeof(r=e({path:"/"},n.defaults,r)).expires&&(r.expires=new Date(1*new Date+864e5*r.expires)),r.expires=r.expires?r.expires.toUTCString():"";try{var a=JSON.stringify(o);/^[\{\[]/.test(a)&&(o=a)}catch(e){}o=i.write?i.write(o,t):encodeURIComponent(String(o)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),t=encodeURIComponent(String(t)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var s="";for(var c in r)r[c]&&(s+="; "+c,!0!==r[c]&&(s+="="+r[c].split(";")[0]));return document.cookie=t+"="+o+s}}function a(e,o){if("undefined"!=typeof document){for(var n={},r=document.cookie?document.cookie.split("; "):[],a=0;a<r.length;a++){var s=r[a].split("="),c=s.slice(1).join("=");o||'"'!==c.charAt(0)||(c=c.slice(1,-1));try{var l=t(s[0]);if(c=(i.read||i)(c,l)||t(c),o)try{c=JSON.parse(c)}catch(e){}if(n[l]=c,e===l)break}catch(e){}}return e?n[e]:n}}return n.set=r,n.get=function(e){return a(e,!1)},n.getJSON=function(e){return a(e,!0)},n.remove=function(t,o){r(t,"",e(o,{expires:-1}))},n.defaults={},n.withConverter=o,n}(function(){})},e.exports=o()},s(c={exports:{}},c.exports),c.exports),u=function(){function e(){this.cache={}}return e.prototype.setItem=function(e,t){this.cache[e]=t},e.prototype.getItem=function(e){return this.cache[e]},e.prototype.removeItem=function(e){this.cache[e]=void 0},e}(),p=function(){function e(){this.support=this.isSupportLS()}return e.prototype.isSupportLS=function(){try{return localStorage.setItem("_applogtest-test-key","hi"),localStorage.getItem("_applogtest-test-key"),localStorage.removeItem("_applogtest-test-key"),!0}catch(e){return!1}},e.prototype.getItem=function(e){try{var t=localStorage.getItem(e),o=t;try{t&&"string"==typeof t&&(o=JSON.parse(t))}catch(e){}return o||{}}catch(e){}return{}},e.prototype.setItem=function(e,t){try{var o="string"==typeof t?t:JSON.stringify(t);localStorage.setItem(e,o)}catch(e){}},e.prototype.removeItem=function(e){try{localStorage.removeItem(e)}catch(e){}},e}(),f=function(){function e(){this.support=this.isSupportSession()}return e.prototype.isSupportSession=function(){try{return sessionStorage.setItem("_applogtest-test-key","hi"),sessionStorage.getItem("_applogtest-test-key"),sessionStorage.removeItem("_applogtest-test-key"),!0}catch(e){return!1}},e.prototype.getItem=function(e){try{var t=sessionStorage.getItem(e),o=t;try{t&&"string"==typeof t&&(o=JSON.parse(t))}catch(e){}return o||{}}catch(e){}return{}},e.prototype.setItem=function(e,t){try{var o="string"==typeof t?t:JSON.stringify(t);sessionStorage.setItem(e,o)}catch(e){}},e.prototype.removeItem=function(e){try{sessionStorage.removeItem(e)}catch(e){}},e}(),m=function(){function e(){this.defaultExpireTime=6048e5,this.local=new p,this.session=new f,this.cache=new u}return e.prototype.getLocalItem=function(e){return this.local.getItem(e)},e.prototype.setLocalItem=function(e,t){this.local.setItem(e,t)},e.prototype.removeLocalItem=function(e){this.local.removeItem(e)},e.prototype.getSessionItem=function(e){return this.session.getItem(e)},e.prototype.setSessionItem=function(e,t){this.session.setItem(e,t)},e.prototype.removeSessionItem=function(e){this.session.removeItem(e)},e.prototype.getCacheItem=function(e){return this.cache.getItem(e)},e.prototype.setCacheItem=function(e,t){this.cache.setItem(e,t)},e.prototype.removeCacheItem=function(e){this.cache.removeItem(e)},e.prototype.getCookie=function(e,t){try{return h.get(e)}catch(e){return""}},e.prototype.setCookie=function(e,t,o,i){void 0===o&&(o=this.defaultExpireTime);try{var n=i||document.domain,r=+new Date+o;h.set(e,t,{expires:new Date(r),path:"/",domain:n})}catch(e){}},e.prototype.removeCookie=function(e,t){try{h.remove(e,{path:"/",domain:t||""})}catch(e){}},e}();!function(e){e[e.Var=0]="Var",e[e.All=1]="All"}(l||(l={}));var y=2592e6,d=function(){function o(){this.fetchStatus="no",this.refreshFetchStatus="complete",this.versions=[],this.extVersions=[],this.mulilinkVersions=[],this.enable_multilink=!1,this.enable_ab_visual=!1,this.editMode=!1,this.callbacks=[],this.data=null,this.changeListener=new Map,this.readyStatus=!1,this.exposureCache=[]}return o.prototype.apply=function(e,t){var o=this;if(this.collect=e,this.config=t,this.config.enable_ab_test){var i=t.enable_multilink,a=t.ab_channel_domain,s=t.enable_ab_visual,c=t.ab_cross,l=t.ab_cookie_domain,h=t.disable_ab_reset,u=a||r(n[t.channel||"cn"]);this.cacheStorgae=new m,this.enable_multilink=i,this.enable_ab_visual=s,this.abKey="__tea_sdk_ab_version_"+t.app_id,this.ab_cross=c,this.ab_cookie_domain=l||"",this.fetchUrl=u+"/service/2/abtest_config/",this.reportUrl=""+e.configManager.getUrl("event"),this.exposureLimit=t.exposure_limit||20,this.ab_batch_time=t.ab_batch_time||500;var p=this.collect.Types;this.types=p,this.collect.on(p.TokenChange,function(e){h||"uuid"===e.type&&o.readyStatus&&(o.clearCache(),o.fetchAB())}),this.collect.on(p.TokenReset,function(){h||o.readyStatus&&(o.clearCache(),o.fetchAB())}),this.collect.on(p.AbVar,function(e){var t=e.name,i=e.defaultValue,n=e.callback;o.getVar(t,i,n)}),this.collect.on(p.AbAllVars,function(e){o.getAllVars(e)}),this.collect.on(p.AbConfig,function(e){var t=e.params,i=e.callback;o.getABconfig(t,i)}),this.collect.on(p.AbExternalVersion,function(e){o.setExternalAbVersion(e)}),this.collect.on(p.AbOpenLayer,function(){o.openOverlayer()}),this.collect.on(p.AbCloseLayer,function(){o.closeOverlayer()}),this.collect.on(p.AbVersionChangeOn,function(e){o.changeListener.set(e,e)}),this.collect.on(p.AbVersionChangeOff,function(e){o.changeListener.get(e)&&o.changeListener.delete(e)}),this.loadMode(),(this.enable_ab_visual||this.enable_multilink)&&this.openOverlayer(this.config.multilink_timeout_ms||500),this.checkLocal(),this.ready("ab"),this.readyStatus||(this.fetchAB(),this.readyStatus=!0),this.collect.emit(p.AbReady)}},o.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var o=this.collect.hook._hooksCache[e];if(!Object.keys(o).length)return;var i=function(e){o[e].length&&o[e].forEach(function(o){t.collect.hook.emit(e,o)})};for(var n in o)i(n)}},o.prototype.loadMode=function(){},o.prototype.checkLocal=function(){var e=this.getABCache(),t=e.ab_version,o=e.ab_ext_version,i=e.ab_version_multilink,n=e.data,r=this.checkFromUrl();r?this.mulilinkVersions.push(r):this.mulilinkVersions=i||[],this.extVersions=o||[],this.versions=t||[],this.data=n;var a=this.versions.concat(this.extVersions);this.enable_multilink&&(a=a.concat(this.mulilinkVersions)),this.configVersions(a.join(","))},o.prototype.checkFromUrl=function(){var e=function(e){var t={};try{var o=a(e).search;(o=o.slice(1)).split("&").forEach(function(e){var o,i,n=e.split("=");n.length&&(o=n[0],i=n[1]);try{t[o]=decodeURIComponent(void 0===i?"":i)}catch(e){t[o]=i}})}catch(e){}return t}(window.location.href);return e&&e.vid?e.vid:""},o.prototype.updateVersions=function(){var e=this.extVersions.length?this.versions.concat(this.extVersions):this.versions;this.enable_multilink&&(e=e.concat(this.mulilinkVersions)),this.configVersions(e.join(",")),this.updateABCache(),this.changeListener.size>0&&this.changeListener.forEach(function(t){"function"==typeof t&&t(e)})},o.prototype.configVersions=function(e){this.collect.configManager.setAbVersion(e)},o.prototype.getVar=function(e,t,o){if(!e)throw new Error("variable must not be empty");if(void 0===t)throw new Error("variable no default value");if("function"!=typeof o)throw new Error("callback must be a function");var i={name:e,defaultValue:t,callback:o,type:l.Var};"complete"===this.fetchStatus&&"complete"===this.refreshFetchStatus?this.getRealVar(i,e):this.callbacks.push(i)},o.prototype.getRealVar=function(e,t){var o=e.name,n=e.defaultValue,r=e.callback,a=this.data;if(a){if(null!=(c=a[o])&&"[object Object]"==Object.prototype.toString.call(c)){var s=a[o].vid;return"$ab_url"===t?this.mulilinkVersions.includes(s)||this.mulilinkVersions.push(s):this.versions.includes(s)||this.versions.push(s),this.updateVersions(),this.fechEvent(s,t,n),r(a[o].val),void this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 曝光了实验"+o,level:"info",time:Date.now(),data:a[o]})}var c;this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 调用getVar",level:"info",time:Date.now(),data:n}),r(n)}else r(n)},o.prototype.getAllVars=function(e){if("function"!=typeof e)throw new Error("callback must be a function");var t={callback:e,type:l.All};"complete"===this.fetchStatus&&"complete"===this.refreshFetchStatus?this.getRealAllVars(t):this.callbacks.push(t)},o.prototype.getRealAllVars=function(e){(0,e.callback)(this.data?JSON.parse(JSON.stringify(this.data)):{}),this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 调用getAllVars",level:"info",time:Date.now(),data:this.data})},o.prototype.fechEvent=function(e,t,o){try{if(this.config.disable_track_event)return;if(!e)return;var n=this.collect.configManager.get(),r=n.header,a=n.user,s=this.getABCache();if(s&&s.uuid&&s.uuid!==a.user_unique_id)return;var c={event:"abtest_exposure",ab_sdk_version:""+e,params:JSON.stringify({app_id:this.config.appId,ab_url:"$ab_url"===t?o:window.location.href}),local_time_ms:Date.now()};r.custom=JSON.stringify(r.custom);var l={events:[c],user:a,header:r};"$ab_url"===t&&window.navigator.sendBeacon?window.navigator.sendBeacon(this.reportUrl,JSON.stringify([l])):this.reportExposure(l)}catch(e){this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:e.message})}},o.prototype.reportExposure=function(e){var t=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report():this.reportTimeout=setTimeout(function(){t.report(),clearTimeout(t.reportTimeout)},this.ab_batch_time)},o.prototype.report=function(){var e=this,t=this.collect.cryptoData(this.exposureCache);this.collect.requestManager.useRequest({url:this.reportUrl,data:t,timeout:1e5,useBeacon:!1,encryption:this.config.enable_encryption,encryption_header:this.config.encryption_header,zip:!0,type:"event"}),this.exposureCache.forEach(function(t){e.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:[t],code:200,status:"success"})}),this.exposureCache=[]},o.prototype.setExternalAbVersion=function(e){this.extVersions=[e],this.updateVersions()},o.prototype.getABconfig=function(e,t){var o=Object.keys(e);o&&o.length&&this.collect.configManager.set(e),this.fetchAB(t)},o.prototype.get=function(e){if(this.ab_cross){var t=this.cacheStorgae.getCookie(e,this.ab_cookie_domain);return t?JSON.parse(t):null}return this.cacheStorgae.getLocalItem(e)},o.prototype.set=function(e,t){this.ab_cross?this.cacheStorgae.setCookie(e,t,y,this.ab_cookie_domain):this.cacheStorgae.setLocalItem(e,t),this.collect.configManager.setAbCache(t)},o.prototype.getABCache=function(e){var t={ab_version:[],ab_ext_version:[],ab_version_multilink:[],data:null,timestamp:+new Date,uuid:""};return t=this.get(this.abKey)||t,Date.now()-t.timestamp>=y?(this.cacheStorgae.removeLocalItem(this.abKey),null):e?t[e]:t},o.prototype.updateABCache=function(){var e=this.getABCache();e.ab_version_multilink=this.mulilinkVersions,e.ab_ext_version=this.extVersions,e.ab_version=this.versions,e.timestamp=Date.now(),this.set(this.abKey,e)},o.prototype.setAbCache=function(e){var t=this.getABCache();t.data=this.data,t.uuid=e,t.timestamp=Date.now(),this.set(this.abKey,t)},o.prototype.clearCache=function(){this.refreshFetchStatus="ing",this.data={},this.extVersions=[],this.mulilinkVersions=[],this.versions=[],this.collect.configManager.clearAbCache()},o.prototype.openOverlayer=function(e){var o=this;if(function(){if(!document.getElementById(t)){var e="body { opacity: 0 !important; }",o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.id=t,i.type="text/css",i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),o.appendChild(i)}}(),e)var i=setTimeout(function(){o.closeOverlayer(),clearTimeout(i)},e)},o.prototype.closeOverlayer=function(){var e;(e=document.getElementById(t))&&e.parentElement.removeChild(e)},o.prototype.fetchComplete=function(e,t){var o=this;if(e&&"[object Object]"==Object.prototype.toString.call(e)){this.data=e,this.setAbCache(t);var i=[];Object.keys(e).forEach(function(t){var o=e[t].vid;o&&i.push(o)}),this.versions=this.versions.filter(function(e){return i.includes(e)});var n=e.$ab_url,r=e.$ab_modification;if(r&&r.val&&this.enable_ab_visual){if(this.collect.destroyInstance)return;this.getVar("$ab_modification",window.location.href,function(){o.closeOverlayer()})}else if(n&&this.enable_multilink){this.mulilinkVersions=this.mulilinkVersions.filter(function(e){return i.includes(e)});var s=n.val,c=n.vid;s&&c&&this.getVar("$ab_url",s,function(){o.editMode||(s!==window.location.href?setTimeout(function(){if(!o.collect.destroyInstance){var e=""+s;e=-1===e.indexOf("http")?"https://"+e:e;var t=a(e).host;try{var i=new URL(e);t!==location.host?i.searchParams.append("vid",c):window.history.replaceState("","",e),window.location.href=i.href}catch(t){window.location.href=e}}},100):o.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbacks.forEach(function(e){return o[e.type===l.Var?"getRealVar":"getRealAllVars"](e,"")}),this.callbacks=[]},o.prototype.fetchAB=function(t){var o=this,n=this.collect.configManager.get(),r=n.header,a=n.user;this.config.enable_anonymousid&&delete a.web_id;var s=a.user_unique_id,c={header:e({aid:this.config.app_id},a||{},r||{},{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})},l=this.collect.cryptoData(c);this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,info:"SDK 发起AB实验请求",level:"info",logType:"fetch",time:Date.now(),data:c,infoType:"sdk"}),this.collect.requestManager.useRequest({url:this.fetchUrl,data:l,success:function(e){o.fetchStatus="complete",o.refreshFetchStatus="complete";var n=e.data;"success"===e.message?(o.fetchComplete(n,s),t&&t(n)):(o.fetchComplete(null,s),t&&t(null)),o.collect.emit(o.types.AbComplete,n),o.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"AB实验请求成功",level:"info",logType:"fetch",time:Date.now(),data:n,infoType:"sdk"})},fail:function(){o.fetchStatus="complete",o.refreshFetchStatus="complete",o.fetchComplete(null,s),t&&t(null),o.collect.emit(o.types.AbTimeout),o.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"AB实验请求网络异常",level:"error",logType:"fetch",time:Date.now(),infoType:"sdk"})},timeout:this.config.ab_timeout||1e4,encryption:this.config.enable_encryption,encryption_header:this.config.encryption_header})},o.prototype.filterUrl=function(e){try{var t="";-1!==e.indexOf("&multilink=true")?t="&multilink=true[\0-ÿ]*":-1!==e.indexOf("?multilink=true")&&(t="\\?multilink=true[\0-ÿ]*");var o=new RegExp(t,"g");e=e.replace(o,"")}catch(e){}return e},o}();export{d as default};