@wetusco/wts-web-sdk 0.1.0-alpha.2

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/CHANGELOG.md ADDED
@@ -0,0 +1,21 @@
1
+ # Changelog
2
+
3
+ All notable changes follow [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and Semantic Versioning.
4
+
5
+ ## [0.1.0-alpha.2] - 2026-07-16
6
+
7
+ ### Changed
8
+
9
+ - Renamed the canonical npm package to `@wetusco/wts-web-sdk`.
10
+ - Preserved the Protocol V2 API and runtime behavior without integration changes.
11
+
12
+ ## [0.1.0-alpha.1] - 2026-07-16
13
+
14
+ ### Added
15
+
16
+ - Consent-first Web Protocol V2 bootstrap and event delivery
17
+ - Explicit and optional SPA page-view tracking
18
+ - Typed custom events and decimal revenue
19
+ - Deterministic signed-link attribution
20
+ - Bounded IndexedDB queue, retry, idempotency, and multi-tab locking
21
+ - SSR-safe ESM/CJS builds and versioned IIFE with SHA-384 SRI
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Wetus
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # @wetusco/wts-web-sdk
2
+
3
+ Consent-first browser measurement and deterministic wts.is link attribution. The SDK is dependency-free, safe to import during server rendering, and never collects DOM content, form values, URL queries, fragments, advertising identifiers, or fingerprints.
4
+
5
+ > `0.1.0-alpha.2` is an early integration release using wts.is Web Protocol V2.
6
+
7
+ ## Requirements
8
+
9
+ - A Web App created in the wts.is dashboard
10
+ - The page origin included in that Web App's exact allowed-origin list
11
+ - Safari 15+ or the latest two major Chrome, Edge, and Firefox releases
12
+ - A consent-management decision supplied on every page load
13
+
14
+ ## npm installation
15
+
16
+ ```bash
17
+ npm install @wetusco/wts-web-sdk@next
18
+ ```
19
+
20
+ ```ts
21
+ import { createWtsClient } from "@wetusco/wts-web-sdk";
22
+
23
+ const wts = createWtsClient({
24
+ sourceKey: "web_public_source_key",
25
+ consent: "pending",
26
+ autoTrackPageViews: false,
27
+ });
28
+
29
+ // Call from your CMP callback. Pending sends nothing and opens no storage.
30
+ await wts.setConsent("granted");
31
+ await wts.page("Pricing");
32
+
33
+ await wts.track(
34
+ "purchase",
35
+ { plan: "enterprise", member: true },
36
+ { amount: "1490.50", currency: "TRY" },
37
+ );
38
+ ```
39
+
40
+ Custom events must be registered in the Web App before they can be accepted. Revenue is a decimal string and always requires a three-letter ISO-4217 currency.
41
+
42
+ ## Script installation
43
+
44
+ Use a versioned artifact and the SRI value shipped next to it. Do not use an unversioned `latest` script in production.
45
+
46
+ ```html
47
+ <script
48
+ src="https://cdn.jsdelivr.net/npm/@wetusco/wts-web-sdk@0.1.0-alpha.2/dist/wts-web.iife.min.js"
49
+ integrity="sha384-yd6nOlkavObZDFnbLq8jTn6bMrD8gIU+Er4oOqzNTa2Mo2VnD6wPG8VFZqVMIKyC"
50
+ crossorigin="anonymous"
51
+ ></script>
52
+ <script>
53
+ const wts = window.WtsWeb.createWtsClient({
54
+ sourceKey: "web_public_source_key",
55
+ consent: "pending",
56
+ });
57
+ </script>
58
+ ```
59
+
60
+ The IIFE exports `window.WtsWeb`. The release workflow records the exact SHA-384 value in `dist/wts-web.iife.min.js.sri`.
61
+
62
+ ## Consent behavior
63
+
64
+ - `pending` is the default. No network request, identity, storage, or queue is created.
65
+ - `granted` opens the first-party IndexedDB queue and starts delivery.
66
+ - `denied` clears all SDK storage and stops delivery.
67
+ - The SDK does not persist the consent decision. Your CMP must call `setConsent` on each page load.
68
+
69
+ Calls to `page` and `track` while pending or denied return an explicit no-op result. They are never retained in memory for later delivery.
70
+
71
+ The anonymous identity is first-party and persistent. The session identity and bootstrap idempotency key live in `sessionStorage`, so full-page navigations in the same browser session do not inflate session counts.
72
+
73
+ ## Page tracking
74
+
75
+ Explicit page tracking is the default and recommended mode:
76
+
77
+ ```ts
78
+ await wts.page("Account overview");
79
+ ```
80
+
81
+ For client-side routers, set `autoTrackPageViews: true`. The SDK observes the initial pathname plus `pushState`, `replaceState`, and `popstate`, deduplicates repeated pathnames, and restores all listeners in `destroy()`. It only sends normalized pathname, optional page name, and referrer hostname.
82
+
83
+ ## Link attribution
84
+
85
+ When a wts.is link is assigned to the same Web App, the redirect adds a short-lived signed `_wts` token. The SDK removes it from the address bar, keeps it only in memory until consent, and redeems it for a seven-day attribution context. The raw token is not stored with events.
86
+
87
+ ## Queue and lifecycle
88
+
89
+ - Persistent first-party IndexedDB FIFO; bounded memory fallback when unavailable
90
+ - Maximum 100 events or 1 MiB
91
+ - Maximum 50 events or 64 KiB per request
92
+ - UUID idempotency, exponential retry with jitter, multi-tab delivery lock
93
+ - `pagehide` and hidden-page delivery with `fetch(..., { keepalive: true })`
94
+
95
+ ```ts
96
+ await wts.flush(); // optional manual delivery
97
+ await wts.reset(); // clears identity, session, queue, and attribution
98
+ wts.destroy(); // removes timers and SPA/lifecycle listeners
99
+ ```
100
+
101
+ ## CSP
102
+
103
+ Allow the collector in your Content Security Policy:
104
+
105
+ ```text
106
+ connect-src 'self' https://collect.wts.is
107
+ ```
108
+
109
+ ## Framework notes
110
+
111
+ Importing the package in Next.js or another SSR runtime is safe. Browser APIs are accessed only when a client is created in a browser. See `examples/vite` and `examples/plain-html` for minimal integrations.
112
+
113
+ ## Privacy and support
114
+
115
+ Read [SECURITY.md](SECURITY.md), [SUPPORT.md](SUPPORT.md), and the wts.is [Web SDK documentation](https://wts.is/en/resources/docs/sdk-web). Please do not report vulnerabilities in public issues.
116
+
117
+ ## License
118
+
119
+ Apache License 2.0.
package/SECURITY.md ADDED
@@ -0,0 +1,15 @@
1
+ # Security and privacy
2
+
3
+ ## Reporting
4
+
5
+ Report suspected vulnerabilities privately to `security@wetus.co`. Include the affected version, reproduction steps, expected impact, and any suggested mitigation. Do not publish credentials, source keys tied to a private environment, attribution tokens, or customer event data in an issue.
6
+
7
+ ## Data boundary
8
+
9
+ The source key is a public identifier, not a secret. Security is enforced with exact allowed origins, entitlement and contract checks, rate limits, schema validation, and event UUID idempotency.
10
+
11
+ The SDK does not collect IDFA, GAID, browser fingerprints, canvas/device fingerprints, third-party cookies, DOM text, form fields, raw IP addresses, raw user agents, URL query strings, or fragments. Anonymous and session UUIDs are first-party values and are HMAC-pseudonymized by the collector.
12
+
13
+ ## Supported versions
14
+
15
+ Security fixes are applied to the latest prerelease during the alpha period. After 1.0, the current major version receives security fixes according to the published support policy.
package/SUPPORT.md ADDED
@@ -0,0 +1,14 @@
1
+ # Support policy
2
+
3
+ ## Browser support
4
+
5
+ - Safari 15+
6
+ - Latest two major versions of Chrome, Edge, and Firefox
7
+
8
+ ## Release support
9
+
10
+ `0.x` releases may include additive API refinement and are intended for controlled pilots. Production adopters should pin an exact version and review the changelog before upgrading. Stable releases follow Semantic Versioning.
11
+
12
+ ## Getting help
13
+
14
+ Use the wts.is support channel for integration help and GitHub issues for reproducible SDK defects that contain no sensitive data. Security reports must follow [SECURITY.md](SECURITY.md).
package/dist/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ 'use strict';var y="0.1.0-alpha.2";var S="_wts";function c(){let n=globalThis.crypto;if(!n)throw new Error("A secure random number generator is required.");if(typeof n.randomUUID=="function")return n.randomUUID();let t=n.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=Array.from(t,i=>i.toString(16).padStart(2,"0"));return `${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}function m(n){return new TextEncoder().encode(JSON.stringify(n)).byteLength}function g(){return typeof navigator>"u"?"en":navigator.language||"en"}function k(){if(!(typeof document>"u"||!document.referrer))try{return new URL(document.referrer).hostname.toLowerCase()||void 0}catch{return}}function v(n,t){n&&typeof console<"u"&&console.warn(`[wts.is] ${t}`);}function R(n){if(!(typeof sessionStorage>"u"))try{let t=JSON.parse(sessionStorage.getItem(I(n))??"null");return t&&A(t.sessionId)&&A(t.bootstrapClientEventId)?{sessionId:t.sessionId,bootstrapClientEventId:t.bootstrapClientEventId}:void 0}catch{return}}function O(n,t){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(I(n),JSON.stringify(t));}catch{}}function T(n){if(!(typeof sessionStorage>"u"))try{sessionStorage.removeItem(I(n));}catch{}}function I(n){return `wts-session-${n}`}function A(n){return typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}var j=1e4,b=class{constructor(t){this.name=t;}async run(t){if(typeof navigator<"u"&&navigator.locks)return navigator.locks.request(this.name,t);this.current&&await this.current;let e=this.acquireLease();if(!e)return;let i=t();this.current=i;try{return await i}finally{this.current===i&&(this.current=void 0),e.release();}}acquireLease(){if(typeof localStorage>"u")return {release(){}};let t=`wts-lock-${this.name}`,e=c(),i=Date.now();try{let r=C(localStorage.getItem(t));return r&&r.expiresAt>i||(localStorage.setItem(t,JSON.stringify({token:e,expiresAt:i+j})),C(localStorage.getItem(t))?.token!==e)?void 0:{release(){C(localStorage.getItem(t))?.token===e&&localStorage.removeItem(t);}}}catch{return {release(){}}}}};function C(n){if(n)try{let t=JSON.parse(n);return typeof t.token=="string"&&typeof t.expiresAt=="number"?{token:t.token,expiresAt:t.expiresAt}:void 0}catch{return}}function q(n){if(typeof window>"u")return ()=>{};let t=window.history,e=t.pushState,i=t.replaceState,r=false,s=()=>{r||(r=true,queueMicrotask(()=>{r=false,n();}));};return t.pushState=function(...o){e.apply(this,o),s();},t.replaceState=function(...o){i.apply(this,o),s();},window.addEventListener("popstate",s),()=>{t.pushState=e,t.replaceState=i,window.removeEventListener("popstate",s);}}var d="meta",u="events";async function _(n){if(typeof indexedDB>"u")throw new Error("IndexedDB is unavailable.");return P.open(n)}async function D(n){if(typeof indexedDB>"u")return;let t=indexedDB.deleteDatabase(N(n));await new Promise((e,i)=>{t.onsuccess=()=>e(),t.onerror=()=>i(t.error??new Error("IndexedDB deletion failed.")),t.onblocked=()=>i(new Error("IndexedDB deletion was blocked by another tab."));});}var w=class{constructor(){this.state={queue:[]};}async load(){return B(this.state)}async saveIdentity(t){this.state.identity={...t};}async saveAttributionContext(t,e){t&&e?(this.state.attributionContextId=t,this.state.attributionContextExpiresAt=e):(delete this.state.attributionContextId,delete this.state.attributionContextExpiresAt);}async enqueue(t){this.state.queue.push(B(t)),W(this.state.queue);}async remove(t){this.state.queue=this.state.queue.filter(e=>!t.has(e.clientEventId));}async clear(){this.state={queue:[]};}close(){}},P=class n{constructor(t){this.database=t;}static async open(t){let e=indexedDB.open(N(t),1);return e.onupgradeneeded=()=>{let i=e.result;i.objectStoreNames.contains(d)||i.createObjectStore(d),i.objectStoreNames.contains(u)||i.createObjectStore(u,{keyPath:"clientEventId"});},new n(await p(e))}async load(){let t=this.database.transaction([d,u],"readonly"),e=t.objectStore(d),i=t.objectStore(u),[r,s,o,a]=await Promise.all([p(e.get("identity")),p(e.get("attributionContextId")),p(e.get("attributionContextExpiresAt")),p(i.getAll())]);return await l(t),a.sort((f,U)=>f.occurredAt.localeCompare(U.occurredAt)),{...r?{identity:r}:{},...s&&o?{attributionContextId:s,attributionContextExpiresAt:o}:{},queue:a}}async saveIdentity(t){await this.writeMeta("identity",t);}async saveAttributionContext(t,e){let i=this.database.transaction(d,"readwrite"),r=i.objectStore(d);t&&e?(r.put(t,"attributionContextId"),r.put(e,"attributionContextExpiresAt")):(r.delete("attributionContextId"),r.delete("attributionContextExpiresAt")),await l(i);}async enqueue(t){let e=await this.load(),i=[...e.queue,t];W(i);let r=new Set(i.map(a=>a.clientEventId)),s=this.database.transaction(u,"readwrite"),o=s.objectStore(u);o.put(t);for(let a of e.queue)r.has(a.clientEventId)||o.delete(a.clientEventId);await l(s);}async remove(t){if(t.size===0)return;let e=this.database.transaction(u,"readwrite"),i=e.objectStore(u);for(let r of t)i.delete(r);await l(e);}async clear(){let t=this.database.transaction([d,u],"readwrite");t.objectStore(d).clear(),t.objectStore(u).clear(),await l(t);}close(){this.database.close();}async writeMeta(t,e){let i=this.database.transaction(d,"readwrite");i.objectStore(d).put(e,t),await l(i);}};function W(n){for(;n.length>100||m(n)>1048576;)n.shift();}function p(n){return new Promise((t,e)=>{n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error??new Error("IndexedDB request failed."));})}function l(n){return new Promise((t,e)=>{n.oncomplete=()=>t(),n.onerror=()=>e(n.error??new Error("IndexedDB transaction failed.")),n.onabort=()=>e(n.error??new Error("IndexedDB transaction aborted."));})}function B(n){return JSON.parse(JSON.stringify(n))}function N(n){return `wts-web-${n}`}var E=class{constructor(t,e){this.collectorOrigin=t;this.timeoutMs=e;}async bootstrap(t){return await(await this.post("/v2/bootstrap",t.sourceKey,{schemaVersion:2,clientEventId:t.clientEventId,...t.identity,occurredAt:new Date().toISOString(),metadata:{platform:"web",sdkVersion:y,locale:g()},...t.attributionToken?{attributionToken:t.attributionToken}:{}},false)).json()}async send(t,e,i){return await(await this.post("/v2/events/batch",t,{schemaVersion:2,events:e},i)).json()}async post(t,e,i,r){let s=new AbortController,o=setTimeout(()=>s.abort(),this.timeoutMs);try{let a=await fetch(`${this.collectorOrigin}${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-WTS-Source-Key":e},body:JSON.stringify(i),credentials:"omit",mode:"cors",cache:"no-store",keepalive:r,signal:s.signal});if(!a.ok)throw await h.fromResponse(a);return a}finally{clearTimeout(o);}}},h=class n extends Error{constructor(e,i,r,s){super(e);this.status=i;this.retryable=r;this.code=s;this.name="WtsTransportError";}static async fromResponse(e){let i={};try{i=await e.json();}catch{}return new n(i.message??`Collector request failed with status ${e.status}.`,e.status,e.status===429||e.status>=500,i.code)}};var V=/^[a-z][a-z0-9_]{1,63}$/,z=/^[A-Za-z0-9_-]{8,128}$/,H=/^[A-Z]{3}$/,X=/^-?\d{1,12}(?:\.\d{1,6})?$/;function L(n){if(!z.test(n.sourceKey))throw new TypeError("sourceKey must be a valid wts.is Web App source key.");let t=new URL(n.collectorOrigin??"https://collect.wts.is");if(t.protocol!=="https:"&&!F(t.hostname))throw new TypeError("collectorOrigin must use HTTPS outside localhost.");if(t.pathname!=="/"||t.search||t.hash)throw new TypeError("collectorOrigin must not include a path, query, or fragment.");let e=n.requestTimeoutMs??2e3;if(!Number.isInteger(e)||e<250||e>3e4)throw new TypeError("requestTimeoutMs must be an integer between 250 and 30000.");return {sourceKey:n.sourceKey,consent:n.consent??"pending",autoTrackPageViews:n.autoTrackPageViews??false,collectorOrigin:t.origin,requestTimeoutMs:e,debug:n.debug??false}}function M(n,t,e){if(!V.test(n))throw new TypeError("eventKey must match ^[a-z][a-z0-9_]{1,63}$.");let i=Object.entries(t);if(i.length>20)throw new TypeError("Events can contain at most 20 properties.");for(let[r,s]of i){if(!/^[a-z][a-z0-9_]{0,63}$/.test(r))throw new TypeError(`Invalid property key: ${r}`);if(!["string","number","boolean"].includes(typeof s))throw new TypeError(`Property ${r} must be a string, number, or boolean.`);if(typeof s=="string"&&s.length>512)throw new TypeError(`Property ${r} cannot exceed 512 characters.`);if(typeof s=="number"&&!Number.isFinite(s))throw new TypeError(`Property ${r} must be finite.`)}if(e&&(!X.test(e.amount)||!H.test(e.currency)))throw new TypeError("Revenue requires a decimal amount and uppercase ISO-4217 currency.")}function $(n){let t=n.startsWith("/")?n:`/${n}`;if(t.includes("?")||t.includes("#"))throw new TypeError("Page pathname cannot include a query or fragment.");if(t.length>2048)throw new TypeError("Page pathname cannot exceed 2048 characters.");return t}function F(n){return n==="localhost"||n==="127.0.0.1"||n==="[::1]"}var Q=10080*6e4,x=class{constructor(t,e){this.bootstrapClientEventId=c();this.bootstrapped=false;this.destroyed=false;this.retryAttempt=0;this.onPageHide=()=>{this.consent==="granted"&&this.lock.run(()=>this.flushExclusive(true));};this.onVisibilityChange=()=>{document.visibilityState==="hidden"&&this.consent==="granted"&&this.lock.run(()=>this.flushExclusive(true));};this.options=L(t),this.consent=this.options.consent,this.transport=e??new E(this.options.collectorOrigin,this.options.requestTimeoutMs),this.lock=new b(`flush-${this.options.sourceKey}`),this.attributionToken=G(),this.installLifecycleListeners(),this.consent==="granted"&&this.startEnable(),this.consent==="denied"&&(this.attributionToken=void 0);}async setConsent(t){if(this.destroyed)return;if(t==="denied"){this.consent="denied",this.cancelRetry();let i=this.storage;i&&await this.lock.run(async()=>{await i.clear(),i.close();});try{await D(this.options.sourceKey);}catch{v(this.options.debug,"Stored SDK data could not be deleted because it is in use.");}this.storage=void 0,this.identity=void 0,this.attributionContextId=void 0,this.attributionContextExpiresAt=void 0,this.attributionToken=void 0,this.bootstrapped=false,T(this.options.sourceKey),this.removeSpaTracking();return}let e=this.consent==="granted";this.consent="granted",(!e||!this.storage)&&await this.startEnable();}async page(t){let e=this.unavailableResult();if(e||(await this.ensureReady(),e=this.unavailableResult(),e))return e;let i=K(),r=k(),s={...this.eventBase("page_view"),pathname:i,...t?.trim()?{pageName:t.trim().slice(0,120)}:{},...r?{referrerHost:r}:{},properties:{}};return await this.enqueue(s),this.lastPagePath=i,{accepted:true,clientEventId:s.clientEventId}}async track(t,e={},i){let r=this.unavailableResult();if(r||(await this.ensureReady(),r=this.unavailableResult(),r))return r;M(t,e,i);let s={...this.eventBase("custom"),eventKey:t,properties:{...e},...i?{revenue:{...i}}:{}};return await this.enqueue(s),{accepted:true,clientEventId:s.clientEventId}}async flush(){return this.consent!=="granted"||this.destroyed||!this.storage?{sent:0,pending:0}:await this.lock.run(async()=>this.flushExclusive(false))??{sent:0,pending:(await this.storage.load()).queue.length}}async reset(){this.cancelRetry(),await this.storage?.clear(),this.identity=void 0,this.attributionContextId=void 0,this.attributionContextExpiresAt=void 0,this.attributionToken=void 0,T(this.options.sourceKey),this.bootstrapClientEventId=c(),this.bootstrapped=false,this.lastPagePath=void 0,this.consent==="granted"&&!this.destroyed&&await this.initializeIdentity();}destroy(){if(this.destroyed)return;this.destroyed=true,this.cancelRetry(),this.removeSpaTracking(),this.removeLifecycleListeners();let t=this.storage;t&&this.lock.run(async()=>t.close());}async enable(){if(!(this.destroyed||this.consent!=="granted")){if(!this.storage)try{this.storage=await _(this.options.sourceKey),await this.storage.load();}catch{this.storage?.close(),this.storage=new w,v(this.options.debug,"IndexedDB unavailable; using a memory-only event queue.");}await this.initializeIdentity();try{await this.ensureBootstrapped();}catch(t){this.handleRetryableError(t);}this.options.autoTrackPageViews&&!this.removeSpaTracker&&(this.removeSpaTracker=q(()=>{this.trackAutomaticPage();}),await this.trackAutomaticPage()),this.flush();}}startEnable(){if(this.enablePromise)return this.enablePromise;let t=this.enable();return this.enablePromise=t,t.finally(()=>{this.enablePromise===t&&(this.enablePromise=void 0);}),t}async ensureReady(){this.consent==="granted"&&(!this.storage||!this.identity)&&await this.startEnable();}async initializeIdentity(){if(!this.storage)return;let t=await this.storage.load(),e=R(this.options.sourceKey);this.identity={anonymousId:t.identity?.anonymousId??c(),sessionId:e?.sessionId??c()},this.bootstrapClientEventId=e?.bootstrapClientEventId??c(),O(this.options.sourceKey,{sessionId:this.identity.sessionId,bootstrapClientEventId:this.bootstrapClientEventId});let i=t.attributionContextExpiresAt?Date.parse(t.attributionContextExpiresAt):Number.NaN;t.attributionContextId&&Number.isFinite(i)&&i>Date.now()?(this.attributionContextId=t.attributionContextId,this.attributionContextExpiresAt=i):(t.attributionContextId||t.attributionContextExpiresAt)&&await this.storage.saveAttributionContext(),(!t.identity||t.identity.anonymousId!==this.identity.anonymousId||t.identity.sessionId!==this.identity.sessionId)&&await this.storage.saveIdentity(this.identity);}async ensureBootstrapped(){if(this.bootstrapped||!this.identity||!this.storage)return;let t=await this.transport.bootstrap({sourceKey:this.options.sourceKey,identity:this.identity,clientEventId:this.bootstrapClientEventId,...this.attributionToken?{attributionToken:this.attributionToken}:{}});if(this.bootstrapped=true,this.attributionToken=void 0,t.attributionContextId){this.attributionContextId=t.attributionContextId;let e=Date.parse(t.serverTime);this.attributionContextExpiresAt=(Number.isFinite(e)?e:Date.now())+Q,await this.storage.saveAttributionContext(t.attributionContextId,new Date(this.attributionContextExpiresAt).toISOString());}this.retryAttempt=0;}async enqueue(t){this.storage&&(await this.storage.enqueue(t),queueMicrotask(()=>{this.flush();}));}async flushExclusive(t){if(!this.storage)return {sent:0,pending:0};if(this.retryTimer&&!t)return {sent:0,pending:(await this.storage.load()).queue.length};try{await this.ensureBootstrapped();let e=await this.storage.load(),i=Z(e.queue,this.activeAttributionContextId());if(i.length===0)return {sent:0,pending:e.queue.length};let r=await this.transport.send(this.options.sourceKey,i,t),s=new Set([...r.accepted,...r.duplicates]),o=!1;for(let f of r.rejected)f.retryable?o=!0:s.add(f.clientEventId);await this.storage.remove(s);let a=(await this.storage.load()).queue.length;return o?this.scheduleRetry():(this.retryAttempt=0,a>0&&queueMicrotask(()=>{this.flush();})),{sent:s.size,pending:a}}catch(e){return this.handleRetryableError(e),{sent:0,pending:(await this.storage.load()).queue.length}}}handleRetryableError(t){if(t instanceof h&&!t.retryable){v(this.options.debug,`Collector rejected the request (${t.code??t.status}).`);return}this.scheduleRetry();}scheduleRetry(){if(this.consent!=="granted"||this.destroyed||this.retryTimer)return;let t=Math.min(6e4,1e3*2**Math.min(this.retryAttempt,6)),e=Math.floor(Math.random()*Math.max(1,t*.25));this.retryAttempt+=1,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.flush();},t+e);}async trackAutomaticPage(){K()!==this.lastPagePath&&await this.page();}eventBase(t){if(!this.identity)throw new Error("Web SDK identity is unavailable.");let e=this.activeAttributionContextId();return {schemaVersion:2,clientEventId:c(),...this.identity,type:t,occurredAt:new Date().toISOString(),metadata:{platform:"web",sdkVersion:y,locale:g()},...e?{attributionContextId:e}:{}}}unavailableResult(){if(this.destroyed)return {accepted:false,reason:"destroyed"};if(this.consent==="pending")return {accepted:false,reason:"consent_pending"};if(this.consent==="denied")return {accepted:false,reason:"consent_denied"}}activeAttributionContextId(){if(this.attributionContextId&&this.attributionContextExpiresAt&&this.attributionContextExpiresAt>Date.now())return this.attributionContextId;(this.attributionContextId||this.attributionContextExpiresAt)&&(this.attributionContextId=void 0,this.attributionContextExpiresAt=void 0,this.storage?.saveAttributionContext());}installLifecycleListeners(){typeof window>"u"||typeof document>"u"||(window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibilityChange));}removeLifecycleListeners(){typeof window>"u"||typeof document>"u"||(window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibilityChange));}removeSpaTracking(){this.removeSpaTracker?.(),this.removeSpaTracker=void 0;}cancelRetry(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;}};function K(){return $(typeof location>"u"?"/":location.pathname)}function G(){if(typeof location>"u"||typeof history>"u")return;let n=new URL(location.href),t=n.searchParams.get(S)??void 0;if(t)return n.searchParams.delete(S),history.replaceState(history.state,"",`${n.pathname}${n.search}${n.hash}`),t}function Z(n,t){let e=[];for(let i of n.slice(0,50)){let r=t?{...i,attributionContextId:t}:i;if(m({schemaVersion:2,events:[...e,r]})>65536)break;e.push(r);}return e}function xt(n){return new x(n)}
2
+ exports.createWtsClient=xt;//# sourceMappingURL=index.cjs.map
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/constants.ts","../src/runtime.ts","../src/multitab-lock.ts","../src/spa-tracker.ts","../src/storage.ts","../src/transport.ts","../src/validation.ts","../src/client.ts","../src/index.ts"],"names":["SDK_VERSION","ATTRIBUTION_QUERY_KEY","createUuid","cryptoApi","bytes","hex","value","byteLength","locale","referrerHost","safeWarn","enabled","message","loadBrowserSession","sourceKey","parsed","sessionKey","isUuid","saveBrowserSession","state","clearBrowserSession","LEASE_MS","MultiTabLock","name","operation","lease","current","key","token","now","parseLease","installSpaTracker","onNavigate","historyApi","originalPush","originalReplace","scheduled","notify","args","META_STORE","EVENT_STORE","createStorage","IndexedDbStorage","deleteStorage","request","databaseName","resolve","reject","MemoryStorage","clone","identity","expiresAt","event","trimQueue","clientEventIds","_IndexedDbStorage","database","requestResult","transaction","meta","events","attributionContextId","attributionContextExpiresAt","queue","transactionDone","left","right","store","retainedIds","item","queued","id","HttpTransport","collectorOrigin","timeoutMs","input","keepalive","path","body","controller","timeout","response","TransportError","_TransportError","status","retryable","code","payload","eventKeyPattern","sourceKeyPattern","currencyPattern","amountPattern","validateOptions","options","collector","isLocalhost","validateEvent","eventKey","properties","revenue","entries","normalizePathname","pathname","normalized","hostname","ATTRIBUTION_CONTEXT_TTL_MS","WtsClientImpl","transport","captureAttributionToken","consent","storage","wasGranted","unavailable","currentPathname","referrer","error","pending","browserSession","contextExpiry","result","serverTime","batch","takeBatch","remove","hasRetryableRejection","rejection","base","jitter","type","url","createWtsClient"],"mappings":"aAAO,IAAMA,CAAAA,CAAc,gBAOpB,IAAMC,CAAAA,CAAwB,OCP9B,SAASC,CAAAA,EAAqB,CACnC,IAAMC,CAAAA,CAAY,WAAW,MAAA,CAC7B,GAAI,CAACA,CAAAA,CAAW,MAAM,IAAI,KAAA,CAAM,+CAA+C,EAC/E,GAAI,OAAOA,EAAU,UAAA,EAAe,UAAA,CAAY,OAAOA,CAAAA,CAAU,UAAA,GACjE,IAAMC,CAAAA,CAAQD,EAAU,eAAA,CAAgB,IAAI,WAAW,EAAE,CAAC,EAC1DC,CAAAA,CAAM,CAAC,EAAKA,CAAAA,CAAM,CAAC,CAAA,CAAK,EAAA,CAAQ,EAAA,CAChCA,CAAAA,CAAM,CAAC,CAAA,CAAKA,CAAAA,CAAM,CAAC,CAAA,CAAK,EAAA,CAAQ,IAChC,IAAMC,CAAAA,CAAM,MAAM,IAAA,CAAKD,CAAAA,CAAQE,GAAUA,CAAAA,CAAM,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,EAAG,GAAG,CAAC,CAAA,CAC5E,OAAO,CAAA,EAAGD,CAAAA,CAAI,MAAM,CAAA,CAAG,CAAC,EAAE,IAAA,CAAK,EAAE,CAAC,CAAA,CAAA,EAAIA,CAAAA,CAAI,MAAM,CAAA,CAAG,CAAC,EAAE,IAAA,CAA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AAGA,EAAI,MAAM,CAAA,EAAGA,EAAI,IAAI,CAAA,CAAE,EAC1ErG,CACT,CAEA,SAAS8F,CAAAA,CAAU3D,CAAAA,CAAmBF,EAA2C,CAC/E,IAAM4D,CAAAA,CAAoB,EAAC,CAC3B,IAAA,IAAWnD,KAAUP,CAAAA,CAAM,KAAA,CAAM,EAAG,EAAgB,CAAA,CAAG,CACrD,IAAMX,CAAAA,CAAQS,EAAuB,CAAE,GAAGS,EAAQ,oBAAA,CAAAT,CAAqB,EAAIS,CAAAA,CAC3E,GAAI/D,EAAW,CAAE,aAAA,CAAe,CAAA,CAAG,MAAA,CAAQ,CAAC,GAAGkH,EAAOrE,CAAK,CAAE,CAAC,CAAA,CAAI,KAAA,CAAiB,MACnFqE,CAAAA,CAAM,IAAA,CAAKrE,CAAK,EAClB,CACA,OAAOqE,CACT,CC7ZO,SAASS,EAAAA,CAAgBrC,CAAAA,CAAsC,CACpE,OAAO,IAAIa,CAAAA,CAAcb,CAAO,CAClC","file":"index.cjs","sourcesContent":["export const SDK_VERSION = \"0.1.0-alpha.2\";\nexport const DEFAULT_COLLECTOR_ORIGIN = \"https://collect.wts.is\";\nexport const MAX_QUEUE_EVENTS = 100;\nexport const MAX_QUEUE_BYTES = 1024 * 1024;\nexport const MAX_BATCH_EVENTS = 50;\nexport const MAX_BATCH_BYTES = 64 * 1024;\nexport const DEFAULT_TIMEOUT_MS = 2_000;\nexport const ATTRIBUTION_QUERY_KEY = \"_wts\";\n","export function createUuid(): string {\n const cryptoApi = globalThis.crypto;\n if (!cryptoApi) throw new Error(\"A secure random number generator is required.\");\n if (typeof cryptoApi.randomUUID === \"function\") return cryptoApi.randomUUID();\n const bytes = cryptoApi.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n\nexport function byteLength(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value)).byteLength;\n}\n\nexport function locale(): string {\n return typeof navigator === \"undefined\" ? \"en\" : navigator.language || \"en\";\n}\n\nexport function referrerHost(): string | undefined {\n if (typeof document === \"undefined\" || !document.referrer) return undefined;\n try {\n return new URL(document.referrer).hostname.toLowerCase() || undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function safeWarn(enabled: boolean, message: string): void {\n if (enabled && typeof console !== \"undefined\") console.warn(`[wts.is] ${message}`);\n}\n\nexport type BrowserSessionState = {\n sessionId: string;\n bootstrapClientEventId: string;\n};\n\nexport function loadBrowserSession(sourceKey: string): BrowserSessionState | undefined {\n if (typeof sessionStorage === \"undefined\") return undefined;\n try {\n const parsed = JSON.parse(sessionStorage.getItem(sessionKey(sourceKey)) ?? \"null\") as {\n sessionId?: unknown;\n bootstrapClientEventId?: unknown;\n } | null;\n return parsed && isUuid(parsed.sessionId) && isUuid(parsed.bootstrapClientEventId)\n ? {\n sessionId: parsed.sessionId,\n bootstrapClientEventId: parsed.bootstrapClientEventId,\n }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function saveBrowserSession(sourceKey: string, state: BrowserSessionState): void {\n if (typeof sessionStorage === \"undefined\") return;\n try {\n sessionStorage.setItem(sessionKey(sourceKey), JSON.stringify(state));\n } catch {\n // Storage restrictions are handled by the SDK's memory-only fallback.\n }\n}\n\nexport function clearBrowserSession(sourceKey: string): void {\n if (typeof sessionStorage === \"undefined\") return;\n try {\n sessionStorage.removeItem(sessionKey(sourceKey));\n } catch {\n // A blocked browser storage API is equivalent to an already cleared session.\n }\n}\n\nfunction sessionKey(sourceKey: string): string {\n return `wts-session-${sourceKey}`;\n}\n\nfunction isUuid(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)\n );\n}\n","import { createUuid } from \"./runtime\";\n\nconst LEASE_MS = 10_000;\n\nexport class MultiTabLock {\n private current: Promise<unknown> | undefined;\n\n constructor(private readonly name: string) {}\n\n async run<T>(operation: () => Promise<T>): Promise<T | undefined> {\n if (typeof navigator !== \"undefined\" && navigator.locks) {\n return navigator.locks.request(this.name, operation);\n }\n if (this.current) await this.current;\n const lease = this.acquireLease();\n if (!lease) return undefined;\n const current = operation();\n this.current = current;\n try {\n return await current;\n } finally {\n if (this.current === current) this.current = undefined;\n lease.release();\n }\n }\n\n private acquireLease(): { release(): void } | undefined {\n if (typeof localStorage === \"undefined\") return { release() {} };\n const key = `wts-lock-${this.name}`;\n const token = createUuid();\n const now = Date.now();\n try {\n const current = parseLease(localStorage.getItem(key));\n if (current && current.expiresAt > now) return undefined;\n localStorage.setItem(key, JSON.stringify({ token, expiresAt: now + LEASE_MS }));\n const acquired = parseLease(localStorage.getItem(key));\n if (acquired?.token !== token) return undefined;\n return {\n release() {\n const latest = parseLease(localStorage.getItem(key));\n if (latest?.token === token) localStorage.removeItem(key);\n },\n };\n } catch {\n return { release() {} };\n }\n }\n}\n\nfunction parseLease(value: string | null): { token: string; expiresAt: number } | undefined {\n if (!value) return undefined;\n try {\n const parsed = JSON.parse(value) as { token?: unknown; expiresAt?: unknown };\n return typeof parsed.token === \"string\" && typeof parsed.expiresAt === \"number\"\n ? { token: parsed.token, expiresAt: parsed.expiresAt }\n : undefined;\n } catch {\n return undefined;\n }\n}\n","export function installSpaTracker(onNavigate: () => void): () => void {\n if (typeof window === \"undefined\") return () => undefined;\n const historyApi = window.history;\n const originalPush = historyApi.pushState;\n const originalReplace = historyApi.replaceState;\n let scheduled = false;\n const notify = () => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n onNavigate();\n });\n };\n historyApi.pushState = function (...args) {\n originalPush.apply(this, args);\n notify();\n };\n historyApi.replaceState = function (...args) {\n originalReplace.apply(this, args);\n notify();\n };\n window.addEventListener(\"popstate\", notify);\n return () => {\n historyApi.pushState = originalPush;\n historyApi.replaceState = originalReplace;\n window.removeEventListener(\"popstate\", notify);\n };\n}\n","import { MAX_QUEUE_BYTES, MAX_QUEUE_EVENTS } from \"./constants\";\nimport { byteLength } from \"./runtime\";\nimport type { Identity, StorageAdapter, StoredState, WebEvent } from \"./types\";\n\nconst META_STORE = \"meta\";\nconst EVENT_STORE = \"events\";\n\nexport async function createStorage(sourceKey: string): Promise<StorageAdapter> {\n if (typeof indexedDB === \"undefined\") throw new Error(\"IndexedDB is unavailable.\");\n return IndexedDbStorage.open(sourceKey);\n}\n\nexport async function deleteStorage(sourceKey: string): Promise<void> {\n if (typeof indexedDB === \"undefined\") return;\n const request = indexedDB.deleteDatabase(databaseName(sourceKey));\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => resolve();\n request.onerror = () => reject(request.error ?? new Error(\"IndexedDB deletion failed.\"));\n request.onblocked = () => reject(new Error(\"IndexedDB deletion was blocked by another tab.\"));\n });\n}\n\nexport class MemoryStorage implements StorageAdapter {\n private state: StoredState = { queue: [] };\n\n async load(): Promise<StoredState> {\n return clone(this.state);\n }\n\n async saveIdentity(identity: Identity): Promise<void> {\n this.state.identity = { ...identity };\n }\n\n async saveAttributionContext(value?: string, expiresAt?: string): Promise<void> {\n if (value && expiresAt) {\n this.state.attributionContextId = value;\n this.state.attributionContextExpiresAt = expiresAt;\n } else {\n delete this.state.attributionContextId;\n delete this.state.attributionContextExpiresAt;\n }\n }\n\n async enqueue(event: WebEvent): Promise<void> {\n this.state.queue.push(clone(event));\n trimQueue(this.state.queue);\n }\n\n async remove(clientEventIds: ReadonlySet<string>): Promise<void> {\n this.state.queue = this.state.queue.filter((event) => !clientEventIds.has(event.clientEventId));\n }\n\n async clear(): Promise<void> {\n this.state = { queue: [] };\n }\n\n close(): void {}\n}\n\nclass IndexedDbStorage implements StorageAdapter {\n private constructor(private readonly database: IDBDatabase) {}\n\n static async open(sourceKey: string): Promise<IndexedDbStorage> {\n const request = indexedDB.open(databaseName(sourceKey), 1);\n request.onupgradeneeded = () => {\n const database = request.result;\n if (!database.objectStoreNames.contains(META_STORE)) database.createObjectStore(META_STORE);\n if (!database.objectStoreNames.contains(EVENT_STORE)) {\n database.createObjectStore(EVENT_STORE, { keyPath: \"clientEventId\" });\n }\n };\n return new IndexedDbStorage(await requestResult(request));\n }\n\n async load(): Promise<StoredState> {\n const transaction = this.database.transaction([META_STORE, EVENT_STORE], \"readonly\");\n const meta = transaction.objectStore(META_STORE);\n const events = transaction.objectStore(EVENT_STORE);\n const [identity, attributionContextId, attributionContextExpiresAt, queue] = await Promise.all([\n requestResult(meta.get(\"identity\") as IDBRequest<Identity | undefined>),\n requestResult(meta.get(\"attributionContextId\") as IDBRequest<string | undefined>),\n requestResult(meta.get(\"attributionContextExpiresAt\") as IDBRequest<string | undefined>),\n requestResult(events.getAll() as IDBRequest<WebEvent[]>),\n ]);\n await transactionDone(transaction);\n queue.sort((left, right) => left.occurredAt.localeCompare(right.occurredAt));\n return {\n ...(identity ? { identity } : {}),\n ...(attributionContextId && attributionContextExpiresAt\n ? { attributionContextId, attributionContextExpiresAt }\n : {}),\n queue,\n };\n }\n\n async saveIdentity(identity: Identity): Promise<void> {\n await this.writeMeta(\"identity\", identity);\n }\n\n async saveAttributionContext(value?: string, expiresAt?: string): Promise<void> {\n const transaction = this.database.transaction(META_STORE, \"readwrite\");\n const store = transaction.objectStore(META_STORE);\n if (value && expiresAt) {\n store.put(value, \"attributionContextId\");\n store.put(expiresAt, \"attributionContextExpiresAt\");\n } else {\n store.delete(\"attributionContextId\");\n store.delete(\"attributionContextExpiresAt\");\n }\n await transactionDone(transaction);\n }\n\n async enqueue(event: WebEvent): Promise<void> {\n const state = await this.load();\n const queue = [...state.queue, event];\n trimQueue(queue);\n const retainedIds = new Set(queue.map((item) => item.clientEventId));\n const transaction = this.database.transaction(EVENT_STORE, \"readwrite\");\n const store = transaction.objectStore(EVENT_STORE);\n store.put(event);\n for (const queued of state.queue) {\n if (!retainedIds.has(queued.clientEventId)) store.delete(queued.clientEventId);\n }\n await transactionDone(transaction);\n }\n\n async remove(clientEventIds: ReadonlySet<string>): Promise<void> {\n if (clientEventIds.size === 0) return;\n const transaction = this.database.transaction(EVENT_STORE, \"readwrite\");\n const store = transaction.objectStore(EVENT_STORE);\n for (const id of clientEventIds) store.delete(id);\n await transactionDone(transaction);\n }\n\n async clear(): Promise<void> {\n const transaction = this.database.transaction([META_STORE, EVENT_STORE], \"readwrite\");\n transaction.objectStore(META_STORE).clear();\n transaction.objectStore(EVENT_STORE).clear();\n await transactionDone(transaction);\n }\n\n close(): void {\n this.database.close();\n }\n\n private async writeMeta(key: string, value: unknown): Promise<void> {\n const transaction = this.database.transaction(META_STORE, \"readwrite\");\n transaction.objectStore(META_STORE).put(value, key);\n await transactionDone(transaction);\n }\n}\n\nfunction trimQueue(queue: WebEvent[]): void {\n while (queue.length > MAX_QUEUE_EVENTS || byteLength(queue) > MAX_QUEUE_BYTES) queue.shift();\n}\n\nfunction requestResult<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error ?? new Error(\"IndexedDB request failed.\"));\n });\n}\n\nfunction transactionDone(transaction: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve();\n transaction.onerror = () =>\n reject(transaction.error ?? new Error(\"IndexedDB transaction failed.\"));\n transaction.onabort = () =>\n reject(transaction.error ?? new Error(\"IndexedDB transaction aborted.\"));\n });\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction databaseName(sourceKey: string): string {\n return `wts-web-${sourceKey}`;\n}\n","import { SDK_VERSION } from \"./constants\";\nimport { locale } from \"./runtime\";\nimport type { BatchResponse, Identity, Transport, WebEvent } from \"./types\";\n\nexport class HttpTransport implements Transport {\n constructor(\n private readonly collectorOrigin: string,\n private readonly timeoutMs: number,\n ) {}\n\n async bootstrap(input: {\n sourceKey: string;\n identity: Identity;\n clientEventId: string;\n attributionToken?: string;\n }): Promise<{ attributionContextId: string | null; serverTime: string }> {\n const response = await this.post(\n \"/v2/bootstrap\",\n input.sourceKey,\n {\n schemaVersion: 2,\n clientEventId: input.clientEventId,\n ...input.identity,\n occurredAt: new Date().toISOString(),\n metadata: { platform: \"web\", sdkVersion: SDK_VERSION, locale: locale() },\n ...(input.attributionToken ? { attributionToken: input.attributionToken } : {}),\n },\n false,\n );\n return (await response.json()) as { attributionContextId: string | null; serverTime: string };\n }\n\n async send(sourceKey: string, events: WebEvent[], keepalive: boolean): Promise<BatchResponse> {\n const response = await this.post(\n \"/v2/events/batch\",\n sourceKey,\n { schemaVersion: 2, events },\n keepalive,\n );\n return (await response.json()) as BatchResponse;\n }\n\n private async post(\n path: string,\n sourceKey: string,\n body: unknown,\n keepalive: boolean,\n ): Promise<Response> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n const response = await fetch(`${this.collectorOrigin}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-WTS-Source-Key\": sourceKey },\n body: JSON.stringify(body),\n credentials: \"omit\",\n mode: \"cors\",\n cache: \"no-store\",\n keepalive,\n signal: controller.signal,\n });\n if (!response.ok) throw await TransportError.fromResponse(response);\n return response;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class TransportError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly retryable: boolean,\n readonly code?: string,\n ) {\n super(message);\n this.name = \"WtsTransportError\";\n }\n\n static async fromResponse(response: Response): Promise<TransportError> {\n let payload: { code?: string; message?: string } = {};\n try {\n payload = (await response.json()) as typeof payload;\n } catch {\n // The SDK intentionally does not surface response bodies in logs.\n }\n return new TransportError(\n payload.message ?? `Collector request failed with status ${response.status}.`,\n response.status,\n response.status === 429 || response.status >= 500,\n payload.code,\n );\n }\n}\n","import type { EventProperties, Revenue, WtsClientOptions } from \"./types\";\n\nconst eventKeyPattern = /^[a-z][a-z0-9_]{1,63}$/;\nconst sourceKeyPattern = /^[A-Za-z0-9_-]{8,128}$/;\nconst currencyPattern = /^[A-Z]{3}$/;\nconst amountPattern = /^-?\\d{1,12}(?:\\.\\d{1,6})?$/;\n\nexport function validateOptions(\n options: WtsClientOptions,\n): Required<\n Pick<\n WtsClientOptions,\n \"sourceKey\" | \"autoTrackPageViews\" | \"collectorOrigin\" | \"requestTimeoutMs\" | \"debug\"\n >\n> & { consent: NonNullable<WtsClientOptions[\"consent\"]> } {\n if (!sourceKeyPattern.test(options.sourceKey)) {\n throw new TypeError(\"sourceKey must be a valid wts.is Web App source key.\");\n }\n const collector = new URL(options.collectorOrigin ?? \"https://collect.wts.is\");\n if (collector.protocol !== \"https:\" && !isLocalhost(collector.hostname)) {\n throw new TypeError(\"collectorOrigin must use HTTPS outside localhost.\");\n }\n if (collector.pathname !== \"/\" || collector.search || collector.hash) {\n throw new TypeError(\"collectorOrigin must not include a path, query, or fragment.\");\n }\n const timeout = options.requestTimeoutMs ?? 2_000;\n if (!Number.isInteger(timeout) || timeout < 250 || timeout > 30_000) {\n throw new TypeError(\"requestTimeoutMs must be an integer between 250 and 30000.\");\n }\n return {\n sourceKey: options.sourceKey,\n consent: options.consent ?? \"pending\",\n autoTrackPageViews: options.autoTrackPageViews ?? false,\n collectorOrigin: collector.origin,\n requestTimeoutMs: timeout,\n debug: options.debug ?? false,\n };\n}\n\nexport function validateEvent(\n eventKey: string,\n properties: EventProperties,\n revenue?: Revenue,\n): void {\n if (!eventKeyPattern.test(eventKey)) {\n throw new TypeError(\"eventKey must match ^[a-z][a-z0-9_]{1,63}$.\");\n }\n const entries = Object.entries(properties);\n if (entries.length > 20) throw new TypeError(\"Events can contain at most 20 properties.\");\n for (const [key, value] of entries) {\n if (!/^[a-z][a-z0-9_]{0,63}$/.test(key)) throw new TypeError(`Invalid property key: ${key}`);\n if (![\"string\", \"number\", \"boolean\"].includes(typeof value)) {\n throw new TypeError(`Property ${key} must be a string, number, or boolean.`);\n }\n if (typeof value === \"string\" && value.length > 512) {\n throw new TypeError(`Property ${key} cannot exceed 512 characters.`);\n }\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n throw new TypeError(`Property ${key} must be finite.`);\n }\n }\n if (revenue && (!amountPattern.test(revenue.amount) || !currencyPattern.test(revenue.currency))) {\n throw new TypeError(\"Revenue requires a decimal amount and uppercase ISO-4217 currency.\");\n }\n}\n\nexport function normalizePathname(pathname: string): string {\n const normalized = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n if (normalized.includes(\"?\") || normalized.includes(\"#\")) {\n throw new TypeError(\"Page pathname cannot include a query or fragment.\");\n }\n if (normalized.length > 2_048)\n throw new TypeError(\"Page pathname cannot exceed 2048 characters.\");\n return normalized;\n}\n\nfunction isLocalhost(hostname: string): boolean {\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\";\n}\n","import { ATTRIBUTION_QUERY_KEY, MAX_BATCH_BYTES, MAX_BATCH_EVENTS, SDK_VERSION } from \"./constants\";\nimport { MultiTabLock } from \"./multitab-lock\";\nimport {\n byteLength,\n clearBrowserSession,\n createUuid,\n loadBrowserSession,\n locale,\n referrerHost,\n safeWarn,\n saveBrowserSession,\n} from \"./runtime\";\nimport { installSpaTracker } from \"./spa-tracker\";\nimport { createStorage, deleteStorage, MemoryStorage } from \"./storage\";\nimport { HttpTransport, TransportError } from \"./transport\";\nimport type {\n ConsentState,\n EventProperties,\n FlushResult,\n Identity,\n OperationResult,\n Revenue,\n StorageAdapter,\n Transport,\n WebEvent,\n WtsClient,\n WtsClientOptions,\n} from \"./types\";\nimport { normalizePathname, validateEvent, validateOptions } from \"./validation\";\n\ntype ResolvedOptions = ReturnType<typeof validateOptions>;\nconst ATTRIBUTION_CONTEXT_TTL_MS = 7 * 24 * 60 * 60_000;\n\nexport class WtsClientImpl implements WtsClient {\n private consent: ConsentState;\n private storage: StorageAdapter | undefined;\n private identity: Identity | undefined;\n private attributionContextId: string | undefined;\n private attributionContextExpiresAt: number | undefined;\n private attributionToken: string | undefined;\n private bootstrapClientEventId = createUuid();\n private bootstrapped = false;\n private destroyed = false;\n private retryAttempt = 0;\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n private enablePromise: Promise<void> | undefined;\n private removeSpaTracker: (() => void) | undefined;\n private lastPagePath: string | undefined;\n private readonly options: ResolvedOptions;\n private readonly transport: Transport;\n private readonly lock: MultiTabLock;\n\n constructor(options: WtsClientOptions, transport?: Transport) {\n this.options = validateOptions(options);\n this.consent = this.options.consent;\n this.transport =\n transport ?? new HttpTransport(this.options.collectorOrigin, this.options.requestTimeoutMs);\n this.lock = new MultiTabLock(`flush-${this.options.sourceKey}`);\n this.attributionToken = captureAttributionToken();\n this.installLifecycleListeners();\n if (this.consent === \"granted\") void this.startEnable();\n if (this.consent === \"denied\") this.attributionToken = undefined;\n }\n\n async setConsent(consent: \"granted\" | \"denied\"): Promise<void> {\n if (this.destroyed) return;\n if (consent === \"denied\") {\n this.consent = \"denied\";\n this.cancelRetry();\n const storage = this.storage;\n if (storage) {\n await this.lock.run(async () => {\n await storage.clear();\n storage.close();\n });\n }\n try {\n await deleteStorage(this.options.sourceKey);\n } catch {\n safeWarn(this.options.debug, \"Stored SDK data could not be deleted because it is in use.\");\n }\n this.storage = undefined;\n this.identity = undefined;\n this.attributionContextId = undefined;\n this.attributionContextExpiresAt = undefined;\n this.attributionToken = undefined;\n this.bootstrapped = false;\n clearBrowserSession(this.options.sourceKey);\n this.removeSpaTracking();\n return;\n }\n const wasGranted = this.consent === \"granted\";\n this.consent = \"granted\";\n if (!wasGranted || !this.storage) await this.startEnable();\n }\n\n async page(name?: string): Promise<OperationResult> {\n let unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n await this.ensureReady();\n unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n const pathname = currentPathname();\n const referrer = referrerHost();\n const event: WebEvent = {\n ...this.eventBase(\"page_view\"),\n pathname,\n ...(name?.trim() ? { pageName: name.trim().slice(0, 120) } : {}),\n ...(referrer ? { referrerHost: referrer } : {}),\n properties: {},\n };\n await this.enqueue(event);\n this.lastPagePath = pathname;\n return { accepted: true, clientEventId: event.clientEventId };\n }\n\n async track(\n eventKey: string,\n properties: EventProperties = {},\n revenue?: Revenue,\n ): Promise<OperationResult> {\n let unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n await this.ensureReady();\n unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n validateEvent(eventKey, properties, revenue);\n const event: WebEvent = {\n ...this.eventBase(\"custom\"),\n eventKey,\n properties: { ...properties },\n ...(revenue ? { revenue: { ...revenue } } : {}),\n };\n await this.enqueue(event);\n return { accepted: true, clientEventId: event.clientEventId };\n }\n\n async flush(): Promise<FlushResult> {\n if (this.consent !== \"granted\" || this.destroyed || !this.storage) {\n return { sent: 0, pending: 0 };\n }\n const result = await this.lock.run(async () => this.flushExclusive(false));\n return result ?? { sent: 0, pending: (await this.storage.load()).queue.length };\n }\n\n async reset(): Promise<void> {\n this.cancelRetry();\n await this.storage?.clear();\n this.identity = undefined;\n this.attributionContextId = undefined;\n this.attributionContextExpiresAt = undefined;\n this.attributionToken = undefined;\n clearBrowserSession(this.options.sourceKey);\n this.bootstrapClientEventId = createUuid();\n this.bootstrapped = false;\n this.lastPagePath = undefined;\n if (this.consent === \"granted\" && !this.destroyed) await this.initializeIdentity();\n }\n\n destroy(): void {\n if (this.destroyed) return;\n this.destroyed = true;\n this.cancelRetry();\n this.removeSpaTracking();\n this.removeLifecycleListeners();\n const storage = this.storage;\n if (storage) void this.lock.run(async () => storage.close());\n }\n\n private async enable(): Promise<void> {\n if (this.destroyed || this.consent !== \"granted\") return;\n if (!this.storage) {\n try {\n this.storage = await createStorage(this.options.sourceKey);\n await this.storage.load();\n } catch {\n this.storage?.close();\n this.storage = new MemoryStorage();\n safeWarn(this.options.debug, \"IndexedDB unavailable; using a memory-only event queue.\");\n }\n }\n await this.initializeIdentity();\n try {\n await this.ensureBootstrapped();\n } catch (error) {\n this.handleRetryableError(error);\n }\n if (this.options.autoTrackPageViews && !this.removeSpaTracker) {\n this.removeSpaTracker = installSpaTracker(() => {\n void this.trackAutomaticPage();\n });\n await this.trackAutomaticPage();\n }\n void this.flush();\n }\n\n private startEnable(): Promise<void> {\n if (this.enablePromise) return this.enablePromise;\n const pending = this.enable();\n this.enablePromise = pending;\n void pending.finally(() => {\n if (this.enablePromise === pending) this.enablePromise = undefined;\n });\n return pending;\n }\n\n private async ensureReady(): Promise<void> {\n if (this.consent === \"granted\" && (!this.storage || !this.identity)) {\n await this.startEnable();\n }\n }\n\n private async initializeIdentity(): Promise<void> {\n if (!this.storage) return;\n const state = await this.storage.load();\n const browserSession = loadBrowserSession(this.options.sourceKey);\n this.identity = {\n anonymousId: state.identity?.anonymousId ?? createUuid(),\n sessionId: browserSession?.sessionId ?? createUuid(),\n };\n this.bootstrapClientEventId = browserSession?.bootstrapClientEventId ?? createUuid();\n saveBrowserSession(this.options.sourceKey, {\n sessionId: this.identity.sessionId,\n bootstrapClientEventId: this.bootstrapClientEventId,\n });\n const contextExpiry = state.attributionContextExpiresAt\n ? Date.parse(state.attributionContextExpiresAt)\n : Number.NaN;\n if (\n state.attributionContextId &&\n Number.isFinite(contextExpiry) &&\n contextExpiry > Date.now()\n ) {\n this.attributionContextId = state.attributionContextId;\n this.attributionContextExpiresAt = contextExpiry;\n } else if (state.attributionContextId || state.attributionContextExpiresAt) {\n await this.storage.saveAttributionContext();\n }\n if (\n !state.identity ||\n state.identity.anonymousId !== this.identity.anonymousId ||\n state.identity.sessionId !== this.identity.sessionId\n ) {\n await this.storage.saveIdentity(this.identity);\n }\n }\n\n private async ensureBootstrapped(): Promise<void> {\n if (this.bootstrapped || !this.identity || !this.storage) return;\n const result = await this.transport.bootstrap({\n sourceKey: this.options.sourceKey,\n identity: this.identity,\n clientEventId: this.bootstrapClientEventId,\n ...(this.attributionToken ? { attributionToken: this.attributionToken } : {}),\n });\n this.bootstrapped = true;\n this.attributionToken = undefined;\n if (result.attributionContextId) {\n this.attributionContextId = result.attributionContextId;\n const serverTime = Date.parse(result.serverTime);\n this.attributionContextExpiresAt =\n (Number.isFinite(serverTime) ? serverTime : Date.now()) + ATTRIBUTION_CONTEXT_TTL_MS;\n await this.storage.saveAttributionContext(\n result.attributionContextId,\n new Date(this.attributionContextExpiresAt).toISOString(),\n );\n }\n this.retryAttempt = 0;\n }\n\n private async enqueue(event: WebEvent): Promise<void> {\n if (!this.storage) return;\n await this.storage.enqueue(event);\n queueMicrotask(() => void this.flush());\n }\n\n private async flushExclusive(keepalive: boolean): Promise<FlushResult> {\n if (!this.storage) return { sent: 0, pending: 0 };\n if (this.retryTimer && !keepalive) {\n return { sent: 0, pending: (await this.storage.load()).queue.length };\n }\n try {\n await this.ensureBootstrapped();\n const state = await this.storage.load();\n const batch = takeBatch(state.queue, this.activeAttributionContextId());\n if (batch.length === 0) return { sent: 0, pending: state.queue.length };\n const response = await this.transport.send(this.options.sourceKey, batch, keepalive);\n const remove = new Set([...response.accepted, ...response.duplicates]);\n let hasRetryableRejection = false;\n for (const rejection of response.rejected) {\n if (rejection.retryable) hasRetryableRejection = true;\n else remove.add(rejection.clientEventId);\n }\n await this.storage.remove(remove);\n const pending = (await this.storage.load()).queue.length;\n if (hasRetryableRejection) this.scheduleRetry();\n else {\n this.retryAttempt = 0;\n if (pending > 0) queueMicrotask(() => void this.flush());\n }\n return { sent: remove.size, pending };\n } catch (error) {\n this.handleRetryableError(error);\n return { sent: 0, pending: (await this.storage.load()).queue.length };\n }\n }\n\n private handleRetryableError(error: unknown): void {\n if (error instanceof TransportError && !error.retryable) {\n safeWarn(\n this.options.debug,\n `Collector rejected the request (${error.code ?? error.status}).`,\n );\n return;\n }\n this.scheduleRetry();\n }\n\n private scheduleRetry(): void {\n if (this.consent !== \"granted\" || this.destroyed || this.retryTimer) return;\n const base = Math.min(60_000, 1_000 * 2 ** Math.min(this.retryAttempt, 6));\n const jitter = Math.floor(Math.random() * Math.max(1, base * 0.25));\n this.retryAttempt += 1;\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n void this.flush();\n }, base + jitter);\n }\n\n private async trackAutomaticPage(): Promise<void> {\n const pathname = currentPathname();\n if (pathname === this.lastPagePath) return;\n await this.page();\n }\n\n private eventBase(type: WebEvent[\"type\"]): Omit<WebEvent, \"properties\"> {\n if (!this.identity) throw new Error(\"Web SDK identity is unavailable.\");\n const attributionContextId = this.activeAttributionContextId();\n return {\n schemaVersion: 2,\n clientEventId: createUuid(),\n ...this.identity,\n type,\n occurredAt: new Date().toISOString(),\n metadata: { platform: \"web\", sdkVersion: SDK_VERSION, locale: locale() },\n ...(attributionContextId ? { attributionContextId } : {}),\n };\n }\n\n private unavailableResult(): OperationResult | undefined {\n if (this.destroyed) return { accepted: false, reason: \"destroyed\" };\n if (this.consent === \"pending\") return { accepted: false, reason: \"consent_pending\" };\n if (this.consent === \"denied\") return { accepted: false, reason: \"consent_denied\" };\n return undefined;\n }\n\n private activeAttributionContextId(): string | undefined {\n if (\n this.attributionContextId &&\n this.attributionContextExpiresAt &&\n this.attributionContextExpiresAt > Date.now()\n ) {\n return this.attributionContextId;\n }\n if (this.attributionContextId || this.attributionContextExpiresAt) {\n this.attributionContextId = undefined;\n this.attributionContextExpiresAt = undefined;\n void this.storage?.saveAttributionContext();\n }\n return undefined;\n }\n\n private installLifecycleListeners(): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n window.addEventListener(\"pagehide\", this.onPageHide);\n document.addEventListener(\"visibilitychange\", this.onVisibilityChange);\n }\n\n private removeLifecycleListeners(): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n window.removeEventListener(\"pagehide\", this.onPageHide);\n document.removeEventListener(\"visibilitychange\", this.onVisibilityChange);\n }\n\n private readonly onPageHide = () => {\n if (this.consent === \"granted\") void this.lock.run(() => this.flushExclusive(true));\n };\n\n private readonly onVisibilityChange = () => {\n if (document.visibilityState === \"hidden\" && this.consent === \"granted\") {\n void this.lock.run(() => this.flushExclusive(true));\n }\n };\n\n private removeSpaTracking(): void {\n this.removeSpaTracker?.();\n this.removeSpaTracker = undefined;\n }\n\n private cancelRetry(): void {\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = undefined;\n }\n}\n\nfunction currentPathname(): string {\n return normalizePathname(typeof location === \"undefined\" ? \"/\" : location.pathname);\n}\n\nfunction captureAttributionToken(): string | undefined {\n if (typeof location === \"undefined\" || typeof history === \"undefined\") return undefined;\n const url = new URL(location.href);\n const token = url.searchParams.get(ATTRIBUTION_QUERY_KEY) ?? undefined;\n if (!token) return undefined;\n url.searchParams.delete(ATTRIBUTION_QUERY_KEY);\n history.replaceState(history.state, \"\", `${url.pathname}${url.search}${url.hash}`);\n return token;\n}\n\nfunction takeBatch(queue: WebEvent[], attributionContextId?: string): WebEvent[] {\n const batch: WebEvent[] = [];\n for (const queued of queue.slice(0, MAX_BATCH_EVENTS)) {\n const event = attributionContextId ? { ...queued, attributionContextId } : queued;\n if (byteLength({ schemaVersion: 2, events: [...batch, event] }) > MAX_BATCH_BYTES) break;\n batch.push(event);\n }\n return batch;\n}\n","import { WtsClientImpl } from \"./client\";\nimport type { WtsClient, WtsClientOptions } from \"./types\";\n\nexport type {\n ConsentState,\n EventProperties,\n FlushResult,\n OperationResult,\n Revenue,\n Scalar,\n WtsClient,\n WtsClientOptions,\n} from \"./types\";\n\nexport function createWtsClient(options: WtsClientOptions): WtsClient {\n return new WtsClientImpl(options);\n}\n"]}
@@ -0,0 +1,36 @@
1
+ type ConsentState = "pending" | "granted" | "denied";
2
+ type Scalar = string | number | boolean;
3
+ type EventProperties = Record<string, Scalar>;
4
+ interface Revenue {
5
+ amount: string;
6
+ currency: string;
7
+ }
8
+ interface WtsClientOptions {
9
+ sourceKey: string;
10
+ consent?: ConsentState;
11
+ autoTrackPageViews?: boolean;
12
+ collectorOrigin?: string;
13
+ requestTimeoutMs?: number;
14
+ debug?: boolean;
15
+ }
16
+ interface OperationResult {
17
+ accepted: boolean;
18
+ reason?: "consent_pending" | "consent_denied" | "destroyed";
19
+ clientEventId?: string;
20
+ }
21
+ interface FlushResult {
22
+ sent: number;
23
+ pending: number;
24
+ }
25
+ interface WtsClient {
26
+ setConsent(consent: "granted" | "denied"): Promise<void>;
27
+ page(name?: string): Promise<OperationResult>;
28
+ track(eventKey: string, properties?: EventProperties, revenue?: Revenue): Promise<OperationResult>;
29
+ flush(): Promise<FlushResult>;
30
+ reset(): Promise<void>;
31
+ destroy(): void;
32
+ }
33
+
34
+ declare function createWtsClient(options: WtsClientOptions): WtsClient;
35
+
36
+ export { type ConsentState, type EventProperties, type FlushResult, type OperationResult, type Revenue, type Scalar, type WtsClient, type WtsClientOptions, createWtsClient };
@@ -0,0 +1,36 @@
1
+ type ConsentState = "pending" | "granted" | "denied";
2
+ type Scalar = string | number | boolean;
3
+ type EventProperties = Record<string, Scalar>;
4
+ interface Revenue {
5
+ amount: string;
6
+ currency: string;
7
+ }
8
+ interface WtsClientOptions {
9
+ sourceKey: string;
10
+ consent?: ConsentState;
11
+ autoTrackPageViews?: boolean;
12
+ collectorOrigin?: string;
13
+ requestTimeoutMs?: number;
14
+ debug?: boolean;
15
+ }
16
+ interface OperationResult {
17
+ accepted: boolean;
18
+ reason?: "consent_pending" | "consent_denied" | "destroyed";
19
+ clientEventId?: string;
20
+ }
21
+ interface FlushResult {
22
+ sent: number;
23
+ pending: number;
24
+ }
25
+ interface WtsClient {
26
+ setConsent(consent: "granted" | "denied"): Promise<void>;
27
+ page(name?: string): Promise<OperationResult>;
28
+ track(eventKey: string, properties?: EventProperties, revenue?: Revenue): Promise<OperationResult>;
29
+ flush(): Promise<FlushResult>;
30
+ reset(): Promise<void>;
31
+ destroy(): void;
32
+ }
33
+
34
+ declare function createWtsClient(options: WtsClientOptions): WtsClient;
35
+
36
+ export { type ConsentState, type EventProperties, type FlushResult, type OperationResult, type Revenue, type Scalar, type WtsClient, type WtsClientOptions, createWtsClient };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ var y="0.1.0-alpha.2";var S="_wts";function c(){let n=globalThis.crypto;if(!n)throw new Error("A secure random number generator is required.");if(typeof n.randomUUID=="function")return n.randomUUID();let t=n.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=Array.from(t,i=>i.toString(16).padStart(2,"0"));return `${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}function m(n){return new TextEncoder().encode(JSON.stringify(n)).byteLength}function g(){return typeof navigator>"u"?"en":navigator.language||"en"}function k(){if(!(typeof document>"u"||!document.referrer))try{return new URL(document.referrer).hostname.toLowerCase()||void 0}catch{return}}function v(n,t){n&&typeof console<"u"&&console.warn(`[wts.is] ${t}`);}function R(n){if(!(typeof sessionStorage>"u"))try{let t=JSON.parse(sessionStorage.getItem(I(n))??"null");return t&&A(t.sessionId)&&A(t.bootstrapClientEventId)?{sessionId:t.sessionId,bootstrapClientEventId:t.bootstrapClientEventId}:void 0}catch{return}}function O(n,t){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(I(n),JSON.stringify(t));}catch{}}function T(n){if(!(typeof sessionStorage>"u"))try{sessionStorage.removeItem(I(n));}catch{}}function I(n){return `wts-session-${n}`}function A(n){return typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}var j=1e4,b=class{constructor(t){this.name=t;}async run(t){if(typeof navigator<"u"&&navigator.locks)return navigator.locks.request(this.name,t);this.current&&await this.current;let e=this.acquireLease();if(!e)return;let i=t();this.current=i;try{return await i}finally{this.current===i&&(this.current=void 0),e.release();}}acquireLease(){if(typeof localStorage>"u")return {release(){}};let t=`wts-lock-${this.name}`,e=c(),i=Date.now();try{let r=C(localStorage.getItem(t));return r&&r.expiresAt>i||(localStorage.setItem(t,JSON.stringify({token:e,expiresAt:i+j})),C(localStorage.getItem(t))?.token!==e)?void 0:{release(){C(localStorage.getItem(t))?.token===e&&localStorage.removeItem(t);}}}catch{return {release(){}}}}};function C(n){if(n)try{let t=JSON.parse(n);return typeof t.token=="string"&&typeof t.expiresAt=="number"?{token:t.token,expiresAt:t.expiresAt}:void 0}catch{return}}function q(n){if(typeof window>"u")return ()=>{};let t=window.history,e=t.pushState,i=t.replaceState,r=false,s=()=>{r||(r=true,queueMicrotask(()=>{r=false,n();}));};return t.pushState=function(...o){e.apply(this,o),s();},t.replaceState=function(...o){i.apply(this,o),s();},window.addEventListener("popstate",s),()=>{t.pushState=e,t.replaceState=i,window.removeEventListener("popstate",s);}}var d="meta",u="events";async function _(n){if(typeof indexedDB>"u")throw new Error("IndexedDB is unavailable.");return P.open(n)}async function D(n){if(typeof indexedDB>"u")return;let t=indexedDB.deleteDatabase(N(n));await new Promise((e,i)=>{t.onsuccess=()=>e(),t.onerror=()=>i(t.error??new Error("IndexedDB deletion failed.")),t.onblocked=()=>i(new Error("IndexedDB deletion was blocked by another tab."));});}var w=class{constructor(){this.state={queue:[]};}async load(){return B(this.state)}async saveIdentity(t){this.state.identity={...t};}async saveAttributionContext(t,e){t&&e?(this.state.attributionContextId=t,this.state.attributionContextExpiresAt=e):(delete this.state.attributionContextId,delete this.state.attributionContextExpiresAt);}async enqueue(t){this.state.queue.push(B(t)),W(this.state.queue);}async remove(t){this.state.queue=this.state.queue.filter(e=>!t.has(e.clientEventId));}async clear(){this.state={queue:[]};}close(){}},P=class n{constructor(t){this.database=t;}static async open(t){let e=indexedDB.open(N(t),1);return e.onupgradeneeded=()=>{let i=e.result;i.objectStoreNames.contains(d)||i.createObjectStore(d),i.objectStoreNames.contains(u)||i.createObjectStore(u,{keyPath:"clientEventId"});},new n(await p(e))}async load(){let t=this.database.transaction([d,u],"readonly"),e=t.objectStore(d),i=t.objectStore(u),[r,s,o,a]=await Promise.all([p(e.get("identity")),p(e.get("attributionContextId")),p(e.get("attributionContextExpiresAt")),p(i.getAll())]);return await l(t),a.sort((f,U)=>f.occurredAt.localeCompare(U.occurredAt)),{...r?{identity:r}:{},...s&&o?{attributionContextId:s,attributionContextExpiresAt:o}:{},queue:a}}async saveIdentity(t){await this.writeMeta("identity",t);}async saveAttributionContext(t,e){let i=this.database.transaction(d,"readwrite"),r=i.objectStore(d);t&&e?(r.put(t,"attributionContextId"),r.put(e,"attributionContextExpiresAt")):(r.delete("attributionContextId"),r.delete("attributionContextExpiresAt")),await l(i);}async enqueue(t){let e=await this.load(),i=[...e.queue,t];W(i);let r=new Set(i.map(a=>a.clientEventId)),s=this.database.transaction(u,"readwrite"),o=s.objectStore(u);o.put(t);for(let a of e.queue)r.has(a.clientEventId)||o.delete(a.clientEventId);await l(s);}async remove(t){if(t.size===0)return;let e=this.database.transaction(u,"readwrite"),i=e.objectStore(u);for(let r of t)i.delete(r);await l(e);}async clear(){let t=this.database.transaction([d,u],"readwrite");t.objectStore(d).clear(),t.objectStore(u).clear(),await l(t);}close(){this.database.close();}async writeMeta(t,e){let i=this.database.transaction(d,"readwrite");i.objectStore(d).put(e,t),await l(i);}};function W(n){for(;n.length>100||m(n)>1048576;)n.shift();}function p(n){return new Promise((t,e)=>{n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error??new Error("IndexedDB request failed."));})}function l(n){return new Promise((t,e)=>{n.oncomplete=()=>t(),n.onerror=()=>e(n.error??new Error("IndexedDB transaction failed.")),n.onabort=()=>e(n.error??new Error("IndexedDB transaction aborted."));})}function B(n){return JSON.parse(JSON.stringify(n))}function N(n){return `wts-web-${n}`}var E=class{constructor(t,e){this.collectorOrigin=t;this.timeoutMs=e;}async bootstrap(t){return await(await this.post("/v2/bootstrap",t.sourceKey,{schemaVersion:2,clientEventId:t.clientEventId,...t.identity,occurredAt:new Date().toISOString(),metadata:{platform:"web",sdkVersion:y,locale:g()},...t.attributionToken?{attributionToken:t.attributionToken}:{}},false)).json()}async send(t,e,i){return await(await this.post("/v2/events/batch",t,{schemaVersion:2,events:e},i)).json()}async post(t,e,i,r){let s=new AbortController,o=setTimeout(()=>s.abort(),this.timeoutMs);try{let a=await fetch(`${this.collectorOrigin}${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-WTS-Source-Key":e},body:JSON.stringify(i),credentials:"omit",mode:"cors",cache:"no-store",keepalive:r,signal:s.signal});if(!a.ok)throw await h.fromResponse(a);return a}finally{clearTimeout(o);}}},h=class n extends Error{constructor(e,i,r,s){super(e);this.status=i;this.retryable=r;this.code=s;this.name="WtsTransportError";}static async fromResponse(e){let i={};try{i=await e.json();}catch{}return new n(i.message??`Collector request failed with status ${e.status}.`,e.status,e.status===429||e.status>=500,i.code)}};var V=/^[a-z][a-z0-9_]{1,63}$/,z=/^[A-Za-z0-9_-]{8,128}$/,H=/^[A-Z]{3}$/,X=/^-?\d{1,12}(?:\.\d{1,6})?$/;function L(n){if(!z.test(n.sourceKey))throw new TypeError("sourceKey must be a valid wts.is Web App source key.");let t=new URL(n.collectorOrigin??"https://collect.wts.is");if(t.protocol!=="https:"&&!F(t.hostname))throw new TypeError("collectorOrigin must use HTTPS outside localhost.");if(t.pathname!=="/"||t.search||t.hash)throw new TypeError("collectorOrigin must not include a path, query, or fragment.");let e=n.requestTimeoutMs??2e3;if(!Number.isInteger(e)||e<250||e>3e4)throw new TypeError("requestTimeoutMs must be an integer between 250 and 30000.");return {sourceKey:n.sourceKey,consent:n.consent??"pending",autoTrackPageViews:n.autoTrackPageViews??false,collectorOrigin:t.origin,requestTimeoutMs:e,debug:n.debug??false}}function M(n,t,e){if(!V.test(n))throw new TypeError("eventKey must match ^[a-z][a-z0-9_]{1,63}$.");let i=Object.entries(t);if(i.length>20)throw new TypeError("Events can contain at most 20 properties.");for(let[r,s]of i){if(!/^[a-z][a-z0-9_]{0,63}$/.test(r))throw new TypeError(`Invalid property key: ${r}`);if(!["string","number","boolean"].includes(typeof s))throw new TypeError(`Property ${r} must be a string, number, or boolean.`);if(typeof s=="string"&&s.length>512)throw new TypeError(`Property ${r} cannot exceed 512 characters.`);if(typeof s=="number"&&!Number.isFinite(s))throw new TypeError(`Property ${r} must be finite.`)}if(e&&(!X.test(e.amount)||!H.test(e.currency)))throw new TypeError("Revenue requires a decimal amount and uppercase ISO-4217 currency.")}function $(n){let t=n.startsWith("/")?n:`/${n}`;if(t.includes("?")||t.includes("#"))throw new TypeError("Page pathname cannot include a query or fragment.");if(t.length>2048)throw new TypeError("Page pathname cannot exceed 2048 characters.");return t}function F(n){return n==="localhost"||n==="127.0.0.1"||n==="[::1]"}var Q=10080*6e4,x=class{constructor(t,e){this.bootstrapClientEventId=c();this.bootstrapped=false;this.destroyed=false;this.retryAttempt=0;this.onPageHide=()=>{this.consent==="granted"&&this.lock.run(()=>this.flushExclusive(true));};this.onVisibilityChange=()=>{document.visibilityState==="hidden"&&this.consent==="granted"&&this.lock.run(()=>this.flushExclusive(true));};this.options=L(t),this.consent=this.options.consent,this.transport=e??new E(this.options.collectorOrigin,this.options.requestTimeoutMs),this.lock=new b(`flush-${this.options.sourceKey}`),this.attributionToken=G(),this.installLifecycleListeners(),this.consent==="granted"&&this.startEnable(),this.consent==="denied"&&(this.attributionToken=void 0);}async setConsent(t){if(this.destroyed)return;if(t==="denied"){this.consent="denied",this.cancelRetry();let i=this.storage;i&&await this.lock.run(async()=>{await i.clear(),i.close();});try{await D(this.options.sourceKey);}catch{v(this.options.debug,"Stored SDK data could not be deleted because it is in use.");}this.storage=void 0,this.identity=void 0,this.attributionContextId=void 0,this.attributionContextExpiresAt=void 0,this.attributionToken=void 0,this.bootstrapped=false,T(this.options.sourceKey),this.removeSpaTracking();return}let e=this.consent==="granted";this.consent="granted",(!e||!this.storage)&&await this.startEnable();}async page(t){let e=this.unavailableResult();if(e||(await this.ensureReady(),e=this.unavailableResult(),e))return e;let i=K(),r=k(),s={...this.eventBase("page_view"),pathname:i,...t?.trim()?{pageName:t.trim().slice(0,120)}:{},...r?{referrerHost:r}:{},properties:{}};return await this.enqueue(s),this.lastPagePath=i,{accepted:true,clientEventId:s.clientEventId}}async track(t,e={},i){let r=this.unavailableResult();if(r||(await this.ensureReady(),r=this.unavailableResult(),r))return r;M(t,e,i);let s={...this.eventBase("custom"),eventKey:t,properties:{...e},...i?{revenue:{...i}}:{}};return await this.enqueue(s),{accepted:true,clientEventId:s.clientEventId}}async flush(){return this.consent!=="granted"||this.destroyed||!this.storage?{sent:0,pending:0}:await this.lock.run(async()=>this.flushExclusive(false))??{sent:0,pending:(await this.storage.load()).queue.length}}async reset(){this.cancelRetry(),await this.storage?.clear(),this.identity=void 0,this.attributionContextId=void 0,this.attributionContextExpiresAt=void 0,this.attributionToken=void 0,T(this.options.sourceKey),this.bootstrapClientEventId=c(),this.bootstrapped=false,this.lastPagePath=void 0,this.consent==="granted"&&!this.destroyed&&await this.initializeIdentity();}destroy(){if(this.destroyed)return;this.destroyed=true,this.cancelRetry(),this.removeSpaTracking(),this.removeLifecycleListeners();let t=this.storage;t&&this.lock.run(async()=>t.close());}async enable(){if(!(this.destroyed||this.consent!=="granted")){if(!this.storage)try{this.storage=await _(this.options.sourceKey),await this.storage.load();}catch{this.storage?.close(),this.storage=new w,v(this.options.debug,"IndexedDB unavailable; using a memory-only event queue.");}await this.initializeIdentity();try{await this.ensureBootstrapped();}catch(t){this.handleRetryableError(t);}this.options.autoTrackPageViews&&!this.removeSpaTracker&&(this.removeSpaTracker=q(()=>{this.trackAutomaticPage();}),await this.trackAutomaticPage()),this.flush();}}startEnable(){if(this.enablePromise)return this.enablePromise;let t=this.enable();return this.enablePromise=t,t.finally(()=>{this.enablePromise===t&&(this.enablePromise=void 0);}),t}async ensureReady(){this.consent==="granted"&&(!this.storage||!this.identity)&&await this.startEnable();}async initializeIdentity(){if(!this.storage)return;let t=await this.storage.load(),e=R(this.options.sourceKey);this.identity={anonymousId:t.identity?.anonymousId??c(),sessionId:e?.sessionId??c()},this.bootstrapClientEventId=e?.bootstrapClientEventId??c(),O(this.options.sourceKey,{sessionId:this.identity.sessionId,bootstrapClientEventId:this.bootstrapClientEventId});let i=t.attributionContextExpiresAt?Date.parse(t.attributionContextExpiresAt):Number.NaN;t.attributionContextId&&Number.isFinite(i)&&i>Date.now()?(this.attributionContextId=t.attributionContextId,this.attributionContextExpiresAt=i):(t.attributionContextId||t.attributionContextExpiresAt)&&await this.storage.saveAttributionContext(),(!t.identity||t.identity.anonymousId!==this.identity.anonymousId||t.identity.sessionId!==this.identity.sessionId)&&await this.storage.saveIdentity(this.identity);}async ensureBootstrapped(){if(this.bootstrapped||!this.identity||!this.storage)return;let t=await this.transport.bootstrap({sourceKey:this.options.sourceKey,identity:this.identity,clientEventId:this.bootstrapClientEventId,...this.attributionToken?{attributionToken:this.attributionToken}:{}});if(this.bootstrapped=true,this.attributionToken=void 0,t.attributionContextId){this.attributionContextId=t.attributionContextId;let e=Date.parse(t.serverTime);this.attributionContextExpiresAt=(Number.isFinite(e)?e:Date.now())+Q,await this.storage.saveAttributionContext(t.attributionContextId,new Date(this.attributionContextExpiresAt).toISOString());}this.retryAttempt=0;}async enqueue(t){this.storage&&(await this.storage.enqueue(t),queueMicrotask(()=>{this.flush();}));}async flushExclusive(t){if(!this.storage)return {sent:0,pending:0};if(this.retryTimer&&!t)return {sent:0,pending:(await this.storage.load()).queue.length};try{await this.ensureBootstrapped();let e=await this.storage.load(),i=Z(e.queue,this.activeAttributionContextId());if(i.length===0)return {sent:0,pending:e.queue.length};let r=await this.transport.send(this.options.sourceKey,i,t),s=new Set([...r.accepted,...r.duplicates]),o=!1;for(let f of r.rejected)f.retryable?o=!0:s.add(f.clientEventId);await this.storage.remove(s);let a=(await this.storage.load()).queue.length;return o?this.scheduleRetry():(this.retryAttempt=0,a>0&&queueMicrotask(()=>{this.flush();})),{sent:s.size,pending:a}}catch(e){return this.handleRetryableError(e),{sent:0,pending:(await this.storage.load()).queue.length}}}handleRetryableError(t){if(t instanceof h&&!t.retryable){v(this.options.debug,`Collector rejected the request (${t.code??t.status}).`);return}this.scheduleRetry();}scheduleRetry(){if(this.consent!=="granted"||this.destroyed||this.retryTimer)return;let t=Math.min(6e4,1e3*2**Math.min(this.retryAttempt,6)),e=Math.floor(Math.random()*Math.max(1,t*.25));this.retryAttempt+=1,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.flush();},t+e);}async trackAutomaticPage(){K()!==this.lastPagePath&&await this.page();}eventBase(t){if(!this.identity)throw new Error("Web SDK identity is unavailable.");let e=this.activeAttributionContextId();return {schemaVersion:2,clientEventId:c(),...this.identity,type:t,occurredAt:new Date().toISOString(),metadata:{platform:"web",sdkVersion:y,locale:g()},...e?{attributionContextId:e}:{}}}unavailableResult(){if(this.destroyed)return {accepted:false,reason:"destroyed"};if(this.consent==="pending")return {accepted:false,reason:"consent_pending"};if(this.consent==="denied")return {accepted:false,reason:"consent_denied"}}activeAttributionContextId(){if(this.attributionContextId&&this.attributionContextExpiresAt&&this.attributionContextExpiresAt>Date.now())return this.attributionContextId;(this.attributionContextId||this.attributionContextExpiresAt)&&(this.attributionContextId=void 0,this.attributionContextExpiresAt=void 0,this.storage?.saveAttributionContext());}installLifecycleListeners(){typeof window>"u"||typeof document>"u"||(window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibilityChange));}removeLifecycleListeners(){typeof window>"u"||typeof document>"u"||(window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibilityChange));}removeSpaTracking(){this.removeSpaTracker?.(),this.removeSpaTracker=void 0;}cancelRetry(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;}};function K(){return $(typeof location>"u"?"/":location.pathname)}function G(){if(typeof location>"u"||typeof history>"u")return;let n=new URL(location.href),t=n.searchParams.get(S)??void 0;if(t)return n.searchParams.delete(S),history.replaceState(history.state,"",`${n.pathname}${n.search}${n.hash}`),t}function Z(n,t){let e=[];for(let i of n.slice(0,50)){let r=t?{...i,attributionContextId:t}:i;if(m({schemaVersion:2,events:[...e,r]})>65536)break;e.push(r);}return e}function xt(n){return new x(n)}
2
+ export{xt as createWtsClient};//# sourceMappingURL=index.js.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/constants.ts","../src/runtime.ts","../src/multitab-lock.ts","../src/spa-tracker.ts","../src/storage.ts","../src/transport.ts","../src/validation.ts","../src/client.ts","../src/index.ts"],"names":["SDK_VERSION","ATTRIBUTION_QUERY_KEY","createUuid","cryptoApi","bytes","hex","value","byteLength","locale","referrerHost","safeWarn","enabled","message","loadBrowserSession","sourceKey","parsed","sessionKey","isUuid","saveBrowserSession","state","clearBrowserSession","LEASE_MS","MultiTabLock","name","operation","lease","current","key","token","now","parseLease","installSpaTracker","onNavigate","historyApi","originalPush","originalReplace","scheduled","notify","args","META_STORE","EVENT_STORE","createStorage","IndexedDbStorage","deleteStorage","request","databaseName","resolve","reject","MemoryStorage","clone","identity","expiresAt","event","trimQueue","clientEventIds","_IndexedDbStorage","database","requestResult","transaction","meta","events","attributionContextId","attributionContextExpiresAt","queue","transactionDone","left","right","store","retainedIds","item","queued","id","HttpTransport","collectorOrigin","timeoutMs","input","keepalive","path","body","controller","timeout","response","TransportError","_TransportError","status","retryable","code","payload","eventKeyPattern","sourceKeyPattern","currencyPattern","amountPattern","validateOptions","options","collector","isLocalhost","validateEvent","eventKey","properties","revenue","entries","normalizePathname","pathname","normalized","hostname","ATTRIBUTION_CONTEXT_TTL_MS","WtsClientImpl","transport","captureAttributionToken","consent","storage","wasGranted","unavailable","currentPathname","referrer","error","pending","browserSession","contextExpiry","result","serverTime","batch","takeBatch","remove","hasRetryableRejection","rejection","base","jitter","type","url","createWtsClient"],"mappings":"AAAO,IAAMA,CAAAA,CAAc,gBAOpB,IAAMC,CAAAA,CAAwB,OCP9B,SAASC,CAAAA,EAAqB,CACnC,IAAMC,CAAAA,CAAY,WAAW,MAAA,CAC7B,G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AA,CAAgBrC,CAAAA,CAAsC,CACpE,OAAO,IAAIa,CAAAA,CAAcb,CAAO,CAClC","file":"index.js","sourcesContent":["export const SDK_VERSION = \"0.1.0-alpha.2\";\nexport const DEFAULT_COLLECTOR_ORIGIN = \"https://collect.wts.is\";\nexport const MAX_QUEUE_EVENTS = 100;\nexport const MAX_QUEUE_BYTES = 1024 * 1024;\nexport const MAX_BATCH_EVENTS = 50;\nexport const MAX_BATCH_BYTES = 64 * 1024;\nexport const DEFAULT_TIMEOUT_MS = 2_000;\nexport const ATTRIBUTION_QUERY_KEY = \"_wts\";\n","export function createUuid(): string {\n const cryptoApi = globalThis.crypto;\n if (!cryptoApi) throw new Error(\"A secure random number generator is required.\");\n if (typeof cryptoApi.randomUUID === \"function\") return cryptoApi.randomUUID();\n const bytes = cryptoApi.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n\nexport function byteLength(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value)).byteLength;\n}\n\nexport function locale(): string {\n return typeof navigator === \"undefined\" ? \"en\" : navigator.language || \"en\";\n}\n\nexport function referrerHost(): string | undefined {\n if (typeof document === \"undefined\" || !document.referrer) return undefined;\n try {\n return new URL(document.referrer).hostname.toLowerCase() || undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function safeWarn(enabled: boolean, message: string): void {\n if (enabled && typeof console !== \"undefined\") console.warn(`[wts.is] ${message}`);\n}\n\nexport type BrowserSessionState = {\n sessionId: string;\n bootstrapClientEventId: string;\n};\n\nexport function loadBrowserSession(sourceKey: string): BrowserSessionState | undefined {\n if (typeof sessionStorage === \"undefined\") return undefined;\n try {\n const parsed = JSON.parse(sessionStorage.getItem(sessionKey(sourceKey)) ?? \"null\") as {\n sessionId?: unknown;\n bootstrapClientEventId?: unknown;\n } | null;\n return parsed && isUuid(parsed.sessionId) && isUuid(parsed.bootstrapClientEventId)\n ? {\n sessionId: parsed.sessionId,\n bootstrapClientEventId: parsed.bootstrapClientEventId,\n }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function saveBrowserSession(sourceKey: string, state: BrowserSessionState): void {\n if (typeof sessionStorage === \"undefined\") return;\n try {\n sessionStorage.setItem(sessionKey(sourceKey), JSON.stringify(state));\n } catch {\n // Storage restrictions are handled by the SDK's memory-only fallback.\n }\n}\n\nexport function clearBrowserSession(sourceKey: string): void {\n if (typeof sessionStorage === \"undefined\") return;\n try {\n sessionStorage.removeItem(sessionKey(sourceKey));\n } catch {\n // A blocked browser storage API is equivalent to an already cleared session.\n }\n}\n\nfunction sessionKey(sourceKey: string): string {\n return `wts-session-${sourceKey}`;\n}\n\nfunction isUuid(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)\n );\n}\n","import { createUuid } from \"./runtime\";\n\nconst LEASE_MS = 10_000;\n\nexport class MultiTabLock {\n private current: Promise<unknown> | undefined;\n\n constructor(private readonly name: string) {}\n\n async run<T>(operation: () => Promise<T>): Promise<T | undefined> {\n if (typeof navigator !== \"undefined\" && navigator.locks) {\n return navigator.locks.request(this.name, operation);\n }\n if (this.current) await this.current;\n const lease = this.acquireLease();\n if (!lease) return undefined;\n const current = operation();\n this.current = current;\n try {\n return await current;\n } finally {\n if (this.current === current) this.current = undefined;\n lease.release();\n }\n }\n\n private acquireLease(): { release(): void } | undefined {\n if (typeof localStorage === \"undefined\") return { release() {} };\n const key = `wts-lock-${this.name}`;\n const token = createUuid();\n const now = Date.now();\n try {\n const current = parseLease(localStorage.getItem(key));\n if (current && current.expiresAt > now) return undefined;\n localStorage.setItem(key, JSON.stringify({ token, expiresAt: now + LEASE_MS }));\n const acquired = parseLease(localStorage.getItem(key));\n if (acquired?.token !== token) return undefined;\n return {\n release() {\n const latest = parseLease(localStorage.getItem(key));\n if (latest?.token === token) localStorage.removeItem(key);\n },\n };\n } catch {\n return { release() {} };\n }\n }\n}\n\nfunction parseLease(value: string | null): { token: string; expiresAt: number } | undefined {\n if (!value) return undefined;\n try {\n const parsed = JSON.parse(value) as { token?: unknown; expiresAt?: unknown };\n return typeof parsed.token === \"string\" && typeof parsed.expiresAt === \"number\"\n ? { token: parsed.token, expiresAt: parsed.expiresAt }\n : undefined;\n } catch {\n return undefined;\n }\n}\n","export function installSpaTracker(onNavigate: () => void): () => void {\n if (typeof window === \"undefined\") return () => undefined;\n const historyApi = window.history;\n const originalPush = historyApi.pushState;\n const originalReplace = historyApi.replaceState;\n let scheduled = false;\n const notify = () => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n onNavigate();\n });\n };\n historyApi.pushState = function (...args) {\n originalPush.apply(this, args);\n notify();\n };\n historyApi.replaceState = function (...args) {\n originalReplace.apply(this, args);\n notify();\n };\n window.addEventListener(\"popstate\", notify);\n return () => {\n historyApi.pushState = originalPush;\n historyApi.replaceState = originalReplace;\n window.removeEventListener(\"popstate\", notify);\n };\n}\n","import { MAX_QUEUE_BYTES, MAX_QUEUE_EVENTS } from \"./constants\";\nimport { byteLength } from \"./runtime\";\nimport type { Identity, StorageAdapter, StoredState, WebEvent } from \"./types\";\n\nconst META_STORE = \"meta\";\nconst EVENT_STORE = \"events\";\n\nexport async function createStorage(sourceKey: string): Promise<StorageAdapter> {\n if (typeof indexedDB === \"undefined\") throw new Error(\"IndexedDB is unavailable.\");\n return IndexedDbStorage.open(sourceKey);\n}\n\nexport async function deleteStorage(sourceKey: string): Promise<void> {\n if (typeof indexedDB === \"undefined\") return;\n const request = indexedDB.deleteDatabase(databaseName(sourceKey));\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => resolve();\n request.onerror = () => reject(request.error ?? new Error(\"IndexedDB deletion failed.\"));\n request.onblocked = () => reject(new Error(\"IndexedDB deletion was blocked by another tab.\"));\n });\n}\n\nexport class MemoryStorage implements StorageAdapter {\n private state: StoredState = { queue: [] };\n\n async load(): Promise<StoredState> {\n return clone(this.state);\n }\n\n async saveIdentity(identity: Identity): Promise<void> {\n this.state.identity = { ...identity };\n }\n\n async saveAttributionContext(value?: string, expiresAt?: string): Promise<void> {\n if (value && expiresAt) {\n this.state.attributionContextId = value;\n this.state.attributionContextExpiresAt = expiresAt;\n } else {\n delete this.state.attributionContextId;\n delete this.state.attributionContextExpiresAt;\n }\n }\n\n async enqueue(event: WebEvent): Promise<void> {\n this.state.queue.push(clone(event));\n trimQueue(this.state.queue);\n }\n\n async remove(clientEventIds: ReadonlySet<string>): Promise<void> {\n this.state.queue = this.state.queue.filter((event) => !clientEventIds.has(event.clientEventId));\n }\n\n async clear(): Promise<void> {\n this.state = { queue: [] };\n }\n\n close(): void {}\n}\n\nclass IndexedDbStorage implements StorageAdapter {\n private constructor(private readonly database: IDBDatabase) {}\n\n static async open(sourceKey: string): Promise<IndexedDbStorage> {\n const request = indexedDB.open(databaseName(sourceKey), 1);\n request.onupgradeneeded = () => {\n const database = request.result;\n if (!database.objectStoreNames.contains(META_STORE)) database.createObjectStore(META_STORE);\n if (!database.objectStoreNames.contains(EVENT_STORE)) {\n database.createObjectStore(EVENT_STORE, { keyPath: \"clientEventId\" });\n }\n };\n return new IndexedDbStorage(await requestResult(request));\n }\n\n async load(): Promise<StoredState> {\n const transaction = this.database.transaction([META_STORE, EVENT_STORE], \"readonly\");\n const meta = transaction.objectStore(META_STORE);\n const events = transaction.objectStore(EVENT_STORE);\n const [identity, attributionContextId, attributionContextExpiresAt, queue] = await Promise.all([\n requestResult(meta.get(\"identity\") as IDBRequest<Identity | undefined>),\n requestResult(meta.get(\"attributionContextId\") as IDBRequest<string | undefined>),\n requestResult(meta.get(\"attributionContextExpiresAt\") as IDBRequest<string | undefined>),\n requestResult(events.getAll() as IDBRequest<WebEvent[]>),\n ]);\n await transactionDone(transaction);\n queue.sort((left, right) => left.occurredAt.localeCompare(right.occurredAt));\n return {\n ...(identity ? { identity } : {}),\n ...(attributionContextId && attributionContextExpiresAt\n ? { attributionContextId, attributionContextExpiresAt }\n : {}),\n queue,\n };\n }\n\n async saveIdentity(identity: Identity): Promise<void> {\n await this.writeMeta(\"identity\", identity);\n }\n\n async saveAttributionContext(value?: string, expiresAt?: string): Promise<void> {\n const transaction = this.database.transaction(META_STORE, \"readwrite\");\n const store = transaction.objectStore(META_STORE);\n if (value && expiresAt) {\n store.put(value, \"attributionContextId\");\n store.put(expiresAt, \"attributionContextExpiresAt\");\n } else {\n store.delete(\"attributionContextId\");\n store.delete(\"attributionContextExpiresAt\");\n }\n await transactionDone(transaction);\n }\n\n async enqueue(event: WebEvent): Promise<void> {\n const state = await this.load();\n const queue = [...state.queue, event];\n trimQueue(queue);\n const retainedIds = new Set(queue.map((item) => item.clientEventId));\n const transaction = this.database.transaction(EVENT_STORE, \"readwrite\");\n const store = transaction.objectStore(EVENT_STORE);\n store.put(event);\n for (const queued of state.queue) {\n if (!retainedIds.has(queued.clientEventId)) store.delete(queued.clientEventId);\n }\n await transactionDone(transaction);\n }\n\n async remove(clientEventIds: ReadonlySet<string>): Promise<void> {\n if (clientEventIds.size === 0) return;\n const transaction = this.database.transaction(EVENT_STORE, \"readwrite\");\n const store = transaction.objectStore(EVENT_STORE);\n for (const id of clientEventIds) store.delete(id);\n await transactionDone(transaction);\n }\n\n async clear(): Promise<void> {\n const transaction = this.database.transaction([META_STORE, EVENT_STORE], \"readwrite\");\n transaction.objectStore(META_STORE).clear();\n transaction.objectStore(EVENT_STORE).clear();\n await transactionDone(transaction);\n }\n\n close(): void {\n this.database.close();\n }\n\n private async writeMeta(key: string, value: unknown): Promise<void> {\n const transaction = this.database.transaction(META_STORE, \"readwrite\");\n transaction.objectStore(META_STORE).put(value, key);\n await transactionDone(transaction);\n }\n}\n\nfunction trimQueue(queue: WebEvent[]): void {\n while (queue.length > MAX_QUEUE_EVENTS || byteLength(queue) > MAX_QUEUE_BYTES) queue.shift();\n}\n\nfunction requestResult<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error ?? new Error(\"IndexedDB request failed.\"));\n });\n}\n\nfunction transactionDone(transaction: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve();\n transaction.onerror = () =>\n reject(transaction.error ?? new Error(\"IndexedDB transaction failed.\"));\n transaction.onabort = () =>\n reject(transaction.error ?? new Error(\"IndexedDB transaction aborted.\"));\n });\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction databaseName(sourceKey: string): string {\n return `wts-web-${sourceKey}`;\n}\n","import { SDK_VERSION } from \"./constants\";\nimport { locale } from \"./runtime\";\nimport type { BatchResponse, Identity, Transport, WebEvent } from \"./types\";\n\nexport class HttpTransport implements Transport {\n constructor(\n private readonly collectorOrigin: string,\n private readonly timeoutMs: number,\n ) {}\n\n async bootstrap(input: {\n sourceKey: string;\n identity: Identity;\n clientEventId: string;\n attributionToken?: string;\n }): Promise<{ attributionContextId: string | null; serverTime: string }> {\n const response = await this.post(\n \"/v2/bootstrap\",\n input.sourceKey,\n {\n schemaVersion: 2,\n clientEventId: input.clientEventId,\n ...input.identity,\n occurredAt: new Date().toISOString(),\n metadata: { platform: \"web\", sdkVersion: SDK_VERSION, locale: locale() },\n ...(input.attributionToken ? { attributionToken: input.attributionToken } : {}),\n },\n false,\n );\n return (await response.json()) as { attributionContextId: string | null; serverTime: string };\n }\n\n async send(sourceKey: string, events: WebEvent[], keepalive: boolean): Promise<BatchResponse> {\n const response = await this.post(\n \"/v2/events/batch\",\n sourceKey,\n { schemaVersion: 2, events },\n keepalive,\n );\n return (await response.json()) as BatchResponse;\n }\n\n private async post(\n path: string,\n sourceKey: string,\n body: unknown,\n keepalive: boolean,\n ): Promise<Response> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n const response = await fetch(`${this.collectorOrigin}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-WTS-Source-Key\": sourceKey },\n body: JSON.stringify(body),\n credentials: \"omit\",\n mode: \"cors\",\n cache: \"no-store\",\n keepalive,\n signal: controller.signal,\n });\n if (!response.ok) throw await TransportError.fromResponse(response);\n return response;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class TransportError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly retryable: boolean,\n readonly code?: string,\n ) {\n super(message);\n this.name = \"WtsTransportError\";\n }\n\n static async fromResponse(response: Response): Promise<TransportError> {\n let payload: { code?: string; message?: string } = {};\n try {\n payload = (await response.json()) as typeof payload;\n } catch {\n // The SDK intentionally does not surface response bodies in logs.\n }\n return new TransportError(\n payload.message ?? `Collector request failed with status ${response.status}.`,\n response.status,\n response.status === 429 || response.status >= 500,\n payload.code,\n );\n }\n}\n","import type { EventProperties, Revenue, WtsClientOptions } from \"./types\";\n\nconst eventKeyPattern = /^[a-z][a-z0-9_]{1,63}$/;\nconst sourceKeyPattern = /^[A-Za-z0-9_-]{8,128}$/;\nconst currencyPattern = /^[A-Z]{3}$/;\nconst amountPattern = /^-?\\d{1,12}(?:\\.\\d{1,6})?$/;\n\nexport function validateOptions(\n options: WtsClientOptions,\n): Required<\n Pick<\n WtsClientOptions,\n \"sourceKey\" | \"autoTrackPageViews\" | \"collectorOrigin\" | \"requestTimeoutMs\" | \"debug\"\n >\n> & { consent: NonNullable<WtsClientOptions[\"consent\"]> } {\n if (!sourceKeyPattern.test(options.sourceKey)) {\n throw new TypeError(\"sourceKey must be a valid wts.is Web App source key.\");\n }\n const collector = new URL(options.collectorOrigin ?? \"https://collect.wts.is\");\n if (collector.protocol !== \"https:\" && !isLocalhost(collector.hostname)) {\n throw new TypeError(\"collectorOrigin must use HTTPS outside localhost.\");\n }\n if (collector.pathname !== \"/\" || collector.search || collector.hash) {\n throw new TypeError(\"collectorOrigin must not include a path, query, or fragment.\");\n }\n const timeout = options.requestTimeoutMs ?? 2_000;\n if (!Number.isInteger(timeout) || timeout < 250 || timeout > 30_000) {\n throw new TypeError(\"requestTimeoutMs must be an integer between 250 and 30000.\");\n }\n return {\n sourceKey: options.sourceKey,\n consent: options.consent ?? \"pending\",\n autoTrackPageViews: options.autoTrackPageViews ?? false,\n collectorOrigin: collector.origin,\n requestTimeoutMs: timeout,\n debug: options.debug ?? false,\n };\n}\n\nexport function validateEvent(\n eventKey: string,\n properties: EventProperties,\n revenue?: Revenue,\n): void {\n if (!eventKeyPattern.test(eventKey)) {\n throw new TypeError(\"eventKey must match ^[a-z][a-z0-9_]{1,63}$.\");\n }\n const entries = Object.entries(properties);\n if (entries.length > 20) throw new TypeError(\"Events can contain at most 20 properties.\");\n for (const [key, value] of entries) {\n if (!/^[a-z][a-z0-9_]{0,63}$/.test(key)) throw new TypeError(`Invalid property key: ${key}`);\n if (![\"string\", \"number\", \"boolean\"].includes(typeof value)) {\n throw new TypeError(`Property ${key} must be a string, number, or boolean.`);\n }\n if (typeof value === \"string\" && value.length > 512) {\n throw new TypeError(`Property ${key} cannot exceed 512 characters.`);\n }\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n throw new TypeError(`Property ${key} must be finite.`);\n }\n }\n if (revenue && (!amountPattern.test(revenue.amount) || !currencyPattern.test(revenue.currency))) {\n throw new TypeError(\"Revenue requires a decimal amount and uppercase ISO-4217 currency.\");\n }\n}\n\nexport function normalizePathname(pathname: string): string {\n const normalized = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n if (normalized.includes(\"?\") || normalized.includes(\"#\")) {\n throw new TypeError(\"Page pathname cannot include a query or fragment.\");\n }\n if (normalized.length > 2_048)\n throw new TypeError(\"Page pathname cannot exceed 2048 characters.\");\n return normalized;\n}\n\nfunction isLocalhost(hostname: string): boolean {\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\";\n}\n","import { ATTRIBUTION_QUERY_KEY, MAX_BATCH_BYTES, MAX_BATCH_EVENTS, SDK_VERSION } from \"./constants\";\nimport { MultiTabLock } from \"./multitab-lock\";\nimport {\n byteLength,\n clearBrowserSession,\n createUuid,\n loadBrowserSession,\n locale,\n referrerHost,\n safeWarn,\n saveBrowserSession,\n} from \"./runtime\";\nimport { installSpaTracker } from \"./spa-tracker\";\nimport { createStorage, deleteStorage, MemoryStorage } from \"./storage\";\nimport { HttpTransport, TransportError } from \"./transport\";\nimport type {\n ConsentState,\n EventProperties,\n FlushResult,\n Identity,\n OperationResult,\n Revenue,\n StorageAdapter,\n Transport,\n WebEvent,\n WtsClient,\n WtsClientOptions,\n} from \"./types\";\nimport { normalizePathname, validateEvent, validateOptions } from \"./validation\";\n\ntype ResolvedOptions = ReturnType<typeof validateOptions>;\nconst ATTRIBUTION_CONTEXT_TTL_MS = 7 * 24 * 60 * 60_000;\n\nexport class WtsClientImpl implements WtsClient {\n private consent: ConsentState;\n private storage: StorageAdapter | undefined;\n private identity: Identity | undefined;\n private attributionContextId: string | undefined;\n private attributionContextExpiresAt: number | undefined;\n private attributionToken: string | undefined;\n private bootstrapClientEventId = createUuid();\n private bootstrapped = false;\n private destroyed = false;\n private retryAttempt = 0;\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n private enablePromise: Promise<void> | undefined;\n private removeSpaTracker: (() => void) | undefined;\n private lastPagePath: string | undefined;\n private readonly options: ResolvedOptions;\n private readonly transport: Transport;\n private readonly lock: MultiTabLock;\n\n constructor(options: WtsClientOptions, transport?: Transport) {\n this.options = validateOptions(options);\n this.consent = this.options.consent;\n this.transport =\n transport ?? new HttpTransport(this.options.collectorOrigin, this.options.requestTimeoutMs);\n this.lock = new MultiTabLock(`flush-${this.options.sourceKey}`);\n this.attributionToken = captureAttributionToken();\n this.installLifecycleListeners();\n if (this.consent === \"granted\") void this.startEnable();\n if (this.consent === \"denied\") this.attributionToken = undefined;\n }\n\n async setConsent(consent: \"granted\" | \"denied\"): Promise<void> {\n if (this.destroyed) return;\n if (consent === \"denied\") {\n this.consent = \"denied\";\n this.cancelRetry();\n const storage = this.storage;\n if (storage) {\n await this.lock.run(async () => {\n await storage.clear();\n storage.close();\n });\n }\n try {\n await deleteStorage(this.options.sourceKey);\n } catch {\n safeWarn(this.options.debug, \"Stored SDK data could not be deleted because it is in use.\");\n }\n this.storage = undefined;\n this.identity = undefined;\n this.attributionContextId = undefined;\n this.attributionContextExpiresAt = undefined;\n this.attributionToken = undefined;\n this.bootstrapped = false;\n clearBrowserSession(this.options.sourceKey);\n this.removeSpaTracking();\n return;\n }\n const wasGranted = this.consent === \"granted\";\n this.consent = \"granted\";\n if (!wasGranted || !this.storage) await this.startEnable();\n }\n\n async page(name?: string): Promise<OperationResult> {\n let unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n await this.ensureReady();\n unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n const pathname = currentPathname();\n const referrer = referrerHost();\n const event: WebEvent = {\n ...this.eventBase(\"page_view\"),\n pathname,\n ...(name?.trim() ? { pageName: name.trim().slice(0, 120) } : {}),\n ...(referrer ? { referrerHost: referrer } : {}),\n properties: {},\n };\n await this.enqueue(event);\n this.lastPagePath = pathname;\n return { accepted: true, clientEventId: event.clientEventId };\n }\n\n async track(\n eventKey: string,\n properties: EventProperties = {},\n revenue?: Revenue,\n ): Promise<OperationResult> {\n let unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n await this.ensureReady();\n unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n validateEvent(eventKey, properties, revenue);\n const event: WebEvent = {\n ...this.eventBase(\"custom\"),\n eventKey,\n properties: { ...properties },\n ...(revenue ? { revenue: { ...revenue } } : {}),\n };\n await this.enqueue(event);\n return { accepted: true, clientEventId: event.clientEventId };\n }\n\n async flush(): Promise<FlushResult> {\n if (this.consent !== \"granted\" || this.destroyed || !this.storage) {\n return { sent: 0, pending: 0 };\n }\n const result = await this.lock.run(async () => this.flushExclusive(false));\n return result ?? { sent: 0, pending: (await this.storage.load()).queue.length };\n }\n\n async reset(): Promise<void> {\n this.cancelRetry();\n await this.storage?.clear();\n this.identity = undefined;\n this.attributionContextId = undefined;\n this.attributionContextExpiresAt = undefined;\n this.attributionToken = undefined;\n clearBrowserSession(this.options.sourceKey);\n this.bootstrapClientEventId = createUuid();\n this.bootstrapped = false;\n this.lastPagePath = undefined;\n if (this.consent === \"granted\" && !this.destroyed) await this.initializeIdentity();\n }\n\n destroy(): void {\n if (this.destroyed) return;\n this.destroyed = true;\n this.cancelRetry();\n this.removeSpaTracking();\n this.removeLifecycleListeners();\n const storage = this.storage;\n if (storage) void this.lock.run(async () => storage.close());\n }\n\n private async enable(): Promise<void> {\n if (this.destroyed || this.consent !== \"granted\") return;\n if (!this.storage) {\n try {\n this.storage = await createStorage(this.options.sourceKey);\n await this.storage.load();\n } catch {\n this.storage?.close();\n this.storage = new MemoryStorage();\n safeWarn(this.options.debug, \"IndexedDB unavailable; using a memory-only event queue.\");\n }\n }\n await this.initializeIdentity();\n try {\n await this.ensureBootstrapped();\n } catch (error) {\n this.handleRetryableError(error);\n }\n if (this.options.autoTrackPageViews && !this.removeSpaTracker) {\n this.removeSpaTracker = installSpaTracker(() => {\n void this.trackAutomaticPage();\n });\n await this.trackAutomaticPage();\n }\n void this.flush();\n }\n\n private startEnable(): Promise<void> {\n if (this.enablePromise) return this.enablePromise;\n const pending = this.enable();\n this.enablePromise = pending;\n void pending.finally(() => {\n if (this.enablePromise === pending) this.enablePromise = undefined;\n });\n return pending;\n }\n\n private async ensureReady(): Promise<void> {\n if (this.consent === \"granted\" && (!this.storage || !this.identity)) {\n await this.startEnable();\n }\n }\n\n private async initializeIdentity(): Promise<void> {\n if (!this.storage) return;\n const state = await this.storage.load();\n const browserSession = loadBrowserSession(this.options.sourceKey);\n this.identity = {\n anonymousId: state.identity?.anonymousId ?? createUuid(),\n sessionId: browserSession?.sessionId ?? createUuid(),\n };\n this.bootstrapClientEventId = browserSession?.bootstrapClientEventId ?? createUuid();\n saveBrowserSession(this.options.sourceKey, {\n sessionId: this.identity.sessionId,\n bootstrapClientEventId: this.bootstrapClientEventId,\n });\n const contextExpiry = state.attributionContextExpiresAt\n ? Date.parse(state.attributionContextExpiresAt)\n : Number.NaN;\n if (\n state.attributionContextId &&\n Number.isFinite(contextExpiry) &&\n contextExpiry > Date.now()\n ) {\n this.attributionContextId = state.attributionContextId;\n this.attributionContextExpiresAt = contextExpiry;\n } else if (state.attributionContextId || state.attributionContextExpiresAt) {\n await this.storage.saveAttributionContext();\n }\n if (\n !state.identity ||\n state.identity.anonymousId !== this.identity.anonymousId ||\n state.identity.sessionId !== this.identity.sessionId\n ) {\n await this.storage.saveIdentity(this.identity);\n }\n }\n\n private async ensureBootstrapped(): Promise<void> {\n if (this.bootstrapped || !this.identity || !this.storage) return;\n const result = await this.transport.bootstrap({\n sourceKey: this.options.sourceKey,\n identity: this.identity,\n clientEventId: this.bootstrapClientEventId,\n ...(this.attributionToken ? { attributionToken: this.attributionToken } : {}),\n });\n this.bootstrapped = true;\n this.attributionToken = undefined;\n if (result.attributionContextId) {\n this.attributionContextId = result.attributionContextId;\n const serverTime = Date.parse(result.serverTime);\n this.attributionContextExpiresAt =\n (Number.isFinite(serverTime) ? serverTime : Date.now()) + ATTRIBUTION_CONTEXT_TTL_MS;\n await this.storage.saveAttributionContext(\n result.attributionContextId,\n new Date(this.attributionContextExpiresAt).toISOString(),\n );\n }\n this.retryAttempt = 0;\n }\n\n private async enqueue(event: WebEvent): Promise<void> {\n if (!this.storage) return;\n await this.storage.enqueue(event);\n queueMicrotask(() => void this.flush());\n }\n\n private async flushExclusive(keepalive: boolean): Promise<FlushResult> {\n if (!this.storage) return { sent: 0, pending: 0 };\n if (this.retryTimer && !keepalive) {\n return { sent: 0, pending: (await this.storage.load()).queue.length };\n }\n try {\n await this.ensureBootstrapped();\n const state = await this.storage.load();\n const batch = takeBatch(state.queue, this.activeAttributionContextId());\n if (batch.length === 0) return { sent: 0, pending: state.queue.length };\n const response = await this.transport.send(this.options.sourceKey, batch, keepalive);\n const remove = new Set([...response.accepted, ...response.duplicates]);\n let hasRetryableRejection = false;\n for (const rejection of response.rejected) {\n if (rejection.retryable) hasRetryableRejection = true;\n else remove.add(rejection.clientEventId);\n }\n await this.storage.remove(remove);\n const pending = (await this.storage.load()).queue.length;\n if (hasRetryableRejection) this.scheduleRetry();\n else {\n this.retryAttempt = 0;\n if (pending > 0) queueMicrotask(() => void this.flush());\n }\n return { sent: remove.size, pending };\n } catch (error) {\n this.handleRetryableError(error);\n return { sent: 0, pending: (await this.storage.load()).queue.length };\n }\n }\n\n private handleRetryableError(error: unknown): void {\n if (error instanceof TransportError && !error.retryable) {\n safeWarn(\n this.options.debug,\n `Collector rejected the request (${error.code ?? error.status}).`,\n );\n return;\n }\n this.scheduleRetry();\n }\n\n private scheduleRetry(): void {\n if (this.consent !== \"granted\" || this.destroyed || this.retryTimer) return;\n const base = Math.min(60_000, 1_000 * 2 ** Math.min(this.retryAttempt, 6));\n const jitter = Math.floor(Math.random() * Math.max(1, base * 0.25));\n this.retryAttempt += 1;\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n void this.flush();\n }, base + jitter);\n }\n\n private async trackAutomaticPage(): Promise<void> {\n const pathname = currentPathname();\n if (pathname === this.lastPagePath) return;\n await this.page();\n }\n\n private eventBase(type: WebEvent[\"type\"]): Omit<WebEvent, \"properties\"> {\n if (!this.identity) throw new Error(\"Web SDK identity is unavailable.\");\n const attributionContextId = this.activeAttributionContextId();\n return {\n schemaVersion: 2,\n clientEventId: createUuid(),\n ...this.identity,\n type,\n occurredAt: new Date().toISOString(),\n metadata: { platform: \"web\", sdkVersion: SDK_VERSION, locale: locale() },\n ...(attributionContextId ? { attributionContextId } : {}),\n };\n }\n\n private unavailableResult(): OperationResult | undefined {\n if (this.destroyed) return { accepted: false, reason: \"destroyed\" };\n if (this.consent === \"pending\") return { accepted: false, reason: \"consent_pending\" };\n if (this.consent === \"denied\") return { accepted: false, reason: \"consent_denied\" };\n return undefined;\n }\n\n private activeAttributionContextId(): string | undefined {\n if (\n this.attributionContextId &&\n this.attributionContextExpiresAt &&\n this.attributionContextExpiresAt > Date.now()\n ) {\n return this.attributionContextId;\n }\n if (this.attributionContextId || this.attributionContextExpiresAt) {\n this.attributionContextId = undefined;\n this.attributionContextExpiresAt = undefined;\n void this.storage?.saveAttributionContext();\n }\n return undefined;\n }\n\n private installLifecycleListeners(): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n window.addEventListener(\"pagehide\", this.onPageHide);\n document.addEventListener(\"visibilitychange\", this.onVisibilityChange);\n }\n\n private removeLifecycleListeners(): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n window.removeEventListener(\"pagehide\", this.onPageHide);\n document.removeEventListener(\"visibilitychange\", this.onVisibilityChange);\n }\n\n private readonly onPageHide = () => {\n if (this.consent === \"granted\") void this.lock.run(() => this.flushExclusive(true));\n };\n\n private readonly onVisibilityChange = () => {\n if (document.visibilityState === \"hidden\" && this.consent === \"granted\") {\n void this.lock.run(() => this.flushExclusive(true));\n }\n };\n\n private removeSpaTracking(): void {\n this.removeSpaTracker?.();\n this.removeSpaTracker = undefined;\n }\n\n private cancelRetry(): void {\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = undefined;\n }\n}\n\nfunction currentPathname(): string {\n return normalizePathname(typeof location === \"undefined\" ? \"/\" : location.pathname);\n}\n\nfunction captureAttributionToken(): string | undefined {\n if (typeof location === \"undefined\" || typeof history === \"undefined\") return undefined;\n const url = new URL(location.href);\n const token = url.searchParams.get(ATTRIBUTION_QUERY_KEY) ?? undefined;\n if (!token) return undefined;\n url.searchParams.delete(ATTRIBUTION_QUERY_KEY);\n history.replaceState(history.state, \"\", `${url.pathname}${url.search}${url.hash}`);\n return token;\n}\n\nfunction takeBatch(queue: WebEvent[], attributionContextId?: string): WebEvent[] {\n const batch: WebEvent[] = [];\n for (const queued of queue.slice(0, MAX_BATCH_EVENTS)) {\n const event = attributionContextId ? { ...queued, attributionContextId } : queued;\n if (byteLength({ schemaVersion: 2, events: [...batch, event] }) > MAX_BATCH_BYTES) break;\n batch.push(event);\n }\n return batch;\n}\n","import { WtsClientImpl } from \"./client\";\nimport type { WtsClient, WtsClientOptions } from \"./types\";\n\nexport type {\n ConsentState,\n EventProperties,\n FlushResult,\n OperationResult,\n Revenue,\n Scalar,\n WtsClient,\n WtsClientOptions,\n} from \"./types\";\n\nexport function createWtsClient(options: WtsClientOptions): WtsClient {\n return new WtsClientImpl(options);\n}\n"]}
@@ -0,0 +1,3 @@
1
+ var WtsWebBundle=(function(){'use strict';var y="0.1.0-alpha.2";var S="_wts";function c(){let n=globalThis.crypto;if(!n)throw new Error("A secure random number generator is required.");if(typeof n.randomUUID=="function")return n.randomUUID();let t=n.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=Array.from(t,i=>i.toString(16).padStart(2,"0"));return `${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}function m(n){return new TextEncoder().encode(JSON.stringify(n)).byteLength}function g(){return typeof navigator>"u"?"en":navigator.language||"en"}function k(){if(!(typeof document>"u"||!document.referrer))try{return new URL(document.referrer).hostname.toLowerCase()||void 0}catch{return}}function v(n,t){n&&typeof console<"u"&&console.warn(`[wts.is] ${t}`);}function R(n){if(!(typeof sessionStorage>"u"))try{let t=JSON.parse(sessionStorage.getItem(I(n))??"null");return t&&A(t.sessionId)&&A(t.bootstrapClientEventId)?{sessionId:t.sessionId,bootstrapClientEventId:t.bootstrapClientEventId}:void 0}catch{return}}function O(n,t){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(I(n),JSON.stringify(t));}catch{}}function T(n){if(!(typeof sessionStorage>"u"))try{sessionStorage.removeItem(I(n));}catch{}}function I(n){return `wts-session-${n}`}function A(n){return typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}var z=1e4,b=class{constructor(t){this.name=t;}async run(t){if(typeof navigator<"u"&&navigator.locks)return navigator.locks.request(this.name,t);this.current&&await this.current;let e=this.acquireLease();if(!e)return;let i=t();this.current=i;try{return await i}finally{this.current===i&&(this.current=void 0),e.release();}}acquireLease(){if(typeof localStorage>"u")return {release(){}};let t=`wts-lock-${this.name}`,e=c(),i=Date.now();try{let r=C(localStorage.getItem(t));return r&&r.expiresAt>i||(localStorage.setItem(t,JSON.stringify({token:e,expiresAt:i+z})),C(localStorage.getItem(t))?.token!==e)?void 0:{release(){C(localStorage.getItem(t))?.token===e&&localStorage.removeItem(t);}}}catch{return {release(){}}}}};function C(n){if(n)try{let t=JSON.parse(n);return typeof t.token=="string"&&typeof t.expiresAt=="number"?{token:t.token,expiresAt:t.expiresAt}:void 0}catch{return}}function q(n){if(typeof window>"u")return ()=>{};let t=window.history,e=t.pushState,i=t.replaceState,r=false,s=()=>{r||(r=true,queueMicrotask(()=>{r=false,n();}));};return t.pushState=function(...o){e.apply(this,o),s();},t.replaceState=function(...o){i.apply(this,o),s();},window.addEventListener("popstate",s),()=>{t.pushState=e,t.replaceState=i,window.removeEventListener("popstate",s);}}var d="meta",u="events";async function _(n){if(typeof indexedDB>"u")throw new Error("IndexedDB is unavailable.");return P.open(n)}async function W(n){if(typeof indexedDB>"u")return;let t=indexedDB.deleteDatabase(N(n));await new Promise((e,i)=>{t.onsuccess=()=>e(),t.onerror=()=>i(t.error??new Error("IndexedDB deletion failed.")),t.onblocked=()=>i(new Error("IndexedDB deletion was blocked by another tab."));});}var w=class{constructor(){this.state={queue:[]};}async load(){return B(this.state)}async saveIdentity(t){this.state.identity={...t};}async saveAttributionContext(t,e){t&&e?(this.state.attributionContextId=t,this.state.attributionContextExpiresAt=e):(delete this.state.attributionContextId,delete this.state.attributionContextExpiresAt);}async enqueue(t){this.state.queue.push(B(t)),D(this.state.queue);}async remove(t){this.state.queue=this.state.queue.filter(e=>!t.has(e.clientEventId));}async clear(){this.state={queue:[]};}close(){}},P=class n{constructor(t){this.database=t;}static async open(t){let e=indexedDB.open(N(t),1);return e.onupgradeneeded=()=>{let i=e.result;i.objectStoreNames.contains(d)||i.createObjectStore(d),i.objectStoreNames.contains(u)||i.createObjectStore(u,{keyPath:"clientEventId"});},new n(await p(e))}async load(){let t=this.database.transaction([d,u],"readonly"),e=t.objectStore(d),i=t.objectStore(u),[r,s,o,a]=await Promise.all([p(e.get("identity")),p(e.get("attributionContextId")),p(e.get("attributionContextExpiresAt")),p(i.getAll())]);return await l(t),a.sort((f,V)=>f.occurredAt.localeCompare(V.occurredAt)),{...r?{identity:r}:{},...s&&o?{attributionContextId:s,attributionContextExpiresAt:o}:{},queue:a}}async saveIdentity(t){await this.writeMeta("identity",t);}async saveAttributionContext(t,e){let i=this.database.transaction(d,"readwrite"),r=i.objectStore(d);t&&e?(r.put(t,"attributionContextId"),r.put(e,"attributionContextExpiresAt")):(r.delete("attributionContextId"),r.delete("attributionContextExpiresAt")),await l(i);}async enqueue(t){let e=await this.load(),i=[...e.queue,t];D(i);let r=new Set(i.map(a=>a.clientEventId)),s=this.database.transaction(u,"readwrite"),o=s.objectStore(u);o.put(t);for(let a of e.queue)r.has(a.clientEventId)||o.delete(a.clientEventId);await l(s);}async remove(t){if(t.size===0)return;let e=this.database.transaction(u,"readwrite"),i=e.objectStore(u);for(let r of t)i.delete(r);await l(e);}async clear(){let t=this.database.transaction([d,u],"readwrite");t.objectStore(d).clear(),t.objectStore(u).clear(),await l(t);}close(){this.database.close();}async writeMeta(t,e){let i=this.database.transaction(d,"readwrite");i.objectStore(d).put(e,t),await l(i);}};function D(n){for(;n.length>100||m(n)>1048576;)n.shift();}function p(n){return new Promise((t,e)=>{n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error??new Error("IndexedDB request failed."));})}function l(n){return new Promise((t,e)=>{n.oncomplete=()=>t(),n.onerror=()=>e(n.error??new Error("IndexedDB transaction failed.")),n.onabort=()=>e(n.error??new Error("IndexedDB transaction aborted."));})}function B(n){return JSON.parse(JSON.stringify(n))}function N(n){return `wts-web-${n}`}var E=class{constructor(t,e){this.collectorOrigin=t;this.timeoutMs=e;}async bootstrap(t){return await(await this.post("/v2/bootstrap",t.sourceKey,{schemaVersion:2,clientEventId:t.clientEventId,...t.identity,occurredAt:new Date().toISOString(),metadata:{platform:"web",sdkVersion:y,locale:g()},...t.attributionToken?{attributionToken:t.attributionToken}:{}},false)).json()}async send(t,e,i){return await(await this.post("/v2/events/batch",t,{schemaVersion:2,events:e},i)).json()}async post(t,e,i,r){let s=new AbortController,o=setTimeout(()=>s.abort(),this.timeoutMs);try{let a=await fetch(`${this.collectorOrigin}${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-WTS-Source-Key":e},body:JSON.stringify(i),credentials:"omit",mode:"cors",cache:"no-store",keepalive:r,signal:s.signal});if(!a.ok)throw await h.fromResponse(a);return a}finally{clearTimeout(o);}}},h=class n extends Error{constructor(e,i,r,s){super(e);this.status=i;this.retryable=r;this.code=s;this.name="WtsTransportError";}static async fromResponse(e){let i={};try{i=await e.json();}catch{}return new n(i.message??`Collector request failed with status ${e.status}.`,e.status,e.status===429||e.status>=500,i.code)}};var H=/^[a-z][a-z0-9_]{1,63}$/,X=/^[A-Za-z0-9_-]{8,128}$/,F=/^[A-Z]{3}$/,J=/^-?\d{1,12}(?:\.\d{1,6})?$/;function L(n){if(!X.test(n.sourceKey))throw new TypeError("sourceKey must be a valid wts.is Web App source key.");let t=new URL(n.collectorOrigin??"https://collect.wts.is");if(t.protocol!=="https:"&&!Y(t.hostname))throw new TypeError("collectorOrigin must use HTTPS outside localhost.");if(t.pathname!=="/"||t.search||t.hash)throw new TypeError("collectorOrigin must not include a path, query, or fragment.");let e=n.requestTimeoutMs??2e3;if(!Number.isInteger(e)||e<250||e>3e4)throw new TypeError("requestTimeoutMs must be an integer between 250 and 30000.");return {sourceKey:n.sourceKey,consent:n.consent??"pending",autoTrackPageViews:n.autoTrackPageViews??false,collectorOrigin:t.origin,requestTimeoutMs:e,debug:n.debug??false}}function M(n,t,e){if(!H.test(n))throw new TypeError("eventKey must match ^[a-z][a-z0-9_]{1,63}$.");let i=Object.entries(t);if(i.length>20)throw new TypeError("Events can contain at most 20 properties.");for(let[r,s]of i){if(!/^[a-z][a-z0-9_]{0,63}$/.test(r))throw new TypeError(`Invalid property key: ${r}`);if(!["string","number","boolean"].includes(typeof s))throw new TypeError(`Property ${r} must be a string, number, or boolean.`);if(typeof s=="string"&&s.length>512)throw new TypeError(`Property ${r} cannot exceed 512 characters.`);if(typeof s=="number"&&!Number.isFinite(s))throw new TypeError(`Property ${r} must be finite.`)}if(e&&(!J.test(e.amount)||!F.test(e.currency)))throw new TypeError("Revenue requires a decimal amount and uppercase ISO-4217 currency.")}function $(n){let t=n.startsWith("/")?n:`/${n}`;if(t.includes("?")||t.includes("#"))throw new TypeError("Page pathname cannot include a query or fragment.");if(t.length>2048)throw new TypeError("Page pathname cannot exceed 2048 characters.");return t}function Y(n){return n==="localhost"||n==="127.0.0.1"||n==="[::1]"}var Z=10080*6e4,x=class{constructor(t,e){this.bootstrapClientEventId=c();this.bootstrapped=false;this.destroyed=false;this.retryAttempt=0;this.onPageHide=()=>{this.consent==="granted"&&this.lock.run(()=>this.flushExclusive(true));};this.onVisibilityChange=()=>{document.visibilityState==="hidden"&&this.consent==="granted"&&this.lock.run(()=>this.flushExclusive(true));};this.options=L(t),this.consent=this.options.consent,this.transport=e??new E(this.options.collectorOrigin,this.options.requestTimeoutMs),this.lock=new b(`flush-${this.options.sourceKey}`),this.attributionToken=tt(),this.installLifecycleListeners(),this.consent==="granted"&&this.startEnable(),this.consent==="denied"&&(this.attributionToken=void 0);}async setConsent(t){if(this.destroyed)return;if(t==="denied"){this.consent="denied",this.cancelRetry();let i=this.storage;i&&await this.lock.run(async()=>{await i.clear(),i.close();});try{await W(this.options.sourceKey);}catch{v(this.options.debug,"Stored SDK data could not be deleted because it is in use.");}this.storage=void 0,this.identity=void 0,this.attributionContextId=void 0,this.attributionContextExpiresAt=void 0,this.attributionToken=void 0,this.bootstrapped=false,T(this.options.sourceKey),this.removeSpaTracking();return}let e=this.consent==="granted";this.consent="granted",(!e||!this.storage)&&await this.startEnable();}async page(t){let e=this.unavailableResult();if(e||(await this.ensureReady(),e=this.unavailableResult(),e))return e;let i=K(),r=k(),s={...this.eventBase("page_view"),pathname:i,...t?.trim()?{pageName:t.trim().slice(0,120)}:{},...r?{referrerHost:r}:{},properties:{}};return await this.enqueue(s),this.lastPagePath=i,{accepted:true,clientEventId:s.clientEventId}}async track(t,e={},i){let r=this.unavailableResult();if(r||(await this.ensureReady(),r=this.unavailableResult(),r))return r;M(t,e,i);let s={...this.eventBase("custom"),eventKey:t,properties:{...e},...i?{revenue:{...i}}:{}};return await this.enqueue(s),{accepted:true,clientEventId:s.clientEventId}}async flush(){return this.consent!=="granted"||this.destroyed||!this.storage?{sent:0,pending:0}:await this.lock.run(async()=>this.flushExclusive(false))??{sent:0,pending:(await this.storage.load()).queue.length}}async reset(){this.cancelRetry(),await this.storage?.clear(),this.identity=void 0,this.attributionContextId=void 0,this.attributionContextExpiresAt=void 0,this.attributionToken=void 0,T(this.options.sourceKey),this.bootstrapClientEventId=c(),this.bootstrapped=false,this.lastPagePath=void 0,this.consent==="granted"&&!this.destroyed&&await this.initializeIdentity();}destroy(){if(this.destroyed)return;this.destroyed=true,this.cancelRetry(),this.removeSpaTracking(),this.removeLifecycleListeners();let t=this.storage;t&&this.lock.run(async()=>t.close());}async enable(){if(!(this.destroyed||this.consent!=="granted")){if(!this.storage)try{this.storage=await _(this.options.sourceKey),await this.storage.load();}catch{this.storage?.close(),this.storage=new w,v(this.options.debug,"IndexedDB unavailable; using a memory-only event queue.");}await this.initializeIdentity();try{await this.ensureBootstrapped();}catch(t){this.handleRetryableError(t);}this.options.autoTrackPageViews&&!this.removeSpaTracker&&(this.removeSpaTracker=q(()=>{this.trackAutomaticPage();}),await this.trackAutomaticPage()),this.flush();}}startEnable(){if(this.enablePromise)return this.enablePromise;let t=this.enable();return this.enablePromise=t,t.finally(()=>{this.enablePromise===t&&(this.enablePromise=void 0);}),t}async ensureReady(){this.consent==="granted"&&(!this.storage||!this.identity)&&await this.startEnable();}async initializeIdentity(){if(!this.storage)return;let t=await this.storage.load(),e=R(this.options.sourceKey);this.identity={anonymousId:t.identity?.anonymousId??c(),sessionId:e?.sessionId??c()},this.bootstrapClientEventId=e?.bootstrapClientEventId??c(),O(this.options.sourceKey,{sessionId:this.identity.sessionId,bootstrapClientEventId:this.bootstrapClientEventId});let i=t.attributionContextExpiresAt?Date.parse(t.attributionContextExpiresAt):Number.NaN;t.attributionContextId&&Number.isFinite(i)&&i>Date.now()?(this.attributionContextId=t.attributionContextId,this.attributionContextExpiresAt=i):(t.attributionContextId||t.attributionContextExpiresAt)&&await this.storage.saveAttributionContext(),(!t.identity||t.identity.anonymousId!==this.identity.anonymousId||t.identity.sessionId!==this.identity.sessionId)&&await this.storage.saveIdentity(this.identity);}async ensureBootstrapped(){if(this.bootstrapped||!this.identity||!this.storage)return;let t=await this.transport.bootstrap({sourceKey:this.options.sourceKey,identity:this.identity,clientEventId:this.bootstrapClientEventId,...this.attributionToken?{attributionToken:this.attributionToken}:{}});if(this.bootstrapped=true,this.attributionToken=void 0,t.attributionContextId){this.attributionContextId=t.attributionContextId;let e=Date.parse(t.serverTime);this.attributionContextExpiresAt=(Number.isFinite(e)?e:Date.now())+Z,await this.storage.saveAttributionContext(t.attributionContextId,new Date(this.attributionContextExpiresAt).toISOString());}this.retryAttempt=0;}async enqueue(t){this.storage&&(await this.storage.enqueue(t),queueMicrotask(()=>{this.flush();}));}async flushExclusive(t){if(!this.storage)return {sent:0,pending:0};if(this.retryTimer&&!t)return {sent:0,pending:(await this.storage.load()).queue.length};try{await this.ensureBootstrapped();let e=await this.storage.load(),i=et(e.queue,this.activeAttributionContextId());if(i.length===0)return {sent:0,pending:e.queue.length};let r=await this.transport.send(this.options.sourceKey,i,t),s=new Set([...r.accepted,...r.duplicates]),o=!1;for(let f of r.rejected)f.retryable?o=!0:s.add(f.clientEventId);await this.storage.remove(s);let a=(await this.storage.load()).queue.length;return o?this.scheduleRetry():(this.retryAttempt=0,a>0&&queueMicrotask(()=>{this.flush();})),{sent:s.size,pending:a}}catch(e){return this.handleRetryableError(e),{sent:0,pending:(await this.storage.load()).queue.length}}}handleRetryableError(t){if(t instanceof h&&!t.retryable){v(this.options.debug,`Collector rejected the request (${t.code??t.status}).`);return}this.scheduleRetry();}scheduleRetry(){if(this.consent!=="granted"||this.destroyed||this.retryTimer)return;let t=Math.min(6e4,1e3*2**Math.min(this.retryAttempt,6)),e=Math.floor(Math.random()*Math.max(1,t*.25));this.retryAttempt+=1,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.flush();},t+e);}async trackAutomaticPage(){K()!==this.lastPagePath&&await this.page();}eventBase(t){if(!this.identity)throw new Error("Web SDK identity is unavailable.");let e=this.activeAttributionContextId();return {schemaVersion:2,clientEventId:c(),...this.identity,type:t,occurredAt:new Date().toISOString(),metadata:{platform:"web",sdkVersion:y,locale:g()},...e?{attributionContextId:e}:{}}}unavailableResult(){if(this.destroyed)return {accepted:false,reason:"destroyed"};if(this.consent==="pending")return {accepted:false,reason:"consent_pending"};if(this.consent==="denied")return {accepted:false,reason:"consent_denied"}}activeAttributionContextId(){if(this.attributionContextId&&this.attributionContextExpiresAt&&this.attributionContextExpiresAt>Date.now())return this.attributionContextId;(this.attributionContextId||this.attributionContextExpiresAt)&&(this.attributionContextId=void 0,this.attributionContextExpiresAt=void 0,this.storage?.saveAttributionContext());}installLifecycleListeners(){typeof window>"u"||typeof document>"u"||(window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibilityChange));}removeLifecycleListeners(){typeof window>"u"||typeof document>"u"||(window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibilityChange));}removeSpaTracking(){this.removeSpaTracker?.(),this.removeSpaTracker=void 0;}cancelRetry(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;}};function K(){return $(typeof location>"u"?"/":location.pathname)}function tt(){if(typeof location>"u"||typeof history>"u")return;let n=new URL(location.href),t=n.searchParams.get(S)??void 0;if(t)return n.searchParams.delete(S),history.replaceState(history.state,"",`${n.pathname}${n.search}${n.hash}`),t}function et(n,t){let e=[];for(let i of n.slice(0,50)){let r=t?{...i,attributionContextId:t}:i;if(m({schemaVersion:2,events:[...e,r]})>65536)break;e.push(r);}return e}function U(n){return new x(n)}var j={createWtsClient:U};typeof window<"u"&&Object.defineProperty(window,"WtsWeb",{value:j,writable:false,configurable:false});var Ct=j;
2
+ return Ct;})();//# sourceMappingURL=wts-web.iife.min.js.map
3
+ //# sourceMappingURL=wts-web.iife.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/constants.ts","../src/runtime.ts","../src/multitab-lock.ts","../src/spa-tracker.ts","../src/storage.ts","../src/transport.ts","../src/validation.ts","../src/client.ts","../src/index.ts","../src/iife.ts"],"names":["SDK_VERSION","ATTRIBUTION_QUERY_KEY","createUuid","cryptoApi","bytes","hex","value","byteLength","locale","referrerHost","safeWarn","enabled","message","loadBrowserSession","sourceKey","parsed","sessionKey","isUuid","saveBrowserSession","state","clearBrowserSession","LEASE_MS","MultiTabLock","name","operation","lease","current","key","token","now","parseLease","installSpaTracker","onNavigate","historyApi","originalPush","originalReplace","scheduled","notify","args","META_STORE","EVENT_STORE","createStorage","IndexedDbStorage","deleteStorage","request","databaseName","resolve","reject","MemoryStorage","clone","identity","expiresAt","event","trimQueue","clientEventIds","_IndexedDbStorage","database","requestResult","transaction","meta","events","attributionContextId","attributionContextExpiresAt","queue","transactionDone","left","right","store","retainedIds","item","queued","id","HttpTransport","collectorOrigin","timeoutMs","input","keepalive","path","body","controller","timeout","response","TransportError","_TransportError","status","retryable","code","payload","eventKeyPattern","sourceKeyPattern","currencyPattern","amountPattern","validateOptions","options","collector","isLocalhost","validateEvent","eventKey","properties","revenue","entries","normalizePathname","pathname","normalized","hostname","ATTRIBUTION_CONTEXT_TTL_MS","WtsClientImpl","transport","captureAttributionToken","consent","storage","wasGranted","unavailable","currentPathname","referrer","error","pending","browserSession","contextExpiry","result","serverTime","batch","takeBatch","remove","hasRetryableRejection","rejection","base","jitter","type","url","createWtsClient","api","iife_default"],"mappings":"0CAAO,IAAMA,CAAAA,CAAc,gBAOpB,IAAMC,CAAAA,CAAwB,OCP9B,SAASC,CAAAA,EAAqB,CACnC,IAAMC,CAAAA,CAAY,WAAW,MAAA,CAC7B,GAAI,CAACA,CAAAA,CAAW,MAAM,IAAI,KAAA,CAAM,+CAA+C,CAAA,CAC/E,GAAI,OAAOA,CAAAA,CAAU,YAAe,UAAA,CAAY,OAAOA,EAAU,UAAA,EAAW,CAC5E,IAAMC,CAAAA,CAAQD,CAAAA,CAAU,gBAAgB,IAAI,UAAA,CAAW,EAAE,CAAC,CAAA,CAC1DC,EAAM,CAAC,CAAA,CAAKA,EAAM,CAAC,CAAA,CAAK,EAAA,CAAQ,EAAA,CAChCA,CAAAA,CAAM,CAAC,EAAKA,CAAAA,CAAM,CAAC,EAAK,EAAA,CAAQ,GAAA,CAChC,IAAMC,CAAAA,CAAM,KAAA,CAAM,KAAKD,CAAAA,CAAQE,CAAAA,EAAUA,EAAM,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,CAAG,GAAG,CAAC,CAAA,CAC5E,OAAO,CAAA,EAAGD,CAAAA,CAAI,KAAA,CAAM,EAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAC,IAAIA,CAAAA,CAAI,KAAA,CAAM,EAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAC,IAAIA,CAAAA,CAA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ULT_COLLECTOR_ORIGIN = \"https://collect.wts.is\";\nexport const MAX_QUEUE_EVENTS = 100;\nexport const MAX_QUEUE_BYTES = 1024 * 1024;\nexport const MAX_BATCH_EVENTS = 50;\nexport const MAX_BATCH_BYTES = 64 * 1024;\nexport const DEFAULT_TIMEOUT_MS = 2_000;\nexport const ATTRIBUTION_QUERY_KEY = \"_wts\";\n","export function createUuid(): string {\n const cryptoApi = globalThis.crypto;\n if (!cryptoApi) throw new Error(\"A secure random number generator is required.\");\n if (typeof cryptoApi.randomUUID === \"function\") return cryptoApi.randomUUID();\n const bytes = cryptoApi.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n\nexport function byteLength(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value)).byteLength;\n}\n\nexport function locale(): string {\n return typeof navigator === \"undefined\" ? \"en\" : navigator.language || \"en\";\n}\n\nexport function referrerHost(): string | undefined {\n if (typeof document === \"undefined\" || !document.referrer) return undefined;\n try {\n return new URL(document.referrer).hostname.toLowerCase() || undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function safeWarn(enabled: boolean, message: string): void {\n if (enabled && typeof console !== \"undefined\") console.warn(`[wts.is] ${message}`);\n}\n\nexport type BrowserSessionState = {\n sessionId: string;\n bootstrapClientEventId: string;\n};\n\nexport function loadBrowserSession(sourceKey: string): BrowserSessionState | undefined {\n if (typeof sessionStorage === \"undefined\") return undefined;\n try {\n const parsed = JSON.parse(sessionStorage.getItem(sessionKey(sourceKey)) ?? \"null\") as {\n sessionId?: unknown;\n bootstrapClientEventId?: unknown;\n } | null;\n return parsed && isUuid(parsed.sessionId) && isUuid(parsed.bootstrapClientEventId)\n ? {\n sessionId: parsed.sessionId,\n bootstrapClientEventId: parsed.bootstrapClientEventId,\n }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function saveBrowserSession(sourceKey: string, state: BrowserSessionState): void {\n if (typeof sessionStorage === \"undefined\") return;\n try {\n sessionStorage.setItem(sessionKey(sourceKey), JSON.stringify(state));\n } catch {\n // Storage restrictions are handled by the SDK's memory-only fallback.\n }\n}\n\nexport function clearBrowserSession(sourceKey: string): void {\n if (typeof sessionStorage === \"undefined\") return;\n try {\n sessionStorage.removeItem(sessionKey(sourceKey));\n } catch {\n // A blocked browser storage API is equivalent to an already cleared session.\n }\n}\n\nfunction sessionKey(sourceKey: string): string {\n return `wts-session-${sourceKey}`;\n}\n\nfunction isUuid(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)\n );\n}\n","import { createUuid } from \"./runtime\";\n\nconst LEASE_MS = 10_000;\n\nexport class MultiTabLock {\n private current: Promise<unknown> | undefined;\n\n constructor(private readonly name: string) {}\n\n async run<T>(operation: () => Promise<T>): Promise<T | undefined> {\n if (typeof navigator !== \"undefined\" && navigator.locks) {\n return navigator.locks.request(this.name, operation);\n }\n if (this.current) await this.current;\n const lease = this.acquireLease();\n if (!lease) return undefined;\n const current = operation();\n this.current = current;\n try {\n return await current;\n } finally {\n if (this.current === current) this.current = undefined;\n lease.release();\n }\n }\n\n private acquireLease(): { release(): void } | undefined {\n if (typeof localStorage === \"undefined\") return { release() {} };\n const key = `wts-lock-${this.name}`;\n const token = createUuid();\n const now = Date.now();\n try {\n const current = parseLease(localStorage.getItem(key));\n if (current && current.expiresAt > now) return undefined;\n localStorage.setItem(key, JSON.stringify({ token, expiresAt: now + LEASE_MS }));\n const acquired = parseLease(localStorage.getItem(key));\n if (acquired?.token !== token) return undefined;\n return {\n release() {\n const latest = parseLease(localStorage.getItem(key));\n if (latest?.token === token) localStorage.removeItem(key);\n },\n };\n } catch {\n return { release() {} };\n }\n }\n}\n\nfunction parseLease(value: string | null): { token: string; expiresAt: number } | undefined {\n if (!value) return undefined;\n try {\n const parsed = JSON.parse(value) as { token?: unknown; expiresAt?: unknown };\n return typeof parsed.token === \"string\" && typeof parsed.expiresAt === \"number\"\n ? { token: parsed.token, expiresAt: parsed.expiresAt }\n : undefined;\n } catch {\n return undefined;\n }\n}\n","export function installSpaTracker(onNavigate: () => void): () => void {\n if (typeof window === \"undefined\") return () => undefined;\n const historyApi = window.history;\n const originalPush = historyApi.pushState;\n const originalReplace = historyApi.replaceState;\n let scheduled = false;\n const notify = () => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n onNavigate();\n });\n };\n historyApi.pushState = function (...args) {\n originalPush.apply(this, args);\n notify();\n };\n historyApi.replaceState = function (...args) {\n originalReplace.apply(this, args);\n notify();\n };\n window.addEventListener(\"popstate\", notify);\n return () => {\n historyApi.pushState = originalPush;\n historyApi.replaceState = originalReplace;\n window.removeEventListener(\"popstate\", notify);\n };\n}\n","import { MAX_QUEUE_BYTES, MAX_QUEUE_EVENTS } from \"./constants\";\nimport { byteLength } from \"./runtime\";\nimport type { Identity, StorageAdapter, StoredState, WebEvent } from \"./types\";\n\nconst META_STORE = \"meta\";\nconst EVENT_STORE = \"events\";\n\nexport async function createStorage(sourceKey: string): Promise<StorageAdapter> {\n if (typeof indexedDB === \"undefined\") throw new Error(\"IndexedDB is unavailable.\");\n return IndexedDbStorage.open(sourceKey);\n}\n\nexport async function deleteStorage(sourceKey: string): Promise<void> {\n if (typeof indexedDB === \"undefined\") return;\n const request = indexedDB.deleteDatabase(databaseName(sourceKey));\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => resolve();\n request.onerror = () => reject(request.error ?? new Error(\"IndexedDB deletion failed.\"));\n request.onblocked = () => reject(new Error(\"IndexedDB deletion was blocked by another tab.\"));\n });\n}\n\nexport class MemoryStorage implements StorageAdapter {\n private state: StoredState = { queue: [] };\n\n async load(): Promise<StoredState> {\n return clone(this.state);\n }\n\n async saveIdentity(identity: Identity): Promise<void> {\n this.state.identity = { ...identity };\n }\n\n async saveAttributionContext(value?: string, expiresAt?: string): Promise<void> {\n if (value && expiresAt) {\n this.state.attributionContextId = value;\n this.state.attributionContextExpiresAt = expiresAt;\n } else {\n delete this.state.attributionContextId;\n delete this.state.attributionContextExpiresAt;\n }\n }\n\n async enqueue(event: WebEvent): Promise<void> {\n this.state.queue.push(clone(event));\n trimQueue(this.state.queue);\n }\n\n async remove(clientEventIds: ReadonlySet<string>): Promise<void> {\n this.state.queue = this.state.queue.filter((event) => !clientEventIds.has(event.clientEventId));\n }\n\n async clear(): Promise<void> {\n this.state = { queue: [] };\n }\n\n close(): void {}\n}\n\nclass IndexedDbStorage implements StorageAdapter {\n private constructor(private readonly database: IDBDatabase) {}\n\n static async open(sourceKey: string): Promise<IndexedDbStorage> {\n const request = indexedDB.open(databaseName(sourceKey), 1);\n request.onupgradeneeded = () => {\n const database = request.result;\n if (!database.objectStoreNames.contains(META_STORE)) database.createObjectStore(META_STORE);\n if (!database.objectStoreNames.contains(EVENT_STORE)) {\n database.createObjectStore(EVENT_STORE, { keyPath: \"clientEventId\" });\n }\n };\n return new IndexedDbStorage(await requestResult(request));\n }\n\n async load(): Promise<StoredState> {\n const transaction = this.database.transaction([META_STORE, EVENT_STORE], \"readonly\");\n const meta = transaction.objectStore(META_STORE);\n const events = transaction.objectStore(EVENT_STORE);\n const [identity, attributionContextId, attributionContextExpiresAt, queue] = await Promise.all([\n requestResult(meta.get(\"identity\") as IDBRequest<Identity | undefined>),\n requestResult(meta.get(\"attributionContextId\") as IDBRequest<string | undefined>),\n requestResult(meta.get(\"attributionContextExpiresAt\") as IDBRequest<string | undefined>),\n requestResult(events.getAll() as IDBRequest<WebEvent[]>),\n ]);\n await transactionDone(transaction);\n queue.sort((left, right) => left.occurredAt.localeCompare(right.occurredAt));\n return {\n ...(identity ? { identity } : {}),\n ...(attributionContextId && attributionContextExpiresAt\n ? { attributionContextId, attributionContextExpiresAt }\n : {}),\n queue,\n };\n }\n\n async saveIdentity(identity: Identity): Promise<void> {\n await this.writeMeta(\"identity\", identity);\n }\n\n async saveAttributionContext(value?: string, expiresAt?: string): Promise<void> {\n const transaction = this.database.transaction(META_STORE, \"readwrite\");\n const store = transaction.objectStore(META_STORE);\n if (value && expiresAt) {\n store.put(value, \"attributionContextId\");\n store.put(expiresAt, \"attributionContextExpiresAt\");\n } else {\n store.delete(\"attributionContextId\");\n store.delete(\"attributionContextExpiresAt\");\n }\n await transactionDone(transaction);\n }\n\n async enqueue(event: WebEvent): Promise<void> {\n const state = await this.load();\n const queue = [...state.queue, event];\n trimQueue(queue);\n const retainedIds = new Set(queue.map((item) => item.clientEventId));\n const transaction = this.database.transaction(EVENT_STORE, \"readwrite\");\n const store = transaction.objectStore(EVENT_STORE);\n store.put(event);\n for (const queued of state.queue) {\n if (!retainedIds.has(queued.clientEventId)) store.delete(queued.clientEventId);\n }\n await transactionDone(transaction);\n }\n\n async remove(clientEventIds: ReadonlySet<string>): Promise<void> {\n if (clientEventIds.size === 0) return;\n const transaction = this.database.transaction(EVENT_STORE, \"readwrite\");\n const store = transaction.objectStore(EVENT_STORE);\n for (const id of clientEventIds) store.delete(id);\n await transactionDone(transaction);\n }\n\n async clear(): Promise<void> {\n const transaction = this.database.transaction([META_STORE, EVENT_STORE], \"readwrite\");\n transaction.objectStore(META_STORE).clear();\n transaction.objectStore(EVENT_STORE).clear();\n await transactionDone(transaction);\n }\n\n close(): void {\n this.database.close();\n }\n\n private async writeMeta(key: string, value: unknown): Promise<void> {\n const transaction = this.database.transaction(META_STORE, \"readwrite\");\n transaction.objectStore(META_STORE).put(value, key);\n await transactionDone(transaction);\n }\n}\n\nfunction trimQueue(queue: WebEvent[]): void {\n while (queue.length > MAX_QUEUE_EVENTS || byteLength(queue) > MAX_QUEUE_BYTES) queue.shift();\n}\n\nfunction requestResult<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error ?? new Error(\"IndexedDB request failed.\"));\n });\n}\n\nfunction transactionDone(transaction: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve();\n transaction.onerror = () =>\n reject(transaction.error ?? new Error(\"IndexedDB transaction failed.\"));\n transaction.onabort = () =>\n reject(transaction.error ?? new Error(\"IndexedDB transaction aborted.\"));\n });\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction databaseName(sourceKey: string): string {\n return `wts-web-${sourceKey}`;\n}\n","import { SDK_VERSION } from \"./constants\";\nimport { locale } from \"./runtime\";\nimport type { BatchResponse, Identity, Transport, WebEvent } from \"./types\";\n\nexport class HttpTransport implements Transport {\n constructor(\n private readonly collectorOrigin: string,\n private readonly timeoutMs: number,\n ) {}\n\n async bootstrap(input: {\n sourceKey: string;\n identity: Identity;\n clientEventId: string;\n attributionToken?: string;\n }): Promise<{ attributionContextId: string | null; serverTime: string }> {\n const response = await this.post(\n \"/v2/bootstrap\",\n input.sourceKey,\n {\n schemaVersion: 2,\n clientEventId: input.clientEventId,\n ...input.identity,\n occurredAt: new Date().toISOString(),\n metadata: { platform: \"web\", sdkVersion: SDK_VERSION, locale: locale() },\n ...(input.attributionToken ? { attributionToken: input.attributionToken } : {}),\n },\n false,\n );\n return (await response.json()) as { attributionContextId: string | null; serverTime: string };\n }\n\n async send(sourceKey: string, events: WebEvent[], keepalive: boolean): Promise<BatchResponse> {\n const response = await this.post(\n \"/v2/events/batch\",\n sourceKey,\n { schemaVersion: 2, events },\n keepalive,\n );\n return (await response.json()) as BatchResponse;\n }\n\n private async post(\n path: string,\n sourceKey: string,\n body: unknown,\n keepalive: boolean,\n ): Promise<Response> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n const response = await fetch(`${this.collectorOrigin}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-WTS-Source-Key\": sourceKey },\n body: JSON.stringify(body),\n credentials: \"omit\",\n mode: \"cors\",\n cache: \"no-store\",\n keepalive,\n signal: controller.signal,\n });\n if (!response.ok) throw await TransportError.fromResponse(response);\n return response;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class TransportError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly retryable: boolean,\n readonly code?: string,\n ) {\n super(message);\n this.name = \"WtsTransportError\";\n }\n\n static async fromResponse(response: Response): Promise<TransportError> {\n let payload: { code?: string; message?: string } = {};\n try {\n payload = (await response.json()) as typeof payload;\n } catch {\n // The SDK intentionally does not surface response bodies in logs.\n }\n return new TransportError(\n payload.message ?? `Collector request failed with status ${response.status}.`,\n response.status,\n response.status === 429 || response.status >= 500,\n payload.code,\n );\n }\n}\n","import type { EventProperties, Revenue, WtsClientOptions } from \"./types\";\n\nconst eventKeyPattern = /^[a-z][a-z0-9_]{1,63}$/;\nconst sourceKeyPattern = /^[A-Za-z0-9_-]{8,128}$/;\nconst currencyPattern = /^[A-Z]{3}$/;\nconst amountPattern = /^-?\\d{1,12}(?:\\.\\d{1,6})?$/;\n\nexport function validateOptions(\n options: WtsClientOptions,\n): Required<\n Pick<\n WtsClientOptions,\n \"sourceKey\" | \"autoTrackPageViews\" | \"collectorOrigin\" | \"requestTimeoutMs\" | \"debug\"\n >\n> & { consent: NonNullable<WtsClientOptions[\"consent\"]> } {\n if (!sourceKeyPattern.test(options.sourceKey)) {\n throw new TypeError(\"sourceKey must be a valid wts.is Web App source key.\");\n }\n const collector = new URL(options.collectorOrigin ?? \"https://collect.wts.is\");\n if (collector.protocol !== \"https:\" && !isLocalhost(collector.hostname)) {\n throw new TypeError(\"collectorOrigin must use HTTPS outside localhost.\");\n }\n if (collector.pathname !== \"/\" || collector.search || collector.hash) {\n throw new TypeError(\"collectorOrigin must not include a path, query, or fragment.\");\n }\n const timeout = options.requestTimeoutMs ?? 2_000;\n if (!Number.isInteger(timeout) || timeout < 250 || timeout > 30_000) {\n throw new TypeError(\"requestTimeoutMs must be an integer between 250 and 30000.\");\n }\n return {\n sourceKey: options.sourceKey,\n consent: options.consent ?? \"pending\",\n autoTrackPageViews: options.autoTrackPageViews ?? false,\n collectorOrigin: collector.origin,\n requestTimeoutMs: timeout,\n debug: options.debug ?? false,\n };\n}\n\nexport function validateEvent(\n eventKey: string,\n properties: EventProperties,\n revenue?: Revenue,\n): void {\n if (!eventKeyPattern.test(eventKey)) {\n throw new TypeError(\"eventKey must match ^[a-z][a-z0-9_]{1,63}$.\");\n }\n const entries = Object.entries(properties);\n if (entries.length > 20) throw new TypeError(\"Events can contain at most 20 properties.\");\n for (const [key, value] of entries) {\n if (!/^[a-z][a-z0-9_]{0,63}$/.test(key)) throw new TypeError(`Invalid property key: ${key}`);\n if (![\"string\", \"number\", \"boolean\"].includes(typeof value)) {\n throw new TypeError(`Property ${key} must be a string, number, or boolean.`);\n }\n if (typeof value === \"string\" && value.length > 512) {\n throw new TypeError(`Property ${key} cannot exceed 512 characters.`);\n }\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n throw new TypeError(`Property ${key} must be finite.`);\n }\n }\n if (revenue && (!amountPattern.test(revenue.amount) || !currencyPattern.test(revenue.currency))) {\n throw new TypeError(\"Revenue requires a decimal amount and uppercase ISO-4217 currency.\");\n }\n}\n\nexport function normalizePathname(pathname: string): string {\n const normalized = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n if (normalized.includes(\"?\") || normalized.includes(\"#\")) {\n throw new TypeError(\"Page pathname cannot include a query or fragment.\");\n }\n if (normalized.length > 2_048)\n throw new TypeError(\"Page pathname cannot exceed 2048 characters.\");\n return normalized;\n}\n\nfunction isLocalhost(hostname: string): boolean {\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\";\n}\n","import { ATTRIBUTION_QUERY_KEY, MAX_BATCH_BYTES, MAX_BATCH_EVENTS, SDK_VERSION } from \"./constants\";\nimport { MultiTabLock } from \"./multitab-lock\";\nimport {\n byteLength,\n clearBrowserSession,\n createUuid,\n loadBrowserSession,\n locale,\n referrerHost,\n safeWarn,\n saveBrowserSession,\n} from \"./runtime\";\nimport { installSpaTracker } from \"./spa-tracker\";\nimport { createStorage, deleteStorage, MemoryStorage } from \"./storage\";\nimport { HttpTransport, TransportError } from \"./transport\";\nimport type {\n ConsentState,\n EventProperties,\n FlushResult,\n Identity,\n OperationResult,\n Revenue,\n StorageAdapter,\n Transport,\n WebEvent,\n WtsClient,\n WtsClientOptions,\n} from \"./types\";\nimport { normalizePathname, validateEvent, validateOptions } from \"./validation\";\n\ntype ResolvedOptions = ReturnType<typeof validateOptions>;\nconst ATTRIBUTION_CONTEXT_TTL_MS = 7 * 24 * 60 * 60_000;\n\nexport class WtsClientImpl implements WtsClient {\n private consent: ConsentState;\n private storage: StorageAdapter | undefined;\n private identity: Identity | undefined;\n private attributionContextId: string | undefined;\n private attributionContextExpiresAt: number | undefined;\n private attributionToken: string | undefined;\n private bootstrapClientEventId = createUuid();\n private bootstrapped = false;\n private destroyed = false;\n private retryAttempt = 0;\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n private enablePromise: Promise<void> | undefined;\n private removeSpaTracker: (() => void) | undefined;\n private lastPagePath: string | undefined;\n private readonly options: ResolvedOptions;\n private readonly transport: Transport;\n private readonly lock: MultiTabLock;\n\n constructor(options: WtsClientOptions, transport?: Transport) {\n this.options = validateOptions(options);\n this.consent = this.options.consent;\n this.transport =\n transport ?? new HttpTransport(this.options.collectorOrigin, this.options.requestTimeoutMs);\n this.lock = new MultiTabLock(`flush-${this.options.sourceKey}`);\n this.attributionToken = captureAttributionToken();\n this.installLifecycleListeners();\n if (this.consent === \"granted\") void this.startEnable();\n if (this.consent === \"denied\") this.attributionToken = undefined;\n }\n\n async setConsent(consent: \"granted\" | \"denied\"): Promise<void> {\n if (this.destroyed) return;\n if (consent === \"denied\") {\n this.consent = \"denied\";\n this.cancelRetry();\n const storage = this.storage;\n if (storage) {\n await this.lock.run(async () => {\n await storage.clear();\n storage.close();\n });\n }\n try {\n await deleteStorage(this.options.sourceKey);\n } catch {\n safeWarn(this.options.debug, \"Stored SDK data could not be deleted because it is in use.\");\n }\n this.storage = undefined;\n this.identity = undefined;\n this.attributionContextId = undefined;\n this.attributionContextExpiresAt = undefined;\n this.attributionToken = undefined;\n this.bootstrapped = false;\n clearBrowserSession(this.options.sourceKey);\n this.removeSpaTracking();\n return;\n }\n const wasGranted = this.consent === \"granted\";\n this.consent = \"granted\";\n if (!wasGranted || !this.storage) await this.startEnable();\n }\n\n async page(name?: string): Promise<OperationResult> {\n let unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n await this.ensureReady();\n unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n const pathname = currentPathname();\n const referrer = referrerHost();\n const event: WebEvent = {\n ...this.eventBase(\"page_view\"),\n pathname,\n ...(name?.trim() ? { pageName: name.trim().slice(0, 120) } : {}),\n ...(referrer ? { referrerHost: referrer } : {}),\n properties: {},\n };\n await this.enqueue(event);\n this.lastPagePath = pathname;\n return { accepted: true, clientEventId: event.clientEventId };\n }\n\n async track(\n eventKey: string,\n properties: EventProperties = {},\n revenue?: Revenue,\n ): Promise<OperationResult> {\n let unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n await this.ensureReady();\n unavailable = this.unavailableResult();\n if (unavailable) return unavailable;\n validateEvent(eventKey, properties, revenue);\n const event: WebEvent = {\n ...this.eventBase(\"custom\"),\n eventKey,\n properties: { ...properties },\n ...(revenue ? { revenue: { ...revenue } } : {}),\n };\n await this.enqueue(event);\n return { accepted: true, clientEventId: event.clientEventId };\n }\n\n async flush(): Promise<FlushResult> {\n if (this.consent !== \"granted\" || this.destroyed || !this.storage) {\n return { sent: 0, pending: 0 };\n }\n const result = await this.lock.run(async () => this.flushExclusive(false));\n return result ?? { sent: 0, pending: (await this.storage.load()).queue.length };\n }\n\n async reset(): Promise<void> {\n this.cancelRetry();\n await this.storage?.clear();\n this.identity = undefined;\n this.attributionContextId = undefined;\n this.attributionContextExpiresAt = undefined;\n this.attributionToken = undefined;\n clearBrowserSession(this.options.sourceKey);\n this.bootstrapClientEventId = createUuid();\n this.bootstrapped = false;\n this.lastPagePath = undefined;\n if (this.consent === \"granted\" && !this.destroyed) await this.initializeIdentity();\n }\n\n destroy(): void {\n if (this.destroyed) return;\n this.destroyed = true;\n this.cancelRetry();\n this.removeSpaTracking();\n this.removeLifecycleListeners();\n const storage = this.storage;\n if (storage) void this.lock.run(async () => storage.close());\n }\n\n private async enable(): Promise<void> {\n if (this.destroyed || this.consent !== \"granted\") return;\n if (!this.storage) {\n try {\n this.storage = await createStorage(this.options.sourceKey);\n await this.storage.load();\n } catch {\n this.storage?.close();\n this.storage = new MemoryStorage();\n safeWarn(this.options.debug, \"IndexedDB unavailable; using a memory-only event queue.\");\n }\n }\n await this.initializeIdentity();\n try {\n await this.ensureBootstrapped();\n } catch (error) {\n this.handleRetryableError(error);\n }\n if (this.options.autoTrackPageViews && !this.removeSpaTracker) {\n this.removeSpaTracker = installSpaTracker(() => {\n void this.trackAutomaticPage();\n });\n await this.trackAutomaticPage();\n }\n void this.flush();\n }\n\n private startEnable(): Promise<void> {\n if (this.enablePromise) return this.enablePromise;\n const pending = this.enable();\n this.enablePromise = pending;\n void pending.finally(() => {\n if (this.enablePromise === pending) this.enablePromise = undefined;\n });\n return pending;\n }\n\n private async ensureReady(): Promise<void> {\n if (this.consent === \"granted\" && (!this.storage || !this.identity)) {\n await this.startEnable();\n }\n }\n\n private async initializeIdentity(): Promise<void> {\n if (!this.storage) return;\n const state = await this.storage.load();\n const browserSession = loadBrowserSession(this.options.sourceKey);\n this.identity = {\n anonymousId: state.identity?.anonymousId ?? createUuid(),\n sessionId: browserSession?.sessionId ?? createUuid(),\n };\n this.bootstrapClientEventId = browserSession?.bootstrapClientEventId ?? createUuid();\n saveBrowserSession(this.options.sourceKey, {\n sessionId: this.identity.sessionId,\n bootstrapClientEventId: this.bootstrapClientEventId,\n });\n const contextExpiry = state.attributionContextExpiresAt\n ? Date.parse(state.attributionContextExpiresAt)\n : Number.NaN;\n if (\n state.attributionContextId &&\n Number.isFinite(contextExpiry) &&\n contextExpiry > Date.now()\n ) {\n this.attributionContextId = state.attributionContextId;\n this.attributionContextExpiresAt = contextExpiry;\n } else if (state.attributionContextId || state.attributionContextExpiresAt) {\n await this.storage.saveAttributionContext();\n }\n if (\n !state.identity ||\n state.identity.anonymousId !== this.identity.anonymousId ||\n state.identity.sessionId !== this.identity.sessionId\n ) {\n await this.storage.saveIdentity(this.identity);\n }\n }\n\n private async ensureBootstrapped(): Promise<void> {\n if (this.bootstrapped || !this.identity || !this.storage) return;\n const result = await this.transport.bootstrap({\n sourceKey: this.options.sourceKey,\n identity: this.identity,\n clientEventId: this.bootstrapClientEventId,\n ...(this.attributionToken ? { attributionToken: this.attributionToken } : {}),\n });\n this.bootstrapped = true;\n this.attributionToken = undefined;\n if (result.attributionContextId) {\n this.attributionContextId = result.attributionContextId;\n const serverTime = Date.parse(result.serverTime);\n this.attributionContextExpiresAt =\n (Number.isFinite(serverTime) ? serverTime : Date.now()) + ATTRIBUTION_CONTEXT_TTL_MS;\n await this.storage.saveAttributionContext(\n result.attributionContextId,\n new Date(this.attributionContextExpiresAt).toISOString(),\n );\n }\n this.retryAttempt = 0;\n }\n\n private async enqueue(event: WebEvent): Promise<void> {\n if (!this.storage) return;\n await this.storage.enqueue(event);\n queueMicrotask(() => void this.flush());\n }\n\n private async flushExclusive(keepalive: boolean): Promise<FlushResult> {\n if (!this.storage) return { sent: 0, pending: 0 };\n if (this.retryTimer && !keepalive) {\n return { sent: 0, pending: (await this.storage.load()).queue.length };\n }\n try {\n await this.ensureBootstrapped();\n const state = await this.storage.load();\n const batch = takeBatch(state.queue, this.activeAttributionContextId());\n if (batch.length === 0) return { sent: 0, pending: state.queue.length };\n const response = await this.transport.send(this.options.sourceKey, batch, keepalive);\n const remove = new Set([...response.accepted, ...response.duplicates]);\n let hasRetryableRejection = false;\n for (const rejection of response.rejected) {\n if (rejection.retryable) hasRetryableRejection = true;\n else remove.add(rejection.clientEventId);\n }\n await this.storage.remove(remove);\n const pending = (await this.storage.load()).queue.length;\n if (hasRetryableRejection) this.scheduleRetry();\n else {\n this.retryAttempt = 0;\n if (pending > 0) queueMicrotask(() => void this.flush());\n }\n return { sent: remove.size, pending };\n } catch (error) {\n this.handleRetryableError(error);\n return { sent: 0, pending: (await this.storage.load()).queue.length };\n }\n }\n\n private handleRetryableError(error: unknown): void {\n if (error instanceof TransportError && !error.retryable) {\n safeWarn(\n this.options.debug,\n `Collector rejected the request (${error.code ?? error.status}).`,\n );\n return;\n }\n this.scheduleRetry();\n }\n\n private scheduleRetry(): void {\n if (this.consent !== \"granted\" || this.destroyed || this.retryTimer) return;\n const base = Math.min(60_000, 1_000 * 2 ** Math.min(this.retryAttempt, 6));\n const jitter = Math.floor(Math.random() * Math.max(1, base * 0.25));\n this.retryAttempt += 1;\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n void this.flush();\n }, base + jitter);\n }\n\n private async trackAutomaticPage(): Promise<void> {\n const pathname = currentPathname();\n if (pathname === this.lastPagePath) return;\n await this.page();\n }\n\n private eventBase(type: WebEvent[\"type\"]): Omit<WebEvent, \"properties\"> {\n if (!this.identity) throw new Error(\"Web SDK identity is unavailable.\");\n const attributionContextId = this.activeAttributionContextId();\n return {\n schemaVersion: 2,\n clientEventId: createUuid(),\n ...this.identity,\n type,\n occurredAt: new Date().toISOString(),\n metadata: { platform: \"web\", sdkVersion: SDK_VERSION, locale: locale() },\n ...(attributionContextId ? { attributionContextId } : {}),\n };\n }\n\n private unavailableResult(): OperationResult | undefined {\n if (this.destroyed) return { accepted: false, reason: \"destroyed\" };\n if (this.consent === \"pending\") return { accepted: false, reason: \"consent_pending\" };\n if (this.consent === \"denied\") return { accepted: false, reason: \"consent_denied\" };\n return undefined;\n }\n\n private activeAttributionContextId(): string | undefined {\n if (\n this.attributionContextId &&\n this.attributionContextExpiresAt &&\n this.attributionContextExpiresAt > Date.now()\n ) {\n return this.attributionContextId;\n }\n if (this.attributionContextId || this.attributionContextExpiresAt) {\n this.attributionContextId = undefined;\n this.attributionContextExpiresAt = undefined;\n void this.storage?.saveAttributionContext();\n }\n return undefined;\n }\n\n private installLifecycleListeners(): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n window.addEventListener(\"pagehide\", this.onPageHide);\n document.addEventListener(\"visibilitychange\", this.onVisibilityChange);\n }\n\n private removeLifecycleListeners(): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n window.removeEventListener(\"pagehide\", this.onPageHide);\n document.removeEventListener(\"visibilitychange\", this.onVisibilityChange);\n }\n\n private readonly onPageHide = () => {\n if (this.consent === \"granted\") void this.lock.run(() => this.flushExclusive(true));\n };\n\n private readonly onVisibilityChange = () => {\n if (document.visibilityState === \"hidden\" && this.consent === \"granted\") {\n void this.lock.run(() => this.flushExclusive(true));\n }\n };\n\n private removeSpaTracking(): void {\n this.removeSpaTracker?.();\n this.removeSpaTracker = undefined;\n }\n\n private cancelRetry(): void {\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = undefined;\n }\n}\n\nfunction currentPathname(): string {\n return normalizePathname(typeof location === \"undefined\" ? \"/\" : location.pathname);\n}\n\nfunction captureAttributionToken(): string | undefined {\n if (typeof location === \"undefined\" || typeof history === \"undefined\") return undefined;\n const url = new URL(location.href);\n const token = url.searchParams.get(ATTRIBUTION_QUERY_KEY) ?? undefined;\n if (!token) return undefined;\n url.searchParams.delete(ATTRIBUTION_QUERY_KEY);\n history.replaceState(history.state, \"\", `${url.pathname}${url.search}${url.hash}`);\n return token;\n}\n\nfunction takeBatch(queue: WebEvent[], attributionContextId?: string): WebEvent[] {\n const batch: WebEvent[] = [];\n for (const queued of queue.slice(0, MAX_BATCH_EVENTS)) {\n const event = attributionContextId ? { ...queued, attributionContextId } : queued;\n if (byteLength({ schemaVersion: 2, events: [...batch, event] }) > MAX_BATCH_BYTES) break;\n batch.push(event);\n }\n return batch;\n}\n","import { WtsClientImpl } from \"./client\";\nimport type { WtsClient, WtsClientOptions } from \"./types\";\n\nexport type {\n ConsentState,\n EventProperties,\n FlushResult,\n OperationResult,\n Revenue,\n Scalar,\n WtsClient,\n WtsClientOptions,\n} from \"./types\";\n\nexport function createWtsClient(options: WtsClientOptions): WtsClient {\n return new WtsClientImpl(options);\n}\n","import { createWtsClient } from \"./index\";\n\nconst api = { createWtsClient };\n\nif (typeof window !== \"undefined\") {\n Object.defineProperty(window, \"WtsWeb\", { value: api, writable: false, configurable: false });\n}\n\nexport default api;\n\ndeclare global {\n interface Window {\n WtsWeb: typeof api;\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ sha384-yd6nOlkavObZDFnbLq8jTn6bMrD8gIU+Er4oOqzNTa2Mo2VnD6wPG8VFZqVMIKyC
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@wetusco/wts-web-sdk",
3
+ "version": "0.1.0-alpha.2",
4
+ "description": "Consent-first web analytics and deterministic link attribution for wts.is.",
5
+ "license": "Apache-2.0",
6
+ "author": "Wetus <info@wetus.co>",
7
+ "homepage": "https://wts.is/en/resources/docs/sdk-web",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/wetuscorp/wtsissdk-web.git"
11
+ },
12
+ "bugs": "https://github.com/wetuscorp/wtsissdk-web/issues",
13
+ "type": "module",
14
+ "main": "./dist/index.cjs",
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md",
27
+ "LICENSE",
28
+ "CHANGELOG.md",
29
+ "SECURITY.md",
30
+ "SUPPORT.md"
31
+ ],
32
+ "sideEffects": false,
33
+ "scripts": {
34
+ "build": "tsup",
35
+ "clean": "rimraf dist coverage",
36
+ "format": "prettier --write .",
37
+ "format:check": "prettier --check .",
38
+ "lint": "eslint . --max-warnings=0",
39
+ "typecheck": "tsc --noEmit",
40
+ "test": "vitest run --coverage",
41
+ "test:browser": "playwright test",
42
+ "verify:contracts": "node scripts/verify-contracts.mjs",
43
+ "verify:package": "node scripts/verify-package.mjs",
44
+ "verify": "npm run format:check && npm run lint && npm run typecheck && npm run test && npm run build && npm run verify:contracts && npm run verify:package",
45
+ "prepack": "npm run verify"
46
+ },
47
+ "devDependencies": {
48
+ "@eslint/js": "^9.39.1",
49
+ "@playwright/test": "^1.57.0",
50
+ "@types/node": "^24.10.1",
51
+ "@vitest/coverage-v8": "^4.0.15",
52
+ "eslint": "^9.39.1",
53
+ "fake-indexeddb": "^6.2.5",
54
+ "happy-dom": "^20.0.11",
55
+ "prettier": "^3.7.4",
56
+ "rimraf": "^6.1.2",
57
+ "tsup": "^8.5.1",
58
+ "typescript": "^5.9.3",
59
+ "typescript-eslint": "^8.48.1",
60
+ "vitest": "^4.0.15"
61
+ },
62
+ "engines": {
63
+ "node": ">=20"
64
+ },
65
+ "publishConfig": {
66
+ "access": "public",
67
+ "provenance": true,
68
+ "tag": "next"
69
+ }
70
+ }