@watchtowerobservability/chrome-extension 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # @watchtowerobservability/chrome-extension
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Errors, a shared session and a durable queue for Manifest V3 extensions on Chrome, Edge and other Chromium browsers.
4
+ It works in the background service worker, popup, options, side panel, offscreen and devtools pages, and content scripts.
5
+ It reuses the [browser SDK](../browser) (transport, ids, stack parser) and has no runtime dependencies of its own.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @watchtowerobservability/chrome-extension
11
+ ```
12
+
13
+ ## Setup
14
+
15
+ ```ts
16
+ // sw.ts: top level, synchronous (MV3 only wakes the worker for listeners registered on the first turn)
17
+ import { init } from "@watchtowerobservability/chrome-extension";
18
+ export const wt = init({ publishableKey: "wtp_...", endpoint: "https://ingest.example.com", service: "my-extension" });
19
+ ```
20
+
21
+ Call `init` the same way in the popup, options page, side panel, offscreen document and content script.
22
+ Pages report themselves; content scripts forward to the service worker.
23
+
24
+ ```json
25
+ {
26
+ "permissions": ["storage", "alarms"],
27
+ "host_permissions": ["https://ingest.example.com/*"],
28
+ "background": { "service_worker": "sw.js", "type": "module" }
29
+ }
30
+ ```
31
+
32
+ - `storage`: the durable queue (`chrome.storage.local`) and shared session (`chrome.storage.session`).
33
+ - `alarms`: the periodic flush (every 30 s, the minimum Chrome allows).
34
+ - Host permission for the ingest origin, so extension pages and the worker can POST without CORS. Content scripts never POST.
35
+ - CSP: the default extension CSP (`script-src 'self'`) is fine; add the ingest origin to `connect-src` only if you override `content_security_policy`.
36
+
37
+ Full example: [examples/basic](examples/basic).
38
+
39
+ ## How it behaves
40
+
41
+ | Topic | Behaviour |
42
+ |---|---|
43
+ | Event tags | `extension.context` (`service_worker`, `popup`, `options`, `side_panel`, `offscreen`, `content_script`, `devtools`), `extension.id`, `extension.manifest_version`; `release` defaults to the manifest `version` |
44
+ | Session | One id in `chrome.storage.session` shared by every context (memory fallback). 30 min idle and 4 h max rollover, same as the browser SDK |
45
+ | Queue | Every event is written to `chrome.storage.local` first (default 1000 events / 1 MiB; oldest dropped, counted in `wt.sdk.dropped`). Flushed on init, `onStartup`, `onInstalled`, a 30 s alarm, and 5 s after an event |
46
+ | Delivery | At-least-once. Events are deleted only after the server accepted them, so a killed worker re-sends; every event has a stable `id` for server-side dedupe |
47
+ | Content scripts | Send `chrome.runtime.sendMessage` to the service worker (sender id is checked). If the worker is unreachable the event is buffered in `chrome.storage.local` |
48
+ | Errors | `error` and `unhandledrejection`. In content scripts only errors whose innermost stack frame is in `chrome-extension://<your id>/` are reported; host page errors are ignored and the host DOM is never read |
49
+ | Privacy | No PII, no host-page URL (opt in to the origin only with `hostOrigin: true`), `beforeSend` can edit or drop any event. Page URL in the envelope is `app:///<your page path>` |
50
+
51
+ Options beyond the browser SDK's `publishableKey`, `endpoint`, `service`, `environment`, `release`, `sampleRate`, `errorSampleRate`, `beforeSend`, `user`, `ignoreUrls`, `debug`:
52
+
53
+ | Option | Default | |
54
+ |---|---|---|
55
+ | `context` | detected | Force the surface. Offscreen pages are not in the manifest, so they are detected by a file name containing `offscreen`; set this otherwise |
56
+ | `wrapListeners` | `false` | Wrap `chrome.*.on*.addListener` callbacks (sync throws and rejected promises) and tag errors with `extension.listener`. Call `init` before adding listeners |
57
+ | `instrumentFetch` | `false` | `resource` events (method, status, duration, URL without query) for `fetch` in the worker and pages |
58
+ | `hostOrigin` | `false` | Content scripts: add the host page origin as `extension.host_origin` |
59
+ | `queue` | `{ maxEvents: 1000, maxBytes: 1048576 }` | Durable queue bounds |
60
+
61
+ Client: `captureError(err, ctx?)`, `checkLastError(where?)` (reports `chrome.runtime.lastError` when set; call it at the top of a callback), `setUser`, `setAttribute`, `flush()`, `sessionId()`, `stop()`, `shutdown()`.
62
+
63
+ ## Source maps
64
+
65
+ Extension URLs contain a per-install id (`chrome-extension://<id>/js/sw.js`). The SDK rewrites every frame to `app:///js/sw.js` and
66
+ sends the debug id the build plugins inject, so maps uploaded once per release resolve for every install.
67
+ Use the browser SDK's plugin in your extension build and set `release` to the manifest version or a git sha:
68
+
69
+ ```ts
70
+ // vite.config.ts
71
+ import { watchtower } from "@watchtowerobservability/browser/vite-plugin";
72
+ export default { build: { sourcemap: true }, plugins: [watchtower({ api: "https://api.example.com", project: "my-project", release: "1.4.0" })] };
73
+ ```
74
+
75
+ Do not ship the `.map` files in the extension package (the plugin deletes them after upload by default).
76
+ Webpack and Rollup plugins are exported the same way (`/webpack-plugin`, `/rollup-plugin`).
77
+
78
+ ## Limits
79
+
80
+ - Chrome kills an idle worker after about 30 s; anything not yet in `chrome.storage.local` at that moment is lost. Events are stored before they are sent.
81
+ - Offline retries happen on the next alarm or wake, not with in-process backoff.
82
+ - Content scripts need the worker to run `init` for their events to be sent. User hash and sampling are applied by the context that flushes.
83
+
84
+ ## License
85
+
86
+ Apache-2.0
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ var A={rum_enabled:!0,replay:{enabled:!1}},f={flushEvents:50,flushMs:5e3,queueMax:500,gzipMinBytes:1024,backoffMaxMs:6e4,idleMs:30*6e4,maxSessionMs:4*36e5,configTimeoutMs:2e3};function I(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let r=0;r<16;r++)e[r]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function j(){let t=globalThis.crypto;return t?.getRandomValues?t.getRandomValues(new Uint32Array(1))[0]/2**32:Math.random()}async function ne(t,e){let n=globalThis.crypto?.subtle;if(!n)return;let r=await n.digest("SHA-256",new TextEncoder().encode(`${e}:${t}`));return[...new Uint8Array(r)].map(o=>o.toString(16).padStart(2,"0")).join("")}async function re(t,e,n=globalThis.fetch?.bind(globalThis)){let r=new AbortController,o=setTimeout(()=>r.abort(),f.configTimeoutMs);try{let l=await n(`${t.replace(/\/$/,"")}/v1/rum/config`,{headers:{Authorization:`Bearer ${e}`},signal:r.signal});if(!l.ok)return A;let u=await l.json();return{...A,...u,replay:{enabled:u.replay?.enabled===!0,...ve(u.replay)}}}catch{return A}finally{clearTimeout(o)}}var ge=new Set(["strict","balanced","relaxed"]),ve=t=>{let e=t?.mask_level;return typeof e=="string"&&ge.has(e)?{mask_level:e}:{}};function oe(){let t=globalThis;return{chrome:t.chrome,location:t.location,hasDocument:typeof t.document<"u",target:t,userAgent:t.navigator?.userAgent}}var we=new Set(["chrome-extension:","moz-extension:"]),W=t=>(t??"").replace(/^\/+/,"").split(/[?#]/)[0];function se(t,e={}){if(!t.hasDocument)return"service_worker";if(!t.location||!we.has(t.location.protocol))return"content_script";if(t.chrome?.devtools)return"devtools";let n=W(t.location.pathname),r=o=>!!o&&W(o)===n;return r(e.devtools_page)?"devtools":r(e.action?.default_popup)||r(e.browser_action?.default_popup)?"popup":r(e.options_page)||r(e.options_ui?.page)?"options":r(e.side_panel?.default_path)?"side_panel":/offscreen/i.test(n)?"offscreen":"popup"}var be=/^(?:chrome|moz)-extension:\/\/[^/]+\/(.*)$/;function H(t){let e=be.exec(t);return e?`app:///${W(e[1])}`:t}function ie(t,e){return!!t&&!!e&&(t.startsWith(`chrome-extension://${e}/`)||t.startsWith(`moz-extension://${e}/`))}var ye=/^\s*at (?:async )?(?:(.*?) \()?(.+?):(\d+):(\d+)\)?\s*$/,Ee=/^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;function K(t){let e=[];for(let n of t.split(`
2
+ `)){let r=ye.exec(n)??Ee.exec(n);r&&e.push({function:r[1]||"?",filename:r[2],lineno:+r[3],colno:+r[4]})}return e.slice(0,50).reverse()}var ae=5e3;function xe(t){let e=t?K(t):[],n=globalThis._wtDebugIds??{},r={},o=e.map(l=>{let u=H(l.filename),a=n[u.replace(/^app:\/\/\//,"")];return a&&(r[u]=a),{...l,filename:u}});return{frames:JSON.stringify(o),debug_ids:JSON.stringify(r)}}function ce(t){let e=new Map,n=(a,c,i,k,y,p)=>{let h={type:a,message:c.slice(0,1024),handled:k,mechanism:y,...xe(i),...p};t.release&&(h.release=t.release);let x=`${a}|${c}|${h.frames}`,w=Date.now();if(!(w-(e.get(x)??-1/0)<ae)){if(e.set(x,w),e.size>100)for(let[g,L]of e)w-L>=ae&&e.delete(g);t.emit("error",a,h)}},r=(a,c)=>{if(!t.ownOnly)return!0;let i=a?K(a).pop():void 0;return ie(i?.filename??c,t.extId)},o=a=>{let c=a,i=c.error;r(i?.stack,c.filename)&&n(i?.name??"Error",c.message??"",i?.stack,!1,"onerror")},l=a=>{let c=a.reason,i=typeof c=="object"&&c!==null?c:void 0;r(i?.stack)&&n(i?.name??"UnhandledRejection",i?i.message??"":String(c),i?.stack,!1,"unhandledrejection")};t.env.target?.addEventListener("error",o),t.env.target?.addEventListener("unhandledrejection",l);let u=t.wrapListeners&&t.env.chrome?ke(t.env.chrome,n):()=>{};return{report:n,uninstall:()=>{t.env.target?.removeEventListener("error",o),t.env.target?.removeEventListener("unhandledrejection",l),u()}}}function ke(t,e){let n=[];for(let[r,o]of Object.entries(t))if(!(!o||typeof o!="object"))for(let[l,u]of Object.entries(o)){let a=u;if(!a||typeof a.addListener!="function")continue;let c=a.addListener.bind(a),i=a.removeListener?.bind(a),k=new WeakMap,y=p=>{let h=p;e(h?.name??"Error",h?.message??String(p),h?.stack,!1,"chrome.listener",{"extension.listener":`${r}.${l}`})};a.addListener=(p,...h)=>{let x=(...w)=>{try{let g=p(...w);return g&&typeof g.then=="function"&&g.then(void 0,y),g}catch(g){throw y(g),g}};return k.set(p,x),c(x,...h)},i&&(a.removeListener=p=>i(k.get(p)??p)),n.push(()=>{a.addListener=c,i&&(a.removeListener=i)})}return()=>n.forEach(r=>r())}function ue(t,e,n){let r=t?.runtime?.lastError?.message;return r?(e("RuntimeLastError",r,new Error(r).stack,!0,"chrome.lastError",n?{"extension.api":n}:void 0),!0):!1}var U=class{constructor(e){this.max=e;this.items=[];this.dropped=0}push(e){this.items.push(e),this.trim()}requeue(e){this.items=e.concat(this.items),this.trim()}take(e){return this.items.splice(0,e)}get length(){return this.items.length}trim(){let e=this.items.length-this.max;e>0&&(this.items.splice(0,e),this.dropped+=e)}};async function Re(t){let e=new TextEncoder().encode(t);if(e.length>f.gzipMinBytes&&typeof CompressionStream=="function")try{let n=new Blob([e]).stream().pipeThrough(new CompressionStream("gzip"));return{data:await new Response(n).arrayBuffer(),gzip:!0}}catch{}return{data:t,gzip:!1}}var $=class{constructor(e){this.o=e;this.queue=new U(f.queueMax);this.started=!1;this.busy=!1;this.failures=0;this.rejected={};this.retryAt=0;this.url=`${e.endpoint.replace(/\/$/,"")}/v1/rum/events`,this.now=e.now??Date.now}start(){this.started=!0,this.restore(),this.queue.length&&this.schedule()}push(e){this.queue.push(e),this.started&&(this.queue.length>=f.flushEvents?this.flush():this.schedule())}schedule(){if(this.timer)return;let e=Math.max(f.flushMs,this.retryAt-this.now());this.timer=setTimeout(()=>{this.timer=void 0,this.flush()},e)}async restore(){try{let e=await this.o.offline?.drain()??[];if(!e.length)return;this.queue.requeue(e),this.schedule()}catch{}}body(e){let n=this.o.envelope();this.queue.dropped&&(n.attrs["wt.sdk.dropped"]=this.queue.dropped);let r=Object.entries(this.rejected);return r.length&&(n.attrs["wt.sdk.rejected"]=r.map(([o,l])=>`${o}:${l}`).join(",")),JSON.stringify({...n,events:e})}async flush(e=!1){if(!this.started||this.busy||!this.queue.length)return;if(!e&&this.now()<this.retryAt)return this.schedule();this.busy=!0;let n=this.queue.take(f.flushEvents);try{await this.o.beforeFlush?.();let{data:r,gzip:o}=await Re(this.body(n)),u=await(this.o.fetch??globalThis.fetch.bind(globalThis))(this.url,{method:"POST",body:r,keepalive:!0,headers:{Authorization:`Bearer ${this.o.key}`,"Content-Type":"application/json",...o?{"Content-Encoding":"gzip"}:{}}});this.handle(u.status,u.headers?.get("Retry-After")??null,n)}catch{await this.park(n)}finally{this.busy=!1}this.queue.length&&this.schedule()}handle(e,n,r){e<300?(this.failures=0,this.restore()):e===429||e>=500?this.backoff(r,n):(this.rejected[e]=(this.rejected[e]??0)+r.length,this.o.onReject?.(e,r.length))}async park(e){if(this.o.offline)try{await this.o.offline.save(e),this.backoff([],null);return}catch{}this.backoff(e,null)}backoff(e,n){this.queue.requeue(e);let r=n===null?NaN:Number(n),o=.5+(this.o.random??Math.random)()/2,l=Math.min(f.backoffMaxMs,1e3*2**this.failures)*o;this.failures++,this.retryAt=this.now()+(Number.isFinite(r)?Math.min(r*1e3,f.backoffMaxMs):l)}flushBeacon(){if(this.started)for(;this.queue.length;){let e=this.queue.take(f.flushEvents),n=this.body(e),r=`${this.url}?k=${encodeURIComponent(this.o.key)}`,o=this.o.beacon??(typeof navigator<"u"?navigator.sendBeacon?.bind(navigator):void 0),l=!1;try{l=o?o(r,new Blob([n],{type:"text/plain"})):!1}catch{}if(!l)try{(this.o.fetch??globalThis.fetch.bind(globalThis))(this.url,{method:"POST",body:n,keepalive:!0,headers:{Authorization:`Bearer ${this.o.key}`,"Content-Type":"application/json"}}).catch(()=>{})}catch{}}}async shutdown(){for(this.timer&&clearTimeout(this.timer),this.timer=void 0;this.queue.length;){let e=this.queue.length;if(await this.flush(!0),this.queue.length>=e)break}}};function le(t){let e,n=async()=>{let r=await t.queue.peek();if(!r.length)return;await t.prepare();let o=await t.queue.dropped(),l=!0,u=new $({endpoint:t.endpoint,key:t.key,fetch:t.fetch,envelope:()=>{let i=t.envelope();return o&&l&&(i.attrs["wt.sdk.dropped"]=o),l=!1,i}});u.start();for(let i of r)u.queue.push(i.event);await u.shutdown();let a=new Set(u.queue.take(r.length).map(i=>i.id)),c=r.filter(i=>!a.has(i.event.id));await t.queue.remove(c.map(i=>i.key)),o&&c.length&&await t.queue.clearDropped()};return()=>(e??(e=n().catch(()=>{}).finally(()=>e=void 0)),e)}var J="wt.q.",T="wt.dropped",Se=0,Q={maxEvents:1e3,maxBytes:1024*1024,trimEvery:10};function q(){let t=new Map;return{async get(e){let n=e==null?[...t.keys()]:[].concat(e);return Object.fromEntries(n.filter(r=>t.has(r)).map(r=>[r,t.get(r)]))},async set(e){for(let[n,r]of Object.entries(e))t.set(n,r)},async remove(e){for(let n of[].concat(e))t.delete(n)}}}var F=class{constructor(e,n=Q){this.area=e;this.lim=n;this.adds=0}async add(e){await this.area.set({[`${J}${String(Date.now()).padStart(15,"0")}.${String(Se++%1e6).padStart(6,"0")}.${e.id}`]:JSON.stringify(e)}),++this.adds%this.lim.trimEvery===0&&await this.trim()}async peek(){let e=await this.area.get(null),n=[];for(let r of Object.keys(e).filter(o=>o.startsWith(J)).sort())try{n.push({key:r,event:JSON.parse(String(e[r]))})}catch{await this.area.remove(r)}return n}remove(e){return e.length?this.area.remove(e):Promise.resolve()}async trim(){let e=await this.area.get(null),n=Object.keys(e).filter(u=>u.startsWith(J)).sort(),r=u=>String(e[u]).length+u.length,o=Math.max(0,n.length-this.lim.maxEvents),l=n.slice(o).reduce((u,a)=>u+r(a),0);for(;l>this.lim.maxBytes&&o<n.length-1;)l-=r(n[o++]);o&&(await this.area.remove(n.slice(0,o)),await this.area.set({[T]:Number((await this.area.get(T))[T]??0)+o}))}async dropped(){return Number((await this.area.get(T))[T]??0)}clearDropped(){return this.area.remove(T)}};var X="wt.session",V=class{constructor(e,n=Date.now){this.now=n;this.area=e??q()}async touch(){let e=this.now(),n;try{n=(await this.area.get(X))[X]}catch{}!n||e-n.last>f.idleMs||e-n.start>f.maxSessionMs?n={id:I(),start:e,last:e,draw:j()}:n={...n,last:e};try{await this.area.set({[X]:n})}catch{}return n}};var _e={name:"@watchtower/chrome-extension",version:"0.1.0"},de="wt-flush",Ae=.5,Te=5e3,Le=16*1024,E=()=>{},Pe={captureError:E,checkLastError:()=>!1,setUser:E,setAttribute:E,flush:()=>Promise.resolve(),sessionId:()=>Promise.resolve(""),stop:E,shutdown:()=>Promise.resolve()};function ut(t){try{return Ce(t)}catch(e){return t?.debug&&console.warn("[watchtower] init failed",e),Pe}}var Me=(t,e=[])=>e.some(n=>typeof n=="string"?t.startsWith(n):n.test(t));function Ce(t){let e=t.env??oe(),n=e.chrome,r=n?.runtime?.getManifest?.()??{},o=n?.runtime?.id,l=t.context??se(e,r),u=t.release??r.version,a=l==="service_worker",c=l==="content_script",i=(e.location?.pathname??"").replace(/^\/+/,""),k=t.fetch??globalThis.fetch?.bind(globalThis),y={"extension.context":l};o&&(y["extension.id"]=o),r.manifest_version&&(y["extension.manifest_version"]=r.manifest_version),c?t.hostOrigin&&e.location?.origin&&(y["extension.host_origin"]=e.location.origin):y["extension.page"]=i;let p=new F(n?.storage?.local??q(),{...Q,...t.queue}),h=new V(n?.storage?.session),x={},w=A,g,L=Promise.resolve(),B=!1,P,C=[],me=()=>({session_id:G,sent_at_ns:Date.now()*1e6,sdk:{..._e},app:{service:t.service,release:u,env:t.environment},page:{url:`app:///${i}`},device:{ua:e.userAgent??""},user:{id_hash:g},attrs:{"extension.id":o??"",...r.manifest_version?{"extension.manifest_version":r.manifest_version}:{}}}),G="",pe=le({queue:p,endpoint:t.endpoint,key:t.publishableKey,envelope:me,fetch:k,prepare:async()=>{G=(await h.touch()).id,await L}}),O=c?Promise.resolve():re(t.endpoint,t.publishableKey,k).then(s=>void(w=s)),_=()=>c?Promise.resolve():O.then(pe),fe=()=>{P||c||(P=setTimeout(()=>{P=void 0,_()},Te))},Y=async s=>{if(await O,B||!w.rum_enabled)return;let d=w.sample_rate??t.sampleRate??1,m=w.error_sample_rate??t.errorSampleRate??1;!((await h.touch()).draw<d)&&!(s.type==="error"&&j()<m)||(await p.add(s),fe())},he=async s=>{try{if((await n.runtime.sendMessage({__wt:1,event:s}))?.ok)return}catch{}await p.add(s).catch(E)},z=(s,d,m={},v)=>{if(B)return;let b={id:I(),ts_ns:Date.now()*1e6,type:s,name:d,attrs:{...x,...y,...m}};v!==void 0&&(b.value=v),t.beforeSend&&(b=t.beforeSend(b)),b&&(c?he(b):Y(b)).catch(E)};if(a&&n){let s=(v,b,D)=>{let R=v;if(R?.__wt!==1)return!1;let S=R.event,te=b.id===o&&!!S&&typeof S.id=="string"&&typeof S.type=="string"&&typeof S.name=="string"&&typeof S.attrs=="object"&&JSON.stringify(S).length<=Le;return te&&Y(S).catch(E),D({ok:te}),!1},d=()=>void _(),m=v=>void(v.name===de&&_());n.runtime?.onMessage?.addListener(s),n.runtime?.onStartup?.addListener(d),n.runtime?.onInstalled?.addListener(d),n.alarms?.onAlarm?.addListener(m),n.alarms?.create(de,{periodInMinutes:Ae}),C.push(()=>{n.runtime?.onMessage?.removeListener?.(s),n.runtime?.onStartup?.removeListener?.(d),n.runtime?.onInstalled?.removeListener?.(d),n.alarms?.onAlarm?.removeListener?.(m)})}let N=ce({env:e,extId:o,release:u,emit:(s,d,m)=>z(s,d,m),ownOnly:c,wrapListeners:t.wrapListeners===!0});if(C.push(N.uninstall),c||_(),t.instrumentFetch&&!c&&globalThis.fetch){let s=globalThis.fetch;globalThis.fetch=async(d,m)=>{let v=typeof d=="string"?d:d instanceof URL?d.href:d.url,b=v.startsWith(t.endpoint)||Me(v,t.ignoreUrls),D=Date.now();try{let R=await s(d,m);return b||z("resource",v.split(/[?#]/)[0],{method:m?.method??"GET",status:R.status},Date.now()-D),R}catch(R){throw b||z("resource",v.split(/[?#]/)[0],{method:m?.method??"GET",status:0},Date.now()-D),R}},C.push(()=>void(globalThis.fetch=s))}let Z=s=>(s?ne(s,w.id_salt??""):Promise.resolve(void 0)).then(d=>void(g=d),()=>void(g=void 0));t.user?.id&&!c&&(L=O.then(()=>Z(t.user?.id)));let M=(s,d)=>(...m)=>{try{return s(...m)}catch(v){return t.debug&&console.warn("[watchtower]",v),d}},ee=M(()=>{B=!0,P&&clearTimeout(P),C.forEach(s=>s())},void 0);return{captureError:M((s,d)=>{let m=s instanceof Error?s:new Error(String(s));N.report(m.name,m.message,m.stack,!0,"manual",d)},void 0),checkLastError:M(s=>ue(n,N.report,s),!1),setUser:M(s=>void(c||(L=O.then(()=>Z(s.id)))),void 0),setAttribute:M((s,d)=>void(x[s]=d),void 0),flush:()=>_().then(E,E),sessionId:()=>h.touch().then(s=>s.id,()=>""),stop:ee,shutdown:async()=>{ee(),await _().catch(E)}}}export{_e as SDK,ut as init,H as normalizeFrameUrl};
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../browser/src/config.ts", "../../browser/src/ids.ts", "../../browser/src/remote_config.ts", "../src/chrome_api.ts", "../src/context.ts", "../../browser/src/instrument/errors.ts", "../src/errors.ts", "../../browser/src/queue.ts", "../../browser/src/transport.ts", "../src/flush.ts", "../src/store.ts", "../src/session.ts", "../src/index.ts"],
4
+ "sourcesContent": ["export type Attrs = Record<string, string | number | boolean>;\nexport type Matcher = string | RegExp;\n\nexport interface RumEventV1 {\n id: string;\n ts_ns: number;\n type: \"view\" | \"vital\" | \"error\" | \"resource\" | \"action\" | \"longtask\" | \"journey\" | \"frustration\" | \"flag\" | \"nav\";\n name: string;\n value?: number;\n attrs: Attrs;\n /** lowercase hex, 32 chars (OTel JSON form) */\n trace_id?: string;\n /** lowercase hex, 16 chars */\n span_id?: string;\n}\n\nimport type { ReplayConfig } from \"./replay/config\";\nimport type { AssistConfig } from \"./assist\";\nexport type { ReplayConfig };\n\nexport interface FlagAdapter {\n name: string;\n attach(record: (key: string, value: unknown) => void): void;\n}\n\nexport interface WatchtowerConfig {\n publishableKey: string;\n /** edge base URL */\n endpoint: string;\n /** gateway base URL for OTLP traces */\n otlpEndpoint?: string;\n service: string;\n release?: string;\n environment?: string;\n /** traceparent is injected only into requests matching these (string = URL prefix); default none */\n propagateTo?: Matcher[];\n /** URL of the lazy instrumentation chunk (default: instrument/index.js beside the core) */\n instrumentUrl?: string;\n /** capture console.error as error events (default off) */\n captureConsoleErrors?: boolean;\n /** console levels sent as OTLP log records with the session id (default none) */\n captureConsole?: Array<\"debug\" | \"log\" | \"info\" | \"warn\" | \"error\">;\n /** automatic user-action spans: a click, submit or Enter starts a span that parents the fetch/XHR\n * spans it causes (needs otlpEndpoint; default on). Name one with `data-wt-action=\"checkout\"`. */\n userActions?: boolean;\n sampleRate?: number;\n errorSampleRate?: number;\n ignoreUrls?: Matcher[];\n beforeSend?: (e: RumEventV1) => RumEventV1 | null;\n /** hashed client-side (SHA-256 + project salt) before send */\n user?: { id?: string };\n replay?: ReplayConfig;\n /** co-browse assist (off by default; the project must turn it on too); `scriptUrl` defaults to assist.js beside the core */\n assist?: AssistConfig & { scriptUrl?: string };\n profiling?: boolean;\n flags?: FlagAdapter[];\n posthog?: { register?: boolean };\n /** dynamic probes: an ingestion key with scope `probes:read`, and the lazy chunk URL (default probes.js beside the core) */\n probes?: { key: string; url?: string };\n /** user feedback (ERR-014): the lazy chunk URL, default feedback.js beside the core */\n feedback?: { scriptUrl?: string };\n /** opt-in: keep an anonymous id in localStorage (default off) */\n persistAnonId?: boolean;\n debug?: boolean;\n}\n\nexport interface RemoteConfig {\n rum_enabled: boolean;\n /** the project's switch for browser log records */\n browser_logs?: boolean;\n sample_rate?: number;\n error_sample_rate?: number;\n /** project salt for client-side user-id hashing */\n id_salt?: string;\n replay: { enabled: boolean; mask_level?: \"strict\" | \"balanced\" | \"relaxed\" };\n profiling?: { enabled?: boolean };\n}\n\n/** Safe defaults when the config endpoint is unreachable: RUM on, replay off. */\nexport const DEFAULT_REMOTE: RemoteConfig = { rum_enabled: true, replay: { enabled: false } };\n\nexport const LIMITS = {\n flushEvents: 50,\n flushMs: 5000,\n queueMax: 500,\n gzipMinBytes: 1024,\n backoffMaxMs: 60_000,\n idleMs: 30 * 60_000,\n maxSessionMs: 4 * 3_600_000,\n configTimeoutMs: 2000,\n} as const;\n\nexport const SDK = { name: \"@watchtower/browser\", version: \"0.1.0\" } as const;\n", "export function uuid(): string {\n const c = globalThis.crypto;\n if (c?.randomUUID) return c.randomUUID();\n const b = new Uint8Array(16);\n if (c?.getRandomValues) c.getRandomValues(b);\n else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256);\n b[6] = (b[6]! & 0x0f) | 0x40;\n b[8] = (b[8]! & 0x3f) | 0x80;\n const h = [...b].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n\n/** Uniform [0,1) draw. */\nexport function rand(): number {\n const c = globalThis.crypto;\n if (c?.getRandomValues) return c.getRandomValues(new Uint32Array(1))[0]! / 2 ** 32;\n return Math.random();\n}\n\n/** SHA-256 hex of `salt:id`, or undefined when SubtleCrypto is missing (insecure context): the raw id is never sent. */\nexport async function hashUserId(id: string, salt: string): Promise<string | undefined> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) return undefined;\n const d = await subtle.digest(\"SHA-256\", new TextEncoder().encode(`${salt}:${id}`));\n return [...new Uint8Array(d)].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n", "import { DEFAULT_REMOTE, LIMITS, type RemoteConfig } from \"./config\";\n\n/** Fetch `/v1/rum/config` with a 2 s timeout; any failure yields the safe defaults (RUM on, replay off). */\nexport async function fetchRemoteConfig(\n endpoint: string,\n key: string,\n f: typeof fetch = globalThis.fetch?.bind(globalThis),\n): Promise<RemoteConfig> {\n const ctl = new AbortController();\n const timer = setTimeout(() => ctl.abort(), LIMITS.configTimeoutMs);\n try {\n const r = await f(`${endpoint.replace(/\\/$/, \"\")}/v1/rum/config`, {\n headers: { Authorization: `Bearer ${key}` },\n signal: ctl.signal,\n });\n if (!r.ok) return DEFAULT_REMOTE;\n const j = (await r.json()) as Partial<RemoteConfig>;\n return { ...DEFAULT_REMOTE, ...j, replay: { enabled: j.replay?.enabled === true, ...maskLevel(j.replay) } };\n } catch {\n return DEFAULT_REMOTE;\n } finally {\n clearTimeout(timer);\n }\n}\n\ntype Level = \"strict\" | \"balanced\" | \"relaxed\";\nconst LEVELS: ReadonlySet<string> = new Set<Level>([\"strict\", \"balanced\", \"relaxed\"]);\n/** Keep the server's mask floor only when it is a known level; anything else is dropped (the local strict default applies). */\nconst maskLevel = (r: unknown): { mask_level?: Level } => {\n const l = (r as { mask_level?: unknown } | undefined)?.mask_level;\n return typeof l === \"string\" && LEVELS.has(l) ? { mask_level: l as Level } : {};\n};\n", "/** The slice of the `chrome.*` API the SDK touches. Hand-written so no `@types/chrome` is needed and tests can fake it. */\nexport interface Evt<A extends unknown[] = unknown[]> {\n addListener(cb: (...a: A) => unknown): void;\n removeListener?(cb: (...a: A) => unknown): void;\n}\n\nexport interface StorageArea {\n get(keys?: string | string[] | null): Promise<Record<string, unknown>>;\n set(items: Record<string, unknown>): Promise<void>;\n remove(keys: string | string[]): Promise<void>;\n}\n\nexport interface Manifest {\n version?: string;\n manifest_version?: number;\n action?: { default_popup?: string };\n browser_action?: { default_popup?: string };\n options_page?: string;\n options_ui?: { page?: string };\n side_panel?: { default_path?: string };\n devtools_page?: string;\n}\n\nexport interface Sender {\n id?: string;\n}\n\nexport interface ChromeApi {\n runtime?: {\n id?: string;\n lastError?: { message?: string };\n getManifest?(): Manifest;\n sendMessage?(msg: unknown): Promise<unknown>;\n onMessage?: Evt<[unknown, Sender, (r?: unknown) => void]>;\n onStartup?: Evt<[]>;\n onInstalled?: Evt<[unknown]>;\n };\n storage?: { local?: StorageArea; session?: StorageArea };\n alarms?: { create(name: string, info: { periodInMinutes?: number; delayInMinutes?: number }): unknown; onAlarm?: Evt<[{ name: string }]> };\n devtools?: unknown;\n}\n\n/** Where the SDK runs. Defaults to the real globals; tests pass fakes so several contexts can share one `chrome`. */\nexport interface Env {\n chrome?: ChromeApi;\n /** `location` of the running context */\n location?: { protocol: string; pathname: string; origin?: string };\n /** false in a service worker */\n hasDocument: boolean;\n /** receives `error` / `unhandledrejection` */\n target?: Pick<EventTarget, \"addEventListener\" | \"removeEventListener\">;\n userAgent?: string;\n}\n\nexport function realEnv(): Env {\n const g = globalThis as unknown as Record<string, unknown>;\n return {\n chrome: g.chrome as ChromeApi | undefined,\n location: g.location as Env[\"location\"],\n hasDocument: typeof g.document !== \"undefined\",\n target: g as unknown as Env[\"target\"],\n userAgent: (g.navigator as { userAgent?: string } | undefined)?.userAgent,\n };\n}\n", "import type { Env, Manifest } from \"./chrome_api\";\n\nexport type ExtContext = \"service_worker\" | \"popup\" | \"options\" | \"side_panel\" | \"offscreen\" | \"content_script\" | \"devtools\";\n\nconst EXT_PROTOCOLS = new Set([\"chrome-extension:\", \"moz-extension:\"]);\nconst strip = (p: string | undefined): string => (p ?? \"\").replace(/^\\/+/, \"\").split(/[?#]/)[0]!;\n\n/** Which extension surface this code runs in. Override with `context` when a page is not declared in the manifest (offscreen pages never are). */\nexport function detectContext(env: Env, m: Manifest = {}): ExtContext {\n if (!env.hasDocument) return \"service_worker\";\n if (!env.location || !EXT_PROTOCOLS.has(env.location.protocol)) return \"content_script\";\n if (env.chrome?.devtools) return \"devtools\";\n const path = strip(env.location.pathname);\n const is = (p: string | undefined): boolean => !!p && strip(p) === path;\n if (is(m.devtools_page)) return \"devtools\";\n if (is(m.action?.default_popup) || is(m.browser_action?.default_popup)) return \"popup\";\n if (is(m.options_page) || is(m.options_ui?.page)) return \"options\";\n if (is(m.side_panel?.default_path)) return \"side_panel\";\n if (/offscreen/i.test(path)) return \"offscreen\";\n return \"popup\";\n}\n\nconst EXT_URL = /^(?:chrome|moz)-extension:\\/\\/[^/]+\\/(.*)$/;\n\n/** `chrome-extension://<per-install id>/js/sw.js?x#y` to `app:///js/sw.js`, so maps uploaded per release match every install. Other URLs pass through. */\nexport function normalizeFrameUrl(url: string): string {\n const m = EXT_URL.exec(url);\n return m ? `app:///${strip(m[1])}` : url;\n}\n\n/** True when the URL is one of this extension's own scripts. */\nexport function isOwnUrl(url: string | undefined, id: string | undefined): boolean {\n return !!url && !!id && (url.startsWith(`chrome-extension://${id}/`) || url.startsWith(`moz-extension://${id}/`));\n}\n", "import { scrubUrl, type Ctx, type Uninstall } from \"./ctx\";\n\nexport interface Frame {\n filename: string;\n function: string;\n lineno: number;\n colno: number;\n}\n\nconst V8 = /^\\s*at (?:async )?(?:(.*?) \\()?(.+?):(\\d+):(\\d+)\\)?\\s*$/;\nconst GECKO = /^\\s*(.*?)@(.+?):(\\d+):(\\d+)\\s*$/;\n\n/**\n * V8 and Gecko/Safari stack text to frames. Returned oldest call first (the worker's\n * `ErrorEventV1` convention: the innermost frame is last), capped at 50.\n */\nexport function parseStack(stack: string): Frame[] {\n const out: Frame[] = [];\n for (const line of stack.split(\"\\n\")) {\n const m = V8.exec(line) ?? GECKO.exec(line);\n if (m) out.push({ function: m[1] || \"?\", filename: m[2]!, lineno: +m[3]!, colno: +m[4]! });\n }\n return out.slice(0, 50).reverse();\n}\n\ninterface DebugIds {\n _wtDebugIds?: Record<string, string>;\n}\n\n/** filename to debug id, only for files that appear in the stack (keeps the event small). */\nfunction debugIdsFor(frames: Frame[]): Record<string, string> {\n const all = (window as unknown as DebugIds)._wtDebugIds ?? {};\n const out: Record<string, string> = {};\n for (const f of frames) {\n let id = all[f.filename];\n if (!id) {\n try {\n id = all[new URL(f.filename).pathname];\n } catch {\n /* relative or opaque filename */\n }\n }\n if (id) out[f.filename] = id;\n }\n return out;\n}\n\nconst DEDUPE_MS = 5000;\n\nexport function installErrors(ctx: Ctx): Uninstall {\n const seen = new Map<string, number>();\n\n const report = (type: string, message: string, stack: string | undefined, handled: boolean, mechanism: string): void => {\n const frames = stack ? parseStack(stack) : [];\n const top = frames[frames.length - 1];\n const key = `${type}|${message}|${top ? `${top.filename}:${top.lineno}:${top.colno}` : \"\"}`;\n const now = Date.now();\n if (now - (seen.get(key) ?? -Infinity) < DEDUPE_MS) return;\n seen.set(key, now);\n if (seen.size > 100) for (const [k, t] of seen) if (now - t >= DEDUPE_MS) seen.delete(k);\n const attrs: Record<string, string | boolean> = {\n type,\n message: message.slice(0, 1024),\n handled,\n mechanism,\n frames: JSON.stringify(frames),\n debug_ids: JSON.stringify(debugIdsFor(frames)),\n };\n if (ctx.cfg.release) attrs.release = ctx.cfg.release;\n ctx.emit(\"error\", type, { attrs });\n };\n\n const onError = (ev: Event): void => {\n const t = ev.target;\n if (t instanceof Element && t !== (document as unknown)) {\n // capture-phase resource failure (img, script, link): errors from elements do not bubble\n const tag = t.tagName;\n if (tag !== \"IMG\" && tag !== \"SCRIPT\" && tag !== \"LINK\") return;\n const src = (t as HTMLImageElement).src ?? (t as HTMLLinkElement).href ?? \"\";\n if (ctx.isOwn(src)) return;\n report(\"ResourceError\", `Failed to load ${tag.toLowerCase()} ${scrubUrl(src)}`, undefined, false, \"resource\");\n return;\n }\n const e = ev as ErrorEvent;\n const err = e.error as { name?: string; stack?: string } | null | undefined;\n report(err?.name ?? \"Error\", e.message ?? \"\", err?.stack, false, \"onerror\");\n };\n const onRejection = (ev: Event): void => {\n const r = (ev as PromiseRejectionEvent).reason as { name?: string; message?: string; stack?: string } | unknown;\n const isObj = typeof r === \"object\" && r !== null;\n const o = r as { name?: string; message?: string; stack?: string };\n report(isObj ? (o.name ?? \"UnhandledRejection\") : \"UnhandledRejection\", isObj ? (o.message ?? \"\") : String(r), isObj ? o.stack : undefined, false, \"unhandledrejection\");\n };\n const onCsp = (ev: Event): void => {\n const e = ev as SecurityPolicyViolationEvent;\n report(\"CSPViolation\", `${e.violatedDirective} blocked ${scrubUrl(e.blockedURI)}`, undefined, false, \"csp\");\n };\n\n window.addEventListener(\"error\", onError, true);\n window.addEventListener(\"unhandledrejection\", onRejection);\n document.addEventListener(\"securitypolicyviolation\", onCsp);\n\n const orig = console.error;\n if (ctx.cfg.captureConsoleErrors) {\n console.error = function (...a: unknown[]) {\n try {\n const first = a[0];\n const e = first instanceof Error ? first : undefined;\n report(e?.name ?? \"ConsoleError\", e?.message ?? a.map(String).join(\" \"), e?.stack, true, \"console\");\n } catch {\n /* never break the host's logging */\n }\n return orig.apply(console, a);\n };\n }\n\n return () => {\n window.removeEventListener(\"error\", onError, true);\n window.removeEventListener(\"unhandledrejection\", onRejection);\n document.removeEventListener(\"securitypolicyviolation\", onCsp);\n if (ctx.cfg.captureConsoleErrors) console.error = orig;\n };\n}\n", "import type { Attrs, RumEventV1 } from \"@watchtowerobservability/browser/src/config\";\nimport { parseStack } from \"@watchtowerobservability/browser/src/instrument/errors\";\nimport type { ChromeApi, Env } from \"./chrome_api\";\nimport { isOwnUrl, normalizeFrameUrl } from \"./context\";\n\ntype Emit = (type: RumEventV1[\"type\"], name: string, attrs: Attrs) => void;\n\nexport interface ErrorOpts {\n env: Env;\n extId: string | undefined;\n release?: string;\n emit: Emit;\n /** content script: only errors whose innermost frame is one of the extension's own scripts */\n ownOnly: boolean;\n wrapListeners: boolean;\n}\n\nconst DEDUPE_MS = 5000;\n\n/** Frames with per-install `chrome-extension://<id>/` URLs rewritten to `app:///`, plus build-time debug ids keyed by the same name. */\nexport function frameAttrs(stack: string | undefined): Attrs {\n const raw = stack ? parseStack(stack) : [];\n const ids = (globalThis as { _wtDebugIds?: Record<string, string> })._wtDebugIds ?? {};\n const debug: Record<string, string> = {};\n const frames = raw.map((f) => {\n const filename = normalizeFrameUrl(f.filename);\n const id = ids[filename.replace(/^app:\\/\\/\\//, \"\")];\n if (id) debug[filename] = id;\n return { ...f, filename };\n });\n return { frames: JSON.stringify(frames), debug_ids: JSON.stringify(debug) };\n}\n\nexport interface ErrorHandle {\n report(type: string, message: string, stack: string | undefined, handled: boolean, mechanism: string, extra?: Attrs): void;\n uninstall(): void;\n}\n\nexport function installErrors(o: ErrorOpts): ErrorHandle {\n const seen = new Map<string, number>();\n const report: ErrorHandle[\"report\"] = (type, message, stack, handled, mechanism, extra) => {\n const attrs: Attrs = { type, message: message.slice(0, 1024), handled, mechanism, ...frameAttrs(stack), ...extra };\n if (o.release) attrs.release = o.release;\n const key = `${type}|${message}|${attrs.frames}`;\n const now = Date.now();\n if (now - (seen.get(key) ?? -Infinity) < DEDUPE_MS) return;\n seen.set(key, now);\n if (seen.size > 100) for (const [k, t] of seen) if (now - t >= DEDUPE_MS) seen.delete(k);\n o.emit(\"error\", type, attrs);\n };\n\n /** Host pages share the content script's `window` events: never report what the extension did not throw. */\n const mine = (stack: string | undefined, filename?: string): boolean => {\n if (!o.ownOnly) return true;\n const top = stack ? parseStack(stack).pop() : undefined;\n return isOwnUrl(top?.filename ?? filename, o.extId);\n };\n\n const onError = (ev: Event): void => {\n const e = ev as ErrorEvent;\n const err = e.error as { name?: string; stack?: string } | null | undefined;\n if (!mine(err?.stack, e.filename)) return;\n report(err?.name ?? \"Error\", e.message ?? \"\", err?.stack, false, \"onerror\");\n };\n const onRejection = (ev: Event): void => {\n const r = (ev as PromiseRejectionEvent).reason as { name?: string; message?: string; stack?: string } | unknown;\n const o2 = (typeof r === \"object\" && r !== null ? r : undefined) as { name?: string; message?: string; stack?: string } | undefined;\n if (!mine(o2?.stack)) return;\n report(o2?.name ?? \"UnhandledRejection\", o2 ? (o2.message ?? \"\") : String(r), o2?.stack, false, \"unhandledrejection\");\n };\n o.env.target?.addEventListener(\"error\", onError);\n o.env.target?.addEventListener(\"unhandledrejection\", onRejection);\n const unwrap = o.wrapListeners && o.env.chrome ? wrapListeners(o.env.chrome, report) : () => undefined;\n return {\n report,\n uninstall: () => {\n o.env.target?.removeEventListener(\"error\", onError);\n o.env.target?.removeEventListener(\"unhandledrejection\", onRejection);\n unwrap();\n },\n };\n}\n\n/**\n * Wrap every `chrome.<ns>.<event>.addListener` so a throwing or rejecting listener is attributed to it\n * (`extension.listener`). Return values pass through, so `onMessage` listeners can still `return true`.\n * Install before your own listeners are added; the SDK's own are registered first and stay unwrapped.\n */\nfunction wrapListeners(chrome: ChromeApi, report: ErrorHandle[\"report\"]): () => void {\n type Fn = (...a: unknown[]) => unknown;\n const restore: Array<() => void> = [];\n for (const [ns, api] of Object.entries(chrome as Record<string, unknown>)) {\n if (!api || typeof api !== \"object\") continue;\n for (const [name, evt] of Object.entries(api as Record<string, unknown>)) {\n const e = evt as { addListener?: (cb: Fn, ...rest: unknown[]) => unknown; removeListener?: (cb: Fn) => unknown } | null;\n if (!e || typeof e.addListener !== \"function\") continue;\n const add = e.addListener.bind(e);\n const rm = e.removeListener?.bind(e);\n const wrapped = new WeakMap<Fn, Fn>();\n const fail = (x: unknown): void => {\n const err = x as { name?: string; message?: string; stack?: string };\n report(err?.name ?? \"Error\", err?.message ?? String(x), err?.stack, false, \"chrome.listener\", { \"extension.listener\": `${ns}.${name}` });\n };\n e.addListener = (cb: Fn, ...rest: unknown[]) => {\n const w: Fn = (...a) => {\n try {\n const r = cb(...a);\n if (r && typeof (r as Promise<unknown>).then === \"function\") (r as Promise<unknown>).then(undefined, fail);\n return r;\n } catch (x) {\n fail(x);\n throw x;\n }\n };\n wrapped.set(cb, w);\n return add(w, ...rest);\n };\n if (rm) e.removeListener = (cb: Fn) => rm(wrapped.get(cb) ?? cb);\n restore.push(() => {\n e.addListener = add;\n if (rm) e.removeListener = rm;\n });\n }\n }\n return () => restore.forEach((r) => r());\n}\n\n/** Report `chrome.runtime.lastError` if set (call it first thing in a callback-style API callback; unread, Chrome only logs it). */\nexport function checkLastError(chrome: ChromeApi | undefined, report: ErrorHandle[\"report\"], where?: string): boolean {\n const m = chrome?.runtime?.lastError?.message;\n if (!m) return false;\n report(\"RuntimeLastError\", m, new Error(m).stack, true, \"chrome.lastError\", where ? { \"extension.api\": where } : undefined);\n return true;\n}\n", "/** Bounded FIFO: when full the oldest event is dropped and counted. */\nexport class BoundedQueue<T> {\n private items: T[] = [];\n dropped = 0;\n constructor(private max: number) {}\n\n push(item: T): void {\n this.items.push(item);\n this.trim();\n }\n\n /** Put a failed batch back in front (still bounded). */\n requeue(items: T[]): void {\n this.items = items.concat(this.items);\n this.trim();\n }\n\n take(n: number): T[] {\n return this.items.splice(0, n);\n }\n\n get length(): number {\n return this.items.length;\n }\n\n private trim(): void {\n const over = this.items.length - this.max;\n if (over > 0) {\n this.items.splice(0, over);\n this.dropped += over;\n }\n }\n}\n\n/** Durable overflow store for events that could not be sent (offline, 5xx). */\nexport interface OfflineStore<T> {\n save(items: T[]): Promise<void>;\n /** Return everything stored and clear it. */\n drain(): Promise<T[]>;\n}\n\nexport const OFFLINE_MAX = 2000;\n\n/** In-memory store: the fallback when IndexedDB is unavailable (private mode, SSR) and the test double. */\nexport class MemoryStore<T> implements OfflineStore<T> {\n items: T[] = [];\n dropped = 0;\n constructor(private max = OFFLINE_MAX) {}\n async save(items: T[]): Promise<void> {\n this.items.push(...items);\n const over = this.items.length - this.max;\n if (over > 0) {\n this.items.splice(0, over);\n this.dropped += over;\n }\n }\n async drain(): Promise<T[]> {\n return this.items.splice(0);\n }\n}\n\n/** IndexedDB store: one record holds the whole bounded array. Falls back to memory when IDB is missing or fails. */\nexport function idbStore<T>(name = \"wt-offline\", max = OFFLINE_MAX): OfflineStore<T> {\n const mem = new MemoryStore<T>(max);\n const open = (): Promise<IDBDatabase> =>\n new Promise((res, rej) => {\n const r = indexedDB.open(name, 1);\n r.onupgradeneeded = () => r.result.createObjectStore(\"q\");\n r.onsuccess = () => res(r.result);\n r.onerror = () => rej(r.error);\n });\n const tx = <R>(mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest<R>): Promise<R> =>\n open().then(\n (db) =>\n new Promise<R>((res, rej) => {\n const t = db.transaction(\"q\", mode);\n const q = fn(t.objectStore(\"q\"));\n t.oncomplete = () => {\n db.close();\n res(q.result);\n };\n t.onerror = t.onabort = () => rej(t.error);\n }),\n );\n const usable = typeof indexedDB !== \"undefined\";\n return {\n async save(items) {\n if (!usable) return mem.save(items);\n try {\n const old = ((await tx(\"readonly\", (s) => s.get(\"items\"))) as T[] | undefined) ?? [];\n await tx(\"readwrite\", (s) => s.put(old.concat(items).slice(-max), \"items\"));\n } catch {\n await mem.save(items);\n }\n },\n async drain() {\n const local = await mem.drain();\n if (!usable) return local;\n try {\n const got = ((await tx(\"readonly\", (s) => s.get(\"items\"))) as T[] | undefined) ?? [];\n await tx(\"readwrite\", (s) => s.delete(\"items\"));\n return got.concat(local);\n } catch {\n return local;\n }\n },\n };\n}\n", "import { LIMITS, type Attrs, type RumEventV1 } from \"./config\";\nimport { BoundedQueue, type OfflineStore } from \"./queue\";\n\n/** Everything in a `RumBatchV1` except the tenant ids (stamped by the edge) and the events. */\nexport interface Envelope {\n session_id: string;\n sent_at_ns: number;\n sdk: { name: string; version: string };\n app: { service: string; release?: string; env?: string };\n page: { url: string; route?: string; referrer?: string };\n device: { ua: string; viewport?: [number, number]; dpr?: number; connection?: string };\n user: { id_hash?: string };\n attrs: Attrs;\n}\n\nexport interface TransportOpts {\n endpoint: string;\n key: string;\n envelope: () => Envelope;\n fetch?: typeof fetch;\n beacon?: (url: string, data: Blob) => boolean;\n random?: () => number;\n now?: () => number;\n /** awaited before each send (e.g. pending user-id hash) */\n beforeFlush?: () => Promise<void>;\n /** durable store for batches that could not be sent; drained back into the queue on start and after a success */\n offline?: OfflineStore<RumEventV1>;\n /** called for every batch the server refused for good (4xx other than 429) */\n onReject?: (status: number, events: number) => void;\n}\n\nasync function encode(body: string): Promise<{ data: BodyInit; gzip: boolean }> {\n const bytes = new TextEncoder().encode(body);\n if (bytes.length > LIMITS.gzipMinBytes && typeof CompressionStream === \"function\") {\n try {\n const s = new Blob([bytes]).stream().pipeThrough(new CompressionStream(\"gzip\"));\n return { data: await new Response(s).arrayBuffer(), gzip: true };\n } catch {\n /* fall through to plain */\n }\n }\n return { data: body, gzip: false };\n}\n\nexport class Transport {\n readonly queue = new BoundedQueue<RumEventV1>(LIMITS.queueMax);\n private started = false;\n private busy = false;\n private failures = 0;\n /** events refused with a permanent 4xx (413, 422, ...), by status; reported in `wt.sdk.rejected` */\n readonly rejected: Record<number, number> = {};\n private retryAt = 0;\n private timer?: ReturnType<typeof setTimeout>;\n private url: string;\n private now: () => number;\n\n constructor(private o: TransportOpts) {\n this.url = `${o.endpoint.replace(/\\/$/, \"\")}/v1/rum/events`;\n this.now = o.now ?? Date.now;\n }\n\n /** Begin sending (after remote config resolves). */\n start(): void {\n this.started = true;\n void this.restore();\n if (this.queue.length) this.schedule();\n }\n\n push(e: RumEventV1): void {\n this.queue.push(e);\n if (!this.started) return;\n if (this.queue.length >= LIMITS.flushEvents) void this.flush();\n else this.schedule();\n }\n\n private schedule(): void {\n if (this.timer) return;\n const wait = Math.max(LIMITS.flushMs, this.retryAt - this.now());\n this.timer = setTimeout(() => {\n this.timer = undefined;\n void this.flush();\n }, wait);\n }\n\n private async restore(): Promise<void> {\n try {\n const saved = (await this.o.offline?.drain()) ?? [];\n if (!saved.length) return;\n this.queue.requeue(saved);\n this.schedule();\n } catch {\n /* offline storage is best effort */\n }\n }\n\n private body(events: RumEventV1[]): string {\n const env = this.o.envelope();\n if (this.queue.dropped) env.attrs[\"wt.sdk.dropped\"] = this.queue.dropped;\n const rej = Object.entries(this.rejected);\n if (rej.length) env.attrs[\"wt.sdk.rejected\"] = rej.map(([k, v]) => `${k}:${v}`).join(\",\");\n return JSON.stringify({ ...env, events });\n }\n\n /** Send one batch. Never throws. `force` ignores the backoff window (shutdown). */\n async flush(force = false): Promise<void> {\n if (!this.started || this.busy || !this.queue.length) return;\n if (!force && this.now() < this.retryAt) return this.schedule();\n this.busy = true;\n const batch = this.queue.take(LIMITS.flushEvents);\n try {\n await this.o.beforeFlush?.();\n const { data, gzip } = await encode(this.body(batch));\n const f = this.o.fetch ?? globalThis.fetch.bind(globalThis);\n const r = await f(this.url, {\n method: \"POST\",\n body: data,\n keepalive: true,\n headers: {\n Authorization: `Bearer ${this.o.key}`,\n \"Content-Type\": \"application/json\",\n ...(gzip ? { \"Content-Encoding\": \"gzip\" } : {}),\n },\n });\n this.handle(r.status, r.headers?.get(\"Retry-After\") ?? null, batch);\n } catch {\n await this.park(batch);\n } finally {\n this.busy = false;\n }\n if (this.queue.length) this.schedule();\n }\n\n private handle(status: number, retryAfter: string | null, batch: RumEventV1[]): void {\n if (status < 300) {\n this.failures = 0;\n void this.restore();\n } else if (status === 429 || status >= 500) {\n this.backoff(batch, retryAfter);\n } else {\n // other 4xx (413, 422): the batch is invalid, retrying cannot help. Dropped, but counted and surfaced.\n this.rejected[status] = (this.rejected[status] ?? 0) + batch.length;\n this.o.onReject?.(status, batch.length);\n }\n }\n\n /** Network failure: persist the batch when a store exists (and back off), else requeue in memory. */\n private async park(batch: RumEventV1[]): Promise<void> {\n if (this.o.offline) {\n try {\n await this.o.offline.save(batch);\n this.backoff([], null);\n return;\n } catch {\n /* fall through to memory */\n }\n }\n this.backoff(batch, null);\n }\n\n private backoff(batch: RumEventV1[], retryAfter: string | null): void {\n this.queue.requeue(batch);\n const secs = retryAfter === null ? NaN : Number(retryAfter);\n const jitter = 0.5 + (this.o.random ?? Math.random)() / 2;\n const exp = Math.min(LIMITS.backoffMaxMs, 1000 * 2 ** this.failures) * jitter;\n this.failures++;\n this.retryAt = this.now() + (Number.isFinite(secs) ? Math.min(secs * 1000, LIMITS.backoffMaxMs) : exp);\n }\n\n /** Unload path: synchronous `sendBeacon` (key in `?k=`, a public key), `fetch keepalive` if refused. */\n flushBeacon(): void {\n if (!this.started) return;\n while (this.queue.length) {\n const batch = this.queue.take(LIMITS.flushEvents);\n const body = this.body(batch);\n const url = `${this.url}?k=${encodeURIComponent(this.o.key)}`;\n const send = this.o.beacon ?? (typeof navigator !== \"undefined\" ? navigator.sendBeacon?.bind(navigator) : undefined);\n let ok = false;\n try {\n ok = send ? send(url, new Blob([body], { type: \"text/plain\" })) : false;\n } catch {\n /* fall through */\n }\n if (!ok) {\n try {\n void (this.o.fetch ?? globalThis.fetch.bind(globalThis))(this.url, {\n method: \"POST\",\n body,\n keepalive: true,\n headers: { Authorization: `Bearer ${this.o.key}`, \"Content-Type\": \"application/json\" },\n }).catch(() => undefined);\n } catch {\n /* best effort */\n }\n }\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.timer) clearTimeout(this.timer);\n this.timer = undefined;\n while (this.queue.length) {\n const before = this.queue.length;\n await this.flush(true);\n if (this.queue.length >= before) break; // failed: do not spin\n }\n }\n}\n", "import type { Envelope } from \"@watchtowerobservability/browser/src/transport\";\nimport { Transport } from \"@watchtowerobservability/browser/src/transport\";\nimport type { DurableQueue } from \"./store\";\n\nexport interface FlushDeps {\n queue: DurableQueue;\n endpoint: string;\n key: string;\n envelope: () => Envelope;\n /** awaited before each flush (session, user hash) */\n prepare: () => Promise<void>;\n fetch?: typeof fetch;\n}\n\n/**\n * Send what is stored, then delete exactly what was delivered. Events stay in storage while in flight, so a worker\n * killed mid-request re-sends them on the next start: at-least-once, with the stable event id as the server's dedupe key.\n * Retries (backoff, 429/5xx) belong to the browser SDK's `Transport`; failed events simply stay stored for the next alarm.\n * Calls overlap-safe within one context; across contexts a duplicate send is possible and deduplicated by id.\n */\nexport function makeFlusher(d: FlushDeps): () => Promise<void> {\n let running: Promise<void> | undefined;\n const run = async (): Promise<void> => {\n const stored = await d.queue.peek();\n if (!stored.length) return;\n await d.prepare();\n const dropped = await d.queue.dropped();\n let first = true;\n const t = new Transport({\n endpoint: d.endpoint,\n key: d.key,\n fetch: d.fetch,\n envelope: () => {\n const env = d.envelope();\n if (dropped && first) env.attrs[\"wt.sdk.dropped\"] = dropped;\n first = false;\n return env;\n },\n });\n t.start();\n for (const s of stored) t.queue.push(s.event);\n await t.shutdown(); // sends every batch it can, stops at the first failure\n const left = new Set(t.queue.take(stored.length).map((e) => e.id));\n const done = stored.filter((s) => !left.has(s.event.id));\n await d.queue.remove(done.map((s) => s.key));\n if (dropped && done.length) await d.queue.clearDropped();\n };\n return () => {\n running ??= run()\n .catch(() => undefined)\n .finally(() => (running = undefined));\n return running;\n };\n}\n", "import type { StorageArea } from \"./chrome_api\";\nimport type { RumEventV1 } from \"@watchtowerobservability/browser/src/config\";\n\nconst PREFIX = \"wt.q.\";\nconst DROPPED = \"wt.dropped\";\nlet seq = 0; // keeps same-millisecond adds of one context in order\n\nexport interface StoreLimits {\n maxEvents: number;\n maxBytes: number;\n /** trim every N adds (a trim reads the whole queue) */\n trimEvery: number;\n}\n\nexport const STORE_DEFAULTS: StoreLimits = { maxEvents: 1000, maxBytes: 1024 * 1024, trimEvery: 10 };\n\nexport interface Queued {\n key: string;\n event: RumEventV1;\n}\n\n/** Same surface as chrome.storage, kept in a Map: the fallback when `chrome.storage` is missing. */\nexport function memoryArea(): StorageArea {\n const m = new Map<string, unknown>();\n return {\n async get(keys) {\n const all = keys == null ? [...m.keys()] : ([] as string[]).concat(keys);\n return Object.fromEntries(all.filter((k) => m.has(k)).map((k) => [k, m.get(k)]));\n },\n async set(items) {\n for (const [k, v] of Object.entries(items)) m.set(k, v);\n },\n async remove(keys) {\n for (const k of ([] as string[]).concat(keys)) m.delete(k);\n },\n };\n}\n\n/**\n * Durable, bounded outgoing queue in `chrome.storage.local`. One storage key per event (`wt.q.<ms>.<seq>.<event id>`), so\n * contexts adding at the same time never overwrite each other. When over the count or byte bound the oldest events are\n * dropped and counted; the count is reported once in `wt.sdk.dropped`.\n */\nexport class DurableQueue {\n private adds = 0;\n constructor(\n private area: StorageArea,\n private lim: StoreLimits = STORE_DEFAULTS,\n ) {}\n\n async add(event: RumEventV1): Promise<void> {\n await this.area.set({ [`${PREFIX}${String(Date.now()).padStart(15, \"0\")}.${String(seq++ % 1e6).padStart(6, \"0\")}.${event.id}`]: JSON.stringify(event) });\n if (++this.adds % this.lim.trimEvery === 0) await this.trim();\n }\n\n /** Everything stored, oldest first. Nothing is removed until `remove` (a killed worker re-sends, never loses). */\n async peek(): Promise<Queued[]> {\n const all = await this.area.get(null);\n const out: Queued[] = [];\n for (const key of Object.keys(all).filter((k) => k.startsWith(PREFIX)).sort()) {\n try {\n out.push({ key, event: JSON.parse(String(all[key])) as RumEventV1 });\n } catch {\n await this.area.remove(key); // corrupt entry\n }\n }\n return out;\n }\n\n remove(keys: string[]): Promise<void> {\n return keys.length ? this.area.remove(keys) : Promise.resolve();\n }\n\n async trim(): Promise<void> {\n const all = await this.area.get(null);\n const keys = Object.keys(all).filter((k) => k.startsWith(PREFIX)).sort();\n const size = (k: string): number => String(all[k]).length + k.length;\n let drop = Math.max(0, keys.length - this.lim.maxEvents);\n let bytes = keys.slice(drop).reduce((n, k) => n + size(k), 0);\n while (bytes > this.lim.maxBytes && drop < keys.length - 1) bytes -= size(keys[drop++]!);\n if (!drop) return;\n await this.area.remove(keys.slice(0, drop));\n await this.area.set({ [DROPPED]: Number((await this.area.get(DROPPED))[DROPPED] ?? 0) + drop });\n }\n\n /** Dropped-event count since the last `clearDropped`. */\n async dropped(): Promise<number> {\n return Number((await this.area.get(DROPPED))[DROPPED] ?? 0);\n }\n\n clearDropped(): Promise<void> {\n return this.area.remove(DROPPED);\n }\n}\n", "import { LIMITS } from \"@watchtowerobservability/browser/src/config\";\nimport { rand, uuid } from \"@watchtowerobservability/browser/src/ids\";\nimport type { StorageArea } from \"./chrome_api\";\nimport { memoryArea } from \"./store\";\n\ninterface Stored {\n id: string;\n start: number;\n last: number;\n draw: number;\n}\n\nconst KEY = \"wt.session\";\n\n/**\n * The browser SDK's session rules (30 min idle, 4 h max) with the state in `chrome.storage.session`, so the service\n * worker, popup and offscreen document share one session id and it survives worker restarts.\n * shortcut: read-modify-write is not atomic, two contexts touching in the same tick may each roll a session; harmless (ids only group events).\n */\nexport class SharedSession {\n private area: StorageArea;\n constructor(area?: StorageArea, private now: () => number = Date.now) {\n this.area = area ?? memoryArea();\n }\n\n async touch(): Promise<Stored> {\n const t = this.now();\n let s: Stored | undefined;\n try {\n s = (await this.area.get(KEY))[KEY] as Stored | undefined;\n } catch {\n /* storage unavailable: start a fresh session */\n }\n if (!s || t - s.last > LIMITS.idleMs || t - s.start > LIMITS.maxSessionMs) s = { id: uuid(), start: t, last: t, draw: rand() };\n else s = { ...s, last: t };\n try {\n await this.area.set({ [KEY]: s });\n } catch {\n /* memory only */\n }\n return s;\n }\n}\n", "import { DEFAULT_REMOTE, type Attrs, type Matcher, type RemoteConfig, type RumEventV1, type WatchtowerConfig } from \"@watchtowerobservability/browser/src/config\";\nimport { hashUserId, rand, uuid } from \"@watchtowerobservability/browser/src/ids\";\nimport { fetchRemoteConfig } from \"@watchtowerobservability/browser/src/remote_config\";\nimport type { Envelope } from \"@watchtowerobservability/browser/src/transport\";\nimport { realEnv, type Env } from \"./chrome_api\";\nimport { detectContext, type ExtContext } from \"./context\";\nimport { checkLastError, installErrors } from \"./errors\";\nimport { makeFlusher } from \"./flush\";\nimport { SharedSession } from \"./session\";\nimport { DurableQueue, STORE_DEFAULTS, memoryArea, type StoreLimits } from \"./store\";\n\nexport type { RumEventV1 } from \"@watchtowerobservability/browser/src/config\";\nexport type { ExtContext } from \"./context\";\nexport { normalizeFrameUrl } from \"./context\";\n\nexport const SDK = { name: \"@watchtower/chrome-extension\", version: \"0.1.0\" } as const;\nconst ALARM = \"wt-flush\";\n/** Chrome 120+ allows 30 s; older versions round up to 1 min on their own. */\nconst ALARM_MINUTES = 0.5;\nconst FLUSH_MS = 5000;\nconst MAX_FORWARDED_BYTES = 16 * 1024;\n\nexport interface ChromeExtensionConfig\n extends Pick<WatchtowerConfig, \"publishableKey\" | \"endpoint\" | \"service\" | \"environment\" | \"sampleRate\" | \"errorSampleRate\" | \"beforeSend\" | \"user\" | \"ignoreUrls\" | \"debug\"> {\n /** default: `chrome.runtime.getManifest().version` */\n release?: string;\n /** force the surface when it cannot be detected (offscreen documents are not in the manifest) */\n context?: ExtContext;\n /** wrap `chrome.*.on*.addListener` callbacks so their errors name the listener; call init before adding listeners (default off) */\n wrapListeners?: boolean;\n /** report fetch calls (service worker and pages) as `resource` events; default off */\n instrumentFetch?: boolean;\n /** content scripts: add the host page origin (never path or query) as `extension.host_origin`; default off */\n hostOrigin?: boolean;\n /** durable queue bounds: defaults 1000 events and 1 MiB in chrome.storage.local */\n queue?: Partial<StoreLimits>;\n /** test hooks */\n env?: Env;\n fetch?: typeof fetch;\n}\n\nexport interface ChromeExtensionClient {\n captureError(err: unknown, ctx?: Attrs): void;\n /** Reports `chrome.runtime.lastError` if set; returns whether it was. */\n checkLastError(where?: string): boolean;\n setUser(u: { id?: string }): void;\n setAttribute(k: string, v: string | number | boolean): void;\n /** Send everything stored now (no-op in content scripts, which forward to the service worker). */\n flush(): Promise<void>;\n sessionId(): Promise<string>;\n stop(): void;\n shutdown(): Promise<void>;\n}\n\nconst noop = (): void => undefined;\nconst NOOP: ChromeExtensionClient = {\n captureError: noop,\n checkLastError: () => false,\n setUser: noop,\n setAttribute: noop,\n flush: () => Promise.resolve(),\n sessionId: () => Promise.resolve(\"\"),\n stop: noop,\n shutdown: () => Promise.resolve(),\n};\n\n/** Never throws into the extension. In a service worker call it synchronously at the top level of the worker script (MV3 requires listeners to register on the first turn). */\nexport function init(cfg: ChromeExtensionConfig): ChromeExtensionClient {\n try {\n return build(cfg);\n } catch (e) {\n if (cfg?.debug) console.warn(\"[watchtower] init failed\", e);\n return NOOP;\n }\n}\n\nconst matches = (url: string, ms: Matcher[] = []): boolean => ms.some((m) => (typeof m === \"string\" ? url.startsWith(m) : m.test(url)));\n\nfunction build(cfg: ChromeExtensionConfig): ChromeExtensionClient {\n const env = cfg.env ?? realEnv();\n const chrome = env.chrome;\n const manifest = chrome?.runtime?.getManifest?.() ?? {};\n const extId = chrome?.runtime?.id;\n const context = cfg.context ?? detectContext(env, manifest);\n const release = cfg.release ?? manifest.version;\n const sw = context === \"service_worker\";\n const content = context === \"content_script\";\n const path = (env.location?.pathname ?? \"\").replace(/^\\/+/, \"\");\n const realFetch = cfg.fetch ?? globalThis.fetch?.bind(globalThis);\n\n const base: Attrs = { \"extension.context\": context };\n if (extId) base[\"extension.id\"] = extId;\n if (manifest.manifest_version) base[\"extension.manifest_version\"] = manifest.manifest_version;\n if (!content) base[\"extension.page\"] = path;\n else if (cfg.hostOrigin && env.location?.origin) base[\"extension.host_origin\"] = env.location.origin;\n\n const queue = new DurableQueue(chrome?.storage?.local ?? memoryArea(), { ...STORE_DEFAULTS, ...cfg.queue });\n const session = new SharedSession(chrome?.storage?.session);\n const attrs: Attrs = {};\n let remote: RemoteConfig = DEFAULT_REMOTE;\n let userHash: string | undefined;\n let userPending: Promise<void> = Promise.resolve();\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const cleanup: Array<() => void> = [];\n\n const envelope = (): Envelope => ({\n session_id: sessionId,\n sent_at_ns: Date.now() * 1e6,\n sdk: { ...SDK },\n app: { service: cfg.service, release, env: cfg.environment },\n // only the extension's own page path; host-page URLs never reach this process\n page: { url: `app:///${path}` },\n device: { ua: env.userAgent ?? \"\" },\n user: { id_hash: userHash },\n attrs: { \"extension.id\": extId ?? \"\", ...(manifest.manifest_version ? { \"extension.manifest_version\": manifest.manifest_version } : {}) },\n });\n let sessionId = \"\";\n const flushNow = makeFlusher({\n queue,\n endpoint: cfg.endpoint,\n key: cfg.publishableKey,\n envelope,\n fetch: realFetch,\n prepare: async () => {\n sessionId = (await session.touch()).id;\n await userPending;\n },\n });\n\n const ready: Promise<void> = content\n ? Promise.resolve()\n : fetchRemoteConfig(cfg.endpoint, cfg.publishableKey, realFetch).then((r) => void (remote = r));\n const flush = (): Promise<void> => (content ? Promise.resolve() : ready.then(flushNow));\n const schedule = (): void => {\n if (timer || content) return;\n timer = setTimeout(() => {\n timer = undefined;\n void flush();\n }, FLUSH_MS);\n };\n\n /** Sampling and storage; runs in the context that flushes (the content script's events arrive here by message). */\n const accept = async (e: RumEventV1): Promise<void> => {\n await ready;\n if (stopped || !remote.rum_enabled) return;\n const rate = remote.sample_rate ?? cfg.sampleRate ?? 1;\n const errRate = remote.error_sample_rate ?? cfg.errorSampleRate ?? 1;\n if (!((await session.touch()).draw < rate) && !(e.type === \"error\" && rand() < errRate)) return;\n await queue.add(e);\n schedule();\n };\n\n const forward = async (e: RumEventV1): Promise<void> => {\n try {\n const r = (await chrome!.runtime!.sendMessage!({ __wt: 1, event: e })) as { ok?: boolean } | undefined;\n if (r?.ok) return;\n } catch {\n /* service worker unavailable, or the extension was reloaded under this script */\n }\n await queue.add(e).catch(noop); // buffered; the service worker flushes it\n };\n\n const emit = (type: RumEventV1[\"type\"], name: string, extra: Attrs = {}, value?: number): void => {\n if (stopped) return;\n let e: RumEventV1 | null = { id: uuid(), ts_ns: Date.now() * 1e6, type, name, attrs: { ...attrs, ...base, ...extra } };\n if (value !== undefined) e.value = value;\n if (cfg.beforeSend) e = cfg.beforeSend(e);\n if (e) void (content ? forward(e) : accept(e)).catch(noop);\n };\n\n if (sw && chrome) {\n const onMessage = (msg: unknown, sender: { id?: string }, respond: (r?: unknown) => void): boolean => {\n const m = msg as { __wt?: number; event?: RumEventV1 } | null;\n if (m?.__wt !== 1) return false;\n const e = m.event;\n const ok = sender.id === extId && !!e && typeof e.id === \"string\" && typeof e.type === \"string\" && typeof e.name === \"string\" && typeof e.attrs === \"object\" && JSON.stringify(e).length <= MAX_FORWARDED_BYTES;\n if (ok) void accept(e!).catch(noop);\n respond({ ok });\n return false;\n };\n const onWake = (): void => void flush();\n const onAlarm = (a: { name: string }): void => void (a.name === ALARM && flush());\n chrome.runtime?.onMessage?.addListener(onMessage);\n chrome.runtime?.onStartup?.addListener(onWake);\n chrome.runtime?.onInstalled?.addListener(onWake);\n chrome.alarms?.onAlarm?.addListener(onAlarm);\n chrome.alarms?.create(ALARM, { periodInMinutes: ALARM_MINUTES });\n cleanup.push(() => {\n chrome.runtime?.onMessage?.removeListener?.(onMessage);\n chrome.runtime?.onStartup?.removeListener?.(onWake);\n chrome.runtime?.onInstalled?.removeListener?.(onWake);\n chrome.alarms?.onAlarm?.removeListener?.(onAlarm);\n });\n }\n // After the SDK's own listeners, so wrapListeners does not wrap them.\n const errors = installErrors({ env, extId, release, emit: (t, n, a) => emit(t, n, a), ownOnly: content, wrapListeners: cfg.wrapListeners === true });\n cleanup.push(errors.uninstall);\n\n // The worker may have been killed with events stored: send them as soon as it is back.\n if (!content) void flush();\n\n if (cfg.instrumentFetch && !content && globalThis.fetch) {\n const orig = globalThis.fetch;\n globalThis.fetch = async (input, init) => {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const skip = url.startsWith(cfg.endpoint) || matches(url, cfg.ignoreUrls);\n const t0 = Date.now();\n try {\n const r = await orig(input, init);\n if (!skip) emit(\"resource\", url.split(/[?#]/)[0]!, { method: init?.method ?? \"GET\", status: r.status }, Date.now() - t0);\n return r;\n } catch (e) {\n if (!skip) emit(\"resource\", url.split(/[?#]/)[0]!, { method: init?.method ?? \"GET\", status: 0 }, Date.now() - t0);\n throw e;\n }\n };\n cleanup.push(() => void (globalThis.fetch = orig));\n }\n\n const hashUser = (id: string | undefined): Promise<void> =>\n (id ? hashUserId(id, remote.id_salt ?? \"\") : Promise.resolve(undefined)).then(\n (h) => void (userHash = h),\n () => void (userHash = undefined),\n );\n if (cfg.user?.id && !content) userPending = ready.then(() => hashUser(cfg.user?.id));\n\n const safe = <A extends unknown[], R>(fn: (...a: A) => R, dflt: R) => (...a: A): R => {\n try {\n return fn(...a);\n } catch (e) {\n if (cfg.debug) console.warn(\"[watchtower]\", e);\n return dflt;\n }\n };\n const stop = safe(() => {\n stopped = true;\n if (timer) clearTimeout(timer);\n cleanup.forEach((c) => c());\n }, undefined);\n\n return {\n captureError: safe((err: unknown, ctx?: Attrs) => {\n const e = err instanceof Error ? err : new Error(String(err));\n errors.report(e.name, e.message, e.stack, true, \"manual\", ctx);\n }, undefined),\n checkLastError: safe((where?: string) => checkLastError(chrome, errors.report, where), false),\n setUser: safe((u: { id?: string }) => void (content || (userPending = ready.then(() => hashUser(u.id)))), undefined),\n setAttribute: safe((k: string, v: string | number | boolean) => void (attrs[k] = v), undefined),\n flush: () => flush().then(noop, noop),\n sessionId: () => session.touch().then((s) => s.id, () => \"\"),\n stop,\n shutdown: async () =>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F,EACMC,GAAOH,EAAK,IAAM,CACtB5C,EAAU,GACNC,GAAO,aAAaA,CAAK,EAC7BC,EAAQ,QAAS8C,GAAMA,EAAE,CAAC,CAC5B,EAAG,MAAS,EAEZ,MAAO,CACL,aAAcJ,EAAK,CAACK,EAAcC,IAAgB,CAChD,IAAMrC,EAAIoC,aAAe,MAAQA,EAAM,IAAI,MAAM,OAAOA,CAAG,CAAC,EAC5DjB,EAAO,OAAOnB,EAAE,KAAMA,EAAE,QAASA,EAAE,MAAO,GAAM,SAAUqC,CAAG,CAC/D,EAAG,MAAS,EACZ,eAAgBN,EAAMO,GAAmBC,GAAe1E,EAAQsD,EAAO,OAAQmB,CAAK,EAAG,EAAK,EAC5F,QAASP,EAAMS,GAAuB,KAAMpE,IAAYc,EAAcQ,EAAM,KAAK,IAAMiC,EAASa,EAAE,EAAE,CAAC,IAAK,MAAS,EACnH,aAAcT,EAAK,CAACU,EAAWC,IAAiC,KAAM5D,EAAM2D,CAAC,EAAIC,GAAI,MAAS,EAC9F,MAAO,IAAM7C,EAAM,EAAE,KAAK3C,EAAMA,CAAI,EACpC,UAAW,IAAM0B,EAAQ,MAAM,EAAE,KAAM,GAAM,EAAE,GAAI,IAAM,EAAE,EAC3D,KAAAsD,GACA,SAAU,SAAY,CACpBA,GAAK,EACL,MAAMrC,EAAM,EAAE,MAAM3C,CAAI,CAC1B,CACF,CACF",
6
+ "names": ["DEFAULT_REMOTE", "LIMITS", "uuid", "c", "b", "i", "h", "x", "rand", "hashUserId", "id", "salt", "subtle", "d", "fetchRemoteConfig", "endpoint", "key", "f", "ctl", "timer", "LIMITS", "r", "DEFAULT_REMOTE", "j", "maskLevel", "LEVELS", "l", "realEnv", "g", "EXT_PROTOCOLS", "strip", "p", "detectContext", "env", "m", "path", "is", "EXT_URL", "normalizeFrameUrl", "url", "isOwnUrl", "id", "V8", "GECKO", "parseStack", "stack", "out", "line", "m", "DEDUPE_MS", "frameAttrs", "stack", "raw", "parseStack", "ids", "debug", "frames", "f", "filename", "normalizeFrameUrl", "id", "installErrors", "o", "seen", "report", "type", "message", "handled", "mechanism", "extra", "attrs", "key", "now", "k", "t", "mine", "top", "isOwnUrl", "onError", "ev", "e", "err", "onRejection", "r", "o2", "unwrap", "wrapListeners", "chrome", "restore", "ns", "api", "name", "evt", "add", "rm", "wrapped", "fail", "x", "cb", "rest", "w", "a", "checkLastError", "where", "m", "BoundedQueue", "max", "item", "items", "n", "over", "encode", "body", "bytes", "LIMITS", "s", "Transport", "o", "BoundedQueue", "wait", "saved", "events", "env", "rej", "k", "v", "force", "batch", "data", "gzip", "r", "status", "retryAfter", "secs", "jitter", "exp", "url", "send", "ok", "before", "makeFlusher", "d", "running", "run", "stored", "dropped", "first", "t", "Transport", "env", "s", "left", "e", "done", "PREFIX", "DROPPED", "seq", "STORE_DEFAULTS", "memoryArea", "m", "keys", "all", "k", "items", "v", "DurableQueue", "area", "lim", "event", "out", "key", "size", "drop", "bytes", "n", "KEY", "SharedSession", "area", "now", "memoryArea", "t", "s", "LIMITS", "uuid", "rand", "SDK", "ALARM", "ALARM_MINUTES", "FLUSH_MS", "MAX_FORWARDED_BYTES", "noop", "NOOP", "init", "cfg", "build", "matches", "url", "ms", "m", "env", "realEnv", "chrome", "manifest", "extId", "context", "detectContext", "release", "sw", "content", "path", "realFetch", "base", "queue", "DurableQueue", "memoryArea", "STORE_DEFAULTS", "session", "SharedSession", "attrs", "remote", "DEFAULT_REMOTE", "userHash", "userPending", "stopped", "timer", "cleanup", "envelope", "sessionId", "flushNow", "makeFlusher", "ready", "fetchRemoteConfig", "r", "flush", "schedule", "accept", "e", "rate", "errRate", "rand", "forward", "emit", "type", "name", "extra", "value", "uuid", "onMessage", "msg", "sender", "respond", "ok", "onWake", "onAlarm", "a", "errors", "installErrors", "t", "n", "orig", "input", "skip", "t0", "hashUser", "id", "hashUserId", "h", "safe", "fn", "dflt", "stop", "c", "err", "ctx", "where", "checkLastError", "u", "k", "v"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@watchtowerobservability/chrome-extension",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "repository": { "type": "git", "url": "git+https://github.com/watchtowerobservability/watchtower-chrome-extension.git" },
5
+ "publishConfig": {
6
+ "access": "public",
7
+ "registry": "https://registry.npmjs.org/"
8
+ },
9
+ "description": "Watchtower SDK for Chrome (MV3) extensions: service worker, pages and content scripts, durable queue, shared session",
10
+ "type": "module",
11
+ "packageManager": "pnpm@11.2.2",
12
+ "sideEffects": false,
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": "./dist/index.js"
17
+ },
18
+ "files": ["dist"],
19
+ "scripts": {
20
+ "prebuild": "node scripts/browser-src.mjs",
21
+ "build": "node esbuild.config.mjs",
22
+ "typecheck": "tsgo --noEmit",
23
+ "test": "vitest run"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "22.10.2",
27
+ "@typescript/native-preview": "7.0.0-dev.20260707.2",
28
+ "esbuild": "0.25.10",
29
+ "vitest": "5.0.5"
30
+ }
31
+ }