@traffical/js-client 0.15.0 → 0.16.0
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/README.md +8 -2
- package/dist/client.d.ts +83 -13
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +255 -60
- package/dist/client.js.map +1 -1
- package/dist/event-logger.d.ts +29 -0
- package/dist/event-logger.d.ts.map +1 -1
- package/dist/event-logger.js +64 -4
- package/dist/event-logger.js.map +1 -1
- package/dist/plugins/decision-tracking.d.ts +7 -0
- package/dist/plugins/decision-tracking.d.ts.map +1 -1
- package/dist/plugins/decision-tracking.js +3 -0
- package/dist/plugins/decision-tracking.js.map +1 -1
- package/dist/plugins/warehouse-native-logger.d.ts.map +1 -1
- package/dist/plugins/warehouse-native-logger.js +4 -0
- package/dist/plugins/warehouse-native-logger.js.map +1 -1
- package/dist/traffical.min.js +2 -2
- package/dist/traffical.min.js.map +3 -3
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +5 -5
package/dist/event-logger.d.ts
CHANGED
|
@@ -24,6 +24,11 @@ export interface EventLoggerOptions {
|
|
|
24
24
|
batchSize?: number;
|
|
25
25
|
/** Auto-flush interval in ms (default: 30000) */
|
|
26
26
|
flushIntervalMs?: number;
|
|
27
|
+
/**
|
|
28
|
+
* Maximum number of events buffered in memory before the oldest is dropped
|
|
29
|
+
* (default: 1000). Bounds memory so the queue never grows without limit.
|
|
30
|
+
*/
|
|
31
|
+
maxQueueSize?: number;
|
|
27
32
|
/**
|
|
28
33
|
* Timeout in ms for the event batch POST (default: 10000).
|
|
29
34
|
* On timeout the request is aborted and treated like a failed send:
|
|
@@ -42,12 +47,17 @@ export declare class EventLogger {
|
|
|
42
47
|
private _batchSize;
|
|
43
48
|
private _flushIntervalMs;
|
|
44
49
|
private _requestTimeoutMs;
|
|
50
|
+
private _maxQueueSize;
|
|
45
51
|
private _onError?;
|
|
46
52
|
private _onSchemaWarnings?;
|
|
47
53
|
private _lifecycleProvider?;
|
|
48
54
|
private _queue;
|
|
49
55
|
private _flushTimer;
|
|
50
56
|
private _isFlushing;
|
|
57
|
+
/** Permanently true after an HTTP 401 kill-switch fires. */
|
|
58
|
+
private _isDisabled;
|
|
59
|
+
/** Count of events dropped because the bounded queue overflowed. */
|
|
60
|
+
private _droppedCount;
|
|
51
61
|
private _visibilityCallback?;
|
|
52
62
|
constructor(options: EventLoggerOptions);
|
|
53
63
|
/**
|
|
@@ -56,8 +66,22 @@ export declare class EventLogger {
|
|
|
56
66
|
log(event: TrackableEvent): void;
|
|
57
67
|
/**
|
|
58
68
|
* Flush all queued events immediately.
|
|
69
|
+
*
|
|
70
|
+
* Delivery outcomes:
|
|
71
|
+
* - 2xx: delivered.
|
|
72
|
+
* - Network error / timeout / 429 / 5xx: transient — events persisted for
|
|
73
|
+
* retry on the next session/visibility change.
|
|
74
|
+
* - HTTP 401: auth kill-switch — delivery is permanently disabled, the queue
|
|
75
|
+
* and any persisted failed events are cleared.
|
|
76
|
+
* - Other 4xx: permanent rejection — the batch is dropped.
|
|
59
77
|
*/
|
|
60
78
|
flush(): Promise<void>;
|
|
79
|
+
/** Permanently disable delivery after a 401 and clear all buffered events. */
|
|
80
|
+
private _disable;
|
|
81
|
+
/** Number of events dropped because the bounded queue overflowed. */
|
|
82
|
+
get droppedCount(): number;
|
|
83
|
+
/** True once an HTTP 401 permanently disabled delivery. */
|
|
84
|
+
get isDisabled(): boolean;
|
|
61
85
|
/**
|
|
62
86
|
* Flush using fetch with keepalive (for page unload).
|
|
63
87
|
*
|
|
@@ -77,6 +101,11 @@ export declare class EventLogger {
|
|
|
77
101
|
* Destroy the logger (cleanup timers and listeners).
|
|
78
102
|
*/
|
|
79
103
|
destroy(): void;
|
|
104
|
+
/**
|
|
105
|
+
* Sends one batch and returns the HTTP status code. Throws only on a
|
|
106
|
+
* transport-level failure (network error / abort), which the caller treats
|
|
107
|
+
* as a transient error. HTTP status classification is done by the caller.
|
|
108
|
+
*/
|
|
80
109
|
private _sendEvents;
|
|
81
110
|
private _persistFailedEvents;
|
|
82
111
|
private _retryFailedEvents;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-logger.d.ts","sourceRoot":"","sources":["../src/event-logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAsB,MAAM,iBAAiB,CAAC;AAC5F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,KAAK,EAAE,iBAAiB,EAAmB,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"event-logger.d.ts","sourceRoot":"","sources":["../src/event-logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAsB,MAAM,iBAAiB,CAAC;AAC5F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,KAAK,EAAE,iBAAiB,EAAmB,MAAM,gBAAgB,CAAC;AASzE,MAAM,WAAW,kBAAkB;IACjC,8BAA8B;IAC9B,QAAQ,EAAE,MAAM,CAAC;IACjB,iCAAiC;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,yCAAyC;IACzC,OAAO,EAAE,eAAe,CAAC;IACzB,sDAAsD;IACtD,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iDAAiD;IACjD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,8BAA8B;IAC9B,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,gBAAgB,CAAC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-13,17 +13,23 @@ const DEFAULT_BATCH_SIZE = 10;
|
|
|
13
13
|
const DEFAULT_FLUSH_INTERVAL_MS = 30000; // 30 seconds
|
|
14
14
|
const DEFAULT_REQUEST_TIMEOUT_MS = 10000; // 10 seconds
|
|
15
15
|
const MAX_FAILED_EVENTS = 100;
|
|
16
|
+
const DEFAULT_MAX_QUEUE_SIZE = 1000; // bounded in-memory queue; overflow drops oldest
|
|
16
17
|
export class EventLogger {
|
|
17
18
|
constructor(options) {
|
|
18
19
|
this._queue = [];
|
|
19
20
|
this._flushTimer = null;
|
|
20
21
|
this._isFlushing = false;
|
|
22
|
+
/** Permanently true after an HTTP 401 kill-switch fires. */
|
|
23
|
+
this._isDisabled = false;
|
|
24
|
+
/** Count of events dropped because the bounded queue overflowed. */
|
|
25
|
+
this._droppedCount = 0;
|
|
21
26
|
this._endpoint = options.endpoint;
|
|
22
27
|
this._apiKey = options.apiKey;
|
|
23
28
|
this._storage = options.storage;
|
|
24
29
|
this._batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
25
30
|
this._flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
|
|
26
31
|
this._requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
32
|
+
this._maxQueueSize = options.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE;
|
|
27
33
|
this._onError = options.onError;
|
|
28
34
|
this._onSchemaWarnings = options.onSchemaWarnings;
|
|
29
35
|
this._lifecycleProvider = options.lifecycleProvider;
|
|
@@ -37,6 +43,14 @@ export class EventLogger {
|
|
|
37
43
|
* Log an event (added to batch queue).
|
|
38
44
|
*/
|
|
39
45
|
log(event) {
|
|
46
|
+
// Delivery permanently disabled (401) — stop buffering entirely.
|
|
47
|
+
if (this._isDisabled)
|
|
48
|
+
return;
|
|
49
|
+
// Bounded queue: drop the oldest event on overflow.
|
|
50
|
+
if (this._queue.length >= this._maxQueueSize) {
|
|
51
|
+
this._queue.shift();
|
|
52
|
+
this._droppedCount++;
|
|
53
|
+
}
|
|
40
54
|
this._queue.push(event);
|
|
41
55
|
// Auto-flush if batch is full
|
|
42
56
|
if (this._queue.length >= this._batchSize) {
|
|
@@ -45,9 +59,17 @@ export class EventLogger {
|
|
|
45
59
|
}
|
|
46
60
|
/**
|
|
47
61
|
* Flush all queued events immediately.
|
|
62
|
+
*
|
|
63
|
+
* Delivery outcomes:
|
|
64
|
+
* - 2xx: delivered.
|
|
65
|
+
* - Network error / timeout / 429 / 5xx: transient — events persisted for
|
|
66
|
+
* retry on the next session/visibility change.
|
|
67
|
+
* - HTTP 401: auth kill-switch — delivery is permanently disabled, the queue
|
|
68
|
+
* and any persisted failed events are cleared.
|
|
69
|
+
* - Other 4xx: permanent rejection — the batch is dropped.
|
|
48
70
|
*/
|
|
49
71
|
async flush() {
|
|
50
|
-
if (this._isFlushing || this._queue.length === 0) {
|
|
72
|
+
if (this._isFlushing || this._isDisabled || this._queue.length === 0) {
|
|
51
73
|
return;
|
|
52
74
|
}
|
|
53
75
|
this._isFlushing = true;
|
|
@@ -55,10 +77,25 @@ export class EventLogger {
|
|
|
55
77
|
const events = [...this._queue];
|
|
56
78
|
this._queue = [];
|
|
57
79
|
try {
|
|
58
|
-
await this._sendEvents(events);
|
|
80
|
+
const status = await this._sendEvents(events);
|
|
81
|
+
if (status >= 200 && status < 300) {
|
|
82
|
+
return; // delivered
|
|
83
|
+
}
|
|
84
|
+
if (status === 401) {
|
|
85
|
+
this._disable(); // auth kill-switch
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (status === 429 || status >= 500) {
|
|
89
|
+
// Transient — persist for retry.
|
|
90
|
+
this._persistFailedEvents(events);
|
|
91
|
+
this._onError?.(new Error(`HTTP ${status}: event delivery failed, will retry`));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
// Other 4xx — permanent rejection; drop the batch.
|
|
95
|
+
this._onError?.(new Error(`HTTP ${status}: batch rejected, dropping ${events.length} events`));
|
|
59
96
|
}
|
|
60
97
|
catch (error) {
|
|
61
|
-
//
|
|
98
|
+
// Network error / abort (timeout) — transient, persist for retry.
|
|
62
99
|
this._persistFailedEvents(events);
|
|
63
100
|
this._onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
64
101
|
}
|
|
@@ -66,6 +103,23 @@ export class EventLogger {
|
|
|
66
103
|
this._isFlushing = false;
|
|
67
104
|
}
|
|
68
105
|
}
|
|
106
|
+
/** Permanently disable delivery after a 401 and clear all buffered events. */
|
|
107
|
+
_disable() {
|
|
108
|
+
if (this._isDisabled)
|
|
109
|
+
return;
|
|
110
|
+
this._isDisabled = true;
|
|
111
|
+
this._queue = [];
|
|
112
|
+
this._storage.remove(FAILED_EVENTS_KEY);
|
|
113
|
+
console.warn("[Traffical] API key rejected (HTTP 401); event delivery disabled for this client");
|
|
114
|
+
}
|
|
115
|
+
/** Number of events dropped because the bounded queue overflowed. */
|
|
116
|
+
get droppedCount() {
|
|
117
|
+
return this._droppedCount;
|
|
118
|
+
}
|
|
119
|
+
/** True once an HTTP 401 permanently disabled delivery. */
|
|
120
|
+
get isDisabled() {
|
|
121
|
+
return this._isDisabled;
|
|
122
|
+
}
|
|
69
123
|
/**
|
|
70
124
|
* Flush using fetch with keepalive (for page unload).
|
|
71
125
|
*
|
|
@@ -121,6 +175,11 @@ export class EventLogger {
|
|
|
121
175
|
}
|
|
122
176
|
this._removeListeners();
|
|
123
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Sends one batch and returns the HTTP status code. Throws only on a
|
|
180
|
+
* transport-level failure (network error / abort), which the caller treats
|
|
181
|
+
* as a transient error. HTTP status classification is done by the caller.
|
|
182
|
+
*/
|
|
124
183
|
async _sendEvents(events) {
|
|
125
184
|
// Abort the request if the edge hangs so the flush settles and events
|
|
126
185
|
// go down the persist-for-retry path (same as any network failure).
|
|
@@ -142,7 +201,7 @@ export class EventLogger {
|
|
|
142
201
|
clearTimeout(timeoutId);
|
|
143
202
|
}
|
|
144
203
|
if (!response.ok) {
|
|
145
|
-
|
|
204
|
+
return response.status;
|
|
146
205
|
}
|
|
147
206
|
if (this._onSchemaWarnings) {
|
|
148
207
|
try {
|
|
@@ -155,6 +214,7 @@ export class EventLogger {
|
|
|
155
214
|
// Response parsing is best-effort for dev-mode warnings
|
|
156
215
|
}
|
|
157
216
|
}
|
|
217
|
+
return response.status;
|
|
158
218
|
}
|
|
159
219
|
_persistFailedEvents(events) {
|
|
160
220
|
const existing = this._storage.get(FAILED_EVENTS_KEY) ?? [];
|
package/dist/event-logger.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-logger.js","sourceRoot":"","sources":["../src/event-logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH,MAAM,iBAAiB,GAAG,eAAe,CAAC;AAC1C,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,yBAAyB,GAAG,KAAM,CAAC,CAAC,aAAa;AACvD,MAAM,0BAA0B,GAAG,KAAM,CAAC,CAAC,aAAa;AACxD,MAAM,iBAAiB,GAAG,GAAG,CAAC;
|
|
1
|
+
{"version":3,"file":"event-logger.js","sourceRoot":"","sources":["../src/event-logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH,MAAM,iBAAiB,GAAG,eAAe,CAAC;AAC1C,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,yBAAyB,GAAG,KAAM,CAAC,CAAC,aAAa;AACvD,MAAM,0BAA0B,GAAG,KAAM,CAAC,CAAC,aAAa;AACxD,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,sBAAsB,GAAG,IAAK,CAAC,CAAC,iDAAiD;AAgCvF,MAAM,OAAO,WAAW;IAqBtB,YAAY,OAA2B;QAT/B,WAAM,GAAqB,EAAE,CAAC;QAC9B,gBAAW,GAAyC,IAAI,CAAC;QACzD,gBAAW,GAAG,KAAK,CAAC;QAC5B,4DA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|
|
|
43
43
|
* This is typically the EventLogger.log() method.
|
|
44
44
|
*/
|
|
45
45
|
log: (event: DecisionEvent) => void;
|
|
46
|
+
/**
|
|
47
|
+
* Returns the CURRENT config bundle version. Used only as a fallback for
|
|
48
|
+
* `configVersion` when the decision metadata lacks a decision-time
|
|
49
|
+
* snapshot (e.g. decisions produced by an older core).
|
|
50
|
+
* This is typically the client's getConfigVersion() method.
|
|
51
|
+
*/
|
|
52
|
+
getConfigVersion?: () => string | null;
|
|
46
53
|
}
|
|
47
54
|
/**
|
|
48
55
|
* Creates a DecisionTrackingPlugin instance.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decision-tracking.d.ts","sourceRoot":"","sources":["../../src/plugins/decision-tracking.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAClD,OAAO,KAAK,EAAkB,aAAa,EAAkB,MAAM,iBAAiB,CAAC;AAMrF;;GAEG;AACH,MAAM,WAAW,6BAA6B;IAC5C;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC,sBAAsB;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,iBAAiB;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,kBAAkB;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,GAAG,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"decision-tracking.d.ts","sourceRoot":"","sources":["../../src/plugins/decision-tracking.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAClD,OAAO,KAAK,EAAkB,aAAa,EAAkB,MAAM,iBAAiB,CAAC;AAMrF;;GAEG;AACH,MAAM,WAAW,6BAA6B;IAC5C;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC,sBAAsB;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,iBAAiB;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,kBAAkB;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,GAAG,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,IAAI,CAAC;IACpC;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;CACxC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,6BAA6B,EACtC,IAAI,EAAE,0BAA0B,GAC/B,eAAe,CA4DjB"}
|
|
@@ -68,6 +68,9 @@ export function createDecisionTrackingPlugin(options, deps) {
|
|
|
68
68
|
layers: decision.metadata.layers,
|
|
69
69
|
// Include filtered context if available (for contextual bandit training)
|
|
70
70
|
context: decision.metadata.filteredContext,
|
|
71
|
+
// Config bundle version the SDK evaluated against — from the
|
|
72
|
+
// decision-time snapshot, falling back to the current version.
|
|
73
|
+
configVersion: decision.metadata.configVersion ?? deps.getConfigVersion?.() ?? undefined,
|
|
71
74
|
sdkName: SDK_NAME,
|
|
72
75
|
sdkVersion: SDK_VERSION,
|
|
73
76
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decision-tracking.js","sourceRoot":"","sources":["../../src/plugins/decision-tracking.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,MAAM,QAAQ,GAA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,CAC/C,OAAO,EAAE,4BAA4B,GACpC,gBAAgB,CAElB"}
|
|
@@ -29,6 +29,10 @@ function toAssignmentProps(entry) {
|
|
|
29
29
|
decision_id: entry.decisionId,
|
|
30
30
|
anonymous_id: entry.anonymousId,
|
|
31
31
|
assignment_id: entry.id,
|
|
32
|
+
bucket: entry.bucket,
|
|
33
|
+
propensity: entry.probability,
|
|
34
|
+
model_version: entry.modelVersion,
|
|
35
|
+
config_version: entry.configVersion,
|
|
32
36
|
...entry.properties,
|
|
33
37
|
};
|
|
34
38
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"warehouse-native-logger.js","sourceRoot":"","sources":["../../src/plugins/warehouse-native-logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AA2DH,MAAM,6BAA6B,GAAG,uBAAuB,CAAC;AAE9D,sFAAsF;AACtF,SAAS,iBAAiB,CAAC,KAAyB;IAClD,OAAO;QACL,QAAQ,EAAE,KAAK,CAAC,OAAO;QACvB,SAAS,EAAE,KAAK,CAAC,QAAQ;QACzB,eAAe,EAAE,KAAK,CAAC,cAAc;QACrC,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,QAAQ,EAAE,KAAK,CAAC,OAAO;QACvB,aAAa,EAAE,KAAK,CAAC,YAAY;QACjC,MAAM,EAAE,KAAK,CAAC,KAAK;QACnB,UAAU,EAAE,KAAK,CAAC,SAAS;QAC3B,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,WAAW,EAAE,KAAK,CAAC,UAAU;QAC7B,YAAY,EAAE,KAAK,CAAC,WAAW;QAC/B,aAAa,EAAE,KAAK,CAAC,EAAE;QACvB,GAAG,KAAK,CAAC,UAAU;KACpB,CAAC;AACJ,CAAC;AAED,uDAAuD;AACvD,SAAS,gBAAgB,CAAC,KAAqB;IAC7C,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACnB,KAAK,UAAU;YACb,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,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE,CACrB,IAAI,CACF,aAAa,CACX,OAAO,CAAC,KAAK,CAAC,EACd,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,SAAS,EAAE,KAAK,CAAC,EAAE,EAAE,SAAS,EAAE,KAAK,CAAC,SAAS,EAAE,EAC3E,YAAY,CAAC,KAAK,CAAC,CACpB,CACF;SACJ,CAAC;IACJ,CAAC;IAED,wBAAwB;IACxB,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;IACjC,OAAO;QACL,gBAAgB,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,mBAAmB,EAAE,iBAAiB,CAAC,KAAK,CAAC,CAAC;QAC3F,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC;KAC7E,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,iCAAiC,CAC/C,OAAqC;IAErC,OAAO,2BAA2B,CAAC,OAAO,CAAC,CAAC,gBAAgB,CAAC;AAC/D,CAAC"}
|
package/dist/traffical.min.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
/* @traffical/js-client v0.
|
|
2
|
-
"use strict";var Traffical=(()=>{var H=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var et=(r,e,t)=>e in r?H(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var tt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),nt=(r,e)=>{for(var t in e)H(r,t,{get:e[t],enumerable:!0})},it=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Qe(e))!Ze.call(r,i)&&i!==t&&H(r,i,{get:()=>e[i],enumerable:!(n=Ye(e,i))||n.enumerable});return r};var rt=r=>it(H({},"__esModule",{value:!0}),r);var h=(r,e,t)=>(et(r,typeof e!="symbol"?e+"":e,t),t);var Ke=tt(()=>{});var dn={};nt(dn,{TrafficalClient:()=>P,createDOMBindingPlugin:()=>Je,createDebugPlugin:()=>Ce,createRedirectAttributionPlugin:()=>Se,createRedirectPlugin:()=>ke,destroy:()=>un,init:()=>an,initSync:()=>cn,instance:()=>ln});function ot(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function le(r,e,t=""){let n=ot(r),i=r?.length,o=e!==void 0;if(!n||o&&i!==e){let s=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof r}`,g=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(g):new TypeError(g)}return r}function ue(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Pe(r,e){le(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function R(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function W(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function T(r,e){return r<<32-e|r>>>e}function Re(r,e={}){let t=(i,o)=>r(o).update(i).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=i=>r(i),Object.assign(t,e),Object.freeze(t)}var Le=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Oe(r,e,t){return r&e^~r&t}function Me(r,e,t){return r&e^r&t^e&t}var G=class{constructor(e,t,n,i){h(this,"blockLen");h(this,"outputLen");h(this,"canXOF",!1);h(this,"padOffset");h(this,"isLE");h(this,"buffer");h(this,"view");h(this,"finished",!1);h(this,"length",0);h(this,"pos",0);h(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=W(this.buffer)}update(e){ue(this),le(e);let{view:t,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=W(e);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ue(this),Pe(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,R(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let u=s;u<i;u++)t[u]=0;n.setBigUint64(i-8,BigInt(this.length*8),o),this.process(n,0);let a=W(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let g=c/4,y=this.get();if(g>y.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<g;u++)a.setUint32(4*u,y[u],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},w=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var st=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),A=new Uint32Array(64),de=class extends G{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[e,t,n,i,o,s,a,c]}set(e,t,n,i,o,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)A[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let x=A[u-15],d=A[u-2],p=T(x,7)^T(x,18)^x>>>3,m=T(d,17)^T(d,19)^d>>>10;A[u]=m+A[u-7]+p+A[u-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:g,H:y}=this;for(let u=0;u<64;u++){let x=T(a,6)^T(a,11)^T(a,25),d=y+x+Oe(a,c,g)+st[u]+A[u]|0,m=(T(n,2)^T(n,13)^T(n,22))+Me(n,i,o)|0;y=g,g=c,c=a,a=s+d|0,s=o,o=i,i=n,n=d+m|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,g=g+this.G|0,y=y+this.H|0,this.set(n,i,o,s,a,c,g,y)}roundClean(){R(A)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),R(this.buffer)}},fe=class extends de{constructor(){super(32);h(this,"A",w[0]|0);h(this,"B",w[1]|0);h(this,"C",w[2]|0);h(this,"D",w[3]|0);h(this,"E",w[4]|0);h(this,"F",w[5]|0);h(this,"G",w[6]|0);h(this,"H",w[7]|0)}};var Be=Re(()=>new fe,Le(1));var Ne=new TextEncoder,ge="v2";function z(r){return Ne.encode(r).length}function q(r,e){let t=z(r),n=z(e);return`traffical:assignment:${ge}|u:${t}:${r}|l:${n}:${e}`}function L(r){return Be(Ne.encode(r))}function O(r){let e=0n;for(let t=0;t<8;t++)e=e<<8n|BigInt(r[t]);return e}function X(r){return O(L(r))}function J(r,e,t){let n=L(q(r,e)),i=O(n);return Number(i%BigInt(t))}function pe(r,e){return r>=e[0]&&r<=e[1]}function Y(r,e){for(let t of e)if(pe(r,t.bucketRange))return t;return null}var at=1n<<53n,ct=9007199254740992;function D(r,e){if(r.length===0||r.length===1)return 0;let t=X(e),n=Number(t%at)/ct,i=0;for(let o=0;o<r.length;o++)if(i+=r[o],n<i)return o;return r.length-1}function he(r,e){let{field:t,op:n,value:i,values:o}=r,s=dt(e,t);switch(n){case"eq":return s===i;case"neq":return s!==i;case"in":return Array.isArray(o)?o.includes(s):!1;case"nin":return Array.isArray(o)?!o.includes(s):!0;case"gt":return typeof s=="number"&&s>i;case"gte":return typeof s=="number"&&s>=i;case"lt":return typeof s=="number"&&s<i;case"lte":return typeof s=="number"&&s<=i;case"contains":return typeof s=="string"&&typeof i=="string"&&s.includes(i);case"startsWith":return typeof s=="string"&&typeof i=="string"&&s.startsWith(i);case"endsWith":return typeof s=="string"&&typeof i=="string"&&s.endsWith(i);case"regex":if(typeof s!="string"||typeof i!="string")return!1;try{return new RegExp(i).test(s)}catch{return!1}case"exists":return s!=null;case"notExists":return s==null;default:return!1}}function Q(r,e){return r.length===0?!0:r.every(t=>he(t,e))}function dt(r,e){let t=e.split("."),n=r;for(let i of t){if(n==null)return;if(typeof n=="object")n=n[i];else return}return n}function me(r,e){let t=r.intercept;for(let{key:n,coef:i,missing:o}of r.numeric){let s=e[n];t+=typeof s=="number"?i*s:o}for(let{key:n,values:i,missing:o}of r.categorical){let s=e[n],a=s!=null?String(s):null;t+=a!==null&&a in i?i[a]:o}return t}function ye(r,e){if(r.length===0)return[];if(r.length===1)return[1];let t=Math.max(e,1e-10),n=r.map(a=>a/t),i=Math.max(...n),o=n.map(a=>Math.exp(a-i)),s=o.reduce((a,c)=>a+c,0);return o.map(a=>a/s)}function ve(r,e){if(r.length===0)return[];if(e<=0)return r;let t=r.length,n=1/t,i=Math.min(e,n),o=r.map(a=>Math.max(a,i)),s=o.reduce((a,c)=>a+c,0);return s===0?Array(t).fill(1/t):o.map(a=>a/s)}function Z(r,e,t){let n=r.contextualModel;if(!n||r.allocations.length===0)return null;let i=ft(n,r.allocations,e),o=ye(i,n.gamma),s=ve(o,n.actionProbabilityFloor),a=`ctx:${t}:${r.id}`,c=D(s,a);return r.allocations[c]}function ft(r,e,t){return e.map(n=>{let i=r.coefficients[n.name];return i?me(i,t):r.defaultAllocationScore})}var gt=r=>crypto.getRandomValues(new Uint8Array(r)),pt=(r,e,t)=>{let n=(2<<Math.log2(r.length-1))-1,i=-~(1.6*n*e/r.length);return(o=e)=>{let s="";for(;;){let a=t(i),c=i|0;for(;c--;)if(s+=r[a[c]&n]||"",s.length>=o)return s}}},Ue=(r,e=21)=>pt(r,e|0,gt);function ee(r){let e=new Error(r);return e.source="ulid",e}var _e="0123456789ABCDEFGHJKMNPQRSTVWXYZ",M=_e.length,Ve=Math.pow(2,48)-1,ht=10,mt=16;function yt(r){let e=Math.floor(r()*M);return e===M&&(e=M-1),_e.charAt(e)}function vt(r,e){if(isNaN(r))throw new Error(r+" must be a number");if(r>Ve)throw ee("cannot encode time greater than "+Ve);if(r<0)throw ee("time must be positive");if(Number.isInteger(Number(r))===!1)throw ee("time must be an integer");let t,n="";for(;e>0;e--)t=r%M,n=_e.charAt(t)+n,r=(r-t)/M;return n}function _t(r,e){let t="";for(;r>0;r--)t=yt(e)+t;return t}function xt(r=!1,e){e||(e=typeof window<"u"?window:null);let t=e&&(e.crypto||e.msCrypto);if(t)return()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};try{let n=Ke();return()=>n.randomBytes(1).readUInt8()/255}catch{}if(r){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw ee("secure crypto unusable, insecure Math.random not allowed")}function bt(r){return r||(r=xt()),function(t){return isNaN(t)&&(t=Date.now()),vt(t,ht)+_t(mt,r)}}var Fe=bt();var Et="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",It=8,jn=Ue(Et,It);function B(r){return`${r}_${Fe()}`}function N(){return B("dec")}function xe(){return B("exp")}function be(){return B("trk")}function Ee(){return B("asn")}function Tt(r,e){let t=new Set;for(let i of e)if(i.contextLogging?.allowedFields)for(let o of i.contextLogging.allowedFields)t.add(o);if(t.size===0)return;let n={};for(let i of t)i in r&&(n[i]=r[i]);return Object.keys(n).length>0?n:void 0}function wt(r,e){let t=[];for(let n of r){let i=e[n];if(i==null)return null;t.push(String(i))}return t.join("_")}function $e(r){if(r<=0)return[];let e=1/r;return Array(r).fill(e)}function At(r,e,t,n){let i=r.entityState?.[e];if(!i)return $e(n);let o=i.entities[t];if(o&&o.weights.length===n)return o.weights;let s=i._global;return s&&s.weights.length===n?s.weights:$e(n)}function kt(r,e,t,n){let i=e.entityConfig;if(!i)return null;let o=wt(i.entityKeys,t);if(!o)return null;let s,a;if(i.dynamicAllocations){let u=i.dynamicAllocations.countKey,x=t[u];if(typeof x!="number"||x<=0)return null;a=Math.floor(x),s=Array.from({length:a},(d,p)=>({id:`${e.id}_dynamic_${p}`,name:String(p),bucketRange:[0,0],overrides:{}}))}else s=e.allocations,a=s.length;if(a===0)return null;let c=At(r,e.id,o,a),g=`${o}:${n}:${e.id}`,y=D(c,g);return{allocation:s[y],entityId:o}}function U(r,e){let t=e[r.hashing.unitKey];return t==null?null:String(t)}function je(r,e,t,n){let i={...t},o=[],s=[];if(!r)return{assignments:i,unitKeyValue:"",layers:o,matchedPolicies:s};let a=U(r,e)??"",c=new Set(Object.keys(t)),g=r.parameters.filter(u=>c.has(u.key));for(let u of g)u.key in i&&(i[u.key]=u.default);let y=new Map;for(let u of g){let x=y.get(u.layerId)||[];x.push(u),y.set(u.layerId,x)}for(let u of r.layers){let x=y.get(u.id),d=x&&x.length>0,p=u.unitKey,m=p?String(e[p]??""):a;if(!m){o.push({layerId:u.id,bucket:-1,...p?{unitKey:p,unitKeyValue:""}:{},...d?{}:{attributionOnly:!0}});continue}let v=J(m,u.id,r.hashing.bucketCount),I,l;for(let f of u.policies)if(f.state==="running"){if(f.eligibleBucketRange){let{start:_,end:b}=f.eligibleBucketRange;if(v<_||v>b)continue}if(Q(f.conditions,e)){if(f.contextualModel){let _=Z(f,e,m);if(_){if(I=f,l=_,s.push(f),d)for(let[b,S]of Object.entries(_.overrides))b in i&&(i[b]=S);break}}if(f.entityConfig&&f.entityConfig.resolutionMode==="bundle"){let _=kt(r,f,e,m);if(_){if(I=f,l=_.allocation,s.push(f),d&&!f.entityConfig.dynamicAllocations)for(let[b,S]of Object.entries(_.allocation.overrides))b in i&&(i[b]=S);break}}else if(f.entityConfig&&f.entityConfig.resolutionMode==="edge"){let _=n?.edgeResults?.get(f.id);if(_){if(I=f,s.push(f),f.entityConfig.dynamicAllocations)l={id:`${f.id}_dynamic_${_.allocationIndex}`,name:String(_.allocationIndex),bucketRange:[0,0],overrides:{}};else if(f.allocations[_.allocationIndex]&&(l=f.allocations[_.allocationIndex],d&&l))for(let[b,S]of Object.entries(l.overrides))b in i&&(i[b]=S);break}continue}else{let _=Y(v,f.allocations);if(_){if(I=f,l=_,s.push(f),d)for(let[b,S]of Object.entries(_.overrides))b in i&&(i[b]=S);break}}}}o.push({layerId:u.id,bucket:v,policyId:I?.id,policyKey:I?.key,allocationId:l?.id,allocationName:l?.name,allocationKey:l?.key,...p?{unitKey:p,unitKeyValue:m}:{},...d?{}:{attributionOnly:!0}})}return{assignments:i,unitKeyValue:a,layers:o,matchedPolicies:s}}function te(r,e,t,n){return je(r,e,t,n).assignments}function ne(r,e,t,n){let{assignments:i,unitKeyValue:o,layers:s,matchedPolicies:a}=je(r,e,t,n),c=Tt(e,a);return{decisionId:N(),assignments:i,metadata:{timestamp:new Date().toISOString(),unitKeyValue:o,layers:s,filteredContext:c}}}var C=class r{constructor(e={}){h(this,"_seen",new Map);h(this,"_ttlMs");h(this,"_maxEntries");h(this,"_lastCleanup",Date.now());this._ttlMs=e.ttlMs??36e5,this._maxEntries=e.maxEntries??1e4}static hashAssignments(e){let t=Object.keys(e).sort(),n=[];for(let i of t){let o=e[i],s=typeof o=="object"?JSON.stringify(o):String(o);n.push(`${i}=${s}`)}return n.join("|")}static createKey(e,t){return`${e}:${t}`}checkAndMark(e,t){let n=r.createKey(e,t),i=Date.now(),o=this._seen.get(n);return o!==void 0&&i-o<this._ttlMs?!1:(this._seen.set(n,i),this._maybeCleanup(i),!0)}wouldBeNew(e,t){let n=r.createKey(e,t),i=Date.now(),o=this._seen.get(n);return o===void 0?!0:i-o>=this._ttlMs}clear(){this._seen.clear()}get size(){return this._seen.size}_maybeCleanup(e){(e-this._lastCleanup>this._ttlMs*.2||this._seen.size>this._maxEntries)&&(this._lastCleanup=e,this._cleanup(e))}_cleanup(e){let t=[];for(let[n,i]of this._seen.entries())e-i>=this._ttlMs&&t.push(n);for(let n of t)this._seen.delete(n);if(this._seen.size>this._maxEntries){let i=Array.from(this._seen.entries()).sort((o,s)=>o[1]-s[1]).slice(0,this._seen.size-this._maxEntries);for(let[o]of i)this._seen.delete(o)}}};var K=class{constructor(e){h(this,"config");h(this,"defaultTimeout");this.config=e,this.defaultTimeout=e.defaultTimeoutMs??5e3}async resolve(e){try{let t=new AbortController,n=setTimeout(()=>t.abort(),this.defaultTimeout),i=`${this.config.baseUrl}/v1/resolve`,o=await fetch(i,{method:"POST",headers:this._headers(),body:JSON.stringify({context:e.context,env:e.env??this.config.env,parameters:e.parameters}),signal:t.signal});return clearTimeout(n),o.ok?await o.json():(console.warn(`[Traffical] Resolve failed: ${o.status} ${o.statusText}`),null)}catch(t){return t instanceof Error&&t.name==="AbortError"?console.warn(`[Traffical] Resolve timed out after ${this.defaultTimeout}ms`):console.warn("[Traffical] Resolve error:",t),null}}async decideEntity(e,t){let n=t??Math.min(this.defaultTimeout,100);try{let i=new AbortController,o=setTimeout(()=>i.abort(),n),s=`${this.config.baseUrl}/v1/decide/${e.policyId}`,a=await fetch(s,{method:"POST",headers:this._headers(),body:JSON.stringify({entityId:e.entityId,unitKeyValue:e.unitKeyValue,allocationCount:e.allocationCount,context:e.context}),signal:i.signal});return clearTimeout(o),a.ok?await a.json():(console.warn(`[Traffical] Edge decide failed: ${a.status} ${a.statusText}`),null)}catch(i){return i instanceof Error&&i.name==="AbortError"?console.warn(`[Traffical] Edge decide timed out after ${n}ms`):console.warn("[Traffical] Edge decide error:",i),null}}async decideEntityBatch(e,t){if(e.length===0)return[];if(e.length===1)return[await this.decideEntity(e[0],t)];let n=t??Math.min(this.defaultTimeout,200);try{let i=new AbortController,o=setTimeout(()=>i.abort(),n),s=`${this.config.baseUrl}/v1/decide/batch`,a=await fetch(s,{method:"POST",headers:this._headers(),body:JSON.stringify({requests:e}),signal:i.signal});return clearTimeout(o),a.ok?(await a.json()).responses:(console.warn(`[Traffical] Edge batch decide failed: ${a.status} ${a.statusText}`),e.map(()=>null))}catch(i){return i instanceof Error&&i.name==="AbortError"?console.warn(`[Traffical] Edge batch decide timed out after ${n}ms`):console.warn("[Traffical] Edge batch decide error:",i),e.map(()=>null)}}_headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"X-Org-Id":this.config.orgId,"X-Project-Id":this.config.projectId,"X-Env":this.config.env}}};function Ie(r,e,t,n,i){let o=[];for(let a of e){let c=t[a];if(c==null)return null;o.push(String(c))}let s=o.join("_");return{policyId:r,entityId:s,unitKeyValue:n,allocationCount:i,context:t}}var ie=class{constructor(e={}){this._seen=new Set;this._lastError=null;this._options=e}capture(e,t,n){try{return t()}catch(i){return this._onError(e,i),n}}async captureAsync(e,t,n){try{return await t()}catch(i){return this._onError(e,i),n}}async swallow(e,t){try{await t()}catch(n){this._onError(e,n)}}getLastError(){let e=this._lastError;return this._lastError=null,e}clearSeen(){this._seen.clear()}_onError(e,t){let n=this._resolveError(t);this._lastError=n;let i=`${e}:${n.name}:${n.message}`;this._seen.has(i)||(this._seen.add(i),console.warn(`[Traffical] Error in ${e}:`,n.message),this._options.onError?.(e,n),this._options.reportErrors&&this._options.errorEndpoint&&this._reportError(e,n).catch(()=>{}))}async _reportError(e,t){if(this._options.errorEndpoint)try{await fetch(this._options.errorEndpoint,{method:"POST",headers:{"Content-Type":"application/json",...this._options.sdkKey&&{"X-Traffical-Key":this._options.sdkKey}},body:JSON.stringify({tag:e,error:t.name,message:t.message,stack:t.stack,timestamp:new Date().toISOString(),sdk:"@traffical/js-client",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})})}catch{}}_resolveError(e){return e instanceof Error?e:typeof e=="string"?new Error(e):new Error("An unknown error occurred")}};var re="failed_events";var oe=class{constructor(e){this._queue=[];this._flushTimer=null;this._isFlushing=!1;this._endpoint=e.endpoint,this._apiKey=e.apiKey,this._storage=e.storage,this._batchSize=e.batchSize??10,this._flushIntervalMs=e.flushIntervalMs??3e4,this._requestTimeoutMs=e.requestTimeoutMs??1e4,this._onError=e.onError,this._onSchemaWarnings=e.onSchemaWarnings,this._lifecycleProvider=e.lifecycleProvider,this._setupListeners(),this._retryFailedEvents(),this._startFlushTimer()}log(e){this._queue.push(e),this._queue.length>=this._batchSize&&this.flush()}async flush(){if(this._isFlushing||this._queue.length===0)return;this._isFlushing=!0;let e=[...this._queue];this._queue=[];try{await this._sendEvents(e)}catch(t){this._persistFailedEvents(e),this._onError?.(t instanceof Error?t:new Error(String(t)))}finally{this._isFlushing=!1}}flushBeacon(){if(this._queue.length===0)return!0;if(typeof fetch>"u")return this.flush(),!1;let e=[...this._queue];return this._queue=[],fetch(this._endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this._apiKey}`},body:JSON.stringify({events:e}),keepalive:!0}).catch(()=>{this._persistFailedEvents(e)}),!0}get queueSize(){return this._queue.length}destroy(){this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),this._removeListeners()}async _sendEvents(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this._requestTimeoutMs),i;try{i=await fetch(this._endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this._apiKey}`},body:JSON.stringify({events:e}),signal:t.signal})}finally{clearTimeout(n)}if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);if(this._onSchemaWarnings)try{let o=await i.json();o.schemaWarnings&&o.schemaWarnings.length>0&&this._onSchemaWarnings(o.schemaWarnings)}catch{}}_persistFailedEvents(e){let n=[...this._storage.get(re)??[],...e].slice(-100);this._storage.set(re,n)}_retryFailedEvents(){let e=this._storage.get(re);!e||e.length===0||(this._storage.remove(re),this._queue.push(...e))}_startFlushTimer(){this._flushIntervalMs<=0||(this._flushTimer=setInterval(()=>{this.flush().catch(()=>{})},this._flushIntervalMs))}_setupListeners(){this._lifecycleProvider&&(this._visibilityCallback=e=>{e==="background"?this._lifecycleProvider?.isUnloading()?this.flushBeacon():this.flush().catch(()=>{}):this._retryFailedEvents()},this._lifecycleProvider.onVisibilityChange(this._visibilityCallback))}_removeListeners(){this._lifecycleProvider&&this._visibilityCallback&&(this._lifecycleProvider.removeVisibilityListener(this._visibilityCallback),this._visibilityCallback=void 0)}};var V="exposure_dedup";var F=class r{constructor(e){this._storage=e.storage,this._sessionTtlMs=e.sessionTtlMs??18e5,this._seen=new Set,this._sessionStart=Date.now(),this._restore()}static createKey(e,t,n){return`${e}:${t}:${n}`}shouldTrack(e){return this._isSessionExpired()&&this._resetSession(),this._seen.has(e)?!1:(this._seen.add(e),this._persist(),!0)}checkAndMark(e,t,n){let i=r.createKey(e,t,n);return this.shouldTrack(i)}clear(){this._seen.clear(),this._storage.remove(V)}get size(){return this._seen.size}_isSessionExpired(){return Date.now()-this._sessionStart>this._sessionTtlMs}_resetSession(){this._seen.clear(),this._sessionStart=Date.now(),this._storage.remove(V)}_persist(){let e={seen:Array.from(this._seen),sessionStart:this._sessionStart};this._storage.set(V,e,this._sessionTtlMs)}_restore(){let e=this._storage.get(V);if(!e)return;if(Date.now()-e.sessionStart>this._sessionTtlMs){this._storage.remove(V);return}this._seen=new Set(e.seen),this._sessionStart=e.sessionStart}};var $="stable_id",$t="traffical_sid";var se=class{constructor(e){this._cachedId=null;this._storage=e.storage,this._useCookieFallback=e.useCookieFallback??!0,this._cookieName=e.cookieName??$t}getId(){if(this._cachedId)return this._cachedId;let e=this._storage.get($);return e?(this._cachedId=e,e):this._useCookieFallback&&(e=this._getCookie(),e)?(this._storage.set($,e),this._cachedId=e,e):(e=this._generateId(),this._persist(e),this._cachedId=e,e)}setId(e){this._persist(e),this._cachedId=e}clear(){this._storage.remove($),this._useCookieFallback&&this._deleteCookie(),this._cachedId=null}hasId(){return this._storage.get($)!==null||this._getCookie()!==null}_persist(e){this._storage.set($,e),this._useCookieFallback&&this._setCookie(e)}_generateId(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}_getCookie(){if(typeof document>"u")return null;try{let e=document.cookie.split(";");for(let t of e){let[n,i]=t.trim().split("=");if(n===this._cookieName&&i)return decodeURIComponent(i)}}catch{}return null}_setCookie(e){if(!(typeof document>"u"))try{document.cookie=`${this._cookieName}=${encodeURIComponent(e)}; max-age=31536000; path=/; SameSite=Lax`}catch{}}_deleteCookie(){if(!(typeof document>"u"))try{document.cookie=`${this._cookieName}=; max-age=0; path=/`}catch{}}};var j="traffical:",Te=class{constructor(){this._available=this._checkAvailability()}get(e){if(!this._available)return null;try{let t=localStorage.getItem(j+e);if(!t)return null;let n=JSON.parse(t);return n.expiresAt&&Date.now()>n.expiresAt?(this.remove(e),null):n.value}catch{return null}}set(e,t,n){if(this._available)try{let i={value:t,...n&&{expiresAt:Date.now()+n}};localStorage.setItem(j+e,JSON.stringify(i))}catch{}}remove(e){if(this._available)try{localStorage.removeItem(j+e)}catch{}}clear(){if(this._available)try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n?.startsWith(j)&&e.push(n)}e.forEach(t=>localStorage.removeItem(t))}catch{}}_checkAvailability(){try{let e=j+"__test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return!1}}},we=class{constructor(){this._store=new Map}get(e){let t=this._store.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.remove(e),null):t.value:null}set(e,t,n){this._store.set(e,{value:t,...n&&{expiresAt:Date.now()+n}})}remove(e){this._store.delete(e)}clear(){this._store.clear()}};function He(){let r=new Te;return r.get("__check__")!==null||jt()?r:new we}function jt(){try{let r="__traffical_storage_test__";return localStorage.setItem(r,"test"),localStorage.removeItem(r),!0}catch{return!1}}var k="0.15.0";var Ht="js-client";function Ae(r,e){let t=new C({ttlMs:r.deduplicationTtlMs});return{name:"decision-tracking",onDecision(n){if(r.disabled)return;let i=n.metadata.unitKeyValue;if(!i)return;let o=C.hashAssignments(n.assignments);if(!t.checkAndMark(i,o))return;let s={type:"decision",id:n.decisionId,orgId:e.orgId,projectId:e.projectId,env:e.env,unitKey:i,timestamp:n.metadata.timestamp,assignments:n.assignments,layers:n.metadata.layers,context:n.metadata.filteredContext,sdkName:Ht,sdkVersion:k};e.log(s)},onDestroy(){t.clear()}}}var Wt="traffical_rdr";function Gt(r,e,t){if(!(typeof document>"u"))try{document.cookie=`${r}=${encodeURIComponent(e)}; max-age=${t}; path=/; SameSite=Lax`}catch{}}function ke(r={}){let e=r.parameterKey??"redirect.url",t=r.compareMode??"pathname",n=r.cookieName??Wt;return{name:"redirect",onInitialize(i){typeof window>"u"||i.decide({context:{},defaults:{[e]:""}})},onBeforeDecision(i){return typeof window>"u"?i:{"url.pathname":window.location.pathname,...i}},onDecision(i){let o=i.assignments[e];if(typeof o!="string"||!o)return;let s=t==="href"?window.location.href:window.location.pathname;if(o===s)return;let a=i.metadata.layers.find(c=>c.policyId&&c.allocationName);a&&Gt(n,JSON.stringify({l:a.layerId,p:a.policyId,a:a.allocationName,ts:Date.now()}),86400),window.location.replace(o)}}}var zt="traffical_rdr";function qt(r){if(typeof document>"u")return null;try{for(let e of document.cookie.split(";")){let[t,n]=e.trim().split("=");if(t===r&&n)return decodeURIComponent(n)}}catch{}return null}function Xt(r,e){let t=qt(r);if(!t)return null;try{let n=JSON.parse(t);return Date.now()-n.ts>e?null:{layerId:n.l,policyId:n.p,allocationName:n.a}}catch{return null}}function Se(r={}){let e=r.cookieName??zt,t=r.expiryMs??864e5;function n(i){let o=Xt(e,t);if(!o)return;i.attribution=i.attribution??[],i.attribution.some(a=>a.layerId===o.layerId&&a.policyId===o.policyId)||i.attribution.push(o)}return{name:"redirect-attribution",onTrack(i){return n(i),!0},onExposure(i){return n(i),!0}}}var ae=[],We={};function Jt(){if(typeof window>"u")return{version:1,instances:We,subscribe:()=>()=>{}};if(!window.__TRAFFICAL_DEBUG__){let r={version:1,instances:We,subscribe(e){return ae.push(e),()=>{ae=ae.filter(t=>t!==e)}}};window.__TRAFFICAL_DEBUG__=r}return window.__TRAFFICAL_DEBUG__}function Ge(r){for(let e of ae)try{e(r)}catch{}}var Yt=0;function Qt(){return`traffical_${Date.now().toString(36)}_${(++Yt).toString(36)}`}function Zt(){return`evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}var en="traffical-debug";function Ce(r={}){let e=r.instanceId??Qt(),t=r.maxEvents??500,n=null,i=null,o={},s=[],a=null,c=null,g=[],y=[],u=[];function x(){return{ready:n?.isInitialized===!0,stableId:n?.getStableId?.()??null,effectiveUnitKey:c,configVersion:n?.getConfigVersion?.()??null,assignments:{...o},layers:[...s],lastDecisionId:a,overrides:n?.getOverrides?.()??{}}}function d(){let l=x();for(let f of y)try{f(l)}catch{}}function p(l,f){let _={id:Zt(),type:l,timestamp:Date.now(),data:f};g.push(_),g.length>t&&g.splice(0,g.length-t);for(let b of u)try{b(_)}catch{}}function m(){if(n)try{n.decide({context:{},defaults:{}})}catch{}}let v={id:e,meta:{orgId:"",projectId:"",env:"",sdkVersion:k},getState:x,subscribe(l){return y.push(l),()=>{y=y.filter(f=>f!==l)}},getEvents(l){return l!==void 0?g.slice(-l):[...g]},onEvent(l){return u.push(l),()=>{u=u.filter(f=>f!==l)}},getConfigBundle(){return i},setUnitKey(l){n?.identify?n.identify(l):n?.setStableId&&n.setStableId(l),d()},setOverride(l,f){n?.applyOverrides&&n.applyOverrides({[l]:f}),d(),m()},clearOverride(l){if(n?.getOverrides&&n?.applyOverrides){let f=n.getOverrides();delete f[l],n.clearOverrides?.(),n.applyOverrides(f)}d(),m()},clearAllOverrides(){n?.clearOverrides?.(),d(),m()},getOverrides(){return n?.getOverrides?.()??{}},reDecide(){m()},async refresh(){n?.refreshConfig&&await n.refreshConfig()}};return{name:en,onInitialize(l){n=l,i&&(v.meta.orgId=i.orgId,v.meta.projectId=i.projectId,v.meta.env=i.env);let f=Jt();f.instances[e]=v,Ge({type:"register",instanceId:e}),d()},onConfigUpdate(l){i=l,v.meta.orgId=l.orgId,v.meta.projectId=l.projectId,v.meta.env=l.env,d()},onDecision(l){o={...l.assignments},s=l.metadata?.layers?[...l.metadata.layers]:[],a=l.decisionId,l.metadata?.unitKeyValue&&(c=l.metadata.unitKeyValue),p("decision",l),d()},onResolve(l){o={...l},d()},onExposure(l){return p("exposure",l),!0},onTrack(l){return p("track",l),!0},onDestroy(){let l=typeof window<"u"?window.__TRAFFICAL_DEBUG__:null;l&&(delete l.instances[e],Ge({type:"unregister",instanceId:e})),y=[],u=[],n=null}}}var ce=class{constructor(){this._plugins=[]}register(e){let t="plugin"in e?e.plugin:e,n="priority"in e?e.priority??0:0;return this._plugins.some(i=>i.plugin.name===t.name)?(console.warn(`[Traffical] Plugin "${t.name}" already registered, skipping.`),!1):(this._plugins.push({plugin:t,priority:n}),this._plugins.sort((i,o)=>o.priority-i.priority),!0)}unregister(e){let t=this._plugins.findIndex(n=>n.plugin.name===e);return t===-1?!1:(this._plugins.splice(t,1),!0)}get(e){return this._plugins.find(t=>t.plugin.name===e)?.plugin}getAll(){return this._plugins.map(e=>e.plugin)}async runInitialize(e){for(let{plugin:t}of this._plugins)if(t.onInitialize)try{await t.onInitialize(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onInitialize error:`,n)}}runConfigUpdate(e){for(let{plugin:t}of this._plugins)if(t.onConfigUpdate)try{t.onConfigUpdate(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onConfigUpdate error:`,n)}}runBeforeDecision(e){let t=e;for(let{plugin:n}of this._plugins)if(n.onBeforeDecision)try{let i=n.onBeforeDecision(t);i&&(t=i)}catch(i){console.warn(`[Traffical] Plugin "${n.name}" onBeforeDecision error:`,i)}return t}runDecision(e){for(let{plugin:t}of this._plugins)if(t.onDecision)try{t.onDecision(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onDecision error:`,n)}}runResolve(e){for(let{plugin:t}of this._plugins)if(t.onResolve)try{t.onResolve(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onResolve error:`,n)}}runExposure(e){for(let{plugin:t}of this._plugins)if(t.onExposure)try{if(t.onExposure(e)===!1)return!1}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onExposure error:`,n)}return!0}runTrack(e){for(let{plugin:t}of this._plugins)if(t.onTrack)try{if(t.onTrack(e)===!1)return!1}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onTrack error:`,n)}return!0}runDestroy(){for(let{plugin:e}of this._plugins)if(e.onDestroy)try{e.onDestroy()}catch(t){console.warn(`[Traffical] Plugin "${e.name}" onDestroy error:`,t)}}clear(){this._plugins=[]}};function ze(){let r=[],e=!1;function t(s){for(let a of r)a(s)}let n=()=>{e=!0,t("background")},i=()=>{typeof document<"u"&&t(document.visibilityState==="hidden"?"background":"foreground")},o=()=>{e=!0,t("background")};return typeof window<"u"&&(window.addEventListener("pagehide",n),window.addEventListener("beforeunload",o)),typeof document<"u"&&document.addEventListener("visibilitychange",i),{onVisibilityChange(s){r.push(s)},removeVisibilityListener(s){let a=r.indexOf(s);a!==-1&&r.splice(a,1)},isUnloading(){return e}}}var De="js-client",tn="https://sdk.traffical.io",nn=6e4,rn=1e4,on=3e5,sn=100,P=class{constructor(e){this._state={bundle:null,etag:null,lastFetchTime:0,lastOfflineWarning:0,refreshTimer:null,isInitialized:!1,serverResponse:null,cachedEdgeResults:null};this._decisionCache=new Map;this._cumulativeAttribution=new Map;this._identityListeners=[];this._overrideListeners=[];this._overrides={};let t=e.evaluationMode??"bundle";this._options={orgId:e.orgId,projectId:e.projectId,env:e.env,apiKey:e.apiKey,baseUrl:e.baseUrl??tn,localConfig:e.localConfig,refreshIntervalMs:e.refreshIntervalMs??nn,attributionMode:e.attributionMode??"cumulative",evaluationMode:t},this._requestTimeoutMs=e.requestTimeoutMs??rn;let n={baseUrl:this._options.baseUrl,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,apiKey:this._options.apiKey};if(this._decisionClient=new K(n),this._errorBoundary=new ie(e.errorBoundary),this._storage=e.storage??He(),this._lifecycleProvider=e.lifecycleProvider??ze(),!e.onSchemaWarnings)try{typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="development"&&(e.onSchemaWarnings=o=>{for(let s of o)console.warn(`[Traffical] Schema warning for "${s.event}":`,s.violations.map(a=>`${a.path}: ${a.message}`).join(", "))})}catch{}if(this._eventLogger=new oe({endpoint:`${this._options.baseUrl}/v1/events/batch`,apiKey:e.apiKey,storage:this._storage,lifecycleProvider:this._lifecycleProvider,batchSize:e.eventBatchSize,flushIntervalMs:e.eventFlushIntervalMs,requestTimeoutMs:e.requestTimeoutMs,onError:i=>{console.warn("[Traffical] Event logging error:",i.message)},onSchemaWarnings:e.onSchemaWarnings}),this._exposureDedup=new F({storage:this._storage,sessionTtlMs:e.exposureSessionTtlMs}),this._stableId=new se({storage:this._storage}),this._plugins=new ce,this._assignmentLogger=e.assignmentLogger,this._byoEventLogger=e.eventLogger,this._disableCloudEvents=e.disableCloudEvents??!1,this._assignmentLoggerDedup=e.deduplicateAssignmentLogger!==!1&&e.assignmentLogger?new F({storage:this._storage,sessionTtlMs:e.exposureSessionTtlMs}):null,e.trackDecisions!==!1&&(!this._disableCloudEvents||this._byoEventLogger)&&this._plugins.register({plugin:Ae({deduplicationTtlMs:e.decisionDeduplicationTtlMs},{orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,log:i=>this._dispatchEvent(i)}),priority:100}),e.plugins)for(let i of e.plugins)this._plugins.register(i);if(this._options.localConfig&&(this._state.bundle=this._options.localConfig,this._plugins.runConfigUpdate(this._options.localConfig)),typeof window<"u"){let i=window;i.__TRAFFICAL_INSTANCES__??(i.__TRAFFICAL_INSTANCES__=[]),i.__TRAFFICAL_INSTANCES__.push(this)}}async initialize(){await this._errorBoundary.captureAsync("initialize",async()=>{this._options.evaluationMode==="server"?await this._fetchServerResolve():await this._fetchConfig(),this._startBackgroundRefresh(),this._state.isInitialized=!0,await this._plugins.runInitialize(this)},void 0)}get isInitialized(){return this._state.isInitialized}destroy(){if(this._state.refreshTimer&&(clearInterval(this._state.refreshTimer),this._state.refreshTimer=null),this._lifecycleProvider.isUnloading()?this._eventLogger.flushBeacon():this._eventLogger.flush().catch(()=>{}),this._eventLogger.destroy(),this._plugins.runDestroy(),this._identityListeners=[],this._overrideListeners=[],this._overrides={},typeof window<"u"){let t=window.__TRAFFICAL_INSTANCES__;if(t){let n=t.indexOf(this);n!==-1&&t.splice(n,1)}}}async refreshConfig(){await this._errorBoundary.swallow("refreshConfig",async()=>{this._options.evaluationMode==="server"?await this._fetchServerResolve():await this._fetchConfig()})}getConfigVersion(){return this._state.serverResponse?.stateVersion??this._state.bundle?.version??null}getParams(e){return this._errorBoundary.capture("getParams",()=>{if(this._options.evaluationMode==="server"&&this._state.serverResponse){let o={...e.defaults};for(let[s,a]of Object.entries(this._state.serverResponse.assignments))s in o&&(o[s]=a);return this._plugins.runResolve(o),this._applyOverridesToResult(o),o}let t=this._getEffectiveBundle(),n=this._enrichContext(e.context),i=te(t,n,e.defaults);return this._plugins.runResolve(i),this._applyOverridesToResult(i),i},e.defaults)}decide(e){return this._errorBoundary.capture("decide",()=>{if(this._options.evaluationMode==="server"&&this._state.serverResponse){let s=this._state.serverResponse,a={...e.defaults};for(let[g,y]of Object.entries(s.assignments))g in a&&(a[g]=y);let c={decisionId:s.decisionId,assignments:a,metadata:s.metadata};return this._cacheDecision(c),this._updateCumulativeAttribution(c),this._plugins.runDecision(c),this._applyOverridesToResult(c.assignments),this._emitAssignmentLogEntries(c,"decision"),c}let t=this._getEffectiveBundle(),n=this._enrichContext(e.context);n=this._plugins.runBeforeDecision(n);let i=this._state.cachedEdgeResults??void 0,o=ne(t,n,e.defaults,i);return this._cacheDecision(o),this._updateCumulativeAttribution(o),this._plugins.runDecision(o),this._applyOverridesToResult(o.assignments),this._emitAssignmentLogEntries(o,"decision"),o},{decisionId:N(),assignments:e.defaults,metadata:{timestamp:new Date().toISOString(),unitKeyValue:"",layers:[]}})}trackExposure(e){this._errorBoundary.capture("trackExposure",()=>{let t=e.metadata.unitKeyValue;if(t){this._emitAssignmentLogEntries(e,"exposure");for(let n of e.metadata.layers){if(!n.policyId||!n.allocationName||n.attributionOnly||!this._exposureDedup.checkAndMark(t,n.policyId,n.allocationName))continue;let o={type:"exposure",id:xe(),decisionId:e.decisionId,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,unitKey:t,timestamp:new Date().toISOString(),assignments:e.assignments,layers:e.metadata.layers,context:e.metadata.filteredContext,sdkName:De,sdkVersion:k};this._plugins.runExposure(o)&&this._dispatchEvent(o)}}},void 0)}track(e,t,n){this._errorBoundary.capture("track",()=>{let i=n?.unitKey??this._stableId.getId(),o=typeof t?.value=="number"?t.value:void 0,s=this._buildAttribution(i,n?.decisionId),a=n?.decisionId,c={type:"track",id:be(),orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,unitKey:i,timestamp:new Date().toISOString(),event:e,value:o,properties:t,decisionId:a,attribution:s,sdkName:De,sdkVersion:k};this._plugins.runTrack(c)&&this._dispatchEvent(c)},void 0)}async flushEvents(){await this._errorBoundary.swallow("flushEvents",async()=>{await this._eventLogger.flush()})}use(e){if(!this._plugins.register(e))return this;if(this._state.isInitialized){try{e.onInitialize?.(this)}catch(n){console.warn(`[Traffical] Plugin "${e.name}" late onInitialize error:`,n)}if(this._state.bundle)try{e.onConfigUpdate?.(this._state.bundle)}catch(n){console.warn(`[Traffical] Plugin "${e.name}" late onConfigUpdate error:`,n)}}return this}getPlugin(e){return this._plugins.get(e)}getStableId(){return this._stableId.getId()}setStableId(e){this._stableId.setId(e)}identify(e){this._stableId.setId(e);for(let t of this._identityListeners)try{t(e)}catch{}}onIdentityChange(e){return this._identityListeners.push(e),()=>{this._identityListeners=this._identityListeners.filter(t=>t!==e)}}onOverridesChange(e){return this._overrideListeners.push(e),()=>{this._overrideListeners=this._overrideListeners.filter(t=>t!==e)}}applyOverrides(e){Object.assign(this._overrides,e),this._notifyOverrideListeners()}clearOverrides(){this._overrides={},this._notifyOverrideListeners()}getOverrides(){return{...this._overrides}}_notifyOverrideListeners(){let e={...this._overrides};for(let t of this._overrideListeners)try{t(e)}catch{}}_dispatchEvent(e){if(this._byoEventLogger)try{this._byoEventLogger(e)}catch{}this._disableCloudEvents||this._eventLogger.log(e)}_emitAssignmentLogEntries(e,t){if(!this._assignmentLogger)return;let n=e.metadata.unitKeyValue;if(n)for(let i of e.metadata.layers)!i.policyId||!i.allocationName||this._assignmentLoggerDedup&&!this._assignmentLoggerDedup.checkAndMark(n,i.policyId,`${i.allocationName}:${t}`)||this._assignmentLogger({unitKey:n,policyId:i.policyId,policyKey:i.policyKey,allocationName:i.allocationName,allocationKey:i.allocationKey,timestamp:e.metadata.timestamp,layerId:i.layerId,allocationId:i.allocationId,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,sdkName:De,sdkVersion:k,properties:e.metadata.filteredContext,type:t,decisionId:e.decisionId,anonymousId:this._stableId.getId(),id:Ee()})}_applyOverridesToResult(e){let t=Object.keys(this._overrides);if(t.length!==0)for(let n of t)n in e&&(e[n]=this._overrides[n])}_getEffectiveBundle(){return this._state.bundle??this._options.localConfig??null}_enrichContext(e){let n=this._getEffectiveBundle()?.hashing?.unitKey??"userId";return e[n]?e:{...e,[n]:this._stableId.getId()}}async _fetchConfig(){let e=`${this._options.baseUrl}/v1/config/${this._options.projectId}?env=${this._options.env}`,t={"Content-Type":"application/json",Authorization:`Bearer ${this._options.apiKey}`};this._state.etag&&(t["If-None-Match"]=this._state.etag);let n=new AbortController,i=setTimeout(()=>n.abort(),this._requestTimeoutMs);try{let o=await fetch(e,{method:"GET",headers:t,signal:n.signal});if(o.status===304){this._state.lastFetchTime=Date.now();return}if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let s=await o.json(),a=o.headers.get("ETag");if(this._state.bundle=s,this._state.etag=a,this._state.lastFetchTime=Date.now(),this._findEdgePolicies(s).length>0){let c=await this._prefetchEdgeResults(s,this._enrichContext({}));this._state.cachedEdgeResults=c}else this._state.cachedEdgeResults=null;this._plugins.runConfigUpdate(s)}catch(o){this._logOfflineWarning(o)}finally{clearTimeout(i)}}_startBackgroundRefresh(){let e=this._options.evaluationMode==="server"?this._state.serverResponse?.suggestedRefreshMs??this._options.refreshIntervalMs:this._options.refreshIntervalMs;e<=0||(this._state.refreshTimer=setInterval(()=>{this._options.evaluationMode==="server"?this._fetchServerResolve().catch(()=>{}):this._fetchConfig().catch(()=>{})},e))}async _fetchServerResolve(){if(this._decisionClient)try{let e=this._enrichContext({}),t=await this._decisionClient.resolve({context:e});t&&(this._state.serverResponse=t,this._state.lastFetchTime=Date.now())}catch(e){this._logOfflineWarning(e)}}_findEdgePolicies(e){let t=[];for(let n of e.layers)for(let i of n.policies)i.state==="running"&&i.entityConfig?.resolutionMode==="edge"&&t.push(i);return t}async _prefetchEdgeResults(e,t){if(!this._decisionClient)return{};let n=this._findEdgePolicies(e);if(n.length===0)return{};let i=U(e,t);if(!i)return{};let o=n.map(s=>{if(!s.entityConfig)return null;let a=s.entityConfig.dynamicAllocations?typeof t[s.entityConfig.dynamicAllocations.countKey]=="number"?Math.floor(t[s.entityConfig.dynamicAllocations.countKey]):0:s.allocations.length;return Ie(s.id,s.entityConfig.entityKeys,t,i,a||void 0)}).filter(s=>s!==null);if(o.length===0)return{};try{let s=await this._decisionClient.decideEntityBatch(o),a=new Map;for(let c=0;c<o.length;c++){let g=s[c];g&&a.set(o[c].policyId,{allocationIndex:g.allocationIndex,entityId:o[c].entityId})}return a.size>0?{edgeResults:a}:{}}catch{return{}}}_logOfflineWarning(e){let t=Date.now();t-this._state.lastOfflineWarning>on&&(console.warn(`[Traffical] Failed to fetch config: ${e instanceof Error?e.message:String(e)}. Using ${this._state.bundle?"cached":"local"} config.`),this._state.lastOfflineWarning=t)}_cacheDecision(e){if(this._decisionCache.size>=sn){let t=this._decisionCache.keys().next().value;t&&this._decisionCache.delete(t)}this._decisionCache.set(e.decisionId,e)}_updateCumulativeAttribution(e){let t=e.metadata.unitKeyValue;if(!t)return;let n=this._cumulativeAttribution.get(t);n||(n=new Map,this._cumulativeAttribution.set(t,n));for(let i of e.metadata.layers){if(!i.policyId||!i.allocationName)continue;let o=`${i.layerId}:${i.policyId}`;n.set(o,{layerId:i.layerId,policyId:i.policyId,allocationName:i.allocationName})}}_buildAttribution(e,t){if(this._options.attributionMode==="decision"){if(!t)return;let i=this._decisionCache.get(t);return i?i.metadata.layers.filter(o=>o.policyId&&o.allocationName).map(o=>({layerId:o.layerId,policyId:o.policyId,allocationName:o.allocationName})):void 0}let n=this._cumulativeAttribution.get(e);return n&&n.size>0?Array.from(n.values()):void 0}};async function qe(r){let e=new P(r);return await e.initialize(),e}function Xe(r){return new P(r)}function Je(r={}){let e={observeMutations:r.observeMutations??!0,debounceMs:r.debounceMs??100},t=[],n={},i=null,o=null;function s(d,p){try{return new RegExp(d).test(p)}catch{return p===d}}function a(d,p,m){if(p==="innerHTML")d.innerHTML=m;else if(p==="textContent")d.textContent=m;else if(p==="src"&&"src"in d)d.src=m;else if(p==="href"&&"href"in d)d.href=m;else if(p.startsWith("style.")){let v=p.slice(6);d.style[v]=m}else d.setAttribute(p,m)}function c(d,p){let m=String(p);try{let v=document.querySelectorAll(d.selector);for(let I of v)a(I,d.property,m)}catch(v){console.warn(`[Traffical DOM Binding] Failed to apply binding for ${d.parameterKey}:`,v)}}function g(d,p=!1){n=d;let m=typeof window<"u"?window.location.pathname:"";for(let v of t){if(!p&&!s(v.urlPattern,m))continue;let I=d[v.parameterKey];I!==void 0&&c(v,I)}}function y(){o&&clearTimeout(o),o=setTimeout(()=>{g(n)},e.debounceMs)}function u(){i||typeof MutationObserver>"u"||typeof document>"u"||(i=new MutationObserver(()=>{y()}),i.observe(document.body,{childList:!0,subtree:!0}))}function x(){i&&(i.disconnect(),i=null),o&&(clearTimeout(o),o=null)}return{name:"dom-binding",onInitialize(){e.observeMutations&&u()},onConfigUpdate(d){t=d.domBindings??[]},onResolve(d){g(d)},onDecision(d){g(d.assignments)},onDestroy(){x(),t=[],n={}},applyBindings(d){g(d||n)},getBindings(){return t}}}var E=null;async function an(r){return E?(console.warn("[Traffical] Client already initialized. Returning existing instance."),E):(E=await qe(r),E)}function cn(r){return E?(console.warn("[Traffical] Client already initialized. Returning existing instance."),E):(E=Xe(r),E.initialize().catch(e=>{console.warn("[Traffical] Initialization error:",e)}),E)}function ln(){return E}function un(){E&&(E.destroy(),E=null)}return rt(dn);})();
|
|
1
|
+
/* @traffical/js-client v0.16.0 */
|
|
2
|
+
"use strict";var Traffical=(()=>{var q=Object.defineProperty;var it=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var ot=Object.prototype.hasOwnProperty;var st=(r,e,t)=>e in r?q(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var at=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ct=(r,e)=>{for(var t in e)q(r,t,{get:e[t],enumerable:!0})},lt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rt(e))!ot.call(r,i)&&i!==t&&q(r,i,{get:()=>e[i],enumerable:!(n=it(e,i))||n.enumerable});return r};var ut=r=>lt(q({},"__esModule",{value:!0}),r);var m=(r,e,t)=>(st(r,typeof e!="symbol"?e+"":e,t),t);var He=at(()=>{});var En={};ct(En,{TrafficalClient:()=>M,createDOMBindingPlugin:()=>nt,createDebugPlugin:()=>Me,createRedirectAttributionPlugin:()=>Le,createRedirectPlugin:()=>Re,destroy:()=>xn,init:()=>vn,initSync:()=>_n,instance:()=>bn});function dt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function he(r,e,t=""){let n=dt(r),i=r?.length,o=e!==void 0;if(!n||o&&i!==e){let s=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof r}`,f=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function pe(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Be(r,e){he(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function B(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function X(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function I(r,e){return r<<32-e|r>>>e}function Ne(r,e={}){let t=(i,o)=>r(o).update(i).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=i=>r(i),Object.assign(t,e),Object.freeze(t)}var Ve=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ue(r,e,t){return r&e^~r&t}function Fe(r,e,t){return r&e^r&t^e&t}var J=class{constructor(e,t,n,i){m(this,"blockLen");m(this,"outputLen");m(this,"canXOF",!1);m(this,"padOffset");m(this,"isLE");m(this,"buffer");m(this,"view");m(this,"finished",!1);m(this,"length",0);m(this,"pos",0);m(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=X(this.buffer)}update(e){pe(this),he(e);let{view:t,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=X(e);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){pe(this),Be(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,B(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let l=s;l<i;l++)t[l]=0;n.setBigUint64(i-8,BigInt(this.length*8),o),this.process(n,0);let a=X(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,h=this.get();if(f>h.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)a.setUint32(4*l,h[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},k=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ft=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),S=new Uint32Array(64),me=class extends J{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[e,t,n,i,o,s,a,c]}set(e,t,n,i,o,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)S[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let _=S[l-15],u=S[l-2],g=I(_,7)^I(_,18)^_>>>3,y=I(u,17)^I(u,19)^u>>>10;S[l]=y+S[l-7]+g+S[l-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:f,H:h}=this;for(let l=0;l<64;l++){let _=I(a,6)^I(a,11)^I(a,25),u=h+_+Ue(a,c,f)+ft[l]+S[l]|0,y=(I(n,2)^I(n,13)^I(n,22))+Fe(n,i,o)|0;h=f,f=c,c=a,a=s+u|0,s=o,o=i,i=n,n=u+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,h=h+this.H|0,this.set(n,i,o,s,a,c,f,h)}roundClean(){B(S)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),B(this.buffer)}},ye=class extends me{constructor(){super(32);m(this,"A",k[0]|0);m(this,"B",k[1]|0);m(this,"C",k[2]|0);m(this,"D",k[3]|0);m(this,"E",k[4]|0);m(this,"F",k[5]|0);m(this,"G",k[6]|0);m(this,"H",k[7]|0)}};var Ke=Ne(()=>new ye,Ve(1));var $e=new TextEncoder,ve="v2";function Q(r){return $e.encode(r).length}function Y(r,e){let t=Q(r),n=Q(e);return`traffical:assignment:${ve}|u:${t}:${r}|l:${n}:${e}`}function N(r){return Ke($e.encode(r))}function V(r){let e=0n;for(let t=0;t<8;t++)e=e<<8n|BigInt(r[t]);return e}function Z(r){return V(N(r))}function ee(r,e,t){let n=N(Y(r,e)),i=V(n);return Number(i%BigInt(t))}function _e(r,e){return r>=e[0]&&r<=e[1]}function te(r,e){for(let t of e)if(_e(r,t.bucketRange))return t;return null}var gt=1n<<53n,ht=9007199254740992;function R(r,e){if(r.length===0||r.length===1)return 0;let t=Z(e),n=Number(t%gt)/ht,i=0;for(let o=0;o<r.length;o++)if(i+=r[o],n<i)return o;return r.length-1}function be(r,e){let{field:t,op:n,value:i,values:o}=r,s=yt(e,t);switch(n){case"eq":return s===i;case"neq":return s!==i;case"in":return Array.isArray(o)?o.includes(s):!1;case"nin":return Array.isArray(o)?!o.includes(s):!0;case"gt":return typeof s=="number"&&s>i;case"gte":return typeof s=="number"&&s>=i;case"lt":return typeof s=="number"&&s<i;case"lte":return typeof s=="number"&&s<=i;case"contains":return typeof s=="string"&&typeof i=="string"&&s.includes(i);case"startsWith":return typeof s=="string"&&typeof i=="string"&&s.startsWith(i);case"endsWith":return typeof s=="string"&&typeof i=="string"&&s.endsWith(i);case"regex":if(typeof s!="string"||typeof i!="string")return!1;try{return new RegExp(i).test(s)}catch{return!1}case"exists":return s!=null;case"notExists":return s==null;default:return!1}}function ne(r,e){return r.length===0?!0:r.every(t=>be(t,e))}function yt(r,e){let t=e.split("."),n=r;for(let i of t){if(n==null)return;if(typeof n=="object")n=n[i];else return}return n}function xe(r,e){let t=r.intercept;for(let{key:n,coef:i,missing:o}of r.numeric){let s=e[n];t+=typeof s=="number"?i*s:o}for(let{key:n,values:i,missing:o}of r.categorical){let s=e[n],a=s!=null?String(s):null;t+=a!==null&&a in i?i[a]:o}return t}function Ee(r,e){if(r.length===0)return[];if(r.length===1)return[1];let t=Math.max(e,1e-10),n=r.map(a=>a/t),i=Math.max(...n),o=n.map(a=>Math.exp(a-i)),s=o.reduce((a,c)=>a+c,0);return o.map(a=>a/s)}function Te(r,e){if(r.length===0)return[];if(e<=0)return r;let t=r.length,n=1/t,i=Math.min(e,n),o=r.map(a=>Math.max(a,i)),s=o.reduce((a,c)=>a+c,0);return s===0?Array(t).fill(1/t):o.map(a=>a/s)}function ie(r,e,t){let n=r.contextualModel;if(!n||r.allocations.length===0)return null;let i=vt(n,r.allocations,e),o=Ee(i,n.gamma),s=Te(o,n.actionProbabilityFloor),a=`ctx:${t}:${r.id}`,c=R(s,a);return{allocation:r.allocations[c],probability:s[c]}}function vt(r,e,t){return e.map(n=>{let i=r.coefficients[n.name];return i?xe(i,t):r.defaultAllocationScore})}var _t=r=>crypto.getRandomValues(new Uint8Array(r)),bt=(r,e,t)=>{let n=(2<<Math.log2(r.length-1))-1,i=-~(1.6*n*e/r.length);return(o=e)=>{let s="";for(;;){let a=t(i),c=i|0;for(;c--;)if(s+=r[a[c]&n]||"",s.length>=o)return s}}},je=(r,e=21)=>bt(r,e|0,_t);function re(r){let e=new Error(r);return e.source="ulid",e}var Ie="0123456789ABCDEFGHJKMNPQRSTVWXYZ",U=Ie.length,We=Math.pow(2,48)-1,xt=10,Et=16;function Tt(r){let e=Math.floor(r()*U);return e===U&&(e=U-1),Ie.charAt(e)}function It(r,e){if(isNaN(r))throw new Error(r+" must be a number");if(r>We)throw re("cannot encode time greater than "+We);if(r<0)throw re("time must be positive");if(Number.isInteger(Number(r))===!1)throw re("time must be an integer");let t,n="";for(;e>0;e--)t=r%U,n=Ie.charAt(t)+n,r=(r-t)/U;return n}function wt(r,e){let t="";for(;r>0;r--)t=Tt(e)+t;return t}function At(r=!1,e){e||(e=typeof window<"u"?window:null);let t=e&&(e.crypto||e.msCrypto);if(t)return()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};try{let n=He();return()=>n.randomBytes(1).readUInt8()/255}catch{}if(r){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw re("secure crypto unusable, insecure Math.random not allowed")}function Ct(r){return r||(r=At()),function(t){return isNaN(t)&&(t=Date.now()),It(t,xt)+wt(Et,r)}}var ze=Ct();var kt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",St=8,ei=je(kt,St);function F(r){return`${r}_${ze()}`}function L(){return F("dec")}function we(){return F("exp")}function Ae(){return F("trk")}function Ce(){return F("asn")}function Dt(r,e){let t=new Set;for(let i of e)if(i.contextLogging?.allowedFields)for(let o of i.contextLogging.allowedFields)t.add(o);if(t.size===0)return;let n={};for(let i of t)i in r&&(n[i]=r[i]);return Object.keys(n).length>0?n:void 0}function Pt(r,e){let t=[];for(let n of r){let i=e[n];if(i==null)return null;t.push(String(i))}return t.join("_")}function Ge(r){if(r<=0)return[];let e=1/r;return Array(r).fill(e)}function Rt(r,e,t,n){let i=r.entityState?.[e];if(!i)return Ge(n);let o=i.entities[t];if(o&&o.weights.length===n)return o.weights;let s=i._global;return s&&s.weights.length===n?s.weights:Ge(n)}function Lt(r,e,t,n){let i=e.entityConfig;if(!i)return null;let o=Pt(i.entityKeys,t);if(!o)return null;let s,a;if(i.dynamicAllocations){let l=i.dynamicAllocations.countKey,_=t[l];if(typeof _!="number"||_<=0)return null;a=Math.floor(_),s=Array.from({length:a},(u,g)=>({id:`${e.id}_dynamic_${g}`,name:String(g),bucketRange:[0,0],overrides:{}}))}else s=e.allocations,a=s.length;if(a===0)return null;let c=Rt(r,e.id,o,a),f=`${o}:${n}:${e.id}`,h=R(c,f);return{allocation:s[h],weight:c[h],entityId:o}}function K(r,e){let t=e[r.hashing.unitKey];return t==null?null:String(t)}function oe(r){return r?.hashing?.unitKey??null}function se(r,e){return r?r.parameters.find(n=>n.key===e)?.layerId??null:null}function qe(r,e,t,n){let i={...t},o=[],s=[];if(!r)return{assignments:i,unitKeyValue:"",layers:o,matchedPolicies:s};let a=K(r,e)??"",c=new Set(Object.keys(t)),f=r.parameters.filter(l=>c.has(l.key));for(let l of f)l.key in i&&(i[l.key]=l.default);let h=new Map;for(let l of f){let _=h.get(l.layerId)||[];_.push(l),h.set(l.layerId,_)}for(let l of r.layers){let _=h.get(l.id),u=_&&_.length>0,g=l.unitKey,y=g!=null;if(y&&String(g).trim()===""){o.push({layerId:l.id,bucket:-1,...u?{}:{attributionOnly:!0}});continue}let b=y?String(e[g]??""):a;if(!b){o.push({layerId:l.id,bucket:-1,...y?{unitKey:g,unitKeyValue:""}:{},...u?{}:{attributionOnly:!0}});continue}let w=ee(b,l.id,r.hashing.bucketCount),d,v,A,O;for(let p of l.policies)if(p.state==="running"){if(p.eligibleBucketRange){let{start:x,end:E}=p.eligibleBucketRange;if(w<x||w>E)continue}if(ne(p.conditions,e)){if(p.contextualModel){let x=ie(p,e,b);if(x){if(d=p,v=x.allocation,A=x.probability,O=p.contextualModel.generatedAt??p.contextualModel.modelVersion,s.push(p),u)for(let[E,C]of Object.entries(x.allocation.overrides))E in i&&(i[E]=C);break}}if(p.entityConfig&&p.entityConfig.resolutionMode==="bundle"){let x=Lt(r,p,e,b);if(x){if(d=p,v=x.allocation,A=x.weight,s.push(p),u&&!p.entityConfig.dynamicAllocations)for(let[E,C]of Object.entries(x.allocation.overrides))E in i&&(i[E]=C);break}}else if(p.entityConfig&&p.entityConfig.resolutionMode==="edge"){let x=n?.edgeResults?.get(p.id);if(x){if(d=p,s.push(p),p.entityConfig.dynamicAllocations)v={id:`${p.id}_dynamic_${x.allocationIndex}`,name:String(x.allocationIndex),bucketRange:[0,0],overrides:{}};else if(p.allocations[x.allocationIndex]&&(v=p.allocations[x.allocationIndex],u&&v))for(let[E,C]of Object.entries(v.overrides))E in i&&(i[E]=C);break}continue}else{let x=te(w,p.allocations);if(x){if(d=p,v=x,p.kind==="adaptive"){let[E,C]=x.bucketRange;A=(C-E+1)/r.hashing.bucketCount}if(s.push(p),u)for(let[E,C]of Object.entries(x.overrides))E in i&&(i[E]=C);break}}}}o.push({layerId:l.id,bucket:w,policyId:d?.id,policyKey:d?.key,allocationId:v?.id,allocationName:v?.name,allocationKey:v?.key,...A!==void 0&&A>0&&A<=1?{probability:A}:{},...O!==void 0?{modelVersion:O}:{},...y?{unitKey:g,unitKeyValue:b}:{},...u?{}:{attributionOnly:!0}})}return{assignments:i,unitKeyValue:a,layers:o,matchedPolicies:s}}function ae(r,e,t,n){return qe(r,e,t,n).assignments}function ce(r,e,t,n){let{assignments:i,unitKeyValue:o,layers:s,matchedPolicies:a}=qe(r,e,t,n),c=Dt(e,a);return{decisionId:L(),assignments:i,metadata:{timestamp:new Date().toISOString(),unitKeyValue:o,layers:s,filteredContext:c,...r?.version?{configVersion:r.version}:{}}}}var P=class r{constructor(e={}){m(this,"_seen",new Map);m(this,"_ttlMs");m(this,"_maxEntries");m(this,"_lastCleanup",Date.now());this._ttlMs=e.ttlMs??36e5,this._maxEntries=e.maxEntries??1e4}static hashAssignments(e){let t=Object.keys(e).sort(),n=[];for(let i of t){let o=e[i],s=typeof o=="object"?JSON.stringify(o):String(o);n.push(`${i}=${s}`)}return n.join("|")}static createKey(e,t){return`${e}:${t}`}checkAndMark(e,t){let n=r.createKey(e,t),i=Date.now(),o=this._seen.get(n);return o!==void 0&&i-o<this._ttlMs?!1:(this._seen.set(n,i),this._maybeCleanup(i),!0)}wouldBeNew(e,t){let n=r.createKey(e,t),i=Date.now(),o=this._seen.get(n);return o===void 0?!0:i-o>=this._ttlMs}clear(){this._seen.clear()}get size(){return this._seen.size}_maybeCleanup(e){(e-this._lastCleanup>this._ttlMs*.2||this._seen.size>this._maxEntries)&&(this._lastCleanup=e,this._cleanup(e))}_cleanup(e){let t=[];for(let[n,i]of this._seen.entries())e-i>=this._ttlMs&&t.push(n);for(let n of t)this._seen.delete(n);if(this._seen.size>this._maxEntries){let i=Array.from(this._seen.entries()).sort((o,s)=>o[1]-s[1]).slice(0,this._seen.size-this._maxEntries);for(let[o]of i)this._seen.delete(o)}}};var $=class{constructor(e){m(this,"config");m(this,"defaultTimeout");this.config=e,this.defaultTimeout=e.defaultTimeoutMs??5e3}async resolve(e){try{let t=new AbortController,n=setTimeout(()=>t.abort(),this.defaultTimeout),i=`${this.config.baseUrl}/v1/resolve`,o=await fetch(i,{method:"POST",headers:this._headers(),body:JSON.stringify({context:e.context,env:e.env??this.config.env,parameters:e.parameters}),signal:t.signal});return clearTimeout(n),o.ok?await o.json():(console.warn(`[Traffical] Resolve failed: ${o.status} ${o.statusText}`),null)}catch(t){return t instanceof Error&&t.name==="AbortError"?console.warn(`[Traffical] Resolve timed out after ${this.defaultTimeout}ms`):console.warn("[Traffical] Resolve error:",t),null}}async decideEntity(e,t){let n=t??Math.min(this.defaultTimeout,100);try{let i=new AbortController,o=setTimeout(()=>i.abort(),n),s=`${this.config.baseUrl}/v1/decide/${e.policyId}`,a=await fetch(s,{method:"POST",headers:this._headers(),body:JSON.stringify({entityId:e.entityId,unitKeyValue:e.unitKeyValue,allocationCount:e.allocationCount,context:e.context}),signal:i.signal});return clearTimeout(o),a.ok?await a.json():(console.warn(`[Traffical] Edge decide failed: ${a.status} ${a.statusText}`),null)}catch(i){return i instanceof Error&&i.name==="AbortError"?console.warn(`[Traffical] Edge decide timed out after ${n}ms`):console.warn("[Traffical] Edge decide error:",i),null}}async decideEntityBatch(e,t){if(e.length===0)return[];if(e.length===1)return[await this.decideEntity(e[0],t)];let n=t??Math.min(this.defaultTimeout,200);try{let i=new AbortController,o=setTimeout(()=>i.abort(),n),s=`${this.config.baseUrl}/v1/decide/batch`,a=await fetch(s,{method:"POST",headers:this._headers(),body:JSON.stringify({requests:e}),signal:i.signal});return clearTimeout(o),a.ok?(await a.json()).responses:(console.warn(`[Traffical] Edge batch decide failed: ${a.status} ${a.statusText}`),e.map(()=>null))}catch(i){return i instanceof Error&&i.name==="AbortError"?console.warn(`[Traffical] Edge batch decide timed out after ${n}ms`):console.warn("[Traffical] Edge batch decide error:",i),e.map(()=>null)}}_headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"X-Org-Id":this.config.orgId,"X-Project-Id":this.config.projectId,"X-Env":this.config.env}}};function ke(r,e,t,n,i){let o=[];for(let a of e){let c=t[a];if(c==null)return null;o.push(String(c))}let s=o.join("_");return{policyId:r,entityId:s,unitKeyValue:n,allocationCount:i,context:t}}var le=class{constructor(e={}){this._seen=new Set;this._lastError=null;this._options=e}capture(e,t,n){try{return t()}catch(i){return this._onError(e,i),n}}async captureAsync(e,t,n){try{return await t()}catch(i){return this._onError(e,i),n}}async swallow(e,t){try{await t()}catch(n){this._onError(e,n)}}getLastError(){let e=this._lastError;return this._lastError=null,e}clearSeen(){this._seen.clear()}_onError(e,t){let n=this._resolveError(t);this._lastError=n;let i=`${e}:${n.name}:${n.message}`;this._seen.has(i)||(this._seen.add(i),console.warn(`[Traffical] Error in ${e}:`,n.message),this._options.onError?.(e,n),this._options.reportErrors&&this._options.errorEndpoint&&this._reportError(e,n).catch(()=>{}))}async _reportError(e,t){if(this._options.errorEndpoint)try{await fetch(this._options.errorEndpoint,{method:"POST",headers:{"Content-Type":"application/json",...this._options.sdkKey&&{"X-Traffical-Key":this._options.sdkKey}},body:JSON.stringify({tag:e,error:t.name,message:t.message,stack:t.stack,timestamp:new Date().toISOString(),sdk:"@traffical/js-client",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})})}catch{}}_resolveError(e){return e instanceof Error?e:typeof e=="string"?new Error(e):new Error("An unknown error occurred")}};var j="failed_events";var ue=class{constructor(e){this._queue=[];this._flushTimer=null;this._isFlushing=!1;this._isDisabled=!1;this._droppedCount=0;this._endpoint=e.endpoint,this._apiKey=e.apiKey,this._storage=e.storage,this._batchSize=e.batchSize??10,this._flushIntervalMs=e.flushIntervalMs??3e4,this._requestTimeoutMs=e.requestTimeoutMs??1e4,this._maxQueueSize=e.maxQueueSize??1e3,this._onError=e.onError,this._onSchemaWarnings=e.onSchemaWarnings,this._lifecycleProvider=e.lifecycleProvider,this._setupListeners(),this._retryFailedEvents(),this._startFlushTimer()}log(e){this._isDisabled||(this._queue.length>=this._maxQueueSize&&(this._queue.shift(),this._droppedCount++),this._queue.push(e),this._queue.length>=this._batchSize&&this.flush())}async flush(){if(this._isFlushing||this._isDisabled||this._queue.length===0)return;this._isFlushing=!0;let e=[...this._queue];this._queue=[];try{let t=await this._sendEvents(e);if(t>=200&&t<300)return;if(t===401){this._disable();return}if(t===429||t>=500){this._persistFailedEvents(e),this._onError?.(new Error(`HTTP ${t}: event delivery failed, will retry`));return}this._onError?.(new Error(`HTTP ${t}: batch rejected, dropping ${e.length} events`))}catch(t){this._persistFailedEvents(e),this._onError?.(t instanceof Error?t:new Error(String(t)))}finally{this._isFlushing=!1}}_disable(){this._isDisabled||(this._isDisabled=!0,this._queue=[],this._storage.remove(j),console.warn("[Traffical] API key rejected (HTTP 401); event delivery disabled for this client"))}get droppedCount(){return this._droppedCount}get isDisabled(){return this._isDisabled}flushBeacon(){if(this._queue.length===0)return!0;if(typeof fetch>"u")return this.flush(),!1;let e=[...this._queue];return this._queue=[],fetch(this._endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this._apiKey}`},body:JSON.stringify({events:e}),keepalive:!0}).catch(()=>{this._persistFailedEvents(e)}),!0}get queueSize(){return this._queue.length}destroy(){this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),this._removeListeners()}async _sendEvents(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this._requestTimeoutMs),i;try{i=await fetch(this._endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this._apiKey}`},body:JSON.stringify({events:e}),signal:t.signal})}finally{clearTimeout(n)}if(!i.ok)return i.status;if(this._onSchemaWarnings)try{let o=await i.json();o.schemaWarnings&&o.schemaWarnings.length>0&&this._onSchemaWarnings(o.schemaWarnings)}catch{}return i.status}_persistFailedEvents(e){let n=[...this._storage.get(j)??[],...e].slice(-100);this._storage.set(j,n)}_retryFailedEvents(){let e=this._storage.get(j);!e||e.length===0||(this._storage.remove(j),this._queue.push(...e))}_startFlushTimer(){this._flushIntervalMs<=0||(this._flushTimer=setInterval(()=>{this.flush().catch(()=>{})},this._flushIntervalMs))}_setupListeners(){this._lifecycleProvider&&(this._visibilityCallback=e=>{e==="background"?this._lifecycleProvider?.isUnloading()?this.flushBeacon():this.flush().catch(()=>{}):this._retryFailedEvents()},this._lifecycleProvider.onVisibilityChange(this._visibilityCallback))}_removeListeners(){this._lifecycleProvider&&this._visibilityCallback&&(this._lifecycleProvider.removeVisibilityListener(this._visibilityCallback),this._visibilityCallback=void 0)}};var H="exposure_dedup";var W=class r{constructor(e){this._storage=e.storage,this._sessionTtlMs=e.sessionTtlMs??18e5,this._seen=new Set,this._sessionStart=Date.now(),this._restore()}static createKey(e,t,n){return`${e}:${t}:${n}`}shouldTrack(e){return this._isSessionExpired()&&this._resetSession(),this._seen.has(e)?!1:(this._seen.add(e),this._persist(),!0)}checkAndMark(e,t,n){let i=r.createKey(e,t,n);return this.shouldTrack(i)}clear(){this._seen.clear(),this._storage.remove(H)}get size(){return this._seen.size}_isSessionExpired(){return Date.now()-this._sessionStart>this._sessionTtlMs}_resetSession(){this._seen.clear(),this._sessionStart=Date.now(),this._storage.remove(H)}_persist(){let e={seen:Array.from(this._seen),sessionStart:this._sessionStart};this._storage.set(H,e,this._sessionTtlMs)}_restore(){let e=this._storage.get(H);if(!e)return;if(Date.now()-e.sessionStart>this._sessionTtlMs){this._storage.remove(H);return}this._seen=new Set(e.seen),this._sessionStart=e.sessionStart}};var z="stable_id",Xt="traffical_sid";var de=class{constructor(e){this._cachedId=null;this._storage=e.storage,this._useCookieFallback=e.useCookieFallback??!0,this._cookieName=e.cookieName??Xt}getId(){if(this._cachedId)return this._cachedId;let e=this._storage.get(z);return e?(this._cachedId=e,e):this._useCookieFallback&&(e=this._getCookie(),e)?(this._storage.set(z,e),this._cachedId=e,e):(e=this._generateId(),this._persist(e),this._cachedId=e,e)}setId(e){this._persist(e),this._cachedId=e}clear(){this._storage.remove(z),this._useCookieFallback&&this._deleteCookie(),this._cachedId=null}hasId(){return this._storage.get(z)!==null||this._getCookie()!==null}_persist(e){this._storage.set(z,e),this._useCookieFallback&&this._setCookie(e)}_generateId(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}_getCookie(){if(typeof document>"u")return null;try{let e=document.cookie.split(";");for(let t of e){let[n,i]=t.trim().split("=");if(n===this._cookieName&&i)return decodeURIComponent(i)}}catch{}return null}_setCookie(e){if(!(typeof document>"u"))try{document.cookie=`${this._cookieName}=${encodeURIComponent(e)}; max-age=31536000; path=/; SameSite=Lax`}catch{}}_deleteCookie(){if(!(typeof document>"u"))try{document.cookie=`${this._cookieName}=; max-age=0; path=/`}catch{}}};var G="traffical:",Se=class{constructor(){this._available=this._checkAvailability()}get(e){if(!this._available)return null;try{let t=localStorage.getItem(G+e);if(!t)return null;let n=JSON.parse(t);return n.expiresAt&&Date.now()>n.expiresAt?(this.remove(e),null):n.value}catch{return null}}set(e,t,n){if(this._available)try{let i={value:t,...n&&{expiresAt:Date.now()+n}};localStorage.setItem(G+e,JSON.stringify(i))}catch{}}remove(e){if(this._available)try{localStorage.removeItem(G+e)}catch{}}clear(){if(this._available)try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n?.startsWith(G)&&e.push(n)}e.forEach(t=>localStorage.removeItem(t))}catch{}}_checkAvailability(){try{let e=G+"__test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return!1}}},De=class{constructor(){this._store=new Map}get(e){let t=this._store.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.remove(e),null):t.value:null}set(e,t,n){this._store.set(e,{value:t,...n&&{expiresAt:Date.now()+n}})}remove(e){this._store.delete(e)}clear(){this._store.clear()}};function Xe(){let r=new Se;return r.get("__check__")!==null||Jt()?r:new De}function Jt(){try{let r="__traffical_storage_test__";return localStorage.setItem(r,"test"),localStorage.removeItem(r),!0}catch{return!1}}var D="0.16.0";var Qt="js-client";function Pe(r,e){let t=new P({ttlMs:r.deduplicationTtlMs});return{name:"decision-tracking",onDecision(n){if(r.disabled)return;let i=n.metadata.unitKeyValue;if(!i)return;let o=P.hashAssignments(n.assignments);if(!t.checkAndMark(i,o))return;let s={type:"decision",id:n.decisionId,orgId:e.orgId,projectId:e.projectId,env:e.env,unitKey:i,timestamp:n.metadata.timestamp,assignments:n.assignments,layers:n.metadata.layers,context:n.metadata.filteredContext,configVersion:n.metadata.configVersion??e.getConfigVersion?.()??void 0,sdkName:Qt,sdkVersion:D};e.log(s)},onDestroy(){t.clear()}}}var Yt="traffical_rdr";function Zt(r,e,t){if(!(typeof document>"u"))try{document.cookie=`${r}=${encodeURIComponent(e)}; max-age=${t}; path=/; SameSite=Lax`}catch{}}function Re(r={}){let e=r.parameterKey??"redirect.url",t=r.compareMode??"pathname",n=r.cookieName??Yt;return{name:"redirect",onInitialize(i){typeof window>"u"||i.decide({context:{},defaults:{[e]:""}})},onBeforeDecision(i){return typeof window>"u"?i:{"url.pathname":window.location.pathname,...i}},onDecision(i){let o=i.assignments[e];if(typeof o!="string"||!o)return;let s=t==="href"?window.location.href:window.location.pathname;if(o===s)return;let a=i.metadata.layers.find(c=>c.policyId&&c.allocationName);a&&Zt(n,JSON.stringify({l:a.layerId,p:a.policyId,a:a.allocationName,ts:Date.now()}),86400),window.location.replace(o)}}}var en="traffical_rdr";function tn(r){if(typeof document>"u")return null;try{for(let e of document.cookie.split(";")){let[t,n]=e.trim().split("=");if(t===r&&n)return decodeURIComponent(n)}}catch{}return null}function nn(r,e){let t=tn(r);if(!t)return null;try{let n=JSON.parse(t);return Date.now()-n.ts>e?null:{layerId:n.l,policyId:n.p,allocationName:n.a}}catch{return null}}function Le(r={}){let e=r.cookieName??en,t=r.expiryMs??864e5;function n(i){let o=nn(e,t);if(!o)return;i.attribution=i.attribution??[],i.attribution.some(a=>a.layerId===o.layerId&&a.policyId===o.policyId)||i.attribution.push(o)}return{name:"redirect-attribution",onTrack(i){return n(i),!0},onExposure(i){return n(i),!0}}}var fe=[],Je={};function rn(){if(typeof window>"u")return{version:1,instances:Je,subscribe:()=>()=>{}};if(!window.__TRAFFICAL_DEBUG__){let r={version:1,instances:Je,subscribe(e){return fe.push(e),()=>{fe=fe.filter(t=>t!==e)}}};window.__TRAFFICAL_DEBUG__=r}return window.__TRAFFICAL_DEBUG__}function Qe(r){for(let e of fe)try{e(r)}catch{}}var on=0;function sn(){return`traffical_${Date.now().toString(36)}_${(++on).toString(36)}`}function an(){return`evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}var cn="traffical-debug";function Me(r={}){let e=r.instanceId??sn(),t=r.maxEvents??500,n=null,i=null,o={},s=[],a=null,c=null,f=[],h=[],l=[];function _(){return{ready:n?.isInitialized===!0,stableId:n?.getStableId?.()??null,effectiveUnitKey:c,configVersion:n?.getConfigVersion?.()??null,assignments:{...o},layers:[...s],lastDecisionId:a,overrides:n?.getOverrides?.()??{}}}function u(){let d=_();for(let v of h)try{v(d)}catch{}}function g(d,v){let A={id:an(),type:d,timestamp:Date.now(),data:v};f.push(A),f.length>t&&f.splice(0,f.length-t);for(let O of l)try{O(A)}catch{}}function y(){if(n)try{n.decide({context:{},defaults:{}})}catch{}}let b={id:e,meta:{orgId:"",projectId:"",env:"",sdkVersion:D},getState:_,subscribe(d){return h.push(d),()=>{h=h.filter(v=>v!==d)}},getEvents(d){return d!==void 0?f.slice(-d):[...f]},onEvent(d){return l.push(d),()=>{l=l.filter(v=>v!==d)}},getConfigBundle(){return i},setUnitKey(d){n?.identify?n.identify(d):n?.setStableId&&n.setStableId(d),u()},setOverride(d,v){n?.applyOverrides&&n.applyOverrides({[d]:v}),u(),y()},clearOverride(d){if(n?.getOverrides&&n?.applyOverrides){let v=n.getOverrides();delete v[d],n.clearOverrides?.(),n.applyOverrides(v)}u(),y()},clearAllOverrides(){n?.clearOverrides?.(),u(),y()},getOverrides(){return n?.getOverrides?.()??{}},reDecide(){y()},async refresh(){n?.refreshConfig&&await n.refreshConfig()}};return{name:cn,onInitialize(d){n=d,i&&(b.meta.orgId=i.orgId,b.meta.projectId=i.projectId,b.meta.env=i.env);let v=rn();v.instances[e]=b,Qe({type:"register",instanceId:e}),u()},onConfigUpdate(d){i=d,b.meta.orgId=d.orgId,b.meta.projectId=d.projectId,b.meta.env=d.env,u()},onDecision(d){o={...d.assignments},s=d.metadata?.layers?[...d.metadata.layers]:[],a=d.decisionId,d.metadata?.unitKeyValue&&(c=d.metadata.unitKeyValue),g("decision",d),u()},onResolve(d){o={...d},u()},onExposure(d){return g("exposure",d),!0},onTrack(d){return g("track",d),!0},onDestroy(){let d=typeof window<"u"?window.__TRAFFICAL_DEBUG__:null;d&&(delete d.instances[e],Qe({type:"unregister",instanceId:e})),h=[],l=[],n=null}}}var ge=class{constructor(){this._plugins=[]}register(e){let t="plugin"in e?e.plugin:e,n="priority"in e?e.priority??0:0;return this._plugins.some(i=>i.plugin.name===t.name)?(console.warn(`[Traffical] Plugin "${t.name}" already registered, skipping.`),!1):(this._plugins.push({plugin:t,priority:n}),this._plugins.sort((i,o)=>o.priority-i.priority),!0)}unregister(e){let t=this._plugins.findIndex(n=>n.plugin.name===e);return t===-1?!1:(this._plugins.splice(t,1),!0)}get(e){return this._plugins.find(t=>t.plugin.name===e)?.plugin}getAll(){return this._plugins.map(e=>e.plugin)}async runInitialize(e){for(let{plugin:t}of this._plugins)if(t.onInitialize)try{await t.onInitialize(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onInitialize error:`,n)}}runConfigUpdate(e){for(let{plugin:t}of this._plugins)if(t.onConfigUpdate)try{t.onConfigUpdate(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onConfigUpdate error:`,n)}}runBeforeDecision(e){let t=e;for(let{plugin:n}of this._plugins)if(n.onBeforeDecision)try{let i=n.onBeforeDecision(t);i&&(t=i)}catch(i){console.warn(`[Traffical] Plugin "${n.name}" onBeforeDecision error:`,i)}return t}runDecision(e){for(let{plugin:t}of this._plugins)if(t.onDecision)try{t.onDecision(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onDecision error:`,n)}}runResolve(e){for(let{plugin:t}of this._plugins)if(t.onResolve)try{t.onResolve(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onResolve error:`,n)}}runExposure(e){for(let{plugin:t}of this._plugins)if(t.onExposure)try{if(t.onExposure(e)===!1)return!1}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onExposure error:`,n)}return!0}runTrack(e){for(let{plugin:t}of this._plugins)if(t.onTrack)try{if(t.onTrack(e)===!1)return!1}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onTrack error:`,n)}return!0}runDestroy(){for(let{plugin:e}of this._plugins)if(e.onDestroy)try{e.onDestroy()}catch(t){console.warn(`[Traffical] Plugin "${e.name}" onDestroy error:`,t)}}clear(){this._plugins=[]}};function Ye(){let r=[],e=!1;function t(s){for(let a of r)a(s)}let n=()=>{e=!0,t("background")},i=()=>{typeof document<"u"&&t(document.visibilityState==="hidden"?"background":"foreground")},o=()=>{e=!0,t("background")};return typeof window<"u"&&(window.addEventListener("pagehide",n),window.addEventListener("beforeunload",o)),typeof document<"u"&&document.addEventListener("visibilitychange",i),{onVisibilityChange(s){r.push(s)},removeVisibilityListener(s){let a=r.indexOf(s);a!==-1&&r.splice(a,1)},isUnloading(){return e}}}var Oe="js-client";function Ze(r,e){if(e!==void 0)return{context:r,defaults:e};let t=r;return{context:t.context,defaults:t.defaults}}var ln="https://sdk.traffical.io",un=6e4,dn=1e4,fn=3e5,gn=3e5,hn=100,pn=.1;function mn(r){let e=r*pn;return r+(Math.random()*2-1)*e}function yn(r){if(!r||typeof r!="object")return!1;let e=r;if(!Array.isArray(e.parameters)||!Array.isArray(e.layers))return!1;let t=e.hashing;return!(!t||typeof t!="object"||typeof t.unitKey!="string"||t.unitKey.length===0||typeof t.bucketCount!="number"||!Number.isInteger(t.bucketCount)||t.bucketCount<1)}var M=class{constructor(e){this._state={bundle:null,etag:null,lastFetchTime:0,lastOfflineWarning:0,lastMalformedWarning:0,refreshTimer:null,isInitialized:!1,serverResponse:null,cachedEdgeResults:null};this._decisionCache=new Map;this._cumulativeAttribution=new Map;this._identityListeners=[];this._overrideListeners=[];this._overrides={};this._lastResolveContextKey=null;this._readyPromise=new Promise(e=>{this._readyResolve=e});let t=e.evaluationMode??"bundle";this._options={orgId:e.orgId,projectId:e.projectId,env:e.env,apiKey:e.apiKey,baseUrl:e.baseUrl??ln,localConfig:e.localConfig,refreshIntervalMs:e.refreshIntervalMs??un,attributionMode:e.attributionMode??"cumulative",evaluationMode:t},this._requestTimeoutMs=e.configTimeoutMs??e.requestTimeoutMs??dn;let n={baseUrl:this._options.baseUrl,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,apiKey:this._options.apiKey,defaultTimeoutMs:e.resolveTimeoutMs??e.requestTimeoutMs};if(this._decisionClient=new $(n),this._errorBoundary=new le(e.errorBoundary),this._storage=e.storage??Xe(),this._lifecycleProvider=e.lifecycleProvider??Ye(),!e.onSchemaWarnings)try{typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="development"&&(e.onSchemaWarnings=o=>{for(let s of o)console.warn(`[Traffical] Schema warning for "${s.event}":`,s.violations.map(a=>`${a.path}: ${a.message}`).join(", "))})}catch{}if(this._eventLogger=new ue({endpoint:`${this._options.baseUrl}/v1/events/batch`,apiKey:e.apiKey,storage:this._storage,lifecycleProvider:this._lifecycleProvider,batchSize:e.batchSize??e.eventBatchSize,flushIntervalMs:e.flushIntervalMs??e.eventFlushIntervalMs,maxQueueSize:e.eventMaxQueueSize,requestTimeoutMs:e.eventsTimeoutMs??e.requestTimeoutMs,onError:i=>{console.warn("[Traffical] Event logging error:",i.message)},onSchemaWarnings:e.onSchemaWarnings}),this._exposureDedup=new W({storage:this._storage,sessionTtlMs:e.exposureSessionTtlMs}),this._stableId=new de({storage:this._storage}),this._plugins=new ge,this._assignmentLogger=e.assignmentLogger,this._byoEventLogger=e.eventLogger,this._disableCloudEvents=e.disableCloudEvents??!1,this._assignmentLoggerDedup=e.deduplicateAssignmentLogger!==!1&&e.assignmentLogger?new W({storage:this._storage,sessionTtlMs:e.exposureSessionTtlMs}):null,e.trackDecisions!==!1&&(!this._disableCloudEvents||this._byoEventLogger)&&this._plugins.register({plugin:Pe({deduplicationTtlMs:e.decisionDeduplicationTtlMs},{orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,log:i=>this._dispatchEvent(i),getConfigVersion:()=>this.getConfigVersion()}),priority:100}),e.plugins)for(let i of e.plugins)this._plugins.register(i);if(this._options.localConfig&&(this._state.bundle=this._options.localConfig,this._plugins.runConfigUpdate(this._options.localConfig)),typeof window<"u"){let i=window;i.__TRAFFICAL_INSTANCES__??(i.__TRAFFICAL_INSTANCES__=[]),i.__TRAFFICAL_INSTANCES__.push(this)}}async initialize(){await this._errorBoundary.captureAsync("initialize",async()=>{this._options.evaluationMode==="server"?await this._fetchServerResolve():await this._fetchConfig(),this._startBackgroundRefresh(),this._state.isInitialized=!0,await this._plugins.runInitialize(this)},void 0),this._readyResolve()}get isInitialized(){return this._state.isInitialized}async waitForReady(){return this._readyPromise}async close(){if(this._state.refreshTimer&&(clearInterval(this._state.refreshTimer),this._state.refreshTimer=null),this._lifecycleProvider.isUnloading()?this._eventLogger.flushBeacon():await this._eventLogger.flush().catch(()=>{}),this._eventLogger.destroy(),this._plugins.runDestroy(),this._identityListeners=[],this._overrideListeners=[],this._overrides={},typeof window<"u"){let t=window.__TRAFFICAL_INSTANCES__;if(t){let n=t.indexOf(this);n!==-1&&t.splice(n,1)}}}destroy(){if(this._state.refreshTimer&&(clearInterval(this._state.refreshTimer),this._state.refreshTimer=null),this._lifecycleProvider.isUnloading()?this._eventLogger.flushBeacon():this._eventLogger.flush().catch(()=>{}),this._eventLogger.destroy(),this._plugins.runDestroy(),this._identityListeners=[],this._overrideListeners=[],this._overrides={},typeof window<"u"){let t=window.__TRAFFICAL_INSTANCES__;if(t){let n=t.indexOf(this);n!==-1&&t.splice(n,1)}}}async refreshConfig(){await this._errorBoundary.swallow("refreshConfig",async()=>{this._options.evaluationMode==="server"?await this._fetchServerResolve():await this._fetchConfig()})}getConfigVersion(){return this._state.serverResponse?.stateVersion??this._state.bundle?.version??null}getUnitKeyField(){return oe(this._getEffectiveBundle())}getParameterLayerId(e){return se(this._getEffectiveBundle(),e)}getParams(e,t){let{context:n,defaults:i}=Ze(e,t);return this._errorBoundary.capture("getParams",()=>{if(this._options.evaluationMode==="server"&&this._state.serverResponse){this._maybeResolveForContext(n);let c={...i};for(let[f,h]of Object.entries(this._state.serverResponse.assignments))f in c&&(c[f]=h);return this._plugins.runResolve(c),this._applyOverridesToResult(c),c}let o=this._getEffectiveBundle(),s=this._enrichContext(n),a=ae(o,s,i);return this._plugins.runResolve(a),this._applyOverridesToResult(a),a},i)}decide(e,t){let{context:n,defaults:i}=Ze(e,t);return this._errorBoundary.capture("decide",()=>{if(this._options.evaluationMode==="server"&&this._state.serverResponse){this._maybeResolveForContext(n);let f=this._state.serverResponse,h={...i};for(let[_,u]of Object.entries(f.assignments))_ in h&&(h[_]=u);let l={decisionId:L(),assignments:h,metadata:{...f.metadata,configVersion:f.stateVersion}};return this._cacheDecision(l),this._updateCumulativeAttribution(l),this._plugins.runDecision(l),this._applyOverridesToResult(l.assignments),this._emitAssignmentLogEntries(l,"decision"),l}let o=this._getEffectiveBundle(),s=this._enrichContext(n);s=this._plugins.runBeforeDecision(s);let a=this._state.cachedEdgeResults??void 0,c=ce(o,s,i,a);return this._cacheDecision(c),this._updateCumulativeAttribution(c),this._plugins.runDecision(c),this._applyOverridesToResult(c.assignments),this._emitAssignmentLogEntries(c,"decision"),c},{decisionId:L(),assignments:i,metadata:{timestamp:new Date().toISOString(),unitKeyValue:"",layers:[]}})}trackExposure(e){this._errorBoundary.capture("trackExposure",()=>{let t=e.metadata.unitKeyValue;if(!t)return;this._emitAssignmentLogEntries(e,"exposure");let n=e.metadata.configVersion??this.getConfigVersion()??void 0,i=[];for(let s of e.metadata.layers)!s.policyId||!s.allocationName||s.attributionOnly||!this._exposureDedup.checkAndMark(t,s.policyId,s.allocationName)||i.push(s);if(i.length===0)return;let o={type:"exposure",id:we(),decisionId:e.decisionId,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,unitKey:t,timestamp:new Date().toISOString(),assignments:e.assignments,layers:i,context:e.metadata.filteredContext,configVersion:n,sdkName:Oe,sdkVersion:D};this._plugins.runExposure(o)&&this._dispatchEvent(o)},void 0)}track(e,t,n){this._errorBoundary.capture("track",()=>{let i=n?.unitKey??this._stableId.getId(),o=typeof n?.value=="number"?n.value:typeof t?.value=="number"?t.value:void 0,s=this._buildAttribution(i,n?.decisionId),a=n?.decisionId,c={type:"track",id:Ae(),orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,unitKey:i,timestamp:new Date().toISOString(),event:e,value:o,values:n?.values,properties:t,decisionId:a,attribution:s,eventTimestamp:n?.eventTimestamp,sdkName:Oe,sdkVersion:D};this._plugins.runTrack(c)&&this._dispatchEvent(c)},void 0)}async flushEvents(){await this._errorBoundary.swallow("flushEvents",async()=>{await this._eventLogger.flush()})}use(e){if(!this._plugins.register(e))return this;if(this._state.isInitialized){try{e.onInitialize?.(this)}catch(n){console.warn(`[Traffical] Plugin "${e.name}" late onInitialize error:`,n)}if(this._state.bundle)try{e.onConfigUpdate?.(this._state.bundle)}catch(n){console.warn(`[Traffical] Plugin "${e.name}" late onConfigUpdate error:`,n)}}return this}getPlugin(e){return this._plugins.get(e)}getStableId(){return this._stableId.getId()}setStableId(e){this._stableId.setId(e)}identify(e){this._stableId.setId(e);for(let t of this._identityListeners)try{t(e)}catch{}}onIdentityChange(e){return this._identityListeners.push(e),()=>{this._identityListeners=this._identityListeners.filter(t=>t!==e)}}onOverridesChange(e){return this._overrideListeners.push(e),()=>{this._overrideListeners=this._overrideListeners.filter(t=>t!==e)}}applyOverrides(e){Object.assign(this._overrides,e),this._notifyOverrideListeners()}clearOverrides(){this._overrides={},this._notifyOverrideListeners()}getOverrides(){return{...this._overrides}}_notifyOverrideListeners(){let e={...this._overrides};for(let t of this._overrideListeners)try{t(e)}catch{}}_dispatchEvent(e){if(this._byoEventLogger)try{this._byoEventLogger(e)}catch{}this._disableCloudEvents||this._eventLogger.log(e)}_emitAssignmentLogEntries(e,t){if(!this._assignmentLogger)return;let n=e.metadata.unitKeyValue;if(!n)return;let i=e.metadata.configVersion??this.getConfigVersion()??void 0;for(let o of e.metadata.layers)!o.policyId||!o.allocationName||this._assignmentLoggerDedup&&!this._assignmentLoggerDedup.checkAndMark(n,o.policyId,`${o.allocationName}:${t}`)||this._assignmentLogger({unitKey:n,policyId:o.policyId,policyKey:o.policyKey,allocationName:o.allocationName,allocationKey:o.allocationKey,timestamp:e.metadata.timestamp,layerId:o.layerId,allocationId:o.allocationId,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,sdkName:Oe,sdkVersion:D,properties:e.metadata.filteredContext,type:t,decisionId:e.decisionId,anonymousId:this._stableId.getId(),id:Ce(),bucket:o.bucket>=0?o.bucket:void 0,probability:o.probability,modelVersion:o.modelVersion,configVersion:i})}_applyOverridesToResult(e){let t=Object.keys(this._overrides);if(t.length!==0)for(let n of t)n in e&&(e[n]=this._overrides[n])}_getEffectiveBundle(){return this._state.bundle??this._options.localConfig??null}_enrichContext(e){let n=this._getEffectiveBundle()?.hashing?.unitKey??"userId";return e[n]?e:{...e,[n]:this._stableId.getId()}}async _fetchConfig(){let e=`${this._options.baseUrl}/v1/config/${encodeURIComponent(this._options.projectId)}?env=${encodeURIComponent(this._options.env)}`,t={"Content-Type":"application/json",Authorization:`Bearer ${this._options.apiKey}`};this._state.etag&&(t["If-None-Match"]=this._state.etag);let n=new AbortController,i=setTimeout(()=>n.abort(),this._requestTimeoutMs);try{let o=await fetch(e,{method:"GET",headers:t,signal:n.signal});if(o.status===304){this._state.lastFetchTime=Date.now();return}if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let s=await o.json(),a=o.headers.get("ETag");if(!yn(s)){this._logMalformedBundleWarning();return}if(this._state.bundle=s,this._state.etag=a,this._state.lastFetchTime=Date.now(),this._findEdgePolicies(s).length>0){let c=await this._prefetchEdgeResults(s,this._enrichContext({}));this._state.cachedEdgeResults=c}else this._state.cachedEdgeResults=null;this._plugins.runConfigUpdate(s)}catch(o){this._logOfflineWarning(o)}finally{clearTimeout(i)}}_startBackgroundRefresh(){let e=this._options.evaluationMode==="server"?this._state.serverResponse?.suggestedRefreshMs??this._options.refreshIntervalMs:this._options.refreshIntervalMs;if(e<=0)return;let t=()=>{this._state.refreshTimer=setTimeout(()=>{t(),this._options.evaluationMode==="server"?this._fetchServerResolve().catch(()=>{}):this._fetchConfig().catch(()=>{})},mn(e))};t()}_maybeResolveForContext(e){let t=this._enrichContext(e),n;try{n=JSON.stringify(t)}catch{n=""}n!==this._lastResolveContextKey&&(this._lastResolveContextKey=n,this._fetchServerResolve(t))}async _fetchServerResolve(e){if(this._decisionClient)try{let t=e??this._enrichContext({}),n=await this._decisionClient.resolve({context:t});n&&(this._state.serverResponse=n,this._state.lastFetchTime=Date.now())}catch(t){this._logOfflineWarning(t)}}_findEdgePolicies(e){let t=[];for(let n of e.layers)for(let i of n.policies)i.state==="running"&&i.entityConfig?.resolutionMode==="edge"&&t.push(i);return t}async _prefetchEdgeResults(e,t){if(!this._decisionClient)return{};let n=this._findEdgePolicies(e);if(n.length===0)return{};let i=K(e,t);if(!i)return{};let o=n.map(s=>{if(!s.entityConfig)return null;let a=s.entityConfig.dynamicAllocations?typeof t[s.entityConfig.dynamicAllocations.countKey]=="number"?Math.floor(t[s.entityConfig.dynamicAllocations.countKey]):0:s.allocations.length;return ke(s.id,s.entityConfig.entityKeys,t,i,a||void 0)}).filter(s=>s!==null);if(o.length===0)return{};try{let s=await this._decisionClient.decideEntityBatch(o),a=new Map;for(let c=0;c<o.length;c++){let f=s[c];f&&a.set(o[c].policyId,{allocationIndex:f.allocationIndex,entityId:o[c].entityId})}return a.size>0?{edgeResults:a}:{}}catch{return{}}}_logOfflineWarning(e){let t=Date.now();t-this._state.lastOfflineWarning>fn&&(console.warn(`[Traffical] Failed to fetch config: ${e instanceof Error?e.message:String(e)}. Using ${this._state.bundle?"cached":"local"} config.`),this._state.lastOfflineWarning=t)}_logMalformedBundleWarning(){let e=Date.now();e-this._state.lastMalformedWarning>gn&&(console.warn(`[Traffical] Discarded malformed config bundle (invalid hashing/shape). Using ${this._state.bundle?"cached":"local"} config.`),this._state.lastMalformedWarning=e)}_cacheDecision(e){if(this._decisionCache.size>=hn){let t=this._decisionCache.keys().next().value;t&&this._decisionCache.delete(t)}this._decisionCache.set(e.decisionId,e)}_updateCumulativeAttribution(e){let t=e.metadata.unitKeyValue;if(!t)return;let n=this._cumulativeAttribution.get(t);n||(n=new Map,this._cumulativeAttribution.set(t,n));for(let i of e.metadata.layers){if(!i.policyId||!i.allocationName)continue;let o=`${i.layerId}:${i.policyId}`;n.set(o,{layerId:i.layerId,policyId:i.policyId,allocationName:i.allocationName})}}_buildAttribution(e,t){if(this._options.attributionMode==="decision"){if(!t)return;let i=this._decisionCache.get(t);return i?i.metadata.layers.filter(o=>o.policyId&&o.allocationName).map(o=>({layerId:o.layerId,policyId:o.policyId,allocationName:o.allocationName})):void 0}let n=this._cumulativeAttribution.get(e);return n&&n.size>0?Array.from(n.values()):void 0}};async function et(r){let e=new M(r);return await e.initialize(),e}function tt(r){return new M(r)}function nt(r={}){let e={observeMutations:r.observeMutations??!0,debounceMs:r.debounceMs??100},t=[],n={},i=null,o=null;function s(u,g){try{return new RegExp(u).test(g)}catch{return g===u}}function a(u,g,y){if(g==="innerHTML")u.innerHTML=y;else if(g==="textContent")u.textContent=y;else if(g==="src"&&"src"in u)u.src=y;else if(g==="href"&&"href"in u)u.href=y;else if(g.startsWith("style.")){let b=g.slice(6);u.style[b]=y}else u.setAttribute(g,y)}function c(u,g){let y=String(g);try{let b=document.querySelectorAll(u.selector);for(let w of b)a(w,u.property,y)}catch(b){console.warn(`[Traffical DOM Binding] Failed to apply binding for ${u.parameterKey}:`,b)}}function f(u,g=!1){n=u;let y=typeof window<"u"?window.location.pathname:"";for(let b of t){if(!g&&!s(b.urlPattern,y))continue;let w=u[b.parameterKey];w!==void 0&&c(b,w)}}function h(){o&&clearTimeout(o),o=setTimeout(()=>{f(n)},e.debounceMs)}function l(){i||typeof MutationObserver>"u"||typeof document>"u"||(i=new MutationObserver(()=>{h()}),i.observe(document.body,{childList:!0,subtree:!0}))}function _(){i&&(i.disconnect(),i=null),o&&(clearTimeout(o),o=null)}return{name:"dom-binding",onInitialize(){e.observeMutations&&l()},onConfigUpdate(u){t=u.domBindings??[]},onResolve(u){f(u)},onDecision(u){f(u.assignments)},onDestroy(){_(),t=[],n={}},applyBindings(u){f(u||n)},getBindings(){return t}}}var T=null;async function vn(r){return T?(console.warn("[Traffical] Client already initialized. Returning existing instance."),T):(T=await et(r),T)}function _n(r){return T?(console.warn("[Traffical] Client already initialized. Returning existing instance."),T):(T=tt(r),T.initialize().catch(e=>{console.warn("[Traffical] Initialization error:",e)}),T)}function bn(){return T}function xn(){T&&(T.destroy(),T=null)}return ut(En);})();
|
|
3
3
|
//# sourceMappingURL=traffical.min.js.map
|