@ah-monica/browser 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +58 -0
- package/dist/client.d.ts +2 -0
- package/dist/client.js +380 -0
- package/dist/iife.d.ts +1 -0
- package/dist/iife.js +2 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +37 -0
- package/dist/monica.min.js +2 -0
- package/dist/transport.d.ts +10 -0
- package/dist/transport.js +127 -0
- package/dist/types.d.ts +45 -0
- package/dist/types.js +1 -0
- package/package.json +45 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# @ah-monica/browser
|
|
2
|
+
|
|
3
|
+
素のJavaScriptを含むbrowser application向けのMONICA SDKです。npm向けESMと、
|
|
4
|
+
`<script>`で読めるIIFE版を同じpackageから配布します。
|
|
5
|
+
|
|
6
|
+
DSNにはbrowserへ公開してよい`mpk_...` keyだけを指定してください。secretの
|
|
7
|
+
`msk_...` keyは初期化時に拒否します。
|
|
8
|
+
|
|
9
|
+
## ESM
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
import * as Monica from '@ah-monica/browser'
|
|
13
|
+
|
|
14
|
+
Monica.init({
|
|
15
|
+
dsn: window.MONICA_DSN,
|
|
16
|
+
environment: 'production',
|
|
17
|
+
release: window.APP_RELEASE,
|
|
18
|
+
screenId: 'admin-users',
|
|
19
|
+
beforeSend(event) {
|
|
20
|
+
delete event.user
|
|
21
|
+
if (event.request) delete event.request.headers
|
|
22
|
+
return event
|
|
23
|
+
},
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
Monica.captureException(error)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## script tag
|
|
30
|
+
|
|
31
|
+
```html
|
|
32
|
+
<script src="/vendor/monica.min.js"></script>
|
|
33
|
+
<script>
|
|
34
|
+
Monica.init({
|
|
35
|
+
dsn: window.MONICA_DSN,
|
|
36
|
+
environment: 'production',
|
|
37
|
+
release: window.APP_RELEASE,
|
|
38
|
+
screenId: 'student-learning'
|
|
39
|
+
})
|
|
40
|
+
</script>
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
IIFEはpackage内の`dist/monica.min.js`です。CDNから使う場合もversionを固定してください。
|
|
44
|
+
|
|
45
|
+
## 収集範囲
|
|
46
|
+
|
|
47
|
+
- `window.onerror`と`unhandledrejection`を自動収集
|
|
48
|
+
- 手動の`captureException()` / `captureMessage()`
|
|
49
|
+
- status 0または400以上のXMLHttpRequestをbreadcrumbへ記録(queryとfragmentは除去)
|
|
50
|
+
- queryとfragmentを除いたpage URL、`screen.id` tag、release
|
|
51
|
+
- 同じerrorを既定1秒の窓で重複排除
|
|
52
|
+
- 送信中のerrorと送信失敗を自動収集へ戻さない
|
|
53
|
+
|
|
54
|
+
`console.error`収集は既定OFFです。有効化する場合だけ
|
|
55
|
+
`captureConsoleErrors: true`を指定します。userは自動検出せず、
|
|
56
|
+
`setUser()`を明示的に呼んだ場合だけeventへ含めます。request body、Cookie、
|
|
57
|
+
Authorizationは自動収集しません。アプリケーション固有のPIIは`beforeSend`で
|
|
58
|
+
allowlist方式により除去してください。
|
package/dist/client.d.ts
ADDED
package/dist/client.js
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { createCoreClient, } from "@ah-monica/core";
|
|
2
|
+
import { createBrowserTransport } from "./transport.js";
|
|
3
|
+
export function createBrowserClient(options) {
|
|
4
|
+
const candidate = options.window ?? (typeof window === "undefined" ? undefined : window);
|
|
5
|
+
if (!candidate)
|
|
6
|
+
throw new Error("A browser window is required");
|
|
7
|
+
const runtime = candidate;
|
|
8
|
+
const fetchImplementation = options.fetch
|
|
9
|
+
?? (typeof runtime.fetch === "function" ? runtime.fetch.bind(runtime) : undefined);
|
|
10
|
+
if (!fetchImplementation)
|
|
11
|
+
throw new Error("A fetch implementation is required");
|
|
12
|
+
const maxBreadcrumbs = positiveInteger(options.maxBreadcrumbs) ? options.maxBreadcrumbs : 50;
|
|
13
|
+
const dedupeWindowMs = options.dedupeWindowMs ?? 1_000;
|
|
14
|
+
if (!Number.isFinite(dedupeWindowMs) || dedupeWindowMs < 0) {
|
|
15
|
+
throw new RangeError("dedupeWindowMs must be a non-negative number");
|
|
16
|
+
}
|
|
17
|
+
const requestTimeoutMs = options.requestTimeoutMs ?? 2_000;
|
|
18
|
+
const maxRetries = options.maxRetries ?? 2;
|
|
19
|
+
const now = options.now ?? (() => new Date());
|
|
20
|
+
const recent = new Map();
|
|
21
|
+
let sending = false;
|
|
22
|
+
let scope = emptyScope();
|
|
23
|
+
let closed = false;
|
|
24
|
+
const uninstallers = [];
|
|
25
|
+
const core = createCoreClient({
|
|
26
|
+
transport: createBrowserTransport({
|
|
27
|
+
dsn: options.dsn,
|
|
28
|
+
fetch: fetchImplementation,
|
|
29
|
+
requestTimeoutMs,
|
|
30
|
+
maxRetries,
|
|
31
|
+
onSendingChange(value) {
|
|
32
|
+
sending = value;
|
|
33
|
+
},
|
|
34
|
+
}),
|
|
35
|
+
environment: options.environment,
|
|
36
|
+
release: options.release,
|
|
37
|
+
sampleRate: options.sampleRate,
|
|
38
|
+
maxQueueSize: options.maxQueueSize,
|
|
39
|
+
batchSize: options.batchSize,
|
|
40
|
+
flushIntervalMs: options.flushIntervalMs,
|
|
41
|
+
now,
|
|
42
|
+
sdk: { name: "@ah-monica/browser", version: "0.1.0" },
|
|
43
|
+
async beforeSend(item, hint) {
|
|
44
|
+
const processed = options.beforeSend ? await options.beforeSend(item, hint) : item;
|
|
45
|
+
if (processed === null)
|
|
46
|
+
return null;
|
|
47
|
+
if (dedupeWindowMs === 0)
|
|
48
|
+
return processed;
|
|
49
|
+
const time = now().getTime();
|
|
50
|
+
const key = dedupeKey(processed);
|
|
51
|
+
const previous = recent.get(key);
|
|
52
|
+
if (previous !== undefined && time - previous < dedupeWindowMs)
|
|
53
|
+
return null;
|
|
54
|
+
recent.set(key, time);
|
|
55
|
+
for (const [recentKey, seenAt] of recent) {
|
|
56
|
+
if (time - seenAt >= dedupeWindowMs)
|
|
57
|
+
recent.delete(recentKey);
|
|
58
|
+
}
|
|
59
|
+
return processed;
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
function setUser(user) {
|
|
63
|
+
if (user === null)
|
|
64
|
+
delete scope.user;
|
|
65
|
+
else
|
|
66
|
+
scope.user = { ...user };
|
|
67
|
+
}
|
|
68
|
+
function addBreadcrumb(breadcrumb) {
|
|
69
|
+
scope.breadcrumbs.push({
|
|
70
|
+
...breadcrumb,
|
|
71
|
+
timestamp: breadcrumb.timestamp ?? now().toISOString(),
|
|
72
|
+
});
|
|
73
|
+
trimBreadcrumbs(scope.breadcrumbs, maxBreadcrumbs);
|
|
74
|
+
}
|
|
75
|
+
function withScope(callback) {
|
|
76
|
+
const parent = scope;
|
|
77
|
+
scope = cloneScope(parent);
|
|
78
|
+
const controller = scopeController(scope, addBreadcrumb);
|
|
79
|
+
try {
|
|
80
|
+
return callback(controller);
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
scope = parent;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function captureException(error, context = {}) {
|
|
87
|
+
return captureExceptionWithMechanism(error, context, {
|
|
88
|
+
type: "generic",
|
|
89
|
+
handled: true,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function captureExceptionWithMechanism(error, context, mechanism, location) {
|
|
93
|
+
if (closed || sending)
|
|
94
|
+
return Promise.resolve(null);
|
|
95
|
+
const exception = normalizeException(error, mechanism, location);
|
|
96
|
+
return core.capture({
|
|
97
|
+
type: "error",
|
|
98
|
+
platform: "javascript",
|
|
99
|
+
level: context.level ?? "error",
|
|
100
|
+
message: exception.values[0]?.value,
|
|
101
|
+
exception,
|
|
102
|
+
...contextValues(context),
|
|
103
|
+
}, { originalException: error });
|
|
104
|
+
}
|
|
105
|
+
function captureMessage(message, level = "info", context = {}) {
|
|
106
|
+
if (closed || sending)
|
|
107
|
+
return Promise.resolve(null);
|
|
108
|
+
return core.capture({
|
|
109
|
+
type: "error",
|
|
110
|
+
platform: "javascript",
|
|
111
|
+
level,
|
|
112
|
+
message,
|
|
113
|
+
...contextValues(context),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
function contextValues(context) {
|
|
117
|
+
const user = context.user ?? scope.user;
|
|
118
|
+
const tags = {
|
|
119
|
+
...(options.screenId ? { "screen.id": options.screenId } : {}),
|
|
120
|
+
...scope.tags,
|
|
121
|
+
...context.tags,
|
|
122
|
+
};
|
|
123
|
+
const contexts = { ...scope.contexts, ...context.contexts };
|
|
124
|
+
const breadcrumbs = [...scope.breadcrumbs, ...(context.breadcrumbs ?? [])].slice(-maxBreadcrumbs);
|
|
125
|
+
const request = context.request ?? {
|
|
126
|
+
// Query strings and fragments frequently contain tokens or student
|
|
127
|
+
// identifiers. The page path is sufficient for grouping and diagnosis.
|
|
128
|
+
url: sanitizeUrl(runtime.location.href, runtime.location.href),
|
|
129
|
+
method: "GET",
|
|
130
|
+
};
|
|
131
|
+
return {
|
|
132
|
+
...(user ? { user: { ...user } } : {}),
|
|
133
|
+
...(Object.keys(tags).length ? { tags } : {}),
|
|
134
|
+
...(Object.keys(contexts).length ? { contexts } : {}),
|
|
135
|
+
...(breadcrumbs.length ? { breadcrumbs } : {}),
|
|
136
|
+
request,
|
|
137
|
+
...(context.fingerprint ? { fingerprint: context.fingerprint } : {}),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function installGlobalHandlers() {
|
|
141
|
+
const onError = (event) => {
|
|
142
|
+
if (sending)
|
|
143
|
+
return;
|
|
144
|
+
const errorEvent = event;
|
|
145
|
+
const error = errorEvent.error ?? new Error(errorEvent.message || "Script error");
|
|
146
|
+
void captureExceptionWithMechanism(error, { level: "error" }, { type: "onerror", handled: false }, {
|
|
147
|
+
filename: errorEvent.filename,
|
|
148
|
+
lineno: errorEvent.lineno,
|
|
149
|
+
colno: errorEvent.colno,
|
|
150
|
+
});
|
|
151
|
+
};
|
|
152
|
+
const onUnhandledRejection = (event) => {
|
|
153
|
+
if (sending)
|
|
154
|
+
return;
|
|
155
|
+
const reason = event.reason;
|
|
156
|
+
void captureExceptionWithMechanism(reason, { level: "error" }, { type: "onunhandledrejection", handled: false });
|
|
157
|
+
};
|
|
158
|
+
const onVisibilityChange = () => {
|
|
159
|
+
if (runtime.document.visibilityState === "hidden")
|
|
160
|
+
void core.flush(requestTimeoutMs);
|
|
161
|
+
};
|
|
162
|
+
runtime.addEventListener("error", onError);
|
|
163
|
+
runtime.addEventListener("unhandledrejection", onUnhandledRejection);
|
|
164
|
+
runtime.document.addEventListener("visibilitychange", onVisibilityChange);
|
|
165
|
+
uninstallers.push(() => {
|
|
166
|
+
runtime.removeEventListener("error", onError);
|
|
167
|
+
runtime.removeEventListener("unhandledrejection", onUnhandledRejection);
|
|
168
|
+
runtime.document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
function installXhrBreadcrumbs() {
|
|
172
|
+
const constructor = runtime.XMLHttpRequest;
|
|
173
|
+
if (!constructor?.prototype)
|
|
174
|
+
return;
|
|
175
|
+
const prototype = constructor.prototype;
|
|
176
|
+
const originalOpen = prototype.open;
|
|
177
|
+
const originalSend = prototype.send;
|
|
178
|
+
const metadata = new WeakMap();
|
|
179
|
+
const mutable = prototype;
|
|
180
|
+
mutable.open = function (...args) {
|
|
181
|
+
const method = typeof args[0] === "string" ? args[0].toUpperCase() : "GET";
|
|
182
|
+
const url = sanitizeUrl(String(args[1] ?? ""), runtime.location.href);
|
|
183
|
+
metadata.set(this, { method, url, startedAt: now().getTime() });
|
|
184
|
+
originalOpen.apply(this, args);
|
|
185
|
+
};
|
|
186
|
+
mutable.send = function (...args) {
|
|
187
|
+
const onLoadEnd = () => {
|
|
188
|
+
const details = metadata.get(this);
|
|
189
|
+
if (!details || (this.status > 0 && this.status < 400))
|
|
190
|
+
return;
|
|
191
|
+
addBreadcrumb({
|
|
192
|
+
type: "http",
|
|
193
|
+
category: "xhr",
|
|
194
|
+
level: "warning",
|
|
195
|
+
message: `${details.method} ${details.url}`,
|
|
196
|
+
data: {
|
|
197
|
+
method: details.method,
|
|
198
|
+
url: details.url,
|
|
199
|
+
status: this.status,
|
|
200
|
+
duration_ms: Math.max(0, now().getTime() - details.startedAt),
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
};
|
|
204
|
+
this.addEventListener("loadend", onLoadEnd, { once: true });
|
|
205
|
+
originalSend.apply(this, args);
|
|
206
|
+
};
|
|
207
|
+
uninstallers.push(() => {
|
|
208
|
+
prototype.open = originalOpen;
|
|
209
|
+
prototype.send = originalSend;
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
function installConsoleCapture() {
|
|
213
|
+
const original = runtime.console.error;
|
|
214
|
+
runtime.console.error = (...values) => {
|
|
215
|
+
original.apply(runtime.console, values);
|
|
216
|
+
if (!sending)
|
|
217
|
+
void captureMessage(values.map(safeString).join(" "), "error");
|
|
218
|
+
};
|
|
219
|
+
uninstallers.push(() => {
|
|
220
|
+
runtime.console.error = original;
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
async function close(timeoutMs) {
|
|
224
|
+
closed = true;
|
|
225
|
+
while (uninstallers.length > 0)
|
|
226
|
+
uninstallers.pop()?.();
|
|
227
|
+
return core.close(timeoutMs);
|
|
228
|
+
}
|
|
229
|
+
if (options.autoCapture ?? true) {
|
|
230
|
+
installGlobalHandlers();
|
|
231
|
+
installXhrBreadcrumbs();
|
|
232
|
+
if (options.captureConsoleErrors ?? false)
|
|
233
|
+
installConsoleCapture();
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
captureException,
|
|
237
|
+
captureMessage,
|
|
238
|
+
setUser,
|
|
239
|
+
addBreadcrumb,
|
|
240
|
+
withScope,
|
|
241
|
+
flush: core.flush,
|
|
242
|
+
close,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
function normalizeException(error, mechanism, location) {
|
|
246
|
+
const values = [];
|
|
247
|
+
const seen = new Set();
|
|
248
|
+
let current = error;
|
|
249
|
+
while (current !== undefined && current !== null && values.length < 10 && !seen.has(current)) {
|
|
250
|
+
seen.add(current);
|
|
251
|
+
if (current instanceof Error) {
|
|
252
|
+
let frames = parseStack(current.stack);
|
|
253
|
+
if (frames.length === 0 && location?.filename) {
|
|
254
|
+
frames = [{
|
|
255
|
+
filename: location.filename,
|
|
256
|
+
...(location.lineno ? { lineno: location.lineno } : {}),
|
|
257
|
+
...(location.colno ? { colno: location.colno } : {}),
|
|
258
|
+
in_app: isInApp(location.filename),
|
|
259
|
+
}];
|
|
260
|
+
}
|
|
261
|
+
values.push({
|
|
262
|
+
type: current.name || "Error",
|
|
263
|
+
value: current.message,
|
|
264
|
+
...(frames.length ? { stacktrace: { frames } } : {}),
|
|
265
|
+
mechanism,
|
|
266
|
+
});
|
|
267
|
+
current = current.cause;
|
|
268
|
+
}
|
|
269
|
+
else {
|
|
270
|
+
values.push({
|
|
271
|
+
type: typeof current,
|
|
272
|
+
value: safeString(current),
|
|
273
|
+
mechanism,
|
|
274
|
+
});
|
|
275
|
+
current = undefined;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (values.length === 0) {
|
|
279
|
+
values.push({ type: "Error", value: "Unknown error", mechanism });
|
|
280
|
+
}
|
|
281
|
+
return { values };
|
|
282
|
+
}
|
|
283
|
+
function parseStack(stack) {
|
|
284
|
+
if (!stack)
|
|
285
|
+
return [];
|
|
286
|
+
const frames = [];
|
|
287
|
+
for (const line of stack.split("\n").slice(1, 201)) {
|
|
288
|
+
const chrome = /^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(line);
|
|
289
|
+
const firefox = /^(.*?)@(.+?):(\d+):(\d+)$/.exec(line);
|
|
290
|
+
const match = chrome ?? firefox;
|
|
291
|
+
if (!match)
|
|
292
|
+
continue;
|
|
293
|
+
const filename = match[2] ?? "[unknown]";
|
|
294
|
+
frames.push({
|
|
295
|
+
filename,
|
|
296
|
+
...(match[1] ? { function: match[1] } : {}),
|
|
297
|
+
lineno: Number(match[3]),
|
|
298
|
+
colno: Number(match[4]),
|
|
299
|
+
in_app: isInApp(filename),
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
return frames.reverse();
|
|
303
|
+
}
|
|
304
|
+
function isInApp(filename) {
|
|
305
|
+
return !/[\\/]node_modules[\\/]/.test(filename)
|
|
306
|
+
&& !/^chrome-extension:|^moz-extension:|^safari-extension:/.test(filename);
|
|
307
|
+
}
|
|
308
|
+
function dedupeKey(item) {
|
|
309
|
+
if (item.fingerprint?.length)
|
|
310
|
+
return `fingerprint:${item.fingerprint.join("|")}`;
|
|
311
|
+
const value = item.exception?.values[0];
|
|
312
|
+
const frame = value?.stacktrace?.frames.at(-1);
|
|
313
|
+
return JSON.stringify([
|
|
314
|
+
value?.type ?? "",
|
|
315
|
+
value?.value ?? item.message ?? "",
|
|
316
|
+
frame?.filename ?? "",
|
|
317
|
+
frame?.lineno ?? 0,
|
|
318
|
+
frame?.colno ?? 0,
|
|
319
|
+
]);
|
|
320
|
+
}
|
|
321
|
+
function sanitizeUrl(value, base) {
|
|
322
|
+
try {
|
|
323
|
+
const url = new URL(value, base);
|
|
324
|
+
url.username = "";
|
|
325
|
+
url.password = "";
|
|
326
|
+
url.search = "";
|
|
327
|
+
url.hash = "";
|
|
328
|
+
return url.toString();
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
return value.split(/[?#]/, 1)[0] ?? "";
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
function safeString(value) {
|
|
335
|
+
if (typeof value === "string")
|
|
336
|
+
return value;
|
|
337
|
+
if (value instanceof Error)
|
|
338
|
+
return `${value.name}: ${value.message}`;
|
|
339
|
+
try {
|
|
340
|
+
return JSON.stringify(value) ?? String(value);
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
return String(value);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function emptyScope() {
|
|
347
|
+
return { tags: {}, contexts: {}, breadcrumbs: [] };
|
|
348
|
+
}
|
|
349
|
+
function cloneScope(value) {
|
|
350
|
+
return {
|
|
351
|
+
...(value.user ? { user: { ...value.user } } : {}),
|
|
352
|
+
tags: { ...value.tags },
|
|
353
|
+
contexts: { ...value.contexts },
|
|
354
|
+
breadcrumbs: value.breadcrumbs.map((breadcrumb) => ({ ...breadcrumb })),
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
function scopeController(state, addBreadcrumb) {
|
|
358
|
+
return {
|
|
359
|
+
setUser(user) {
|
|
360
|
+
if (user === null)
|
|
361
|
+
delete state.user;
|
|
362
|
+
else
|
|
363
|
+
state.user = { ...user };
|
|
364
|
+
},
|
|
365
|
+
setTag(key, value) {
|
|
366
|
+
state.tags[key] = value;
|
|
367
|
+
},
|
|
368
|
+
setContext(key, value) {
|
|
369
|
+
state.contexts[key] = value;
|
|
370
|
+
},
|
|
371
|
+
addBreadcrumb,
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
function trimBreadcrumbs(breadcrumbs, max) {
|
|
375
|
+
if (breadcrumbs.length > max)
|
|
376
|
+
breadcrumbs.splice(0, breadcrumbs.length - max);
|
|
377
|
+
}
|
|
378
|
+
function positiveInteger(value) {
|
|
379
|
+
return value !== undefined && Number.isSafeInteger(value) && value > 0;
|
|
380
|
+
}
|
package/dist/iife.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/iife.js
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createBrowserClient } from "./client.js";
|
|
2
|
+
import type { BrowserCaptureContext, BrowserClientOptions, BrowserScope, MonicaBrowserClient } from "./types.js";
|
|
3
|
+
export declare function init(options: BrowserClientOptions): MonicaBrowserClient;
|
|
4
|
+
export declare function captureException(error: unknown, context?: BrowserCaptureContext): Promise<string | null>;
|
|
5
|
+
export declare function captureMessage(message: string, level?: BrowserCaptureContext["level"], context?: Omit<BrowserCaptureContext, "level">): Promise<string | null>;
|
|
6
|
+
export declare function setUser(user: Parameters<MonicaBrowserClient["setUser"]>[0]): void;
|
|
7
|
+
export declare function addBreadcrumb(breadcrumb: Parameters<MonicaBrowserClient["addBreadcrumb"]>[0]): void;
|
|
8
|
+
export declare function withScope<T>(callback: (scope: BrowserScope) => T): T;
|
|
9
|
+
export declare function flush(timeoutMs?: number): Promise<import("@ah-monica/core").FlushResult>;
|
|
10
|
+
export declare function close(timeoutMs?: number): Promise<import("@ah-monica/core").FlushResult>;
|
|
11
|
+
export { createBrowserClient };
|
|
12
|
+
export type { BrowserCaptureContext, BrowserClientOptions, BrowserScope, MonicaBrowserClient, } from "./types.js";
|
|
13
|
+
export type { BeforeSend, FlushResult, MonicaBreadcrumb, MonicaErrorItem, MonicaItem, MonicaLevel, MonicaRequest, MonicaUser, } from "@ah-monica/core";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { createBrowserClient } from "./client.js";
|
|
2
|
+
let currentClient;
|
|
3
|
+
export function init(options) {
|
|
4
|
+
if (currentClient)
|
|
5
|
+
void currentClient.close();
|
|
6
|
+
currentClient = createBrowserClient(options);
|
|
7
|
+
return currentClient;
|
|
8
|
+
}
|
|
9
|
+
export function captureException(error, context) {
|
|
10
|
+
return client().captureException(error, context);
|
|
11
|
+
}
|
|
12
|
+
export function captureMessage(message, level, context) {
|
|
13
|
+
return client().captureMessage(message, level, context);
|
|
14
|
+
}
|
|
15
|
+
export function setUser(user) {
|
|
16
|
+
client().setUser(user);
|
|
17
|
+
}
|
|
18
|
+
export function addBreadcrumb(breadcrumb) {
|
|
19
|
+
client().addBreadcrumb(breadcrumb);
|
|
20
|
+
}
|
|
21
|
+
export function withScope(callback) {
|
|
22
|
+
return client().withScope(callback);
|
|
23
|
+
}
|
|
24
|
+
export function flush(timeoutMs) {
|
|
25
|
+
return client().flush(timeoutMs);
|
|
26
|
+
}
|
|
27
|
+
export async function close(timeoutMs) {
|
|
28
|
+
const active = client();
|
|
29
|
+
currentClient = undefined;
|
|
30
|
+
return active.close(timeoutMs);
|
|
31
|
+
}
|
|
32
|
+
function client() {
|
|
33
|
+
if (!currentClient)
|
|
34
|
+
throw new Error("Monica.init() must be called first");
|
|
35
|
+
return currentClient;
|
|
36
|
+
}
|
|
37
|
+
export { createBrowserClient };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(()=>{var r=Object.defineProperty;var i=(F)=>F;function s(F,N){this[F]=i.bind(null,N)}var n=(F,N)=>{for(var J in N)r(F,J,{get:N[J],enumerable:!0,configurable:!0,set:s.bind(N,J)})};var o=((F)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(F,{get:(N,J)=>(typeof require<"u"?require:N)[J]}):F)(function(F){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+F+'" is not supported')});var v={};n(v,{withScope:()=>VF,setUser:()=>UF,init:()=>QF,flush:()=>jF,createBrowserClient:()=>g,close:()=>DF,captureMessage:()=>OF,captureException:()=>LF,addBreadcrumb:()=>RF});var t=new TextEncoder;function b(F){e(F);let N=F.maxQueueSize??100,J=Math.min(F.batchSize??30,N,100),$=F.flushIntervalMs??5000,G=F.sampleRate??1,Z=F.now??(()=>new Date),Q=F.random??Math.random,w=F.generateEventId??(()=>crypto.randomUUID()),C=F.sdk??{name:"@ah-monica/core",version:"0.1.0"},X=[],K=new Set,_=0,A=!1,j,D;function S(){if(j!==void 0||X.length===0||A)return;j=setTimeout(()=>{j=void 0,k()},$),j.unref?.()}function E(){if(j===void 0)return;clearTimeout(j),j=void 0}async function k(R){if(D)return D;if(X.length===0)return!0;E();let W=0,O,V="";while(X.length>0&&!O){V=Z().toISOString();let Y=Math.min(J,X.length);while(Y>0){let H={sdk:C,sent_at:V,discarded:_,items:X.slice(0,Y)},U=Number.POSITIVE_INFINITY;try{U=t.encode(JSON.stringify(H)).byteLength}catch{}if(U<=1e6){O=X.splice(0,Y);break}Y-=1}if(!O)X.shift(),_+=1,W+=1}if(!O)return W===0;let I=_;_=0;let P=F.transport.send({sdk:C,sent_at:V,discarded:I,items:O},R).then((Y)=>{if(!Y.accepted)_+=O.length+I;return Y.accepted&&W===0}).catch(()=>{return _+=O.length+I,!1});D=P;try{return await P}finally{if(D===P)D=void 0;S()}}function h(R,W={}){if(A)return Promise.resolve(null);let O=(async()=>{if(Q()>=G)return null;let V=typeof R.event_id==="string"?R.event_id:w(),I=typeof R.timestamp==="string"?R.timestamp:Z().toISOString(),P={...R,event_id:V,timestamp:I,environment:R.environment??F.environment,...F.release!==void 0&&R.release===void 0?{release:F.release}:{}};if(F.beforeSend){let Y=await F.beforeSend(P,W);if(Y===null)return null;P=Y}if(X.length>=N)X.shift(),_+=1;if(X.push(P),P.level==="fatal"||X.length>=J)k();else S();return V})().catch(()=>null);return K.add(O),O.finally(()=>K.delete(O)),O}async function q(R=2000){let W=Date.now()+Math.max(0,R),O=!0;while(K.size>0){let V=W-Date.now();if(V<=0)return{accepted:!1,discarded:_,remaining:X.length};if(!await d(Promise.allSettled([...K]),V))return{accepted:!1,discarded:_,remaining:X.length}}while(X.length>0||D){let V=W-Date.now();if(V<=0)return{accepted:!1,discarded:_,remaining:X.length};let I=D??k(),P=await d(I,V);if(P===void 0)return{accepted:!1,discarded:_,remaining:X.length};O=O&&P}return E(),{accepted:O,discarded:_,remaining:X.length}}async function x(R){return A=!0,E(),q(R)}return{capture:h,flush:q,close:x}}function e(F){if(typeof F.environment!=="string"||!F.environment.trim())throw TypeError("environment must not be empty");if(F.sampleRate!==void 0&&(!Number.isFinite(F.sampleRate)||F.sampleRate<0||F.sampleRate>1))throw RangeError("sampleRate must be between 0 and 1");for(let[N,J]of[["maxQueueSize",F.maxQueueSize],["batchSize",F.batchSize],["flushIntervalMs",F.flushIntervalMs]])if(J!==void 0&&(!Number.isSafeInteger(J)||J<=0))throw RangeError(`${N} must be a positive integer`)}async function d(F,N){let J;try{return await Promise.race([F,new Promise(($)=>{J=setTimeout(()=>$(void 0),N),J.unref?.()})])}finally{if(J!==void 0)clearTimeout(J)}}function p(F){if(!Number.isSafeInteger(F.requestTimeoutMs)||F.requestTimeoutMs<=0)throw RangeError("requestTimeoutMs must be a positive integer");if(!Number.isSafeInteger(F.maxRetries)||F.maxRetries<0)throw RangeError("maxRetries must be a non-negative integer");let{endpoint:N,key:J}=JF(F.dsn);return{async send($,G){if(G?.aborted)return{accepted:!1};F.onSendingChange(!0);try{let Z=await NF($);for(let Q=0;Q<=F.maxRetries;Q+=1){let w=new AbortController,C=()=>w.abort(G?.reason);if(G?.addEventListener("abort",C,{once:!0}),G?.aborted)C();let X=setTimeout(()=>w.abort(),F.requestTimeoutMs);try{let K=await F.fetch(N,{method:"POST",headers:{"Content-Type":"application/json","Content-Encoding":"gzip","X-Monica-Key":J},body:Z,keepalive:!0,signal:w.signal});if(K.ok)return{accepted:!0,status:K.status};if(K.status!==429&&K.status<500)return{accepted:!1,status:K.status};if(Q===F.maxRetries)return{accepted:!1,status:K.status};let _=K.status===429?PF(K.headers.get("Retry-After")):void 0;await c(_??m(Q),G)}catch{if(G?.aborted||Q===F.maxRetries)return{accepted:!1};await c(m(Q),G).catch(()=>{return})}finally{clearTimeout(X),G?.removeEventListener("abort",C)}}return{accepted:!1}}catch{return{accepted:!1}}finally{F.onSendingChange(!1)}}}}function JF(F){let N;try{N=new URL(F)}catch{throw TypeError("dsn must be a valid URL")}let J=decodeURIComponent(N.username);if(!J)throw TypeError("dsn must include an API key as the username");if(!J.startsWith("mpk_"))throw TypeError("browser dsn must contain a public mpk_ key; never expose an msk_ key");let $=N.protocol==="http:"&&(N.hostname==="localhost"||N.hostname==="127.0.0.1");if(N.protocol!=="https:"&&!$)throw TypeError("dsn must use https except for localhost");return N.username="",N.password="",N.pathname="/v1/envelope",N.search="",N.hash="",{endpoint:N.toString(),key:J}}async function NF(F){let N=new Blob([JSON.stringify(F)]).stream();return new Response(N.pipeThrough(new CompressionStream("gzip"))).arrayBuffer()}function PF(F){if(!F||!/^\d+$/.test(F))return;return Math.min(Number(F)*1000,60000)}function m(F){return Math.floor(Math.min(1000*2**F,1e4)*(0.5+Math.random()*0.5))}function c(F,N){if(N?.aborted)return Promise.reject(N.reason);return new Promise((J,$)=>{let G=()=>{clearTimeout(Z),N?.removeEventListener("abort",G),$(N?.reason)},Z=setTimeout(()=>{N?.removeEventListener("abort",G),J()},F);if(N?.addEventListener("abort",G,{once:!0}),N?.aborted)G()})}function g(F){let N=F.window??(typeof window>"u"?void 0:window);if(!N)throw Error("A browser window is required");let J=N,$=F.fetch??(typeof J.fetch==="function"?J.fetch.bind(J):void 0);if(!$)throw Error("A fetch implementation is required");let G=KF(F.maxBreadcrumbs)?F.maxBreadcrumbs:50,Z=F.dedupeWindowMs??1000;if(!Number.isFinite(Z)||Z<0)throw RangeError("dedupeWindowMs must be a non-negative number");let Q=F.requestTimeoutMs??2000,w=F.maxRetries??2,C=F.now??(()=>new Date),X=new Map,K=!1,_=$F(),A=!1,j=[],D=b({transport:p({dsn:F.dsn,fetch:$,requestTimeoutMs:Q,maxRetries:w,onSendingChange(P){K=P}}),environment:F.environment,release:F.release,sampleRate:F.sampleRate,maxQueueSize:F.maxQueueSize,batchSize:F.batchSize,flushIntervalMs:F.flushIntervalMs,now:C,sdk:{name:"@ah-monica/browser",version:"0.1.0"},async beforeSend(P,Y){let H=F.beforeSend?await F.beforeSend(P,Y):P;if(H===null)return null;if(Z===0)return H;let U=C().getTime(),L=_F(H),T=X.get(L);if(T!==void 0&&U-T<Z)return null;X.set(L,U);for(let[B,y]of X)if(U-y>=Z)X.delete(B);return H}});function S(P){if(P===null)delete _.user;else _.user={...P}}function E(P){_.breadcrumbs.push({...P,timestamp:P.timestamp??C().toISOString()}),HF(_.breadcrumbs,G)}function k(P){let Y=_;_=GF(Y);let H=XF(_,E);try{return P(H)}finally{_=Y}}function h(P,Y={}){return q(P,Y,{type:"generic",handled:!0})}function q(P,Y,H,U){if(A||K)return Promise.resolve(null);let L=YF(P,H,U);return D.capture({type:"error",platform:"javascript",level:Y.level??"error",message:L.values[0]?.value,exception:L,...R(Y)},{originalException:P})}function x(P,Y="info",H={}){if(A||K)return Promise.resolve(null);return D.capture({type:"error",platform:"javascript",level:Y,message:P,...R(H)})}function R(P){let Y=P.user??_.user,H={...F.screenId?{"screen.id":F.screenId}:{},..._.tags,...P.tags},U={..._.contexts,...P.contexts},L=[..._.breadcrumbs,...P.breadcrumbs??[]].slice(-G),T=P.request??{url:l(J.location.href,J.location.href),method:"GET"};return{...Y?{user:{...Y}}:{},...Object.keys(H).length?{tags:H}:{},...Object.keys(U).length?{contexts:U}:{},...L.length?{breadcrumbs:L}:{},request:T,...P.fingerprint?{fingerprint:P.fingerprint}:{}}}function W(){let P=(U)=>{if(K)return;let L=U,T=L.error??Error(L.message||"Script error");q(T,{level:"error"},{type:"onerror",handled:!1},{filename:L.filename,lineno:L.lineno,colno:L.colno})},Y=(U)=>{if(K)return;let L=U.reason;q(L,{level:"error"},{type:"onunhandledrejection",handled:!1})},H=()=>{if(J.document.visibilityState==="hidden")D.flush(Q)};J.addEventListener("error",P),J.addEventListener("unhandledrejection",Y),J.document.addEventListener("visibilitychange",H),j.push(()=>{J.removeEventListener("error",P),J.removeEventListener("unhandledrejection",Y),J.document.removeEventListener("visibilitychange",H)})}function O(){let P=J.XMLHttpRequest;if(!P?.prototype)return;let Y=P.prototype,H=Y.open,U=Y.send,L=new WeakMap,T=Y;T.open=function(...B){let y=typeof B[0]==="string"?B[0].toUpperCase():"GET",z=l(String(B[1]??""),J.location.href);L.set(this,{method:y,url:z,startedAt:C().getTime()}),H.apply(this,B)},T.send=function(...B){let y=()=>{let z=L.get(this);if(!z||this.status>0&&this.status<400)return;E({type:"http",category:"xhr",level:"warning",message:`${z.method} ${z.url}`,data:{method:z.method,url:z.url,status:this.status,duration_ms:Math.max(0,C().getTime()-z.startedAt)}})};this.addEventListener("loadend",y,{once:!0}),U.apply(this,B)},j.push(()=>{Y.open=H,Y.send=U})}function V(){let P=J.console.error;J.console.error=(...Y)=>{if(P.apply(J.console,Y),!K)x(Y.map(a).join(" "),"error")},j.push(()=>{J.console.error=P})}async function I(P){A=!0;while(j.length>0)j.pop()?.();return D.close(P)}if(F.autoCapture??!0){if(W(),O(),F.captureConsoleErrors??!1)V()}return{captureException:h,captureMessage:x,setUser:S,addBreadcrumb:E,withScope:k,flush:D.flush,close:I}}function YF(F,N,J){let $=[],G=new Set,Z=F;while(Z!==void 0&&Z!==null&&$.length<10&&!G.has(Z))if(G.add(Z),Z instanceof Error){let Q=ZF(Z.stack);if(Q.length===0&&J?.filename)Q=[{filename:J.filename,...J.lineno?{lineno:J.lineno}:{},...J.colno?{colno:J.colno}:{},in_app:u(J.filename)}];$.push({type:Z.name||"Error",value:Z.message,...Q.length?{stacktrace:{frames:Q}}:{},mechanism:N}),Z=Z.cause}else $.push({type:typeof Z,value:a(Z),mechanism:N}),Z=void 0;if($.length===0)$.push({type:"Error",value:"Unknown error",mechanism:N});return{values:$}}function ZF(F){if(!F)return[];let N=[];for(let J of F.split(`
|
|
2
|
+
`).slice(1,201)){let $=/^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(J),G=/^(.*?)@(.+?):(\d+):(\d+)$/.exec(J),Z=$??G;if(!Z)continue;let Q=Z[2]??"[unknown]";N.push({filename:Q,...Z[1]?{function:Z[1]}:{},lineno:Number(Z[3]),colno:Number(Z[4]),in_app:u(Q)})}return N.reverse()}function u(F){return!/[\\/]node_modules[\\/]/.test(F)&&!/^chrome-extension:|^moz-extension:|^safari-extension:/.test(F)}function _F(F){if(F.fingerprint?.length)return`fingerprint:${F.fingerprint.join("|")}`;let N=F.exception?.values[0],J=N?.stacktrace?.frames.at(-1);return JSON.stringify([N?.type??"",N?.value??F.message??"",J?.filename??"",J?.lineno??0,J?.colno??0])}function l(F,N){try{let J=new URL(F,N);return J.username="",J.password="",J.search="",J.hash="",J.toString()}catch{return F.split(/[?#]/,1)[0]??""}}function a(F){if(typeof F==="string")return F;if(F instanceof Error)return`${F.name}: ${F.message}`;try{return JSON.stringify(F)??String(F)}catch{return String(F)}}function $F(){return{tags:{},contexts:{},breadcrumbs:[]}}function GF(F){return{...F.user?{user:{...F.user}}:{},tags:{...F.tags},contexts:{...F.contexts},breadcrumbs:F.breadcrumbs.map((N)=>({...N}))}}function XF(F,N){return{setUser(J){if(J===null)delete F.user;else F.user={...J}},setTag(J,$){F.tags[J]=$},setContext(J,$){F.contexts[J]=$},addBreadcrumb:N}}function HF(F,N){if(F.length>N)F.splice(0,F.length-N)}function KF(F){return F!==void 0&&Number.isSafeInteger(F)&&F>0}var f;function QF(F){if(f)f.close();return f=g(F),f}function LF(F,N){return M().captureException(F,N)}function OF(F,N,J){return M().captureMessage(F,N,J)}function UF(F){M().setUser(F)}function RF(F){M().addBreadcrumb(F)}function VF(F){return M().withScope(F)}function jF(F){return M().flush(F)}async function DF(F){let N=M();return f=void 0,N.close(F)}function M(){if(!f)throw Error("Monica.init() must be called first");return f}globalThis.Monica=v;})();
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { FetchLike, MonicaTransport } from "@ah-monica/core";
|
|
2
|
+
interface BrowserTransportOptions {
|
|
3
|
+
dsn: string;
|
|
4
|
+
fetch: FetchLike;
|
|
5
|
+
requestTimeoutMs: number;
|
|
6
|
+
maxRetries: number;
|
|
7
|
+
onSendingChange(sending: boolean): void;
|
|
8
|
+
}
|
|
9
|
+
export declare function createBrowserTransport(options: BrowserTransportOptions): MonicaTransport;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
export function createBrowserTransport(options) {
|
|
2
|
+
if (!Number.isSafeInteger(options.requestTimeoutMs) || options.requestTimeoutMs <= 0) {
|
|
3
|
+
throw new RangeError("requestTimeoutMs must be a positive integer");
|
|
4
|
+
}
|
|
5
|
+
if (!Number.isSafeInteger(options.maxRetries) || options.maxRetries < 0) {
|
|
6
|
+
throw new RangeError("maxRetries must be a non-negative integer");
|
|
7
|
+
}
|
|
8
|
+
const { endpoint, key } = parseDsn(options.dsn);
|
|
9
|
+
return {
|
|
10
|
+
async send(envelope, outerSignal) {
|
|
11
|
+
if (outerSignal?.aborted)
|
|
12
|
+
return { accepted: false };
|
|
13
|
+
options.onSendingChange(true);
|
|
14
|
+
try {
|
|
15
|
+
const body = await gzipEnvelope(envelope);
|
|
16
|
+
for (let attempt = 0; attempt <= options.maxRetries; attempt += 1) {
|
|
17
|
+
const controller = new AbortController();
|
|
18
|
+
const abort = () => controller.abort(outerSignal?.reason);
|
|
19
|
+
outerSignal?.addEventListener("abort", abort, { once: true });
|
|
20
|
+
// Close the race between send()'s initial check and listener install.
|
|
21
|
+
if (outerSignal?.aborted)
|
|
22
|
+
abort();
|
|
23
|
+
const timeout = setTimeout(() => controller.abort(), options.requestTimeoutMs);
|
|
24
|
+
try {
|
|
25
|
+
const response = await options.fetch(endpoint, {
|
|
26
|
+
method: "POST",
|
|
27
|
+
headers: {
|
|
28
|
+
"Content-Type": "application/json",
|
|
29
|
+
"Content-Encoding": "gzip",
|
|
30
|
+
"X-Monica-Key": key,
|
|
31
|
+
},
|
|
32
|
+
body,
|
|
33
|
+
keepalive: true,
|
|
34
|
+
signal: controller.signal,
|
|
35
|
+
});
|
|
36
|
+
if (response.ok)
|
|
37
|
+
return { accepted: true, status: response.status };
|
|
38
|
+
if (response.status !== 429 && response.status < 500) {
|
|
39
|
+
return { accepted: false, status: response.status };
|
|
40
|
+
}
|
|
41
|
+
if (attempt === options.maxRetries) {
|
|
42
|
+
return { accepted: false, status: response.status };
|
|
43
|
+
}
|
|
44
|
+
const retryAfter = response.status === 429
|
|
45
|
+
? retryAfterMilliseconds(response.headers.get("Retry-After"))
|
|
46
|
+
: undefined;
|
|
47
|
+
await delay(retryAfter ?? backoff(attempt), outerSignal);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
if (outerSignal?.aborted || attempt === options.maxRetries) {
|
|
51
|
+
return { accepted: false };
|
|
52
|
+
}
|
|
53
|
+
await delay(backoff(attempt), outerSignal).catch(() => undefined);
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
clearTimeout(timeout);
|
|
57
|
+
outerSignal?.removeEventListener("abort", abort);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return { accepted: false };
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return { accepted: false };
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
options.onSendingChange(false);
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function parseDsn(dsn) {
|
|
72
|
+
let url;
|
|
73
|
+
try {
|
|
74
|
+
url = new URL(dsn);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
throw new TypeError("dsn must be a valid URL");
|
|
78
|
+
}
|
|
79
|
+
const key = decodeURIComponent(url.username);
|
|
80
|
+
if (!key)
|
|
81
|
+
throw new TypeError("dsn must include an API key as the username");
|
|
82
|
+
if (!key.startsWith("mpk_")) {
|
|
83
|
+
throw new TypeError("browser dsn must contain a public mpk_ key; never expose an msk_ key");
|
|
84
|
+
}
|
|
85
|
+
const localHttp = url.protocol === "http:"
|
|
86
|
+
&& (url.hostname === "localhost" || url.hostname === "127.0.0.1");
|
|
87
|
+
if (url.protocol !== "https:" && !localHttp) {
|
|
88
|
+
throw new TypeError("dsn must use https except for localhost");
|
|
89
|
+
}
|
|
90
|
+
url.username = "";
|
|
91
|
+
url.password = "";
|
|
92
|
+
url.pathname = "/v1/envelope";
|
|
93
|
+
url.search = "";
|
|
94
|
+
url.hash = "";
|
|
95
|
+
return { endpoint: url.toString(), key };
|
|
96
|
+
}
|
|
97
|
+
async function gzipEnvelope(envelope) {
|
|
98
|
+
const source = new Blob([JSON.stringify(envelope)]).stream();
|
|
99
|
+
return new Response(source.pipeThrough(new CompressionStream("gzip"))).arrayBuffer();
|
|
100
|
+
}
|
|
101
|
+
function retryAfterMilliseconds(value) {
|
|
102
|
+
if (!value || !/^\d+$/.test(value))
|
|
103
|
+
return undefined;
|
|
104
|
+
return Math.min(Number(value) * 1_000, 60_000);
|
|
105
|
+
}
|
|
106
|
+
function backoff(attempt) {
|
|
107
|
+
return Math.floor(Math.min(1_000 * 2 ** attempt, 10_000) * (0.5 + Math.random() * 0.5));
|
|
108
|
+
}
|
|
109
|
+
function delay(milliseconds, signal) {
|
|
110
|
+
if (signal?.aborted)
|
|
111
|
+
return Promise.reject(signal.reason);
|
|
112
|
+
return new Promise((resolve, reject) => {
|
|
113
|
+
const onAbort = () => {
|
|
114
|
+
clearTimeout(timeout);
|
|
115
|
+
signal?.removeEventListener("abort", onAbort);
|
|
116
|
+
reject(signal?.reason);
|
|
117
|
+
};
|
|
118
|
+
const timeout = setTimeout(() => {
|
|
119
|
+
signal?.removeEventListener("abort", onAbort);
|
|
120
|
+
resolve();
|
|
121
|
+
}, milliseconds);
|
|
122
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
123
|
+
// Close the race between the first aborted check and listener install.
|
|
124
|
+
if (signal?.aborted)
|
|
125
|
+
onAbort();
|
|
126
|
+
});
|
|
127
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { BeforeSend, FetchLike, FlushResult, MonicaBreadcrumb, MonicaLevel, MonicaRequest, MonicaUser } from "@ah-monica/core";
|
|
2
|
+
export interface BrowserClientOptions {
|
|
3
|
+
dsn: string;
|
|
4
|
+
environment: string;
|
|
5
|
+
release?: string;
|
|
6
|
+
screenId?: string;
|
|
7
|
+
sampleRate?: number;
|
|
8
|
+
maxBreadcrumbs?: number;
|
|
9
|
+
maxQueueSize?: number;
|
|
10
|
+
batchSize?: number;
|
|
11
|
+
flushIntervalMs?: number;
|
|
12
|
+
requestTimeoutMs?: number;
|
|
13
|
+
maxRetries?: number;
|
|
14
|
+
dedupeWindowMs?: number;
|
|
15
|
+
autoCapture?: boolean;
|
|
16
|
+
captureConsoleErrors?: boolean;
|
|
17
|
+
beforeSend?: BeforeSend;
|
|
18
|
+
fetch?: FetchLike;
|
|
19
|
+
window?: Window & typeof globalThis;
|
|
20
|
+
now?: () => Date;
|
|
21
|
+
}
|
|
22
|
+
export interface BrowserCaptureContext {
|
|
23
|
+
level?: MonicaLevel;
|
|
24
|
+
user?: MonicaUser;
|
|
25
|
+
tags?: Record<string, string>;
|
|
26
|
+
contexts?: Record<string, unknown>;
|
|
27
|
+
breadcrumbs?: MonicaBreadcrumb[];
|
|
28
|
+
request?: MonicaRequest;
|
|
29
|
+
fingerprint?: string[];
|
|
30
|
+
}
|
|
31
|
+
export interface BrowserScope {
|
|
32
|
+
setUser(user: MonicaUser | null): void;
|
|
33
|
+
setTag(key: string, value: string): void;
|
|
34
|
+
setContext(key: string, value: unknown): void;
|
|
35
|
+
addBreadcrumb(breadcrumb: MonicaBreadcrumb): void;
|
|
36
|
+
}
|
|
37
|
+
export interface MonicaBrowserClient {
|
|
38
|
+
captureException(error: unknown, context?: BrowserCaptureContext): Promise<string | null>;
|
|
39
|
+
captureMessage(message: string, level?: MonicaLevel, context?: Omit<BrowserCaptureContext, "level">): Promise<string | null>;
|
|
40
|
+
setUser(user: MonicaUser | null): void;
|
|
41
|
+
addBreadcrumb(breadcrumb: MonicaBreadcrumb): void;
|
|
42
|
+
withScope<T>(callback: (scope: BrowserScope) => T): T;
|
|
43
|
+
flush(timeoutMs?: number): Promise<FlushResult>;
|
|
44
|
+
close(timeoutMs?: number): Promise<FlushResult>;
|
|
45
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ah-monica/browser",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Browser SDK for sending JavaScript errors to MONICA",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": ["dist", "README.md", "LICENSE"],
|
|
9
|
+
"main": "./dist/index.js",
|
|
10
|
+
"module": "./dist/index.js",
|
|
11
|
+
"unpkg": "./dist/monica.min.js",
|
|
12
|
+
"jsdelivr": "./dist/monica.min.js",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./monica.min.js": "./dist/monica.min.js"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "bun run build:core && tsc -p tsconfig.build.json && bun build ./dist/iife.js --outfile ./dist/monica.min.js --format=iife --minify",
|
|
23
|
+
"build:core": "bun run --filter @ah-monica/core build",
|
|
24
|
+
"pack:check": "bun run build && bun pm pack --dry-run",
|
|
25
|
+
"test": "bun run build:core && bun test",
|
|
26
|
+
"test:runtime": "bun run build && node test/runtime-smoke.mjs",
|
|
27
|
+
"typecheck": "bun run build:core && tsc --noEmit"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public",
|
|
31
|
+
"registry": "https://registry.npmjs.org"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/Accel-Hack/monica.git",
|
|
36
|
+
"directory": "sdk/typescript/browser"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@ah-monica/core": "0.1.0"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@types/bun": "^1.2.21",
|
|
43
|
+
"typescript": "^5.9.2"
|
|
44
|
+
}
|
|
45
|
+
}
|