@sazabi/browser 0.2.0-dev.ga327325 → 0.2.0-dev.ga3ff689
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 +202 -0
- package/README.md +67 -38
- package/dist/index.js +2 -2
- package/dist/index.js.map +6 -5
- package/dist/intake-url.d.ts +38 -0
- package/dist/types.d.ts +15 -4
- package/package.json +4 -4
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 2026 Sazabi
|
|
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,89 +1,109 @@
|
|
|
1
|
-
# @sazabi/browser
|
|
1
|
+
# @sazabi/browser-sdk
|
|
2
2
|
|
|
3
|
-
Capture what
|
|
3
|
+
Capture what happens in your users' browsers with `@sazabi/browser-sdk`, the official Sazabi browser SDK. It emits a session-scoped stream of navigation, interactions, console output, JavaScript errors, and network calls as OTLP log records, and injects W3C trace context into your API requests so a frontend symptom and its backend cause share a trace id.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
`@sazabi/browser-sdk` is a zero-dependency browser library you install in your own web app. It lets you:
|
|
6
|
+
|
|
7
|
+
- Follow a single visitor's session across tabs, from first page load to error
|
|
8
|
+
- Catch uncaught exceptions and unhandled promise rejections with stack traces
|
|
9
|
+
- See rage clicks and dead clicks — the interactions that signal frustration
|
|
10
|
+
- Join frontend network calls to backend logs on a shared `trace_id`
|
|
11
|
+
- Use AI to investigate a browser session end to end
|
|
12
|
+
|
|
13
|
+
~8 KB gzipped, and designed to never break your app: every hook is wrapped, every patch is reversible, and input values are never captured.
|
|
6
14
|
|
|
7
15
|
## Install
|
|
8
16
|
|
|
9
17
|
```sh
|
|
10
|
-
|
|
11
|
-
# or:
|
|
18
|
+
npm install @sazabi/browser-sdk
|
|
19
|
+
# or: bun add / pnpm add / yarn add
|
|
12
20
|
```
|
|
13
21
|
|
|
22
|
+
## Get your intake URL
|
|
23
|
+
|
|
24
|
+
Sign in to Sazabi, go to **Settings > Log streams**, choose **Web**, and click **Add**. Sazabi mints a public key and shows your complete intake URL at the top of the setup screen.
|
|
25
|
+
|
|
26
|
+
The SDK needs both values: the intake URL as `intakeHost` (the SDK appends the `/v1/logs` signal path itself) and the full `sazabi_public_...` value as `publicKey`.
|
|
27
|
+
|
|
28
|
+
Unlike most credentials, this one is **meant** to ship in your browser bundle — a public key can only write telemetry into your project, never read from it.
|
|
29
|
+
|
|
14
30
|
## Quick start
|
|
15
31
|
|
|
16
32
|
```ts
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
import "@sazabi/browser/register";
|
|
33
|
+
// Import first, because a module that runs earlier can capture the native
|
|
34
|
+
// fetch/XHR/history references before the SDK wraps them.
|
|
35
|
+
import "@sazabi/browser-sdk/register";
|
|
20
36
|
|
|
21
|
-
import { init } from "@sazabi/browser";
|
|
37
|
+
import { init } from "@sazabi/browser-sdk";
|
|
22
38
|
|
|
23
39
|
init({
|
|
24
|
-
|
|
25
|
-
|
|
40
|
+
intakeHost: "https://<public-key-hex>.<region>.intake.sazabi.com",
|
|
41
|
+
publicKey: "sazabi_public_<public-key-hex>",
|
|
26
42
|
serviceName: "my-web-app",
|
|
43
|
+
serviceVersion: process.env.GIT_SHA,
|
|
44
|
+
environment: "production",
|
|
27
45
|
});
|
|
28
46
|
```
|
|
29
47
|
|
|
30
|
-
`
|
|
48
|
+
`init()` is idempotent, never throws into your app, and no-ops during server-side rendering, so it is safe in a shared entry module.
|
|
31
49
|
|
|
32
|
-
The register import is optional but recommended. `init()` alone also instruments, but only at call time — HTTP
|
|
50
|
+
The register import is optional but recommended. `init()` alone also instruments, but only at call time — and every static import in your entry file evaluates before its first statement, so an HTTP client constructed at module scope wins that race. Requests that slip past instrumentation are still observed through a resource-timing fallback, and the SDK emits a once-per-origin `instrumentation_gap` diagnostic naming the escaped origin, so the gap is visible rather than silent.
|
|
33
51
|
|
|
34
52
|
## What gets captured
|
|
35
53
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
| `
|
|
39
|
-
|
|
40
|
-
| `
|
|
41
|
-
| `
|
|
42
|
-
| `
|
|
43
|
-
| `
|
|
44
|
-
| `
|
|
54
|
+
Every event carries a cross-tab `session.id`, a per-tab `session.window_id`, `session.distinct_id`, and the page URL, so one user's activity reads as a single ordered timeline. The `web.event_type` attribute names the kind:
|
|
55
|
+
|
|
56
|
+
| `web.event_type` | Contents |
|
|
57
|
+
|------------------|----------|
|
|
58
|
+
| `navigation` | Page loads and SPA route changes — History API, hash, back/forward, and the Navigation API |
|
|
59
|
+
| `click` | Capture-phase clicks with a privacy-safe selector and the element's label ("Save changes") |
|
|
60
|
+
| `rage_click` / `dead_click` | Frustration signals: rapid repeat clicks, and clicks with no visible response |
|
|
61
|
+
| `input` | One event per field engagement — which field, for how long, how many edits, whether pasted. Never keystrokes, values, or value lengths |
|
|
62
|
+
| `error` | Uncaught exceptions and unhandled rejections with `exception.type`, `exception.message`, and `exception.stacktrace` |
|
|
63
|
+
| `network` | fetch and XHR calls with method, status, and duration — plus the trace context injected into them |
|
|
64
|
+
| `log` | Mirrored `console.error` / `console.warn` output, plus anything you send with `log()` |
|
|
45
65
|
| `custom` | Marks you add with `addEvent()` |
|
|
46
66
|
|
|
47
|
-
Every event carries a cross-tab `session.id`, a per-tab `session.window_id`, and the page URL, so a user's activity reads as one ordered timeline.
|
|
48
|
-
|
|
49
67
|
## Correlate with your backend
|
|
50
68
|
|
|
51
|
-
The SDK injects a W3C `traceparent` header into same-origin requests by default. To
|
|
69
|
+
The SDK injects a W3C `traceparent` header into same-origin requests by default. To reach an API on another origin, allowlist it — and make sure that API's CORS configuration includes `traceparent` in `Access-Control-Allow-Headers`, or the browser preflight fails and those requests break:
|
|
52
70
|
|
|
53
71
|
```ts
|
|
54
72
|
init({
|
|
55
|
-
//
|
|
73
|
+
// …
|
|
56
74
|
network: {
|
|
57
75
|
allowlist: ["https://api.example.com"],
|
|
58
76
|
},
|
|
59
77
|
});
|
|
60
78
|
```
|
|
61
79
|
|
|
62
|
-
Backend log lines that run inside the extracted trace context then share a `trace_id` with the originating browser request. If your backend runs OpenTelemetry, extraction already happens by default
|
|
80
|
+
Backend log lines that run inside the extracted trace context then share a `trace_id` with the originating browser request. If your backend runs OpenTelemetry, that extraction already happens by default. Set `network: { sampledFlag: true }` if you also want your backend tracer to *record* those traces — the logs-side join works either way.
|
|
63
81
|
|
|
64
|
-
The SDK also records platform request ids echoed on responses (`x-request-id`, `cf-ray`, `x-vercel-id`, and similar) as `web.network.request_id`, giving you an exact join key against CDN and platform logs with no backend changes.
|
|
82
|
+
The SDK also records platform request ids echoed on responses (`x-request-id`, `cf-ray`, `x-vercel-id`, and similar) as `web.network.request_id`, giving you an exact join key against CDN and platform logs with no backend changes. Reading these cross-origin requires the header in `Access-Control-Expose-Headers`.
|
|
65
83
|
|
|
66
84
|
## Identify users
|
|
67
85
|
|
|
68
86
|
```ts
|
|
69
|
-
import { identify, reset } from "@sazabi/browser";
|
|
87
|
+
import { identify, reset } from "@sazabi/browser-sdk";
|
|
70
88
|
|
|
71
|
-
identify("user_123", { plan: "pro" }); // on
|
|
72
|
-
reset(); // on
|
|
89
|
+
identify("user_123", { plan: "pro" }); // on sign-in — use your internal id, not an email
|
|
90
|
+
reset(); // on sign-out
|
|
73
91
|
```
|
|
74
92
|
|
|
75
|
-
`identify()` stamps `session.distinct_id` on subsequent events and records the traits on the identify event. `reset()` clears the identity and rotates the session so activity on a shared device never threads into the previous user's timeline; switching identities without a `reset()` rotates automatically.
|
|
93
|
+
`identify()` stamps `session.distinct_id` on subsequent events and records the traits on the identify event. `reset()` clears the identity and rotates the session and window ids, so activity on a shared device never threads into the previous user's timeline; switching identities without a `reset()` rotates automatically.
|
|
94
|
+
|
|
95
|
+
Identity is client-asserted — treat it as a claim, not as authentication.
|
|
76
96
|
|
|
77
97
|
## Logs, custom events, and console output
|
|
78
98
|
|
|
79
99
|
```ts
|
|
80
|
-
import { addEvent, log } from "@sazabi/browser";
|
|
100
|
+
import { addEvent, log } from "@sazabi/browser-sdk";
|
|
81
101
|
|
|
82
102
|
addEvent("checkout_started", { cartValue: 42 });
|
|
83
103
|
log("WARN", "cache lookup failed", { requestId: "req_9" });
|
|
84
104
|
```
|
|
85
105
|
|
|
86
|
-
`console.error` and `console.warn` are mirrored into the event stream by default
|
|
106
|
+
`console.error` and `console.warn` are mirrored into the event stream by default, and the original console behavior is untouched. Configure with `console: { levels: [...] }` or turn it off with `console: { capture: false }`.
|
|
87
107
|
|
|
88
108
|
## Consent
|
|
89
109
|
|
|
@@ -91,11 +111,13 @@ If your users must opt in before capture, pass a consent gate — nothing is ins
|
|
|
91
111
|
|
|
92
112
|
```ts
|
|
93
113
|
init({
|
|
94
|
-
//
|
|
114
|
+
// …
|
|
95
115
|
consent: () => cookieBanner.accepted(),
|
|
96
116
|
});
|
|
97
117
|
```
|
|
98
118
|
|
|
119
|
+
`identify()` calls made while consent is pending are buffered and applied when capture starts.
|
|
120
|
+
|
|
99
121
|
## Configuration
|
|
100
122
|
|
|
101
123
|
| Option | Default | Purpose |
|
|
@@ -113,7 +135,14 @@ init({
|
|
|
113
135
|
|
|
114
136
|
## Privacy and safety
|
|
115
137
|
|
|
116
|
-
- Input values, keystrokes, request bodies, and response bodies are never captured — not even value lengths.
|
|
117
|
-
- Element names come from developer-authored sources only (`aria-label`, `<label>`, `placeholder`, button captions), and only for interactive elements
|
|
118
|
-
-
|
|
138
|
+
- **Input values, keystrokes, request bodies, and response bodies are never captured** — not even value lengths.
|
|
139
|
+
- Element names come from developer-authored sources only (`aria-label`, `<label>`, `placeholder`, button captions), and only for interactive elements. Clicks on plain containers, where user content lives, record selectors only.
|
|
140
|
+
- Add `data-sazabi-mask` to any element to suppress text capture for its whole subtree, or `data-sazabi-name` to set an element's reported name explicitly.
|
|
141
|
+
- Every patch is transparent, idempotent, and reversible. SDK failures are invisible to your app, and `shutdown()` restores the original functions.
|
|
119
142
|
- Events are delivered as OTLP/HTTP log records with batching, and flushed with `keepalive` when the tab closes.
|
|
143
|
+
|
|
144
|
+
## Verifying it works
|
|
145
|
+
|
|
146
|
+
Load your app and click through a few pages. The SDK flushes every 5 seconds and again when the tab is hidden or closed, so the first events land within about 10 seconds. In your browser's network tab, filter for `intake` — POSTs to `/v1/logs` should return 200.
|
|
147
|
+
|
|
148
|
+
Full setup guide and troubleshooting: [docs.sazabi.com/data/log-sources/endpoint/web](https://docs.sazabi.com/data/log-sources/endpoint/web).
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as P,b as H,d as ae,e as ce,f as q,g as z,h as ue,i as J,k as de,l as le}from"./chunk-rfm4nnme.js";var v=(e,t=4096)=>e.length>t?e.slice(0,t):e,h=(e,t="",n=0)=>{let r={};for(let[s,o]of Object.entries(e)){let i=t?`${t}.${s}`:s;if(o===null||o===void 0)continue;if(typeof o==="object"&&!Array.isArray(o)&&n<4){Object.assign(r,h(o,i,n+1));continue}if(typeof o==="number"||typeof o==="boolean")r[i]=o;else if(typeof o==="string")r[i]=v(o);else try{r[i]=v(JSON.stringify(o)??"")}catch{}}return r};var x="[@sazabi/browser]",pe={error:"ERROR",warn:"WARN",info:"INFO",debug:"DEBUG"},D=1000,fe=4000,me=(e)=>{let t;if(typeof e==="string")t=e;else if(e instanceof Error)t=`${e.name}: ${e.message}`;else try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>D?`${t.slice(0,D)}…`:t},V=(e)=>{let t=[],n=!1;for(let r of e.levels){let s=console[r];if(typeof s!=="function"||H(s))continue;let o=function(...i){if(s.apply(this??console,i),n)return;try{if(typeof i[0]==="string"&&i[0].startsWith(x))return;n=!0;let c=i.map(me).join(" ").slice(0,fe);e.emit({type:"log",body:c||`console.${r}`,severity:pe[r],timeUnixMs:Date.now(),attributes:{"web.console.level":r}})}catch{}finally{n=!1}};P(o),console[r]=o,t.push(()=>{if(console[r]===o)console[r]=s})}return{teardown(){for(let r of t)try{r()}catch{}}}};var U=(e)=>{let t=(r)=>{try{let s=r.error,o=s instanceof Error?s.name:"Error",i=r.message||"Unknown error";e.emit({type:"error",body:v(`${o}: ${i}`,512),severity:"ERROR",timeUnixMs:Date.now(),attributes:{"exception.type":o,"exception.message":i,"exception.stacktrace":s instanceof Error?s.stack??"":"","web.error.kind":"uncaught","web.error.filename":r.filename||void 0,"web.error.lineno":r.lineno||void 0,"web.error.colno":r.colno||void 0}})}catch{}},n=(r)=>{try{let s=r.reason,o=s instanceof Error,i=o?s.name:"UnhandledRejection",c=o?s.message:String(s);e.emit({type:"error",body:v(`${i}: ${c}`,512),severity:"ERROR",timeUnixMs:Date.now(),attributes:{"exception.type":i,"exception.message":c,"exception.stacktrace":o?s.stack??"":"","web.error.kind":"unhandledrejection"}})}catch{}};return window.addEventListener("error",t),window.addEventListener("unhandledrejection",n),{teardown(){window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",n)}}};var ge=["button","a[href]","summary",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="option"]','[role="checkbox"]','[role="switch"]','input[type="submit"]','input[type="button"]','input[type="reset"]'].join(","),w=(e)=>{if(!e)return;let t=e.replace(/\s+/g," ").trim();if(!t)return;return t.length>64?`${t.slice(0,64)}…`:t},K=(e)=>{try{return e.closest("[data-sazabi-mask]")!==null}catch{return!0}},W=(e)=>{let t=w(e.getAttribute("data-sazabi-name"));if(t)return t;let n=w(e.getAttribute("aria-label"));if(n)return n;let r=e.getAttribute("aria-labelledby");if(!r)return;return w(r.split(/\s+/).map((s)=>document.getElementById(s)?.textContent??"").join(" "))},F=(e)=>{try{if(K(e))return;let t=W(e);if(t)return t;if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)for(let r of Array.from(e.labels??[])){let s=w(r.textContent);if(s)return s}let n=w(e.getAttribute("placeholder"));if(n)return n;return w(e.getAttribute("name"))}catch{return}},B=(e)=>{try{let t=e.closest(ge);if(!t||K(t))return;let n=W(t);if(n)return n;if(t instanceof HTMLInputElement)return w(t.getAttribute("value"));return w(t.textContent)}catch{return}};var G=1000,Y=30,ye=4,Ee=800,be=200,ve="a,button,[role=button],input,select,textarea,label,summary,[tabindex],[onclick]",R=(e)=>{let t=e.getAttribute("data-testid");if(t)return`[data-testid="${t}"]`;if(e.id)return`#${e.id}`;let n=[],r=e;while(r&&n.length<3){let s=r.tagName.toLowerCase();if(r.id){n.unshift(`#${r.id}`);break}let o=Array.from(r.classList).slice(0,2);if(o.length>0)s+=`.${o.join(".")}`;n.unshift(s),r=r.parentElement}return n.join(" > ").slice(0,be)},j=(e)=>{let t=0,n=0,r=[],s=Number.NEGATIVE_INFINITY,o=new Set,i=new MutationObserver(()=>{t=performance.now()});try{i.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0})}catch{}let c=(m)=>{try{let y=m.target;if(!(y instanceof Element))return;let a=performance.now(),u=R(y),d=y.tagName.toLowerCase(),l=B(y);e.emit({type:"click",body:l?`click "${l}"`:`click ${u}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l}}),r.push({time:a,x:m.clientX,y:m.clientY});while(r.length>0&&a-r[0].time>G)r.shift();let f=r.filter((g)=>Math.abs(g.x-m.clientX)<=Y&&Math.abs(g.y-m.clientY)<=Y);if(f.length>=ye&&a-s>G)s=a,e.emit({type:"rage_click",body:l?`rage click "${l}"`:`rage click ${u}`,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l,"web.click_count":f.length}});if(y.closest(ve)){let g=a,S=window.setTimeout(()=>{o.delete(S);try{if(t<=g&&n<=g)e.emit({type:"dead_click",body:l?`dead click "${l}"`:`dead click ${u}`,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l}})}catch{}},Ee);o.add(S)}}catch{}};return document.addEventListener("click",c,{capture:!0,passive:!0}),{notifyNavigation(){n=performance.now()},teardown(){document.removeEventListener("click",c,{capture:!0}),i.disconnect();for(let m of o)window.clearTimeout(m);o.clear()}}};var we=1e4,Se=20,he=new Set(["button","submit","reset","image","checkbox","radio","range","file","color"]),Ie=(e)=>{if(e instanceof HTMLInputElement){let t=(e.type||"text").toLowerCase();return he.has(t)?void 0:t}if(e instanceof HTMLTextAreaElement)return"textarea";if(e instanceof HTMLSelectElement)return"select";if(e instanceof HTMLElement&&e.isContentEditable)return"contenteditable";return},X=(e)=>{let t=new Map,n=(a,u)=>{t.delete(a.element);try{e.emit({type:"input",body:a.name?`input "${a.name}"`:`input ${a.selector}`,severity:"INFO",timeUnixMs:a.startUnixMs,attributes:{"web.element.selector":a.selector,"web.element.name":a.name,"web.input.field_type":a.fieldType,"web.input.edit_count":a.editCount,"web.input.duration_ms":Math.max(0,Math.round(a.lastInputPerf-a.startPerf)),...a.pasted?{"web.input.pasted":!0}:{},"web.input.ended_by":u}})}catch{}},r=(a)=>{for(let u of Array.from(t.values()))n(u,a)},s=(a)=>{for(let u of Array.from(t.values()))if(a-u.lastInputPerf>we)n(u,"idle")},o=(a)=>{try{let u=performance.now();s(u);let d=a.target,l=Ie(d);if(l===void 0||!(d instanceof Element))return;if(a.type==="change"&&l!=="select")return;let f=t.get(d);if(!f){if(t.size>=Se)return;f={element:d,selector:R(d),name:F(d),fieldType:l,startUnixMs:Date.now(),startPerf:u,lastInputPerf:u,editCount:0,pasted:!1},t.set(d,f)}f.editCount+=1,f.lastInputPerf=u;let g=a.inputType;if(typeof g==="string"&&g.startsWith("insertFromPaste"))f.pasted=!0;if(a.type==="change"&&l==="select")n(f,"change")}catch{}},i=(a)=>{try{let u=a.target;if(u instanceof Element){let d=t.get(u);if(d)n(d,"blur")}}catch{}},c=(a)=>{try{if(a.key!=="Enter")return;let u=a.target;if(u instanceof Element){let d=t.get(u);if(d)n(d,"enter")}}catch{}},m=()=>{if(document.visibilityState==="hidden")r("hidden")},y=()=>{r("unload")};return document.addEventListener("input",o,{capture:!0,passive:!0}),document.addEventListener("change",o,{capture:!0,passive:!0}),document.addEventListener("focusout",i,{capture:!0,passive:!0}),document.addEventListener("keydown",c,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",m),window.addEventListener("pagehide",y),{notifyNavigation(){r("navigation")},teardown(){document.removeEventListener("input",o,{capture:!0}),document.removeEventListener("change",o,{capture:!0}),document.removeEventListener("focusout",i,{capture:!0}),document.removeEventListener("keydown",c,{capture:!0}),document.removeEventListener("visibilitychange",m),window.removeEventListener("pagehide",y),r("unload")}}};var Q=(e)=>{if(typeof PerformanceObserver>"u")return{teardown(){}};let t=new Set,n=(o)=>{let i;try{i=new URL(o).origin}catch{return}if(t.has(i))return;t.add(i);let c=`requests to ${i} bypass SDK instrumentation (fetch/XHR captured pre-init). Fix: import "@sazabi/browser/register" first.`;e.emit({type:"log",body:c,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.sdk.diagnostic":"instrumentation_gap","web.sdk.bypassed_origin":i}});try{console.warn(`${x} ${c}`)}catch{}},r=(o)=>{try{if(o.initiatorType!=="fetch"&&o.initiatorType!=="xmlhttprequest")return;let i=o.name;if(e.isInternalUrl(i))return;if(J(i,o.startTime))return;let c=o.responseStatus??0,m=Math.round(performance.timeOrigin+o.startTime+o.duration);if(e.emit({type:"network",body:`request ${q(i)} → ${c>0?c:"observed"}`,severity:c>0?z(c):"INFO",timeUnixMs:m,attributes:{"http.response.status_code":c>0?c:void 0,"url.full":i,"web.network.kind":o.initiatorType==="fetch"?"fetch":"xhr","web.network.duration_ms":Math.round(o.duration),"web.network.source":"resource-timing"}}),e.isInjectionTarget(i))n(i)}catch{}},s;try{s=new PerformanceObserver((o)=>{for(let i of o.getEntries())r(i)}),s.observe({type:"resource",buffered:!0})}catch{return{teardown(){}}}return{teardown(){try{s.disconnect()}catch{}}}};var Ae=()=>{let e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join("")},_=(e)=>`${e}_${Date.now().toString(36)}${Ae()}`,Z=(e)=>{let t=new Map;return{get(n){try{return e().getItem(n)}catch{return t.get(n)??null}},set(n,r){try{e().setItem(n,r)}catch{t.set(n,r)}},remove(n){t.delete(n);try{e().removeItem(n)}catch{}}}},_e=(e)=>{if(!e)return;try{let t=JSON.parse(e);if(typeof t==="object"&&t!==null&&typeof t.id==="string"&&typeof t.startedAt==="number"&&typeof t.lastActivityAt==="number")return t}catch{}return},ee=()=>{let e=Z(()=>window.localStorage),t=Z(()=>window.sessionStorage),n=0,r=()=>{let i=Date.now(),c=_e(e.get("sazabi.session"));if(c&&i-c.lastActivityAt<=1800000&&i-c.startedAt<=86400000)return c;let m={id:_("sess"),startedAt:i,lastActivityAt:i};return e.set("sazabi.session",JSON.stringify(m)),n=i,m},s=t.get("sazabi.windowId");if(!s)s=_("win"),t.set("sazabi.windowId",s);let o=()=>{let i=Date.now();e.set("sazabi.session",JSON.stringify({id:_("sess"),startedAt:i,lastActivityAt:i})),n=i,s=_("win"),t.set("sazabi.windowId",s)};return{getSessionId(){return r().id},getWindowId(){return s},getDistinctId(){return e.get("sazabi.distinctId")??void 0},setDistinctId(i){let c=e.get("sazabi.distinctId")??void 0;if(c!==void 0&&c!==i)o();e.set("sazabi.distinctId",i)},reset(){e.remove("sazabi.distinctId"),o()},touch(){let i=Date.now(),c=r();if(i-n>=5000)e.set("sazabi.session",JSON.stringify({...c,lastActivityAt:i})),n=i}}};var Te=/^[0-9a-f]{32}$/,Ce=/^[0-9a-f]{16}$/,xe="0".repeat(32),Re="0".repeat(16),te=(e)=>{let t=new Uint8Array(e);do crypto.getRandomValues(t);while(t.every((n)=>n===0));return Array.from(t,(n)=>n.toString(16).padStart(2,"0")).join("")},Oe=(e)=>{if(typeof e!=="object"||e===null)return!1;let{traceId:t,spanId:n,traceFlags:r}=e;return typeof t==="string"&&Te.test(t)&&t!==xe&&typeof n==="string"&&Ce.test(n)&&n!==Re&&typeof r==="number"},Ne=Symbol.for("opentelemetry.js.api.1"),ke=Symbol.for("OpenTelemetry Context Key SPAN"),Le=()=>{try{let r=globalThis[Ne]?.context?.active?.()?.getValue?.(ke)?.spanContext?.();return Oe(r)?r:void 0}catch{return}},Me=(e)=>{let t=(e.traceFlags&255).toString(16).padStart(2,"0");return`00-${e.traceId}-${e.spanId}-${t}`},De=(e)=>{try{return e.traceState?.serialize()||void 0}catch{return}},ne=(e)=>{let t=()=>({traceId:te(16),spanId:te(8),traceFlags:e.sampledFlag?1:0});return{forRequest(){let n=Le()??t(),r={traceparent:Me(n)},s=De(n);if(s)r.tracestate=s;return{headers:r,traceId:n.traceId,spanId:n.spanId}}}};var T="@sazabi/browser",I="0.2.0";var Pe={DEBUG:5,INFO:9,WARN:13,ERROR:17},He=1024,Ve=(e)=>{if(typeof e==="boolean")return{boolValue:e};if(typeof e==="number")return Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e};return{stringValue:v(e)}},re=(e)=>{let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;t.push({key:n,value:Ve(r)})}return t},oe=(e,t)=>{let n={timeUnixNano:`${e.timeUnixMs}000000`,severityNumber:Pe[e.severity],severityText:e.severity,body:{stringValue:v(e.body,He)},attributes:re({...t,...e.attributes})};if(e.traceId)n.traceId=e.traceId;if(e.spanId)n.spanId=e.spanId;return n},ie=(e)=>{let t=[],n=0,r,s=!1,o=(d)=>JSON.stringify({resourceLogs:[{resource:{attributes:re(e.resourceAttributes)},scopeLogs:[{scope:{name:T,version:I},logRecords:d}]}]}),i=o([]).length+64,c=Math.max(4096,e.maxBatchBytes-i),m=()=>{if(r!==void 0)window.clearTimeout(r),r=void 0},y=()=>{if(r!==void 0||s)return;r=window.setTimeout(()=>{r=void 0,u()},e.flushIntervalMs)},a=()=>{let d=[],l=[],f=0;for(let g of t){if(l.length>0&&f+g.bytes>c)d.push(l),l=[],f=0;l.push(g.record),f+=g.bytes}if(l.length>0)d.push(l);return t.length=0,n=0,d},u=async(d)=>{if(m(),t.length===0)return;let l=a().map((f)=>e.fetchImpl(e.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.publicKey}`},body:o(f),keepalive:d?.keepalive===!0}).catch(()=>{}));await Promise.all(l)};return{enqueue(d){if(s)return;let l=JSON.stringify(d).length+1;t.push({record:d,bytes:l}),n+=l;while(t.length>e.maxQueuedEvents){let f=t.shift();if(f)n-=f.bytes}if(n>=c)u();else y()},flush:u,async shutdown(){s=!0,await u()}}};var Ue=5000,Ke=57344,$e=500,We=["x-request-id","cf-ray","x-vercel-id","x-amz-cf-id","fly-request-id"],E,O=!1,A,C=!1,se=(e)=>{let t=window.fetch.bind(window),n=e.intakeHost.replace(/\/+$/,""),r=`${n}/v1/logs`,s=ee();if(C)s.reset(),C=!1;let o=A;if(A=void 0,o)s.setDistinctId(o.distinctId);let i=ie({url:r,publicKey:e.publicKey,resourceAttributes:{"service.name":e.serviceName,"service.version":e.serviceVersion,"deployment.environment":e.environment,"telemetry.sdk.name":T,"telemetry.sdk.version":I,"telemetry.sdk.language":"webjs","browser.user_agent":navigator.userAgent,"browser.language":navigator.language},fetchImpl:t,flushIntervalMs:e.flushIntervalMs??Ue,maxBatchBytes:e.maxBatchBytes??Ke,maxQueuedEvents:e.maxQueuedEvents??$e}),c=(p)=>{try{s.touch();let b={"web.event_type":p.type,"session.id":s.getSessionId(),"session.window_id":s.getWindowId(),"session.distinct_id":s.getDistinctId(),"web.page.url":window.location.href,"derived.source":"sdk"};i.enqueue(oe(p,b))}catch{}},m=(p)=>p.startsWith(n),y=(p)=>{try{c(p())}catch{}},a=[],u=U({emit:c});a.push(()=>u.teardown());let d=j({emit:c});a.push(()=>d.teardown());let l;if(e.input?.capture!==!1)l=X({emit:c}),a.push(()=>l?.teardown());let f=ce({emit:c,onNavigate:()=>{d.notifyNavigation(),l?.notifyNavigation()}});if(a.push(()=>f.teardown()),e.console?.capture!==!1){let p=V({emit:c,levels:e.console?.levels??["error","warn"]});a.push(()=>p.teardown())}let g=e.network??{},S=g.capture??!0,N=g.propagateTraceContext??!0;if(S||N){let p=le({emit:c,traceContext:ne({sampledFlag:g.sampledFlag??!1}),capture:S,propagateTraceContext:N,allowlist:g.allowlist??[],requestIdHeaders:g.requestIdHeaders??We,isInternalUrl:m});a.push(()=>p.teardown())}if(S&&g.resourceFallback!==!1){let p=Q({emit:c,isInternalUrl:m,isInjectionTarget:ue});a.push(()=>p.teardown())}let k=()=>{if(document.visibilityState==="hidden")i.flush({keepalive:!0})},L=()=>{i.flush({keepalive:!0})};if(document.addEventListener("visibilitychange",k),window.addEventListener("pagehide",L),a.push(()=>{document.removeEventListener("visibilitychange",k),window.removeEventListener("pagehide",L)}),E={identify(p,b){y(()=>(s.setDistinctId(p),{type:"custom",body:`identify ${p}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.custom.name":"identify",...b?h(b,"custom"):{}}}))},reset(){try{s.reset()}catch{}},addEvent(p,b){y(()=>({type:"custom",body:`custom ${p}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.custom.name":p,...b?h(b,"custom"):{}}}))},log(p,b,M){y(()=>({type:"log",body:b,severity:p,timeUnixMs:Date.now(),attributes:M?h(M):{}}))},flush(){return i.flush()},async shutdown(){for(let p of a.reverse())try{p()}catch{}de(),ae(),await i.shutdown()}},o)E.identify(o.distinctId,o.traits)},ht=(e)=>{if(typeof window>"u")return;if(O)return;if(O=!0,!e.publicKey||!e.intakeHost||!e.serviceName){console.warn("[@sazabi/browser] init() requires publicKey, intakeHost, and serviceName; SDK disabled.");return}if(e.consent===void 0){se(e);return}try{Promise.resolve(e.consent()).then((t)=>{if(t===!0)se(e)}).catch(()=>{})}catch{}},It=(e,t)=>{if(E)E.identify(e,t);else A={distinctId:e,traits:t}},At=()=>{if(E)E.reset();else C=!0,A=void 0},_t=(e,t)=>{E?.addEvent(e,t)},Tt=(e,t,n)=>{E?.log(e,t,n)},Ct=async()=>{await E?.flush()},xt=async()=>{let e=E;E=void 0,O=!1,A=void 0,C=!1,await e?.shutdown()};export{I as SDK_VERSION,_t as addEvent,Ct as flush,It as identify,ht as init,Tt as log,At as reset,xt as shutdown};
|
|
1
|
+
import{a as P,b as H,d as ce,e as ue,f as q,g as J,h as de,i as Q,k as le,l as pe}from"./chunk-rfm4nnme.js";var v=(e,t=4096)=>e.length>t?e.slice(0,t):e,I=(e,t="",n=0)=>{let r={};for(let[s,o]of Object.entries(e)){let i=t?`${t}.${s}`:s;if(o===null||o===void 0)continue;if(typeof o==="object"&&!Array.isArray(o)&&n<4){Object.assign(r,I(o,i,n+1));continue}if(typeof o==="number"||typeof o==="boolean")r[i]=o;else if(typeof o==="string")r[i]=v(o);else try{r[i]=v(JSON.stringify(o)??"")}catch{}}return r};var R="[@sazabi/browser]",fe={error:"ERROR",warn:"WARN",info:"INFO",debug:"DEBUG"},U=1000,me=4000,ge=(e)=>{let t;if(typeof e==="string")t=e;else if(e instanceof Error)t=`${e.name}: ${e.message}`;else try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>U?`${t.slice(0,U)}…`:t},K=(e)=>{let t=[],n=!1;for(let r of e.levels){let s=console[r];if(typeof s!=="function"||H(s))continue;let o=function(...i){if(s.apply(this??console,i),n)return;try{if(typeof i[0]==="string"&&i[0].startsWith(R))return;n=!0;let c=i.map(ge).join(" ").slice(0,me);e.emit({type:"log",body:c||`console.${r}`,severity:fe[r],timeUnixMs:Date.now(),attributes:{"web.console.level":r}})}catch{}finally{n=!1}};P(o),console[r]=o,t.push(()=>{if(console[r]===o)console[r]=s})}return{teardown(){for(let r of t)try{r()}catch{}}}};var V=(e)=>{let t=(r)=>{try{let s=r.error,o=s instanceof Error?s.name:"Error",i=r.message||"Unknown error";e.emit({type:"error",body:v(`${o}: ${i}`,512),severity:"ERROR",timeUnixMs:Date.now(),attributes:{"exception.type":o,"exception.message":i,"exception.stacktrace":s instanceof Error?s.stack??"":"","web.error.kind":"uncaught","web.error.filename":r.filename||void 0,"web.error.lineno":r.lineno||void 0,"web.error.colno":r.colno||void 0}})}catch{}},n=(r)=>{try{let s=r.reason,o=s instanceof Error,i=o?s.name:"UnhandledRejection",c=o?s.message:String(s);e.emit({type:"error",body:v(`${i}: ${c}`,512),severity:"ERROR",timeUnixMs:Date.now(),attributes:{"exception.type":i,"exception.message":c,"exception.stacktrace":o?s.stack??"":"","web.error.kind":"unhandledrejection"}})}catch{}};return window.addEventListener("error",t),window.addEventListener("unhandledrejection",n),{teardown(){window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",n)}}};var ye=["button","a[href]","summary",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="option"]','[role="checkbox"]','[role="switch"]','input[type="submit"]','input[type="button"]','input[type="reset"]'].join(","),w=(e)=>{if(!e)return;let t=e.replace(/\s+/g," ").trim();if(!t)return;return t.length>64?`${t.slice(0,64)}…`:t},W=(e)=>{try{return e.closest("[data-sazabi-mask]")!==null}catch{return!0}},F=(e)=>{let t=w(e.getAttribute("data-sazabi-name"));if(t)return t;let n=w(e.getAttribute("aria-label"));if(n)return n;let r=e.getAttribute("aria-labelledby");if(!r)return;return w(r.split(/\s+/).map((s)=>document.getElementById(s)?.textContent??"").join(" "))},G=(e)=>{try{if(W(e))return;let t=F(e);if(t)return t;if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)for(let r of Array.from(e.labels??[])){let s=w(r.textContent);if(s)return s}let n=w(e.getAttribute("placeholder"));if(n)return n;return w(e.getAttribute("name"))}catch{return}},B=(e)=>{try{let t=e.closest(ye);if(!t||W(t))return;let n=F(t);if(n)return n;if(t instanceof HTMLInputElement)return w(t.getAttribute("value"));return w(t.textContent)}catch{return}};var Y=1000,j=30,Ee=4,be=800,ve=200,we="a,button,[role=button],input,select,textarea,label,summary,[tabindex],[onclick]",O=(e)=>{let t=e.getAttribute("data-testid");if(t)return`[data-testid="${t}"]`;if(e.id)return`#${e.id}`;let n=[],r=e;while(r&&n.length<3){let s=r.tagName.toLowerCase();if(r.id){n.unshift(`#${r.id}`);break}let o=Array.from(r.classList).slice(0,2);if(o.length>0)s+=`.${o.join(".")}`;n.unshift(s),r=r.parentElement}return n.join(" > ").slice(0,ve)},X=(e)=>{let t=0,n=0,r=[],s=Number.NEGATIVE_INFINITY,o=new Set,i=new MutationObserver(()=>{t+=1});try{i.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0})}catch{}let c=(m)=>{try{let y=m.target;if(!(y instanceof Element))return;let a=performance.now(),u=O(y),d=y.tagName.toLowerCase(),l=B(y);e.emit({type:"click",body:l?`click "${l}"`:`click ${u}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l}}),r.push({time:a,x:m.clientX,y:m.clientY});while(r.length>0&&a-r[0].time>Y)r.shift();let f=r.filter((g)=>Math.abs(g.x-m.clientX)<=j&&Math.abs(g.y-m.clientY)<=j);if(f.length>=Ee&&a-s>Y)s=a,e.emit({type:"rage_click",body:l?`rage click "${l}"`:`rage click ${u}`,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l,"web.click_count":f.length}});if(y.closest(we)){let g=t,S=n,h=window.setTimeout(()=>{o.delete(h);try{if(t===g&&n===S)e.emit({type:"dead_click",body:l?`dead click "${l}"`:`dead click ${u}`,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l}})}catch{}},be);o.add(h)}}catch{}};return document.addEventListener("click",c,{capture:!0,passive:!0}),{notifyNavigation(){n+=1},teardown(){document.removeEventListener("click",c,{capture:!0}),i.disconnect();for(let m of o)window.clearTimeout(m);o.clear()}}};var Se=1e4,he=20,Ie=new Set(["button","submit","reset","image","checkbox","radio","range","file","color"]),Ae=(e)=>{if(e instanceof HTMLInputElement){let t=(e.type||"text").toLowerCase();return Ie.has(t)?void 0:t}if(e instanceof HTMLTextAreaElement)return"textarea";if(e instanceof HTMLSelectElement)return"select";if(e instanceof HTMLElement&&e.isContentEditable)return"contenteditable";return},z=(e)=>{let t=new Map,n=(a,u)=>{t.delete(a.element);try{e.emit({type:"input",body:a.name?`input "${a.name}"`:`input ${a.selector}`,severity:"INFO",timeUnixMs:a.startUnixMs,attributes:{"web.element.selector":a.selector,"web.element.name":a.name,"web.input.field_type":a.fieldType,"web.input.edit_count":a.editCount,"web.input.duration_ms":Math.max(0,Math.round(a.lastInputPerf-a.startPerf)),...a.pasted?{"web.input.pasted":!0}:{},"web.input.ended_by":u}})}catch{}},r=(a)=>{for(let u of Array.from(t.values()))n(u,a)},s=(a)=>{for(let u of Array.from(t.values()))if(a-u.lastInputPerf>Se)n(u,"idle")},o=(a)=>{try{let u=performance.now();s(u);let d=a.target,l=Ae(d);if(l===void 0||!(d instanceof Element))return;if(a.type==="change"&&l!=="select")return;let f=t.get(d);if(!f){if(t.size>=he)return;f={element:d,selector:O(d),name:G(d),fieldType:l,startUnixMs:Date.now(),startPerf:u,lastInputPerf:u,editCount:0,pasted:!1},t.set(d,f)}f.editCount+=1,f.lastInputPerf=u;let g=a.inputType;if(typeof g==="string"&&g.startsWith("insertFromPaste"))f.pasted=!0;if(a.type==="change"&&l==="select")n(f,"change")}catch{}},i=(a)=>{try{let u=a.target;if(u instanceof Element){let d=t.get(u);if(d)n(d,"blur")}}catch{}},c=(a)=>{try{if(a.key!=="Enter")return;let u=a.target;if(u instanceof Element){let d=t.get(u);if(d)n(d,"enter")}}catch{}},m=()=>{if(document.visibilityState==="hidden")r("hidden")},y=()=>{r("unload")};return document.addEventListener("input",o,{capture:!0,passive:!0}),document.addEventListener("change",o,{capture:!0,passive:!0}),document.addEventListener("focusout",i,{capture:!0,passive:!0}),document.addEventListener("keydown",c,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",m),window.addEventListener("pagehide",y),{notifyNavigation(){r("navigation")},teardown(){document.removeEventListener("input",o,{capture:!0}),document.removeEventListener("change",o,{capture:!0}),document.removeEventListener("focusout",i,{capture:!0}),document.removeEventListener("keydown",c,{capture:!0}),document.removeEventListener("visibilitychange",m),window.removeEventListener("pagehide",y),r("unload")}}};var _e=/^([0-9a-f]{32})\./,Te=/^[a-z0-9-]+?-([0-9a-f]{32})\./,xe=(e)=>{let t;try{t=new URL(e).hostname}catch{return}let n=(_e.exec(t)??Te.exec(t))?.[1];return n?`sazabi_public_${n}`:void 0};var Ce=(e)=>{let t;try{t=new URL(e)}catch{return}if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=t.pathname.replace(/\/+$/,"");if(n.endsWith("/v1/logs"))n=n.slice(0,-8);return`${t.origin}${n}`},N=(e)=>{let t=e.intakeUrl??e.intakeHost;if(!t)return;let n=Ce(t);if(!n)return;let r=e.publicKey??xe(t);if(!r)return;return{baseUrl:n,publicKey:r}};var Z=(e)=>{if(typeof PerformanceObserver>"u")return{teardown(){}};let t=new Set,n=(o)=>{let i;try{i=new URL(o).origin}catch{return}if(t.has(i))return;t.add(i);let c=`requests to ${i} bypass SDK instrumentation (fetch/XHR captured pre-init). Fix: import "@sazabi/browser/register" first.`;e.emit({type:"log",body:c,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.sdk.diagnostic":"instrumentation_gap","web.sdk.bypassed_origin":i}});try{console.warn(`${R} ${c}`)}catch{}},r=(o)=>{try{if(o.initiatorType!=="fetch"&&o.initiatorType!=="xmlhttprequest")return;let i=o.name;if(e.isInternalUrl(i))return;if(Q(i,o.startTime))return;let c=o.responseStatus??0,m=Math.round(performance.timeOrigin+o.startTime+o.duration);if(e.emit({type:"network",body:`request ${q(i)} → ${c>0?c:"observed"}`,severity:c>0?J(c):"INFO",timeUnixMs:m,attributes:{"http.response.status_code":c>0?c:void 0,"url.full":i,"web.network.kind":o.initiatorType==="fetch"?"fetch":"xhr","web.network.duration_ms":Math.round(o.duration),"web.network.source":"resource-timing"}}),e.isInjectionTarget(i))n(i)}catch{}},s;try{s=new PerformanceObserver((o)=>{for(let i of o.getEntries())r(i)}),s.observe({type:"resource",buffered:!0})}catch{return{teardown(){}}}return{teardown(){try{s.disconnect()}catch{}}}};var Re=()=>{let e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join("")},T=(e)=>`${e}_${Date.now().toString(36)}${Re()}`,ee=(e)=>{let t=new Map;return{get(n){try{return e().getItem(n)}catch{return t.get(n)??null}},set(n,r){try{e().setItem(n,r)}catch{t.set(n,r)}},remove(n){t.delete(n);try{e().removeItem(n)}catch{}}}},Oe=(e)=>{if(!e)return;try{let t=JSON.parse(e);if(typeof t==="object"&&t!==null&&typeof t.id==="string"&&typeof t.startedAt==="number"&&typeof t.lastActivityAt==="number")return t}catch{}return},te=()=>{let e=ee(()=>window.localStorage),t=ee(()=>window.sessionStorage),n=0,r=()=>{let i=Date.now(),c=Oe(e.get("sazabi.session"));if(c&&i-c.lastActivityAt<=1800000&&i-c.startedAt<=86400000)return c;let m={id:T("sess"),startedAt:i,lastActivityAt:i};return e.set("sazabi.session",JSON.stringify(m)),n=i,m},s=t.get("sazabi.windowId");if(!s)s=T("win"),t.set("sazabi.windowId",s);let o=()=>{let i=Date.now();e.set("sazabi.session",JSON.stringify({id:T("sess"),startedAt:i,lastActivityAt:i})),n=i,s=T("win"),t.set("sazabi.windowId",s)};return{getSessionId(){return r().id},getWindowId(){return s},getDistinctId(){return e.get("sazabi.distinctId")??void 0},setDistinctId(i){let c=e.get("sazabi.distinctId")??void 0;if(c!==void 0&&c!==i)o();e.set("sazabi.distinctId",i)},reset(){e.remove("sazabi.distinctId"),o()},touch(){let i=Date.now(),c=r();if(i-n>=5000)e.set("sazabi.session",JSON.stringify({...c,lastActivityAt:i})),n=i}}};var Ne=/^[0-9a-f]{32}$/,ke=/^[0-9a-f]{16}$/,Le="0".repeat(32),Me="0".repeat(16),ne=(e)=>{let t=new Uint8Array(e);do crypto.getRandomValues(t);while(t.every((n)=>n===0));return Array.from(t,(n)=>n.toString(16).padStart(2,"0")).join("")},De=(e)=>{if(typeof e!=="object"||e===null)return!1;let{traceId:t,spanId:n,traceFlags:r}=e;return typeof t==="string"&&Ne.test(t)&&t!==Le&&typeof n==="string"&&ke.test(n)&&n!==Me&&typeof r==="number"},Ue=Symbol.for("opentelemetry.js.api.1"),Pe=Symbol.for("OpenTelemetry Context Key SPAN"),He=()=>{try{let r=globalThis[Ue]?.context?.active?.()?.getValue?.(Pe)?.spanContext?.();return De(r)?r:void 0}catch{return}},Ke=(e)=>{let t=(e.traceFlags&255).toString(16).padStart(2,"0");return`00-${e.traceId}-${e.spanId}-${t}`},Ve=(e)=>{try{return e.traceState?.serialize()||void 0}catch{return}},re=(e)=>{let t=()=>({traceId:ne(16),spanId:ne(8),traceFlags:e.sampledFlag?1:0});return{forRequest(){let n=He()??t(),r={traceparent:Ke(n)},s=Ve(n);if(s)r.tracestate=s;return{headers:r,traceId:n.traceId,spanId:n.spanId}}}};var x="@sazabi/browser",A="0.2.0";var $e={DEBUG:5,INFO:9,WARN:13,ERROR:17},We=1024,Fe=(e)=>{if(typeof e==="boolean")return{boolValue:e};if(typeof e==="number")return Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e};return{stringValue:v(e)}},oe=(e)=>{let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;t.push({key:n,value:Fe(r)})}return t},ie=(e,t)=>{let n={timeUnixNano:`${e.timeUnixMs}000000`,severityNumber:$e[e.severity],severityText:e.severity,body:{stringValue:v(e.body,We)},attributes:oe({...t,...e.attributes})};if(e.traceId)n.traceId=e.traceId;if(e.spanId)n.spanId=e.spanId;return n},se=(e)=>{let t=[],n=0,r,s=!1,o=(d)=>JSON.stringify({resourceLogs:[{resource:{attributes:oe(e.resourceAttributes)},scopeLogs:[{scope:{name:x,version:A},logRecords:d}]}]}),i=o([]).length+64,c=Math.max(4096,e.maxBatchBytes-i),m=()=>{if(r!==void 0)window.clearTimeout(r),r=void 0},y=()=>{if(r!==void 0||s)return;r=window.setTimeout(()=>{r=void 0,u()},e.flushIntervalMs)},a=()=>{let d=[],l=[],f=0;for(let g of t){if(l.length>0&&f+g.bytes>c)d.push(l),l=[],f=0;l.push(g.record),f+=g.bytes}if(l.length>0)d.push(l);return t.length=0,n=0,d},u=async(d)=>{if(m(),t.length===0)return;let l=a().map((f)=>e.fetchImpl(e.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.publicKey}`},body:o(f),keepalive:d?.keepalive===!0}).catch(()=>{}));await Promise.all(l)};return{enqueue(d){if(s)return;let l=JSON.stringify(d).length+1;t.push({record:d,bytes:l}),n+=l;while(t.length>e.maxQueuedEvents){let f=t.shift();if(f)n-=f.bytes}if(n>=c)u();else y()},flush:u,async shutdown(){s=!0,await u()}}};var Ge=5000,Be=57344,Ye=500,je=["x-request-id","cf-ray","x-vercel-id","x-amz-cf-id","fly-request-id"],E,k=!1,_,C=!1,ae=(e)=>{let t=window.fetch.bind(window),n=N(e);if(!n)return;let r=`${n.baseUrl}/v1/logs`,s=te();if(C)s.reset(),C=!1;let o=_;if(_=void 0,o)s.setDistinctId(o.distinctId);let i=se({url:r,publicKey:n.publicKey,resourceAttributes:{"service.name":e.serviceName,"service.version":e.serviceVersion,"deployment.environment":e.environment,"telemetry.sdk.name":x,"telemetry.sdk.version":A,"telemetry.sdk.language":"webjs","browser.user_agent":navigator.userAgent,"browser.language":navigator.language},fetchImpl:t,flushIntervalMs:e.flushIntervalMs??Ge,maxBatchBytes:e.maxBatchBytes??Be,maxQueuedEvents:e.maxQueuedEvents??Ye}),c=(p)=>{try{s.touch();let b={"web.event_type":p.type,"session.id":s.getSessionId(),"session.window_id":s.getWindowId(),"session.distinct_id":s.getDistinctId(),"web.page.url":window.location.href,"derived.source":"sdk"};i.enqueue(ie(p,b))}catch{}},m=(p)=>p.startsWith(n.baseUrl),y=(p)=>{try{c(p())}catch{}},a=[],u=V({emit:c});a.push(()=>u.teardown());let d=X({emit:c});a.push(()=>d.teardown());let l;if(e.input?.capture!==!1)l=z({emit:c}),a.push(()=>l?.teardown());let f=ue({emit:c,onNavigate:()=>{d.notifyNavigation(),l?.notifyNavigation()}});if(a.push(()=>f.teardown()),e.console?.capture!==!1){let p=K({emit:c,levels:e.console?.levels??["error","warn"]});a.push(()=>p.teardown())}let g=e.network??{},S=g.capture??!0,h=g.propagateTraceContext??!0;if(S||h){let p=pe({emit:c,traceContext:re({sampledFlag:g.sampledFlag??!1}),capture:S,propagateTraceContext:h,allowlist:g.allowlist??[],requestIdHeaders:g.requestIdHeaders??je,isInternalUrl:m});a.push(()=>p.teardown())}if(S&&g.resourceFallback!==!1){let p=Z({emit:c,isInternalUrl:m,isInjectionTarget:de});a.push(()=>p.teardown())}let L=()=>{if(document.visibilityState==="hidden")i.flush({keepalive:!0})},M=()=>{i.flush({keepalive:!0})};if(document.addEventListener("visibilitychange",L),window.addEventListener("pagehide",M),a.push(()=>{document.removeEventListener("visibilitychange",L),window.removeEventListener("pagehide",M)}),E={identify(p,b){y(()=>(s.setDistinctId(p),{type:"custom",body:`identify ${p}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.custom.name":"identify",...b?I(b,"custom"):{}}}))},reset(){try{s.reset()}catch{}},addEvent(p,b){y(()=>({type:"custom",body:`custom ${p}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.custom.name":p,...b?I(b,"custom"):{}}}))},log(p,b,D){y(()=>({type:"log",body:b,severity:p,timeUnixMs:Date.now(),attributes:D?I(D):{}}))},flush(){return i.flush()},async shutdown(){for(let p of a.reverse())try{p()}catch{}le(),ce(),await i.shutdown()}},o)E.identify(o.distinctId,o.traits)},Rt=(e)=>{if(typeof window>"u")return;if(k)return;if(k=!0,!e.serviceName||!N(e)){console.warn("[@sazabi/browser] init() requires intakeUrl and serviceName; SDK disabled. Pass publicKey too if the intake URL is a proxy that carries no key.");return}if(e.consent===void 0){ae(e);return}try{Promise.resolve(e.consent()).then((t)=>{if(t===!0)ae(e)}).catch(()=>{})}catch{}},Ot=(e,t)=>{if(E)E.identify(e,t);else _={distinctId:e,traits:t}},Nt=()=>{if(E)E.reset();else C=!0,_=void 0},kt=(e,t)=>{E?.addEvent(e,t)},Lt=(e,t,n)=>{E?.log(e,t,n)},Mt=async()=>{await E?.flush()},Dt=async()=>{let e=E;E=void 0,k=!1,_=void 0,C=!1,await e?.shutdown()};export{A as SDK_VERSION,kt as addEvent,Mt as flush,Ot as identify,Rt as init,Lt as log,Nt as reset,Dt as shutdown};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=091BD9F6835879A764756E2164756E21
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/attributes.ts", "../src/console.ts", "../src/errors.ts", "../src/element-name.ts", "../src/interactions.ts", "../src/input-capture.ts", "../src/resource-observer.ts", "../src/session.ts", "../src/trace-context.ts", "../src/version.ts", "../src/transport.ts", "../src/index.ts"],
|
|
3
|
+
"sources": ["../src/attributes.ts", "../src/console.ts", "../src/errors.ts", "../src/element-name.ts", "../src/interactions.ts", "../src/input-capture.ts", "../src/intake-url.ts", "../src/resource-observer.ts", "../src/session.ts", "../src/trace-context.ts", "../src/version.ts", "../src/transport.ts", "../src/index.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import type { EventAttributes } from \"./types\";\n\nconst MAX_VALUE_LENGTH = 4096;\nconst MAX_FLATTEN_DEPTH = 4;\n\nexport const truncateValue = (value: string, max = MAX_VALUE_LENGTH): string =>\n value.length > max ? value.slice(0, max) : value;\n\n/**\n * Flatten nested metadata into dot-keyed scalar attributes. Non-scalar leaves\n * are JSON-stringified; strings are length-capped so a hostile or buggy page\n * cannot inflate rows.\n */\nexport const flattenAttributes = (\n input: Record<string, unknown>,\n prefix = \"\",\n depth = 0,\n): EventAttributes => {\n const result: EventAttributes = {};\n\n for (const [key, rawValue] of Object.entries(input)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (rawValue === null || rawValue === undefined) {\n continue;\n }\n\n if (\n typeof rawValue === \"object\" &&\n !Array.isArray(rawValue) &&\n depth < MAX_FLATTEN_DEPTH\n ) {\n Object.assign(\n result,\n flattenAttributes(\n rawValue as Record<string, unknown>,\n fullKey,\n depth + 1,\n ),\n );\n continue;\n }\n\n if (typeof rawValue === \"number\" || typeof rawValue === \"boolean\") {\n result[fullKey] = rawValue;\n } else if (typeof rawValue === \"string\") {\n result[fullKey] = truncateValue(rawValue);\n } else {\n try {\n result[fullKey] = truncateValue(JSON.stringify(rawValue) ?? \"\");\n } catch {\n // Circular or unserializable — drop rather than throw into the host.\n }\n }\n }\n\n return result;\n};\n",
|
|
6
6
|
"import { isWrapped, markWrapped } from \"./patch-marker\";\nimport type { ConsoleCaptureLevel, EventSeverity, WebEvent } from \"./types\";\n\nexport interface ConsoleCaptureOptions {\n emit(event: WebEvent): void;\n levels: ConsoleCaptureLevel[];\n}\n\nexport interface ConsoleCaptureHandle {\n teardown(): void;\n}\n\n/** SDK-emitted console lines carry this prefix and are never re-captured. */\nexport const SDK_CONSOLE_PREFIX = \"[@sazabi/browser]\";\n\nconst SEVERITY_BY_LEVEL: Record<ConsoleCaptureLevel, EventSeverity> = {\n error: \"ERROR\",\n warn: \"WARN\",\n info: \"INFO\",\n debug: \"DEBUG\",\n};\n\nconst MAX_ARG_CHARS = 1_000;\nconst MAX_BODY_CHARS = 4_000;\n\nconst stringifyArg = (value: unknown): string => {\n let text: string;\n if (typeof value === \"string\") {\n text = value;\n } else if (value instanceof Error) {\n text = `${value.name}: ${value.message}`;\n } else {\n try {\n text = JSON.stringify(value) ?? String(value);\n } catch {\n text = String(value);\n }\n }\n return text.length > MAX_ARG_CHARS\n ? `${text.slice(0, MAX_ARG_CHARS)}…`\n : text;\n};\n\n/**\n * Mirror selected console levels into the event stream as `log` events.\n * The original console method always runs first — devtools behavior is never\n * altered — and capture failures are swallowed. Lines the SDK itself prints\n * (prefixed with SDK_CONSOLE_PREFIX) are skipped to avoid self-capture.\n */\nexport const installConsoleCapture = (\n options: ConsoleCaptureOptions,\n): ConsoleCaptureHandle => {\n const restores: Array<() => void> = [];\n let emitting = false;\n\n for (const level of options.levels) {\n const original = console[level];\n if (typeof original !== \"function\" || isWrapped(original)) {\n continue;\n }\n\n const wrapped = function (this: unknown, ...args: unknown[]): void {\n original.apply(this ?? console, args);\n if (emitting) return;\n try {\n if (\n typeof args[0] === \"string\" &&\n args[0].startsWith(SDK_CONSOLE_PREFIX)\n ) {\n return;\n }\n emitting = true;\n const body = args.map(stringifyArg).join(\" \").slice(0, MAX_BODY_CHARS);\n options.emit({\n type: \"log\",\n body: body || `console.${level}`,\n severity: SEVERITY_BY_LEVEL[level],\n timeUnixMs: Date.now(),\n attributes: {\n \"web.console.level\": level,\n },\n });\n } catch {\n // Capture failures must never surface to the host.\n } finally {\n emitting = false;\n }\n };\n\n markWrapped(wrapped);\n console[level] = wrapped as typeof original;\n restores.push(() => {\n if (console[level] === wrapped) {\n console[level] = original;\n }\n });\n }\n\n return {\n teardown() {\n for (const restore of restores) {\n try {\n restore();\n } catch {\n // Best-effort restore.\n }\n }\n },\n };\n};\n",
|
|
7
7
|
"import { truncateValue } from \"./attributes\";\nimport type { WebEvent } from \"./types\";\n\nexport interface ErrorCaptureOptions {\n emit(event: WebEvent): void;\n}\n\nexport interface ErrorCaptureHandle {\n teardown(): void;\n}\n\nexport const installErrorCapture = (\n options: ErrorCaptureOptions,\n): ErrorCaptureHandle => {\n const onError = (event: ErrorEvent): void => {\n try {\n const error: unknown = event.error;\n const exceptionType = error instanceof Error ? error.name : \"Error\";\n const message = event.message || \"Unknown error\";\n\n options.emit({\n type: \"error\",\n body: truncateValue(`${exceptionType}: ${message}`, 512),\n severity: \"ERROR\",\n timeUnixMs: Date.now(),\n attributes: {\n \"exception.type\": exceptionType,\n \"exception.message\": message,\n \"exception.stacktrace\":\n error instanceof Error ? (error.stack ?? \"\") : \"\",\n \"web.error.kind\": \"uncaught\",\n \"web.error.filename\": event.filename || undefined,\n \"web.error.lineno\": event.lineno || undefined,\n \"web.error.colno\": event.colno || undefined,\n },\n });\n } catch {\n // Capture failures must never surface to the host.\n }\n };\n\n const onUnhandledRejection = (event: PromiseRejectionEvent): void => {\n try {\n const reason: unknown = event.reason;\n const isError = reason instanceof Error;\n const exceptionType = isError ? reason.name : \"UnhandledRejection\";\n const message = isError ? reason.message : String(reason);\n\n options.emit({\n type: \"error\",\n body: truncateValue(`${exceptionType}: ${message}`, 512),\n severity: \"ERROR\",\n timeUnixMs: Date.now(),\n attributes: {\n \"exception.type\": exceptionType,\n \"exception.message\": message,\n \"exception.stacktrace\": isError ? (reason.stack ?? \"\") : \"\",\n \"web.error.kind\": \"unhandledrejection\",\n },\n });\n } catch {\n // Capture failures must never surface to the host.\n }\n };\n\n window.addEventListener(\"error\", onError);\n window.addEventListener(\"unhandledrejection\", onUnhandledRejection);\n\n return {\n teardown() {\n window.removeEventListener(\"error\", onError);\n window.removeEventListener(\"unhandledrejection\", onUnhandledRejection);\n },\n };\n};\n",
|
|
8
8
|
"/**\n * Human-readable element names for timeline events — a pragmatic subset of\n * the ARIA accessible-name computation, biased hard toward developer-authored\n * sources. The bright line: app-authored static text (labels, aria-label,\n * placeholder, button captions) is capturable; user-reflected text (values,\n * selected options, data rendered into the DOM) is not. `data-sazabi-name`\n * overrides any element's reported name; `data-sazabi-mask` on an ancestor\n * suppresses name capture for the whole subtree.\n */\n\nconst MAX_NAME_CHARS = 64;\nconst NAME_ATTRIBUTE = \"data-sazabi-name\";\nconst MASK_ATTRIBUTE = \"data-sazabi-mask\";\n\n/**\n * Click-name eligibility: genuinely interactive elements only. Clicks on\n * plain containers (divs, table cells — where user content lives) get a\n * selector but never text.\n */\nconst INTERACTIVE_NAME_SELECTOR = [\n \"button\",\n \"a[href]\",\n \"summary\",\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"tab\"]',\n '[role=\"menuitem\"]',\n '[role=\"menuitemcheckbox\"]',\n '[role=\"menuitemradio\"]',\n '[role=\"option\"]',\n '[role=\"checkbox\"]',\n '[role=\"switch\"]',\n 'input[type=\"submit\"]',\n 'input[type=\"button\"]',\n 'input[type=\"reset\"]',\n].join(\",\");\n\nconst normalizeName = (raw: string | null | undefined): string | undefined => {\n if (!raw) return undefined;\n const collapsed = raw.replace(/\\s+/g, \" \").trim();\n if (!collapsed) return undefined;\n return collapsed.length > MAX_NAME_CHARS\n ? `${collapsed.slice(0, MAX_NAME_CHARS)}…`\n : collapsed;\n};\n\nconst isMasked = (element: Element): boolean => {\n try {\n return element.closest(`[${MASK_ATTRIBUTE}]`) !== null;\n } catch {\n return true; // Fail closed: no name beats a leaked name.\n }\n};\n\n/** Shared dev-authored sources: override attr → aria-label → aria-labelledby. */\nconst authoredName = (element: Element): string | undefined => {\n const explicit = normalizeName(element.getAttribute(NAME_ATTRIBUTE));\n if (explicit) return explicit;\n const ariaLabel = normalizeName(element.getAttribute(\"aria-label\"));\n if (ariaLabel) return ariaLabel;\n\n const ids = element.getAttribute(\"aria-labelledby\");\n if (!ids) return undefined;\n return normalizeName(\n ids\n .split(/\\s+/)\n .map((id) => document.getElementById(id)?.textContent ?? \"\")\n .join(\" \"),\n );\n};\n\n/**\n * Name for an input/textarea/select/contenteditable — developer-authored\n * sources only; the field's value and (for selects) the chosen option text\n * are never read.\n */\nexport const computeInputName = (element: Element): string | undefined => {\n try {\n if (isMasked(element)) return undefined;\n\n const named = authoredName(element);\n if (named) return named;\n\n if (\n element instanceof HTMLInputElement ||\n element instanceof HTMLTextAreaElement ||\n element instanceof HTMLSelectElement\n ) {\n for (const label of Array.from(element.labels ?? [])) {\n const labelText = normalizeName(label.textContent);\n if (labelText) return labelText;\n }\n }\n\n const placeholder = normalizeName(element.getAttribute(\"placeholder\"));\n if (placeholder) return placeholder;\n return normalizeName(element.getAttribute(\"name\"));\n } catch {\n return undefined;\n }\n};\n\n/**\n * Name for a click target: nearest interactive ancestor's accessible-ish\n * name. Residual risk is labels that interpolate user data (\"Delete 'My\n * Project'\") — that is app-authored markup, capped at 64 chars, and\n * suppressible via `data-sazabi-mask` / overridable via `data-sazabi-name`.\n */\nexport const computeClickName = (target: Element): string | undefined => {\n try {\n const interactive = target.closest(INTERACTIVE_NAME_SELECTOR);\n if (!interactive || isMasked(interactive)) return undefined;\n\n const named = authoredName(interactive);\n if (named) return named;\n\n if (interactive instanceof HTMLInputElement) {\n // submit/button/reset inputs: the value attribute IS the caption.\n return normalizeName(interactive.getAttribute(\"value\"));\n }\n return normalizeName(interactive.textContent);\n } catch {\n return undefined;\n }\n};\n",
|
|
9
|
-
"import { computeClickName } from \"./element-name\";\nimport type { WebEvent } from \"./types\";\n\nexport interface InteractionCaptureOptions {\n emit(event: WebEvent): void;\n}\n\nexport interface InteractionCaptureHandle {\n /** Navigation counts as a click response for dead-click detection. */\n notifyNavigation(): void;\n teardown(): void;\n}\n\nconst RAGE_WINDOW_MS = 1000;\nconst RAGE_RADIUS_PX = 30;\nconst RAGE_CLICK_COUNT = 4;\nconst DEAD_CLICK_TIMEOUT_MS = 800;\nconst MAX_SELECTOR_LENGTH = 200;\n\nconst INTERACTIVE_SELECTOR =\n \"a,button,[role=button],input,select,textarea,label,summary,[tabindex],[onclick]\";\n\n/** Short, stable-ish selector for an element; never includes text content. */\nexport const computeSelector = (element: Element): string => {\n const testId = element.getAttribute(\"data-testid\");\n if (testId) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id) {\n return `#${element.id}`;\n }\n\n const segments: string[] = [];\n let current: Element | null = element;\n while (current && segments.length < 3) {\n let segment = current.tagName.toLowerCase();\n if (current.id) {\n segments.unshift(`#${current.id}`);\n break;\n }\n const classes = Array.from(current.classList).slice(0, 2);\n if (classes.length > 0) {\n segment += `.${classes.join(\".\")}`;\n }\n segments.unshift(segment);\n current = current.parentElement;\n }\n return segments.join(\" > \").slice(0, MAX_SELECTOR_LENGTH);\n};\n\ninterface RecentClick {\n time: number;\n x: number;\n y: number;\n}\n\nexport const installInteractionCapture = (\n options: InteractionCaptureOptions,\n): InteractionCaptureHandle => {\n let
|
|
9
|
+
"import { computeClickName } from \"./element-name\";\nimport type { WebEvent } from \"./types\";\n\nexport interface InteractionCaptureOptions {\n emit(event: WebEvent): void;\n}\n\nexport interface InteractionCaptureHandle {\n /** Navigation counts as a click response for dead-click detection. */\n notifyNavigation(): void;\n teardown(): void;\n}\n\nconst RAGE_WINDOW_MS = 1000;\nconst RAGE_RADIUS_PX = 30;\nconst RAGE_CLICK_COUNT = 4;\nconst DEAD_CLICK_TIMEOUT_MS = 800;\nconst MAX_SELECTOR_LENGTH = 200;\n\nconst INTERACTIVE_SELECTOR =\n \"a,button,[role=button],input,select,textarea,label,summary,[tabindex],[onclick]\";\n\n/** Short, stable-ish selector for an element; never includes text content. */\nexport const computeSelector = (element: Element): string => {\n const testId = element.getAttribute(\"data-testid\");\n if (testId) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id) {\n return `#${element.id}`;\n }\n\n const segments: string[] = [];\n let current: Element | null = element;\n while (current && segments.length < 3) {\n let segment = current.tagName.toLowerCase();\n if (current.id) {\n segments.unshift(`#${current.id}`);\n break;\n }\n const classes = Array.from(current.classList).slice(0, 2);\n if (classes.length > 0) {\n segment += `.${classes.join(\".\")}`;\n }\n segments.unshift(segment);\n current = current.parentElement;\n }\n return segments.join(\" > \").slice(0, MAX_SELECTOR_LENGTH);\n};\n\ninterface RecentClick {\n time: number;\n x: number;\n y: number;\n}\n\nexport const installInteractionCapture = (\n options: InteractionCaptureOptions,\n): InteractionCaptureHandle => {\n // Monotonic counters, not timestamps. `performance.now()` is coarsened\n // (Chromium clamps it, and more so without cross-origin isolation), and the\n // click -> handler -> microtask -> MutationObserver path finishes well inside\n // one tick — measured 142/200 equal readings in the Chromium suite's own\n // environment. Any timestamp comparison therefore has to guess about\n // same-tick activity: `<=` called every snappy answered click dead, while `<`\n // let activity that merely *preceded* a click suppress a genuine dead one.\n // Counters captured at click time ask the exact question instead — \"did\n // anything happen after this click?\" — with no dependence on clock\n // resolution.\n let domActivityGeneration = 0;\n let navigationGeneration = 0;\n const recentClicks: RecentClick[] = [];\n // Not 0: performance.now() < 1s during early page life would read as\n // \"just reported\" and suppress a genuine first-second rage burst.\n let rageReportedAt = Number.NEGATIVE_INFINITY;\n const pendingDeadClickTimers = new Set<number>();\n\n const observer = new MutationObserver(() => {\n domActivityGeneration += 1;\n });\n try {\n observer.observe(document.documentElement, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n } catch {\n // Without mutation signal, dead clicks are simply never reported.\n }\n\n const onClick = (event: MouseEvent): void => {\n try {\n const target = event.target;\n if (!(target instanceof Element)) {\n return;\n }\n\n const now = performance.now();\n const selector = computeSelector(target);\n const tag = target.tagName.toLowerCase();\n const name = computeClickName(target);\n\n options.emit({\n type: \"click\",\n body: name ? `click \"${name}\"` : `click ${selector}`,\n severity: \"INFO\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.element.selector\": selector,\n \"web.element.tag\": tag,\n \"web.element.name\": name,\n },\n });\n\n // Rage click: repeated clicks in a tight radius within the window.\n recentClicks.push({ time: now, x: event.clientX, y: event.clientY });\n while (\n recentClicks.length > 0 &&\n now - (recentClicks[0] as RecentClick).time > RAGE_WINDOW_MS\n ) {\n recentClicks.shift();\n }\n const clustered = recentClicks.filter(\n (click) =>\n Math.abs(click.x - event.clientX) <= RAGE_RADIUS_PX &&\n Math.abs(click.y - event.clientY) <= RAGE_RADIUS_PX,\n );\n if (\n clustered.length >= RAGE_CLICK_COUNT &&\n now - rageReportedAt > RAGE_WINDOW_MS\n ) {\n rageReportedAt = now;\n options.emit({\n type: \"rage_click\",\n body: name ? `rage click \"${name}\"` : `rage click ${selector}`,\n severity: \"WARN\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.element.selector\": selector,\n \"web.element.tag\": tag,\n \"web.element.name\": name,\n \"web.click_count\": clustered.length,\n },\n });\n }\n\n // Dead click: an interactive target where nothing observable follows.\n if (target.closest(INTERACTIVE_SELECTOR)) {\n const domGenAtClick = domActivityGeneration;\n const navGenAtClick = navigationGeneration;\n const timer = window.setTimeout(() => {\n pendingDeadClickTimers.delete(timer);\n try {\n // Unchanged counters mean nothing observable followed the click.\n if (\n domActivityGeneration === domGenAtClick &&\n navigationGeneration === navGenAtClick\n ) {\n options.emit({\n type: \"dead_click\",\n body: name ? `dead click \"${name}\"` : `dead click ${selector}`,\n severity: \"WARN\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.element.selector\": selector,\n \"web.element.tag\": tag,\n \"web.element.name\": name,\n },\n });\n }\n } catch {\n // Never throw from a timer into the host.\n }\n }, DEAD_CLICK_TIMEOUT_MS);\n pendingDeadClickTimers.add(timer);\n }\n } catch {\n // Capture failures must never surface to the host.\n }\n };\n\n document.addEventListener(\"click\", onClick, { capture: true, passive: true });\n\n return {\n notifyNavigation() {\n navigationGeneration += 1;\n },\n teardown() {\n document.removeEventListener(\"click\", onClick, { capture: true });\n observer.disconnect();\n for (const timer of pendingDeadClickTimers) {\n window.clearTimeout(timer);\n }\n pendingDeadClickTimers.clear();\n },\n };\n};\n",
|
|
10
10
|
"import { computeInputName } from \"./element-name\";\nimport { computeSelector } from \"./interactions\";\nimport type { WebEvent } from \"./types\";\n\nexport interface InputCaptureOptions {\n emit(event: WebEvent): void;\n}\n\nexport interface InputCaptureHandle {\n /** SPA navigation ends any open episodes. */\n notifyNavigation(): void;\n teardown(): void;\n}\n\nconst IDLE_END_MS = 10_000;\nconst MAX_TRACKED_EPISODES = 20;\n\n/** Input types that are click-like toggles, not typing surfaces. */\nconst NON_TEXT_INPUT_TYPES = new Set([\n \"button\",\n \"submit\",\n \"reset\",\n \"image\",\n \"checkbox\",\n \"radio\",\n \"range\",\n \"file\",\n \"color\",\n]);\n\ntype EpisodeEndReason =\n | \"blur\"\n | \"enter\"\n | \"change\"\n | \"idle\"\n | \"navigation\"\n | \"hidden\"\n | \"unload\";\n\ninterface InputEpisode {\n element: Element;\n selector: string;\n name?: string;\n fieldType: string;\n startUnixMs: number;\n startPerf: number;\n lastInputPerf: number;\n editCount: number;\n pasted: boolean;\n}\n\nconst editableFieldType = (target: EventTarget | null): string | undefined => {\n if (target instanceof HTMLInputElement) {\n const type = (target.type || \"text\").toLowerCase();\n return NON_TEXT_INPUT_TYPES.has(type) ? undefined : type;\n }\n if (target instanceof HTMLTextAreaElement) return \"textarea\";\n if (target instanceof HTMLSelectElement) return \"select\";\n if (target instanceof HTMLElement && target.isContentEditable) {\n return \"contenteditable\";\n }\n return undefined;\n};\n\n/**\n * Field-interaction episodes: one `input` event per engagement with an\n * editable element, not per keystroke. The event is timestamped at episode\n * START (so the timeline reads causally: typed → the request that followed)\n * and emitted when the episode ends — blur, Enter, ~10s idle, SPA\n * navigation, tab hidden, or teardown.\n *\n * Privacy invariants: `event.data`, field values, selected option text, and\n * key identities are never read (Enter is inspected solely as a boundary and\n * never recorded); no value derivatives, including length. Names come from\n * developer-authored sources only (see element-name.ts).\n */\nexport const installInputCapture = (\n options: InputCaptureOptions,\n): InputCaptureHandle => {\n const episodes = new Map<Element, InputEpisode>();\n\n const endEpisode = (\n episode: InputEpisode,\n endedBy: EpisodeEndReason,\n ): void => {\n episodes.delete(episode.element);\n try {\n options.emit({\n type: \"input\",\n body: episode.name\n ? `input \"${episode.name}\"`\n : `input ${episode.selector}`,\n severity: \"INFO\",\n timeUnixMs: episode.startUnixMs,\n attributes: {\n \"web.element.selector\": episode.selector,\n \"web.element.name\": episode.name,\n \"web.input.field_type\": episode.fieldType,\n \"web.input.edit_count\": episode.editCount,\n \"web.input.duration_ms\": Math.max(\n 0,\n Math.round(episode.lastInputPerf - episode.startPerf),\n ),\n ...(episode.pasted ? { \"web.input.pasted\": true } : {}),\n \"web.input.ended_by\": endedBy,\n },\n });\n } catch {\n // Capture failures must never surface to the host.\n }\n };\n\n const endAll = (endedBy: EpisodeEndReason): void => {\n for (const episode of Array.from(episodes.values())) {\n endEpisode(episode, endedBy);\n }\n };\n\n const sweepIdle = (now: number): void => {\n for (const episode of Array.from(episodes.values())) {\n if (now - episode.lastInputPerf > IDLE_END_MS) {\n endEpisode(episode, \"idle\");\n }\n }\n };\n\n const onInput = (event: Event): void => {\n try {\n const now = performance.now();\n sweepIdle(now);\n\n const target = event.target;\n const fieldType = editableFieldType(target);\n if (fieldType === undefined || !(target instanceof Element)) {\n return;\n }\n // `change` matters only for selects (option committed): for text\n // fields it fires at commit time and would double-count the episode.\n if (event.type === \"change\" && fieldType !== \"select\") {\n return;\n }\n\n let episode = episodes.get(target);\n if (!episode) {\n if (episodes.size >= MAX_TRACKED_EPISODES) {\n return; // Safety valve; the idle sweep keeps this map tiny.\n }\n episode = {\n element: target,\n selector: computeSelector(target),\n name: computeInputName(target),\n fieldType,\n startUnixMs: Date.now(),\n startPerf: now,\n lastInputPerf: now,\n editCount: 0,\n pasted: false,\n };\n episodes.set(target, episode);\n }\n\n episode.editCount += 1;\n episode.lastInputPerf = now;\n // Only the paste marker is read off the event — never `data`/values.\n const inputType = (event as InputEvent).inputType;\n if (\n typeof inputType === \"string\" &&\n inputType.startsWith(\"insertFromPaste\")\n ) {\n episode.pasted = true;\n }\n\n // A select commits atomically on change; there is no blur to wait for\n // (programmatic/JS-driven selects never focus the element).\n if (event.type === \"change\" && fieldType === \"select\") {\n endEpisode(episode, \"change\");\n }\n } catch {\n // Capture failures must never surface to the host.\n }\n };\n\n const onFocusOut = (event: Event): void => {\n try {\n const target = event.target;\n if (target instanceof Element) {\n const episode = episodes.get(target);\n if (episode) endEpisode(episode, \"blur\");\n }\n } catch {\n // Ignore.\n }\n };\n\n const onKeyDown = (event: KeyboardEvent): void => {\n try {\n // Enter is the only key ever inspected, solely as an episode\n // boundary; key identities are never recorded.\n if (event.key !== \"Enter\") return;\n const target = event.target;\n if (target instanceof Element) {\n const episode = episodes.get(target);\n if (episode) endEpisode(episode, \"enter\");\n }\n } catch {\n // Ignore.\n }\n };\n\n const onVisibilityChange = (): void => {\n if (document.visibilityState === \"hidden\") {\n endAll(\"hidden\");\n }\n };\n const onPageHide = (): void => {\n endAll(\"unload\");\n };\n\n document.addEventListener(\"input\", onInput, { capture: true, passive: true });\n // Selects commit through `change`; some drivers/frameworks emit it without\n // a preceding `input`.\n document.addEventListener(\"change\", onInput, {\n capture: true,\n passive: true,\n });\n document.addEventListener(\"focusout\", onFocusOut, {\n capture: true,\n passive: true,\n });\n document.addEventListener(\"keydown\", onKeyDown, {\n capture: true,\n passive: true,\n });\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n window.addEventListener(\"pagehide\", onPageHide);\n\n return {\n notifyNavigation() {\n endAll(\"navigation\");\n },\n teardown() {\n document.removeEventListener(\"input\", onInput, { capture: true });\n document.removeEventListener(\"change\", onInput, { capture: true });\n document.removeEventListener(\"focusout\", onFocusOut, { capture: true });\n document.removeEventListener(\"keydown\", onKeyDown, { capture: true });\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n window.removeEventListener(\"pagehide\", onPageHide);\n endAll(\"unload\");\n },\n };\n};\n",
|
|
11
|
+
"/**\n * Resolving the intake endpoint from a single URL.\n *\n * Every other Sazabi log source is configured with one intake URL, and public\n * keys are meant to stay a low-level detail customers never handle. The key is\n * already in the URL: the intake edge reconstructs it from the hostname\n * (terraform/main/cloudfront-functions/intake-router.js), so the SDK can do the\n * same reconstruction locally and send the Bearer header itself.\n *\n * Two keyed shapes exist, matching the edge's two grammars:\n * {hex}.{region}.intake.{domain} — prefixless (what log sources issue)\n * {adapter}-{hex}.{region}.intake.{domain} — keyed-adapter (legacy, still served)\n *\n * A URL in neither shape is not an error: it may be a proxy or a custom\n * endpoint. The SDK then requires an explicit `publicKey`, so a\n * misconfiguration surfaces as a clear warning rather than silent no-auth.\n */\n\nconst KEYED_HOST = /^([0-9a-f]{32})\\./;\nconst KEYED_ADAPTER_HOST = /^[a-z0-9-]+?-([0-9a-f]{32})\\./;\n\nexport interface ResolvedIntakeEndpoint {\n /**\n * Base to POST to — origin plus any proxy path prefix, no trailing slash.\n * The transport appends `/v1/logs`.\n */\n baseUrl: string;\n /** Credential for the Authorization header, derived or explicit. */\n publicKey: string;\n}\n\n/** Public key embedded in a keyed intake hostname, if it carries one. */\nexport const publicKeyFromIntakeUrl = (url: string): string | undefined => {\n let host: string;\n try {\n host = new URL(url).hostname;\n } catch {\n return undefined;\n }\n const hex = (KEYED_HOST.exec(host) ?? KEYED_ADAPTER_HOST.exec(host))?.[1];\n return hex ? `sazabi_public_${hex}` : undefined;\n};\n\n/**\n * Normalize a configured intake URL to a base the transport can suffix with\n * `/v1/logs`: drop a terminal `/v1/logs` so both the bare host and the full\n * OTLP endpoint work (the two forms customers copy from setup instructions),\n * and drop query/hash, which the OTLP POST has no use for.\n *\n * A path prefix is preserved. Reducing this to `origin` would break the\n * documented proxy escape hatch two ways: records for a proxy mounted at\n * `https://example.com/otel` would go to `/v1/logs`, and the internal-request\n * filter — a `startsWith` on this base — would suppress network capture for\n * every request sharing that origin, including the customer's own API traffic.\n *\n * Only `http:` and `https:` resolve. Any other scheme would leave the SDK\n * looking initialized while `fetch` rejects the protocol and the transport\n * swallows the error, dropping every event; failing closed here surfaces the\n * misconfiguration as the same init warning as a missing URL.\n */\nconst SIGNAL_PATH = \"/v1/logs\";\n\nexport const intakeBaseFromUrl = (url: string): string | undefined => {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return undefined;\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n return undefined;\n }\n let path = parsed.pathname.replace(/\\/+$/, \"\");\n if (path.endsWith(SIGNAL_PATH)) {\n path = path.slice(0, -SIGNAL_PATH.length);\n }\n return `${parsed.origin}${path}`;\n};\n\n/**\n * Resolve the endpoint from config. An explicit `publicKey` always wins, so a\n * non-keyed or proxied endpoint stays configurable.\n */\nexport const resolveIntakeEndpoint = (config: {\n intakeUrl?: string;\n intakeHost?: string;\n publicKey?: string;\n}): ResolvedIntakeEndpoint | undefined => {\n const configured = config.intakeUrl ?? config.intakeHost;\n if (!configured) return undefined;\n\n const baseUrl = intakeBaseFromUrl(configured);\n if (!baseUrl) return undefined;\n\n const publicKey = config.publicKey ?? publicKeyFromIntakeUrl(configured);\n if (!publicKey) return undefined;\n\n return { baseUrl, publicKey };\n};\n",
|
|
11
12
|
"import { SDK_CONSOLE_PREFIX } from \"./console\";\nimport { consumeWrapperSeen } from \"./network\";\nimport { severityForStatus, urlPath } from \"./network-event-format\";\nimport type { WebEvent } from \"./types\";\n\nexport interface ResourceObserverOptions {\n emit(event: WebEvent): void;\n /** SDK-internal endpoints: never reported. */\n isInternalUrl(url: string): boolean;\n /** Would the active config have injected trace context into this URL? */\n isInjectionTarget(url: string): boolean;\n}\n\nexport interface ResourceObserverHandle {\n teardown(): void;\n}\n\n/**\n * Patch-independent network visibility: PerformanceObserver resource timing\n * sees every fetch/XHR the page performs — including ones issued by clients\n * that captured the native functions before the SDK patched (`buffered: true`\n * also replays requests from before init). Wrapper-captured requests are\n * deduped out via the wrapper-seen ledger; the leftovers get a degraded\n * network event (no method, no trace id — observation cannot inject), plus a\n * once-per-origin instrumentation-gap diagnostic when the URL was an\n * injection target, so bypass is a visible signal instead of silent loss.\n */\nexport const installResourceObserver = (\n options: ResourceObserverOptions,\n): ResourceObserverHandle => {\n if (typeof PerformanceObserver === \"undefined\") {\n return { teardown() {} };\n }\n\n const diagnosedOrigins = new Set<string>();\n\n const diagnoseBypass = (url: string): void => {\n let origin: string;\n try {\n origin = new URL(url).origin;\n } catch {\n return;\n }\n if (diagnosedOrigins.has(origin)) return;\n diagnosedOrigins.add(origin);\n\n const message = `requests to ${origin} bypass SDK instrumentation (fetch/XHR captured pre-init). Fix: import \"@sazabi/browser/register\" first.`;\n options.emit({\n type: \"log\",\n body: message,\n severity: \"WARN\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.sdk.diagnostic\": \"instrumentation_gap\",\n \"web.sdk.bypassed_origin\": origin,\n },\n });\n try {\n console.warn(`${SDK_CONSOLE_PREFIX} ${message}`);\n } catch {\n // Console unavailability is not our problem.\n }\n };\n\n const handleEntry = (entry: PerformanceResourceTiming): void => {\n try {\n if (\n entry.initiatorType !== \"fetch\" &&\n entry.initiatorType !== \"xmlhttprequest\"\n ) {\n return;\n }\n const url = entry.name;\n if (options.isInternalUrl(url)) return;\n if (consumeWrapperSeen(url, entry.startTime)) return;\n\n // Typed required in current lib.dom, but absent in older engines.\n const status = (entry.responseStatus as number | undefined) ?? 0;\n const completedAtMs = Math.round(\n performance.timeOrigin + entry.startTime + entry.duration,\n );\n\n options.emit({\n type: \"network\",\n body: `request ${urlPath(url)} → ${status > 0 ? status : \"observed\"}`,\n severity: status > 0 ? severityForStatus(status) : \"INFO\",\n timeUnixMs: completedAtMs,\n attributes: {\n \"http.response.status_code\": status > 0 ? status : undefined,\n \"url.full\": url,\n \"web.network.kind\": entry.initiatorType === \"fetch\" ? \"fetch\" : \"xhr\",\n \"web.network.duration_ms\": Math.round(entry.duration),\n \"web.network.source\": \"resource-timing\",\n },\n });\n\n if (options.isInjectionTarget(url)) {\n diagnoseBypass(url);\n }\n } catch {\n // Observation failures must never surface to the host.\n }\n };\n\n let observer: PerformanceObserver;\n try {\n observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n handleEntry(entry as PerformanceResourceTiming);\n }\n });\n observer.observe({ type: \"resource\", buffered: true });\n } catch {\n return { teardown() {} };\n }\n\n return {\n teardown() {\n try {\n observer.disconnect();\n } catch {\n // Best-effort.\n }\n },\n };\n};\n",
|
|
12
13
|
"const SESSION_STORAGE_KEY = \"sazabi.session\";\nconst WINDOW_STORAGE_KEY = \"sazabi.windowId\";\nconst DISTINCT_STORAGE_KEY = \"sazabi.distinctId\";\n\nconst SESSION_IDLE_MS = 30 * 60 * 1000;\nconst SESSION_MAX_MS = 24 * 60 * 60 * 1000;\n/** Throttle localStorage activity writes; click bursts must not spam storage. */\nconst ACTIVITY_PERSIST_INTERVAL_MS = 5_000;\n\ninterface StoredSession {\n id: string;\n startedAt: number;\n lastActivityAt: number;\n}\n\nexport interface SessionManager {\n getSessionId(): string;\n getWindowId(): string;\n getDistinctId(): string | undefined;\n /**\n * Set the client-asserted identity. Switching from one identity directly\n * to a different one rotates the session and window ids so two users on a\n * shared device never thread into one timeline.\n */\n setDistinctId(distinctId: string): void;\n /** Logout: clear identity and rotate both session and window ids. */\n reset(): void;\n /** Record user activity; may rotate the session on idle/max-age expiry. */\n touch(): void;\n}\n\nconst randomSuffix = (): string => {\n const bytes = new Uint8Array(8);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n};\n\nconst newId = (prefix: string): string =>\n `${prefix}_${Date.now().toString(36)}${randomSuffix()}`;\n\n/**\n * Storage access that degrades to in-memory when storage is unavailable\n * (Safari private mode, disabled cookies, sandboxed iframes). A degraded\n * session is per-page rather than cross-tab — acceptable fallback.\n */\nconst createSafeStorage = (\n getStore: () => Storage,\n): {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n} => {\n const memory = new Map<string, string>();\n return {\n get(key) {\n try {\n return getStore().getItem(key);\n } catch {\n return memory.get(key) ?? null;\n }\n },\n set(key, value) {\n try {\n getStore().setItem(key, value);\n } catch {\n memory.set(key, value);\n }\n },\n remove(key) {\n memory.delete(key);\n try {\n getStore().removeItem(key);\n } catch {\n // Fallback map already cleared.\n }\n },\n };\n};\n\nconst parseStoredSession = (raw: string | null): StoredSession | undefined => {\n if (!raw) return undefined;\n try {\n const parsed: unknown = JSON.parse(raw);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n typeof (parsed as StoredSession).id === \"string\" &&\n typeof (parsed as StoredSession).startedAt === \"number\" &&\n typeof (parsed as StoredSession).lastActivityAt === \"number\"\n ) {\n return parsed as StoredSession;\n }\n } catch {\n // Corrupt value — treat as absent and rotate.\n }\n return undefined;\n};\n\n/**\n * Cross-tab session identity. `session.id` is the visit (localStorage, shared\n * across tabs, last-writer-wins on rotation races — a split session is\n * cosmetic, not data loss). `session.window_id` is this tab (sessionStorage).\n * `session.distinct_id` is read through storage so identify/reset in one tab\n * is visible to sibling tabs on their next event.\n */\nexport const createSessionManager = (): SessionManager => {\n const local = createSafeStorage(() => window.localStorage);\n const session = createSafeStorage(() => window.sessionStorage);\n\n let lastPersistedActivity = 0;\n\n const readOrRotate = (): StoredSession => {\n const now = Date.now();\n const stored = parseStoredSession(local.get(SESSION_STORAGE_KEY));\n\n if (\n stored &&\n now - stored.lastActivityAt <= SESSION_IDLE_MS &&\n now - stored.startedAt <= SESSION_MAX_MS\n ) {\n return stored;\n }\n\n const fresh: StoredSession = {\n id: newId(\"sess\"),\n startedAt: now,\n lastActivityAt: now,\n };\n local.set(SESSION_STORAGE_KEY, JSON.stringify(fresh));\n lastPersistedActivity = now;\n return fresh;\n };\n\n let windowId = session.get(WINDOW_STORAGE_KEY);\n if (!windowId) {\n windowId = newId(\"win\");\n session.set(WINDOW_STORAGE_KEY, windowId);\n }\n\n const rotate = (): void => {\n const now = Date.now();\n local.set(\n SESSION_STORAGE_KEY,\n JSON.stringify({\n id: newId(\"sess\"),\n startedAt: now,\n lastActivityAt: now,\n }),\n );\n lastPersistedActivity = now;\n windowId = newId(\"win\");\n session.set(WINDOW_STORAGE_KEY, windowId);\n };\n\n return {\n getSessionId() {\n return readOrRotate().id;\n },\n getWindowId() {\n return windowId as string;\n },\n getDistinctId() {\n return local.get(DISTINCT_STORAGE_KEY) ?? undefined;\n },\n setDistinctId(id: string) {\n const current = local.get(DISTINCT_STORAGE_KEY) ?? undefined;\n if (current !== undefined && current !== id) {\n // Identity switch without reset(): defensive rotation so the new\n // user's events never join the previous user's session.\n rotate();\n }\n local.set(DISTINCT_STORAGE_KEY, id);\n },\n reset() {\n local.remove(DISTINCT_STORAGE_KEY);\n rotate();\n },\n touch() {\n const now = Date.now();\n const current = readOrRotate();\n if (now - lastPersistedActivity >= ACTIVITY_PERSIST_INTERVAL_MS) {\n local.set(\n SESSION_STORAGE_KEY,\n JSON.stringify({ ...current, lastActivityAt: now }),\n );\n lastPersistedActivity = now;\n }\n },\n };\n};\n",
|
|
13
14
|
"export interface RequestTraceContext {\n /** Headers to inject (`traceparent`, and `tracestate` when present). */\n headers: Record<string, string>;\n traceId: string;\n spanId: string;\n}\n\nexport interface TraceContextManager {\n /** Trace context for one outgoing request, minted at request time. */\n forRequest(): RequestTraceContext;\n}\n\n/** The subset of an OTel SpanContext this module consumes. */\nexport interface HostSpanContext {\n traceId: string;\n spanId: string;\n traceFlags: number;\n traceState?: { serialize(): string };\n}\n\nconst SAMPLED_FLAG = 0x1;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\nconst ALL_ZERO_TRACE_ID = \"0\".repeat(32);\nconst ALL_ZERO_SPAN_ID = \"0\".repeat(16);\n\nconst randomHexId = (byteLength: number): string => {\n const bytes = new Uint8Array(byteLength);\n do {\n crypto.getRandomValues(bytes);\n } while (bytes.every((b) => b === 0)); // all-zero ids are invalid per W3C spec\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n};\n\nconst isValidHostSpanContext = (\n candidate: unknown,\n): candidate is HostSpanContext => {\n if (typeof candidate !== \"object\" || candidate === null) return false;\n const { traceId, spanId, traceFlags } = candidate as HostSpanContext;\n return (\n typeof traceId === \"string\" &&\n TRACE_ID_PATTERN.test(traceId) &&\n traceId !== ALL_ZERO_TRACE_ID &&\n typeof spanId === \"string\" &&\n SPAN_ID_PATTERN.test(spanId) &&\n spanId !== ALL_ZERO_SPAN_ID &&\n typeof traceFlags === \"number\"\n );\n};\n\n// ------------------------------------------------- host OTel interop --------\n// Dependency-free read of the host app's active span, through the\n// @opentelemetry/api package's own cross-copy compatibility contract: every\n// api copy interoperates via the global delegate registered at\n// Symbol.for(\"opentelemetry.js.api.1\"), and context keys are Symbol.for(...)\n// strings — that registry IS the mechanism by which independent api copies\n// find each other, which is what makes it load-bearing rather than private.\n// An integration test against the real api package (devDependency) pins the\n// contract; any shape drift degrades here to \"no active span\" and we mint\n// our own roots instead.\n\nconst OTEL_GLOBAL_KEY = Symbol.for(\"opentelemetry.js.api.1\");\nconst OTEL_SPAN_CONTEXT_KEY = Symbol.for(\"OpenTelemetry Context Key SPAN\");\n\ninterface OtelGlobalShape {\n context?: {\n active?: () => { getValue?: (key: symbol) => unknown } | undefined;\n };\n}\n\nexport const readHostSpanContext = (): HostSpanContext | undefined => {\n try {\n const otelApi = (globalThis as Record<symbol, unknown>)[OTEL_GLOBAL_KEY] as\n | OtelGlobalShape\n | undefined;\n const activeContext = otelApi?.context?.active?.();\n const span = activeContext?.getValue?.(OTEL_SPAN_CONTEXT_KEY) as\n | { spanContext?: () => unknown }\n | undefined;\n const candidate = span?.spanContext?.();\n return isValidHostSpanContext(candidate) ? candidate : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst formatTraceparent = (spanContext: HostSpanContext): string => {\n const flags = (spanContext.traceFlags & 0xff).toString(16).padStart(2, \"0\");\n return `00-${spanContext.traceId}-${spanContext.spanId}-${flags}`;\n};\n\nconst readTraceState = (spanContext: HostSpanContext): string | undefined => {\n try {\n const serialized = spanContext.traceState?.serialize();\n return serialized || undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * W3C trace context for outgoing requests — hand-rolled header formatting\n * (equivalence-tested against OTel's W3CTraceContextPropagator), zero\n * runtime dependencies. If the host app runs its own OTel and has an active\n * span, that span's context (including its flags and tracestate) is reused\n * so we join the customer's trace instead of forking a new one; otherwise a\n * fresh root is minted with the sampled flag defaulting to off (`-00`).\n */\nexport const createTraceContextManager = (options: {\n sampledFlag: boolean;\n}): TraceContextManager => {\n const mintRootSpanContext = (): HostSpanContext => ({\n traceId: randomHexId(16),\n spanId: randomHexId(8),\n traceFlags: options.sampledFlag ? SAMPLED_FLAG : 0,\n });\n\n return {\n forRequest() {\n const spanContext = readHostSpanContext() ?? mintRootSpanContext();\n const headers: Record<string, string> = {\n traceparent: formatTraceparent(spanContext),\n };\n const traceState = readTraceState(spanContext);\n if (traceState) {\n headers.tracestate = traceState;\n }\n return {\n headers,\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n };\n },\n };\n};\n",
|
|
14
15
|
"export const SDK_NAME = \"@sazabi/browser\";\nexport const SDK_VERSION = \"0.2.0\";\n",
|
|
15
16
|
"import { truncateValue } from \"./attributes\";\nimport type {\n AttributeValue,\n EventAttributes,\n EventSeverity,\n WebEvent,\n} from \"./types\";\nimport { SDK_NAME, SDK_VERSION } from \"./version\";\n\ntype OtlpAnyValue =\n | { stringValue: string }\n | { intValue: string }\n | { doubleValue: number }\n | { boolValue: boolean };\n\ninterface OtlpKeyValue {\n key: string;\n value: OtlpAnyValue;\n}\n\nexport interface OtlpLogRecord {\n timeUnixNano: string;\n severityNumber: number;\n severityText: EventSeverity;\n body: { stringValue: string };\n attributes: OtlpKeyValue[];\n /** OTLP/JSON encodes trace/span ids as hex (unlike proto3 JSON's base64). */\n traceId?: string;\n spanId?: string;\n}\n\nconst SEVERITY_NUMBERS: Record<EventSeverity, number> = {\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n};\n\nconst MAX_BODY_LENGTH = 1024;\n\nconst encodeValue = (value: AttributeValue): OtlpAnyValue => {\n if (typeof value === \"boolean\") {\n return { boolValue: value };\n }\n if (typeof value === \"number\") {\n // proto3 JSON maps int64 to string; doubles stay numeric.\n return Number.isInteger(value)\n ? { intValue: String(value) }\n : { doubleValue: value };\n }\n return { stringValue: truncateValue(value) };\n};\n\nconst encodeAttributes = (attributes: EventAttributes): OtlpKeyValue[] => {\n const encoded: OtlpKeyValue[] = [];\n for (const [key, value] of Object.entries(attributes)) {\n if (value === undefined) {\n continue;\n }\n encoded.push({ key, value: encodeValue(value) });\n }\n return encoded;\n};\n\nexport const encodeLogRecord = (\n event: WebEvent,\n baseAttributes: EventAttributes,\n): OtlpLogRecord => {\n const record: OtlpLogRecord = {\n timeUnixNano: `${event.timeUnixMs}000000`,\n severityNumber: SEVERITY_NUMBERS[event.severity],\n severityText: event.severity,\n body: { stringValue: truncateValue(event.body, MAX_BODY_LENGTH) },\n attributes: encodeAttributes({ ...baseAttributes, ...event.attributes }),\n };\n if (event.traceId) {\n record.traceId = event.traceId;\n }\n if (event.spanId) {\n record.spanId = event.spanId;\n }\n return record;\n};\n\nexport interface TransportOptions {\n /** Full OTLP logs endpoint, e.g. `https://web.<region>.intake.<domain>/v1/logs`. */\n url: string;\n publicKey: string;\n resourceAttributes: EventAttributes;\n /**\n * The fetch to deliver with — captured before the SDK's network patch\n * installs, so exporter traffic can never recurse through our own wrapper\n * or appear in the captured event stream.\n */\n fetchImpl: typeof fetch;\n flushIntervalMs: number;\n maxBatchBytes: number;\n maxQueuedEvents: number;\n}\n\nexport interface Transport {\n enqueue(record: OtlpLogRecord): void;\n /**\n * Deliver everything queued. `keepalive: true` is for unload paths — each\n * request body must stay inside the browser's ~64 KiB keepalive budget,\n * which enqueue-side chunking guarantees via `maxBatchBytes`.\n */\n flush(options?: { keepalive?: boolean }): Promise<void>;\n shutdown(): Promise<void>;\n}\n\ninterface QueuedRecord {\n record: OtlpLogRecord;\n bytes: number;\n}\n\nexport const createTransport = (options: TransportOptions): Transport => {\n const queue: QueuedRecord[] = [];\n let queuedBytes = 0;\n let timer: number | undefined;\n let shutDown = false;\n\n const buildEnvelope = (records: OtlpLogRecord[]): string =>\n JSON.stringify({\n resourceLogs: [\n {\n resource: {\n attributes: encodeAttributes(options.resourceAttributes),\n },\n scopeLogs: [\n {\n scope: { name: SDK_NAME, version: SDK_VERSION },\n logRecords: records,\n },\n ],\n },\n ],\n });\n\n const envelopeOverhead = buildEnvelope([]).length + 64;\n const chunkBudget = Math.max(4096, options.maxBatchBytes - envelopeOverhead);\n\n const clearTimer = (): void => {\n if (timer !== undefined) {\n window.clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const scheduleFlush = (): void => {\n if (timer !== undefined || shutDown) {\n return;\n }\n timer = window.setTimeout(() => {\n timer = undefined;\n void flush();\n }, options.flushIntervalMs);\n };\n\n const takeChunks = (): OtlpLogRecord[][] => {\n const chunks: OtlpLogRecord[][] = [];\n let current: OtlpLogRecord[] = [];\n let currentBytes = 0;\n\n for (const queued of queue) {\n if (current.length > 0 && currentBytes + queued.bytes > chunkBudget) {\n chunks.push(current);\n current = [];\n currentBytes = 0;\n }\n current.push(queued.record);\n currentBytes += queued.bytes;\n }\n if (current.length > 0) {\n chunks.push(current);\n }\n\n queue.length = 0;\n queuedBytes = 0;\n return chunks;\n };\n\n const flush = async (flushOptions?: {\n keepalive?: boolean;\n }): Promise<void> => {\n clearTimer();\n if (queue.length === 0) {\n return;\n }\n\n const requests = takeChunks().map((chunk) =>\n options\n .fetchImpl(options.url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${options.publicKey}`,\n },\n body: buildEnvelope(chunk),\n keepalive: flushOptions?.keepalive === true,\n })\n .catch(() => {\n // Delivery is best-effort; the SDK must stay silent on failure.\n }),\n );\n\n await Promise.all(requests);\n };\n\n return {\n enqueue(record) {\n if (shutDown) {\n return;\n }\n const bytes = JSON.stringify(record).length + 1;\n queue.push({ record, bytes });\n queuedBytes += bytes;\n\n while (queue.length > options.maxQueuedEvents) {\n const dropped = queue.shift();\n if (dropped) {\n queuedBytes -= dropped.bytes;\n }\n }\n\n if (queuedBytes >= chunkBudget) {\n void flush();\n } else {\n scheduleFlush();\n }\n },\n flush,\n async shutdown() {\n shutDown = true;\n await flush();\n },\n };\n};\n",
|
|
16
|
-
"import { flattenAttributes } from \"./attributes\";\nimport { installConsoleCapture } from \"./console\";\nimport { installErrorCapture } from \"./errors\";\nimport { type InputCaptureHandle, installInputCapture } from \"./input-capture\";\nimport { installInteractionCapture } from \"./interactions\";\nimport {\n installNavigationCapture,\n uninstallNavigationPatches,\n} from \"./navigation\";\nimport {\n installNetworkCapture,\n isActiveInjectionTarget,\n uninstallNetworkPatches,\n} from \"./network\";\nimport { installResourceObserver } from \"./resource-observer\";\nimport { createSessionManager } from \"./session\";\nimport { createTraceContextManager } from \"./trace-context\";\nimport { createTransport, encodeLogRecord } from \"./transport\";\nimport type {\n BrowserSdkConfig,\n EventAttributes,\n EventSeverity,\n NetworkCaptureConfig,\n WebEvent,\n} from \"./types\";\nimport { SDK_NAME, SDK_VERSION } from \"./version\";\n\nexport type {\n AttributeValue,\n BrowserSdkConfig,\n ConsoleCaptureConfig,\n ConsoleCaptureLevel,\n EventAttributes,\n EventSeverity,\n InputCaptureConfig,\n NetworkCaptureConfig,\n WebEvent,\n WebEventType,\n} from \"./types\";\nexport { SDK_VERSION } from \"./version\";\n\nconst DEFAULT_FLUSH_INTERVAL_MS = 5_000;\nconst DEFAULT_MAX_BATCH_BYTES = 57_344;\nconst DEFAULT_MAX_QUEUED_EVENTS = 500;\n/**\n * Platform request-id response headers probed for `web.network.request_id`,\n * in priority order: generic first, then common CDN/PaaS edges.\n */\nconst DEFAULT_REQUEST_ID_HEADERS = [\n \"x-request-id\",\n \"cf-ray\",\n \"x-vercel-id\",\n \"x-amz-cf-id\",\n \"fly-request-id\",\n];\n\ninterface SdkInstance {\n identify(distinctId: string, traits?: Record<string, unknown>): void;\n reset(): void;\n addEvent(name: string, attributes?: Record<string, unknown>): void;\n log(\n severity: EventSeverity,\n message: string,\n metadata?: Record<string, unknown>,\n ): void;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\ninterface PendingIdentity {\n distinctId: string;\n traits?: Record<string, unknown>;\n}\n\nlet instance: SdkInstance | undefined;\nlet initialized = false;\nlet pendingIdentity: PendingIdentity | undefined;\nlet pendingReset = false;\n\nconst start = (config: BrowserSdkConfig): void => {\n // Bound before capture activates. Under `register` this may already be the\n // dormant wrapper; intake URLs take its internal passthrough branch, so\n // transport traffic never recurses into capture either way.\n const prePatchFetch = window.fetch.bind(window);\n\n const intakeBase = config.intakeHost.replace(/\\/+$/, \"\");\n const intakeUrl = `${intakeBase}/v1/logs`;\n\n const session = createSessionManager();\n // Apply buffered identity before any capture emits, so even the initial\n // navigation event carries the identity claimed while consent was pending.\n if (pendingReset) {\n session.reset();\n pendingReset = false;\n }\n const appliedPendingIdentity = pendingIdentity;\n pendingIdentity = undefined;\n if (appliedPendingIdentity) {\n session.setDistinctId(appliedPendingIdentity.distinctId);\n }\n\n const transport = createTransport({\n url: intakeUrl,\n publicKey: config.publicKey,\n resourceAttributes: {\n \"service.name\": config.serviceName,\n \"service.version\": config.serviceVersion,\n \"deployment.environment\": config.environment,\n \"telemetry.sdk.name\": SDK_NAME,\n \"telemetry.sdk.version\": SDK_VERSION,\n \"telemetry.sdk.language\": \"webjs\",\n \"browser.user_agent\": navigator.userAgent,\n \"browser.language\": navigator.language,\n },\n fetchImpl: prePatchFetch,\n flushIntervalMs: config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n maxBatchBytes: config.maxBatchBytes ?? DEFAULT_MAX_BATCH_BYTES,\n maxQueuedEvents: config.maxQueuedEvents ?? DEFAULT_MAX_QUEUED_EVENTS,\n });\n\n const emit = (event: WebEvent): void => {\n try {\n session.touch();\n const base: EventAttributes = {\n \"web.event_type\": event.type,\n \"session.id\": session.getSessionId(),\n \"session.window_id\": session.getWindowId(),\n \"session.distinct_id\": session.getDistinctId(),\n \"web.page.url\": window.location.href,\n \"derived.source\": \"sdk\",\n };\n transport.enqueue(encodeLogRecord(event, base));\n } catch {\n // Emitting must never throw into the host.\n }\n };\n\n const isInternalUrl = (url: string): boolean => url.startsWith(intakeBase);\n\n // Guards event construction (attribute flattening can throw on exotic\n // input); emit() itself already guards delivery.\n const safeEmitEvent = (build: () => WebEvent): void => {\n try {\n emit(build());\n } catch {\n // Never throw into the host.\n }\n };\n\n const teardowns: Array<() => void> = [];\n\n const errorCapture = installErrorCapture({ emit });\n teardowns.push(() => errorCapture.teardown());\n\n const interactions = installInteractionCapture({ emit });\n teardowns.push(() => interactions.teardown());\n\n let inputCapture: InputCaptureHandle | undefined;\n if (config.input?.capture !== false) {\n inputCapture = installInputCapture({ emit });\n teardowns.push(() => inputCapture?.teardown());\n }\n\n const navigation = installNavigationCapture({\n emit,\n onNavigate: () => {\n interactions.notifyNavigation();\n inputCapture?.notifyNavigation();\n },\n });\n teardowns.push(() => navigation.teardown());\n\n if (config.console?.capture !== false) {\n const consoleCapture = installConsoleCapture({\n emit,\n levels: config.console?.levels ?? [\"error\", \"warn\"],\n });\n teardowns.push(() => consoleCapture.teardown());\n }\n\n const networkConfig: NetworkCaptureConfig = config.network ?? {};\n const networkCapture = networkConfig.capture ?? true;\n const propagateTraceContext = networkConfig.propagateTraceContext ?? true;\n if (networkCapture || propagateTraceContext) {\n const network = installNetworkCapture({\n emit,\n traceContext: createTraceContextManager({\n sampledFlag: networkConfig.sampledFlag ?? false,\n }),\n capture: networkCapture,\n propagateTraceContext,\n allowlist: networkConfig.allowlist ?? [],\n requestIdHeaders:\n networkConfig.requestIdHeaders ?? DEFAULT_REQUEST_ID_HEADERS,\n isInternalUrl,\n });\n teardowns.push(() => network.teardown());\n }\n\n if (networkCapture && networkConfig.resourceFallback !== false) {\n const resourceObserver = installResourceObserver({\n emit,\n isInternalUrl,\n isInjectionTarget: isActiveInjectionTarget,\n });\n teardowns.push(() => resourceObserver.teardown());\n }\n\n // Unload flush: visibilitychange→hidden is the reliable signal; pagehide\n // covers bfcache navigations. keepalive lets the batch outlive the page.\n const onVisibilityChange = (): void => {\n if (document.visibilityState === \"hidden\") {\n void transport.flush({ keepalive: true });\n }\n };\n const onPageHide = (): void => {\n void transport.flush({ keepalive: true });\n };\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n window.addEventListener(\"pagehide\", onPageHide);\n teardowns.push(() => {\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n window.removeEventListener(\"pagehide\", onPageHide);\n });\n\n instance = {\n identify(distinctId, traits) {\n safeEmitEvent(() => {\n session.setDistinctId(distinctId);\n return {\n type: \"custom\",\n body: `identify ${distinctId}`,\n severity: \"INFO\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.custom.name\": \"identify\",\n ...(traits ? flattenAttributes(traits, \"custom\") : {}),\n },\n };\n });\n },\n reset() {\n try {\n session.reset();\n } catch {\n // Never throw into the host.\n }\n },\n addEvent(name, attributes) {\n safeEmitEvent(() => ({\n type: \"custom\",\n body: `custom ${name}`,\n severity: \"INFO\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.custom.name\": name,\n ...(attributes ? flattenAttributes(attributes, \"custom\") : {}),\n },\n }));\n },\n log(severity, message, metadata) {\n safeEmitEvent(() => ({\n type: \"log\",\n body: message,\n severity,\n timeUnixMs: Date.now(),\n // Raw-key flattening (no prefix) for parity with app loggers,\n // so existing log queries keep their attribute names.\n attributes: metadata ? flattenAttributes(metadata) : {},\n }));\n },\n flush() {\n return transport.flush();\n },\n async shutdown() {\n for (const teardown of teardowns.reverse()) {\n try {\n teardown();\n } catch {\n // Teardown must be best-effort.\n }\n }\n // Deactivation above leaves dormant patches; full shutdown restores\n // the natives (when still ours).\n uninstallNetworkPatches();\n uninstallNavigationPatches();\n await transport.shutdown();\n },\n };\n\n // The identify event for a pre-consent identify() is emitted only now that\n // capture exists; the id itself was applied to the session earlier.\n if (appliedPendingIdentity) {\n instance.identify(\n appliedPendingIdentity.distinctId,\n appliedPendingIdentity.traits,\n );\n }\n};\n\n/**\n * Initialize the SDK. Idempotent: repeat calls are ignored. When `consent`\n * is provided, nothing new is installed — no listeners, no patches, no\n * network — until it resolves true; on false (or a throw) the SDK stays\n * dormant. (Patches pre-installed by `@sazabi/browser/register` exist\n * but remain inert passthroughs until activation.)\n */\nexport const init = (config: BrowserSdkConfig): void => {\n if (typeof window === \"undefined\") {\n return; // SSR — nothing to capture.\n }\n if (initialized) {\n return;\n }\n initialized = true;\n\n if (!config.publicKey || !config.intakeHost || !config.serviceName) {\n // Developer-facing misconfiguration: warn once, never throw.\n console.warn(\n \"[@sazabi/browser] init() requires publicKey, intakeHost, and serviceName; SDK disabled.\",\n );\n return;\n }\n\n if (config.consent === undefined) {\n start(config);\n return;\n }\n\n try {\n void Promise.resolve(config.consent())\n .then((granted) => {\n if (granted === true) {\n start(config);\n }\n })\n .catch(() => {\n // Consent evaluation failed — stay dormant.\n });\n } catch {\n // Synchronous throw from consent() — stay dormant.\n }\n};\n\n/** Set the client-asserted user identity (`session.distinct_id`). */\nexport const identify = (\n distinctId: string,\n traits?: Record<string, unknown>,\n): void => {\n if (instance) {\n instance.identify(distinctId, traits);\n } else {\n // Buffer identity across a pending consent gate; the identify event is\n // emitted when capture starts.\n pendingIdentity = { distinctId, traits };\n }\n};\n\n/**\n * Logout: clear the client-asserted identity and rotate both session and\n * window ids, so later activity on this device never threads into the\n * previous user's timeline.\n */\nexport const reset = (): void => {\n if (instance) {\n instance.reset();\n } else {\n pendingReset = true;\n pendingIdentity = undefined;\n }\n};\n\n/** Emit a custom mark into the session event stream. */\nexport const addEvent = (\n name: string,\n attributes?: Record<string, unknown>,\n): void => {\n instance?.addEvent(name, attributes);\n};\n\n/**\n * Emit an application log line (`web.event_type: \"log\"`) with session context\n * attached. Drops silently before init/consent, like all capture.\n */\nexport const log = (\n severity: EventSeverity,\n message: string,\n metadata?: Record<string, unknown>,\n): void => {\n instance?.log(severity, message, metadata);\n};\n\n/** Force-flush queued events. */\nexport const flush = async (): Promise<void> => {\n await instance?.flush();\n};\n\n/** Tear down all patches/listeners (restoring originals) and flush. */\nexport const shutdown = async (): Promise<void> => {\n const active = instance;\n instance = undefined;\n initialized = false;\n pendingIdentity = undefined;\n pendingReset = false;\n await active?.shutdown();\n};\n"
|
|
17
|
+
"import { flattenAttributes } from \"./attributes\";\nimport { installConsoleCapture } from \"./console\";\nimport { installErrorCapture } from \"./errors\";\nimport { type InputCaptureHandle, installInputCapture } from \"./input-capture\";\nimport { resolveIntakeEndpoint } from \"./intake-url\";\nimport { installInteractionCapture } from \"./interactions\";\nimport {\n installNavigationCapture,\n uninstallNavigationPatches,\n} from \"./navigation\";\nimport {\n installNetworkCapture,\n isActiveInjectionTarget,\n uninstallNetworkPatches,\n} from \"./network\";\nimport { installResourceObserver } from \"./resource-observer\";\nimport { createSessionManager } from \"./session\";\nimport { createTraceContextManager } from \"./trace-context\";\nimport { createTransport, encodeLogRecord } from \"./transport\";\nimport type {\n BrowserSdkConfig,\n EventAttributes,\n EventSeverity,\n NetworkCaptureConfig,\n WebEvent,\n} from \"./types\";\nimport { SDK_NAME, SDK_VERSION } from \"./version\";\n\nexport type {\n AttributeValue,\n BrowserSdkConfig,\n ConsoleCaptureConfig,\n ConsoleCaptureLevel,\n EventAttributes,\n EventSeverity,\n InputCaptureConfig,\n NetworkCaptureConfig,\n WebEvent,\n WebEventType,\n} from \"./types\";\nexport { SDK_VERSION } from \"./version\";\n\nconst DEFAULT_FLUSH_INTERVAL_MS = 5_000;\nconst DEFAULT_MAX_BATCH_BYTES = 57_344;\nconst DEFAULT_MAX_QUEUED_EVENTS = 500;\n/**\n * Platform request-id response headers probed for `web.network.request_id`,\n * in priority order: generic first, then common CDN/PaaS edges.\n */\nconst DEFAULT_REQUEST_ID_HEADERS = [\n \"x-request-id\",\n \"cf-ray\",\n \"x-vercel-id\",\n \"x-amz-cf-id\",\n \"fly-request-id\",\n];\n\ninterface SdkInstance {\n identify(distinctId: string, traits?: Record<string, unknown>): void;\n reset(): void;\n addEvent(name: string, attributes?: Record<string, unknown>): void;\n log(\n severity: EventSeverity,\n message: string,\n metadata?: Record<string, unknown>,\n ): void;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\ninterface PendingIdentity {\n distinctId: string;\n traits?: Record<string, unknown>;\n}\n\nlet instance: SdkInstance | undefined;\nlet initialized = false;\nlet pendingIdentity: PendingIdentity | undefined;\nlet pendingReset = false;\n\nconst start = (config: BrowserSdkConfig): void => {\n // Bound before capture activates. Under `register` this may already be the\n // dormant wrapper; intake URLs take its internal passthrough branch, so\n // transport traffic never recurses into capture either way.\n const prePatchFetch = window.fetch.bind(window);\n\n // Validated in init(); the endpoint carries its own credential when the URL\n // is a keyed intake host.\n const endpoint = resolveIntakeEndpoint(config);\n if (!endpoint) {\n return;\n }\n const intakeUrl = `${endpoint.baseUrl}/v1/logs`;\n\n const session = createSessionManager();\n // Apply buffered identity before any capture emits, so even the initial\n // navigation event carries the identity claimed while consent was pending.\n if (pendingReset) {\n session.reset();\n pendingReset = false;\n }\n const appliedPendingIdentity = pendingIdentity;\n pendingIdentity = undefined;\n if (appliedPendingIdentity) {\n session.setDistinctId(appliedPendingIdentity.distinctId);\n }\n\n const transport = createTransport({\n url: intakeUrl,\n publicKey: endpoint.publicKey,\n resourceAttributes: {\n \"service.name\": config.serviceName,\n \"service.version\": config.serviceVersion,\n \"deployment.environment\": config.environment,\n \"telemetry.sdk.name\": SDK_NAME,\n \"telemetry.sdk.version\": SDK_VERSION,\n \"telemetry.sdk.language\": \"webjs\",\n \"browser.user_agent\": navigator.userAgent,\n \"browser.language\": navigator.language,\n },\n fetchImpl: prePatchFetch,\n flushIntervalMs: config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n maxBatchBytes: config.maxBatchBytes ?? DEFAULT_MAX_BATCH_BYTES,\n maxQueuedEvents: config.maxQueuedEvents ?? DEFAULT_MAX_QUEUED_EVENTS,\n });\n\n const emit = (event: WebEvent): void => {\n try {\n session.touch();\n const base: EventAttributes = {\n \"web.event_type\": event.type,\n \"session.id\": session.getSessionId(),\n \"session.window_id\": session.getWindowId(),\n \"session.distinct_id\": session.getDistinctId(),\n \"web.page.url\": window.location.href,\n \"derived.source\": \"sdk\",\n };\n transport.enqueue(encodeLogRecord(event, base));\n } catch {\n // Emitting must never throw into the host.\n }\n };\n\n // Scoped to the resolved base, proxy path prefix included: a proxy sharing\n // an origin with the customer's own API must not suppress their traffic.\n const isInternalUrl = (url: string): boolean =>\n url.startsWith(endpoint.baseUrl);\n\n // Guards event construction (attribute flattening can throw on exotic\n // input); emit() itself already guards delivery.\n const safeEmitEvent = (build: () => WebEvent): void => {\n try {\n emit(build());\n } catch {\n // Never throw into the host.\n }\n };\n\n const teardowns: Array<() => void> = [];\n\n const errorCapture = installErrorCapture({ emit });\n teardowns.push(() => errorCapture.teardown());\n\n const interactions = installInteractionCapture({ emit });\n teardowns.push(() => interactions.teardown());\n\n let inputCapture: InputCaptureHandle | undefined;\n if (config.input?.capture !== false) {\n inputCapture = installInputCapture({ emit });\n teardowns.push(() => inputCapture?.teardown());\n }\n\n const navigation = installNavigationCapture({\n emit,\n onNavigate: () => {\n interactions.notifyNavigation();\n inputCapture?.notifyNavigation();\n },\n });\n teardowns.push(() => navigation.teardown());\n\n if (config.console?.capture !== false) {\n const consoleCapture = installConsoleCapture({\n emit,\n levels: config.console?.levels ?? [\"error\", \"warn\"],\n });\n teardowns.push(() => consoleCapture.teardown());\n }\n\n const networkConfig: NetworkCaptureConfig = config.network ?? {};\n const networkCapture = networkConfig.capture ?? true;\n const propagateTraceContext = networkConfig.propagateTraceContext ?? true;\n if (networkCapture || propagateTraceContext) {\n const network = installNetworkCapture({\n emit,\n traceContext: createTraceContextManager({\n sampledFlag: networkConfig.sampledFlag ?? false,\n }),\n capture: networkCapture,\n propagateTraceContext,\n allowlist: networkConfig.allowlist ?? [],\n requestIdHeaders:\n networkConfig.requestIdHeaders ?? DEFAULT_REQUEST_ID_HEADERS,\n isInternalUrl,\n });\n teardowns.push(() => network.teardown());\n }\n\n if (networkCapture && networkConfig.resourceFallback !== false) {\n const resourceObserver = installResourceObserver({\n emit,\n isInternalUrl,\n isInjectionTarget: isActiveInjectionTarget,\n });\n teardowns.push(() => resourceObserver.teardown());\n }\n\n // Unload flush: visibilitychange→hidden is the reliable signal; pagehide\n // covers bfcache navigations. keepalive lets the batch outlive the page.\n const onVisibilityChange = (): void => {\n if (document.visibilityState === \"hidden\") {\n void transport.flush({ keepalive: true });\n }\n };\n const onPageHide = (): void => {\n void transport.flush({ keepalive: true });\n };\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n window.addEventListener(\"pagehide\", onPageHide);\n teardowns.push(() => {\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n window.removeEventListener(\"pagehide\", onPageHide);\n });\n\n instance = {\n identify(distinctId, traits) {\n safeEmitEvent(() => {\n session.setDistinctId(distinctId);\n return {\n type: \"custom\",\n body: `identify ${distinctId}`,\n severity: \"INFO\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.custom.name\": \"identify\",\n ...(traits ? flattenAttributes(traits, \"custom\") : {}),\n },\n };\n });\n },\n reset() {\n try {\n session.reset();\n } catch {\n // Never throw into the host.\n }\n },\n addEvent(name, attributes) {\n safeEmitEvent(() => ({\n type: \"custom\",\n body: `custom ${name}`,\n severity: \"INFO\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.custom.name\": name,\n ...(attributes ? flattenAttributes(attributes, \"custom\") : {}),\n },\n }));\n },\n log(severity, message, metadata) {\n safeEmitEvent(() => ({\n type: \"log\",\n body: message,\n severity,\n timeUnixMs: Date.now(),\n // Raw-key flattening (no prefix) for parity with app loggers,\n // so existing log queries keep their attribute names.\n attributes: metadata ? flattenAttributes(metadata) : {},\n }));\n },\n flush() {\n return transport.flush();\n },\n async shutdown() {\n for (const teardown of teardowns.reverse()) {\n try {\n teardown();\n } catch {\n // Teardown must be best-effort.\n }\n }\n // Deactivation above leaves dormant patches; full shutdown restores\n // the natives (when still ours).\n uninstallNetworkPatches();\n uninstallNavigationPatches();\n await transport.shutdown();\n },\n };\n\n // The identify event for a pre-consent identify() is emitted only now that\n // capture exists; the id itself was applied to the session earlier.\n if (appliedPendingIdentity) {\n instance.identify(\n appliedPendingIdentity.distinctId,\n appliedPendingIdentity.traits,\n );\n }\n};\n\n/**\n * Initialize the SDK. Idempotent: repeat calls are ignored. When `consent`\n * is provided, nothing new is installed — no listeners, no patches, no\n * network — until it resolves true; on false (or a throw) the SDK stays\n * dormant. (Patches pre-installed by `@sazabi/browser/register` exist\n * but remain inert passthroughs until activation.)\n */\nexport const init = (config: BrowserSdkConfig): void => {\n if (typeof window === \"undefined\") {\n return; // SSR — nothing to capture.\n }\n if (initialized) {\n return;\n }\n initialized = true;\n\n if (!config.serviceName || !resolveIntakeEndpoint(config)) {\n // Developer-facing misconfiguration: warn once, never throw.\n console.warn(\n \"[@sazabi/browser] init() requires intakeUrl and serviceName; SDK disabled. \" +\n \"Pass publicKey too if the intake URL is a proxy that carries no key.\",\n );\n return;\n }\n\n if (config.consent === undefined) {\n start(config);\n return;\n }\n\n try {\n void Promise.resolve(config.consent())\n .then((granted) => {\n if (granted === true) {\n start(config);\n }\n })\n .catch(() => {\n // Consent evaluation failed — stay dormant.\n });\n } catch {\n // Synchronous throw from consent() — stay dormant.\n }\n};\n\n/** Set the client-asserted user identity (`session.distinct_id`). */\nexport const identify = (\n distinctId: string,\n traits?: Record<string, unknown>,\n): void => {\n if (instance) {\n instance.identify(distinctId, traits);\n } else {\n // Buffer identity across a pending consent gate; the identify event is\n // emitted when capture starts.\n pendingIdentity = { distinctId, traits };\n }\n};\n\n/**\n * Logout: clear the client-asserted identity and rotate both session and\n * window ids, so later activity on this device never threads into the\n * previous user's timeline.\n */\nexport const reset = (): void => {\n if (instance) {\n instance.reset();\n } else {\n pendingReset = true;\n pendingIdentity = undefined;\n }\n};\n\n/** Emit a custom mark into the session event stream. */\nexport const addEvent = (\n name: string,\n attributes?: Record<string, unknown>,\n): void => {\n instance?.addEvent(name, attributes);\n};\n\n/**\n * Emit an application log line (`web.event_type: \"log\"`) with session context\n * attached. Drops silently before init/consent, like all capture.\n */\nexport const log = (\n severity: EventSeverity,\n message: string,\n metadata?: Record<string, unknown>,\n): void => {\n instance?.log(severity, message, metadata);\n};\n\n/** Force-flush queued events. */\nexport const flush = async (): Promise<void> => {\n await instance?.flush();\n};\n\n/** Tear down all patches/listeners (restoring originals) and flush. */\nexport const shutdown = async (): Promise<void> => {\n const active = instance;\n instance = undefined;\n initialized = false;\n pendingIdentity = undefined;\n pendingReset = false;\n await active?.shutdown();\n};\n"
|
|
17
18
|
],
|
|
18
|
-
"mappings": "4GAKO,IAAM,EAAgB,CAAC,EAAe,EAHpB,OAIvB,EAAM,OAAS,EAAM,EAAM,MAAM,EAAG,CAAG,EAAI,EAOhC,EAAoB,CAC/B,EACA,EAAS,GACT,EAAQ,IACY,CACpB,IAAM,EAA0B,CAAC,EAEjC,QAAY,EAAK,KAAa,OAAO,QAAQ,CAAK,EAAG,CACnD,IAAM,EAAU,EAAS,GAAG,KAAU,IAAQ,EAE9C,GAAI,IAAa,MAAQ,IAAa,OACpC,SAGF,GACE,OAAO,IAAa,UACpB,CAAC,MAAM,QAAQ,CAAQ,GACvB,EA3BoB,EA4BpB,CACA,OAAO,OACL,EACA,EACE,EACA,EACA,EAAQ,CACV,CACF,EACA,SAGF,GAAI,OAAO,IAAa,UAAY,OAAO,IAAa,UACtD,EAAO,GAAW,EACb,QAAI,OAAO,IAAa,SAC7B,EAAO,GAAW,EAAc,CAAQ,EAExC,QAAI,CACF,EAAO,GAAW,EAAc,KAAK,UAAU,CAAQ,GAAK,EAAE,EAC9D,KAAM,GAMZ,OAAO,GC3CF,IAAM,EAAqB,oBAE5B,GAAgE,CACpE,MAAO,QACP,KAAM,OACN,KAAM,OACN,MAAO,OACT,EAEM,EAAgB,KAChB,GAAiB,KAEjB,GAAe,CAAC,IAA2B,CAC/C,IAAI,EACJ,GAAI,OAAO,IAAU,SACnB,EAAO,EACF,QAAI,aAAiB,MAC1B,EAAO,GAAG,EAAM,SAAS,EAAM,UAE/B,QAAI,CACF,EAAO,KAAK,UAAU,CAAK,GAAK,OAAO,CAAK,EAC5C,KAAM,CACN,EAAO,OAAO,CAAK,EAGvB,OAAO,EAAK,OAAS,EACjB,GAAG,EA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AI,EAAO,UAAY,OAAW,CAChC,GAAM,CAAM,EACZ,OAGF,GAAI,CACG,QAAQ,QAAQ,EAAO,QAAQ,CAAC,EAClC,KAAK,CAAC,IAAY,CACjB,GAAI,IAAY,GACd,GAAM,CAAM,EAEf,EACA,MAAM,IAAM,EAEZ,EACH,KAAM,IAMG,GAAW,CACtB,EACA,IACS,CACT,GAAI,EACF,EAAS,SAAS,EAAY,CAAM,EAIpC,OAAkB,CAAE,aAAY,QAAO,GAS9B,GAAQ,IAAY,CAC/B,GAAI,EACF,EAAS,MAAM,EAEf,OAAe,GACf,EAAkB,QAKT,GAAW,CACtB,EACA,IACS,CACT,GAAU,SAAS,EAAM,CAAU,GAOxB,GAAM,CACjB,EACA,EACA,IACS,CACT,GAAU,IAAI,EAAU,EAAS,CAAQ,GAI9B,GAAQ,SAA2B,CAC9C,MAAM,GAAU,MAAM,GAIX,GAAW,SAA2B,CACjD,IAAM,EAAS,EACf,EAAW,OACX,EAAc,GACd,EAAkB,OAClB,EAAe,GACf,MAAM,GAAQ,SAAS",
|
|
20
|
+
"debugId": "091BD9F6835879A764756E2164756E21",
|
|
20
21
|
"names": []
|
|
21
22
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolving the intake endpoint from a single URL.
|
|
3
|
+
*
|
|
4
|
+
* Every other Sazabi log source is configured with one intake URL, and public
|
|
5
|
+
* keys are meant to stay a low-level detail customers never handle. The key is
|
|
6
|
+
* already in the URL: the intake edge reconstructs it from the hostname
|
|
7
|
+
* (terraform/main/cloudfront-functions/intake-router.js), so the SDK can do the
|
|
8
|
+
* same reconstruction locally and send the Bearer header itself.
|
|
9
|
+
*
|
|
10
|
+
* Two keyed shapes exist, matching the edge's two grammars:
|
|
11
|
+
* {hex}.{region}.intake.{domain} — prefixless (what log sources issue)
|
|
12
|
+
* {adapter}-{hex}.{region}.intake.{domain} — keyed-adapter (legacy, still served)
|
|
13
|
+
*
|
|
14
|
+
* A URL in neither shape is not an error: it may be a proxy or a custom
|
|
15
|
+
* endpoint. The SDK then requires an explicit `publicKey`, so a
|
|
16
|
+
* misconfiguration surfaces as a clear warning rather than silent no-auth.
|
|
17
|
+
*/
|
|
18
|
+
export interface ResolvedIntakeEndpoint {
|
|
19
|
+
/**
|
|
20
|
+
* Base to POST to — origin plus any proxy path prefix, no trailing slash.
|
|
21
|
+
* The transport appends `/v1/logs`.
|
|
22
|
+
*/
|
|
23
|
+
baseUrl: string;
|
|
24
|
+
/** Credential for the Authorization header, derived or explicit. */
|
|
25
|
+
publicKey: string;
|
|
26
|
+
}
|
|
27
|
+
/** Public key embedded in a keyed intake hostname, if it carries one. */
|
|
28
|
+
export declare const publicKeyFromIntakeUrl: (url: string) => string | undefined;
|
|
29
|
+
export declare const intakeBaseFromUrl: (url: string) => string | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Resolve the endpoint from config. An explicit `publicKey` always wins, so a
|
|
32
|
+
* non-keyed or proxied endpoint stays configurable.
|
|
33
|
+
*/
|
|
34
|
+
export declare const resolveIntakeEndpoint: (config: {
|
|
35
|
+
intakeUrl?: string;
|
|
36
|
+
intakeHost?: string;
|
|
37
|
+
publicKey?: string;
|
|
38
|
+
}) => ResolvedIntakeEndpoint | undefined;
|
package/dist/types.d.ts
CHANGED
|
@@ -64,10 +64,21 @@ export interface NetworkCaptureConfig {
|
|
|
64
64
|
sampledFlag?: boolean;
|
|
65
65
|
}
|
|
66
66
|
export interface BrowserSdkConfig {
|
|
67
|
-
/**
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
67
|
+
/**
|
|
68
|
+
* The project's intake URL, exactly as the log source issues it — e.g.
|
|
69
|
+
* `https://<key>.us-west-2.intake.sazabi.com`. The credential is embedded in
|
|
70
|
+
* the hostname, so this is normally the only endpoint config needed; `/v1/logs`
|
|
71
|
+
* may be included or omitted.
|
|
72
|
+
*/
|
|
73
|
+
intakeUrl?: string;
|
|
74
|
+
/**
|
|
75
|
+
* Public ingest key (`sazabi_public_...`). Optional: derived from `intakeUrl`
|
|
76
|
+
* when that URL is a keyed intake host. Set it only for a proxy or custom
|
|
77
|
+
* endpoint whose hostname carries no key.
|
|
78
|
+
*/
|
|
79
|
+
publicKey?: string;
|
|
80
|
+
/** @deprecated Use `intakeUrl`. Accepted as an alias. */
|
|
81
|
+
intakeHost?: string;
|
|
71
82
|
/** Logical service name for the frontend app. */
|
|
72
83
|
serviceName: string;
|
|
73
84
|
/** Service version (e.g. git SHA). */
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sazabi/browser",
|
|
3
|
-
"description": "Sazabi browser observability SDK
|
|
4
|
-
"version": "0.2.0-dev.
|
|
3
|
+
"description": "Sazabi browser observability SDK — semantic event stream capture with W3C trace context propagation",
|
|
4
|
+
"version": "0.2.0-dev.ga3ff689",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"sideEffects": [
|
|
23
23
|
"./dist/register.js"
|
|
24
24
|
],
|
|
25
|
-
"license": "
|
|
25
|
+
"license": "Apache-2.0",
|
|
26
26
|
"homepage": "https://github.com/sazabi/browser",
|
|
27
27
|
"repository": {
|
|
28
28
|
"type": "git",
|
|
@@ -32,4 +32,4 @@
|
|
|
32
32
|
"access": "public",
|
|
33
33
|
"registry": "https://registry.npmjs.org"
|
|
34
34
|
}
|
|
35
|
-
}
|
|
35
|
+
}
|