@catch.dev/core 0.0.0-stage → 1.0.5

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.
Files changed (43) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +265 -2
  3. package/dist/browser/browser/fetch.d.ts +14 -0
  4. package/dist/browser/browser/globals.d.ts +23 -0
  5. package/dist/browser/browser/init.d.ts +2 -0
  6. package/dist/browser/browser/user.d.ts +16 -0
  7. package/dist/browser/core.d.ts +19 -0
  8. package/dist/browser/index.d.ts +3 -0
  9. package/dist/browser/index.js +2 -0
  10. package/dist/browser/index.js.map +1 -0
  11. package/dist/browser/log.d.ts +30 -0
  12. package/dist/cjs/browser/browser/fetch.d.ts +14 -0
  13. package/dist/cjs/browser/browser/globals.d.ts +23 -0
  14. package/dist/cjs/browser/browser/init.d.ts +2 -0
  15. package/dist/cjs/browser/browser/user.d.ts +16 -0
  16. package/dist/cjs/browser/core.d.ts +19 -0
  17. package/dist/cjs/browser/index.d.ts +3 -0
  18. package/dist/cjs/browser/index.js +2 -0
  19. package/dist/cjs/browser/index.js.map +1 -0
  20. package/dist/cjs/browser/log.d.ts +30 -0
  21. package/dist/cjs/node/core.d.ts +19 -0
  22. package/dist/cjs/node/index.d.ts +3 -0
  23. package/dist/cjs/node/index.js +1380 -0
  24. package/dist/cjs/node/index.js.map +1 -0
  25. package/dist/cjs/node/log.d.ts +30 -0
  26. package/dist/cjs/node/node/builtin.d.ts +10 -0
  27. package/dist/cjs/node/node/fetch.d.ts +11 -0
  28. package/dist/cjs/node/node/globals.d.ts +17 -0
  29. package/dist/cjs/node/node/init.d.ts +2 -0
  30. package/dist/cjs/node/node/rejections.d.ts +3 -0
  31. package/dist/cjs/node/node/user.d.ts +5 -0
  32. package/dist/cjs/package.json +3 -0
  33. package/dist/node/core.d.ts +19 -0
  34. package/dist/node/index.d.ts +3 -0
  35. package/dist/node/index.js +6 -0
  36. package/dist/node/log.d.ts +30 -0
  37. package/dist/node/node/builtin.d.ts +10 -0
  38. package/dist/node/node/fetch.d.ts +11 -0
  39. package/dist/node/node/globals.d.ts +17 -0
  40. package/dist/node/node/init.d.ts +2 -0
  41. package/dist/node/node/rejections.d.ts +3 -0
  42. package/dist/node/node/user.d.ts +5 -0
  43. package/package.json +101 -3
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 The catch.dev authors
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,266 @@
1
- # Temporary Holding Version
1
+ # @catch.dev/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The [catch.dev](https://catch.dev) error tracker for JavaScript. It runs in browsers and
4
+ in Node.js. The React, Next.js, Express and NestJS packages are built on it.
5
+
6
+ ```bash
7
+ npm install @catch.dev/core
8
+ ```
9
+
10
+ ```ts
11
+ import { init, log, identify } from '@catch.dev/core';
12
+
13
+ init('YOUR_ACCESS_KEY', '1.4.2', 'production');
14
+ ```
15
+
16
+ `init(key, version?, environment?, baseUrl?, options?)` starts it. From then on:
17
+
18
+ - **In a browser** it reports uncaught errors and unhandled promise rejections. It
19
+ listens with `addEventListener`, so your own `window.onerror` keeps working.
20
+ - **In Node.js** it reports uncaught exceptions and unhandled promise rejections, and
21
+ the process then does what it would have done without the SDK. With no listener of
22
+ your own that means Node prints the error and exits with code 1, a moment later (once
23
+ the report has left, 2 seconds at most). If your app has its own `uncaughtException`
24
+ or `unhandledRejection` listener, the SDK reports and leaves the rest as it is, exit
25
+ code included (a listener that ends the process at once leaves the report no time:
26
+ see below). The same goes for a framework that keeps its server running through
27
+ such errors, as Next.js does. More, and what Node's other `--unhandled-rejections`
28
+ modes mean for it, under [Crashes in Node.js](#crashes-in-nodejs).
29
+
30
+ Bundlers pick the browser build on their own. To name one, import
31
+ `@catch.dev/core/browser` or `@catch.dev/core/node`.
32
+
33
+ It loads with `import` and with `require()`, on Node 18 or later, and comes with its
34
+ types.
35
+
36
+ ## Reporting by hand
37
+
38
+ ```ts
39
+ try {
40
+ await chargeCard(order);
41
+ } catch (error) {
42
+ const caught = error instanceof Error ? error : new Error(String(error));
43
+ log(caught.message, 'checkout', undefined, undefined, caught, { orderId: order.id });
44
+ }
45
+ ```
46
+
47
+ `log(message, source?, line?, column?, error?, meta?)` never throws and never waits for
48
+ the network. `meta` is a flat map; values are sent as strings.
49
+
50
+ ## Users
51
+
52
+ ```ts
53
+ identify(user.id); // after sign-in (browser)
54
+ identify(''); // after sign-out
55
+ ```
56
+
57
+ In a browser the id is attached to later events. On a server `identify` does nothing: a
58
+ process serves many users at once, so pass the user with the event (`meta.userId`), which
59
+ is what the Express package does for you.
60
+
61
+ ## What is sent, and what is stored
62
+
63
+ Each event carries the message, the stack trace, the source file, line and column, the
64
+ time, your version and environment, and the access key. In a browser it also carries:
65
+
66
+ | | |
67
+ |---|---|
68
+ | `userAgent`, `language` | from the browser |
69
+ | `visitorId` | a random id, kept in `localStorage` under `catchdev.visitorId`, so one browser counts as one visitor |
70
+ | `userId` | only after `identify()`, kept under `catchdev.userId` |
71
+
72
+ An error in a script written into the page itself names the page's own address as its
73
+ file, query string included. The server records the address the event came from and an
74
+ approximate location derived from it. No cookies are set and none are sent.
75
+
76
+ When the visitor clicks, types or touches, a `ping` says that the site is in use, at most
77
+ once every five minutes from a page. The dashboard then shows your app as live before it
78
+ has sent an error. A ping carries no id and no browser details, and makes none. The server
79
+ stores nothing of it but when your access key last sent one.
80
+
81
+ Both are yours to turn off:
82
+
83
+ ```ts
84
+ init(key, version, environment, undefined, {
85
+ trackActivity: false, // no pings
86
+ rememberVisitor: false, // nothing in localStorage; ids last for the page only
87
+ });
88
+ ```
89
+
90
+ Turning `rememberVisitor` off also removes what an earlier visit stored under those two
91
+ keys. Turning it on later (once the visitor has agreed, say) keeps the ids from that
92
+ point. Nothing is written to storage before `init()` is called.
93
+
94
+ ## Delivery
95
+
96
+ An event is sent once, right away. If that fails it is tried again on a timer, five
97
+ times in all, a minute apart at first and further apart after that. A request that gets
98
+ no answer in 10 seconds counts as failed. At most 30 failed events wait at once and at
99
+ most 120 events a minute are sent. Nothing blocks your code, and nothing is printed to
100
+ the console. A host that freezes the process between requests, as AWS Lambda and Vercel do,
101
+ freezes an event that hasn't left yet with it: it goes out with the next request, and is lost
102
+ if the host stops the process first.
103
+
104
+ Without an access key nothing is sent.
105
+
106
+ ## Crashes in Node.js
107
+
108
+ Node ends a process over an error that nobody listens for, and so does a process
109
+ manager or another crash reporter that finds no listener but its own. A listener of the
110
+ SDK's that was always there would be counted by all of them, and a crashed process
111
+ would stay up. So the SDK listens as little as it can:
112
+
113
+ - **Uncaught exceptions.** The SDK is not a listener for `uncaughtException`. It
114
+ watches, and becomes one only for a crash that nobody else is listening for, for as
115
+ long as its report takes to leave (2 seconds at most). Then it takes itself away and
116
+ hands the error back to Node, which prints it and ends the process as it always does.
117
+ - **Unhandled rejections.** The SDK listens for `unhandledRejection` only while
118
+ something else does: your app, your framework, a test runner. Then it reports, and
119
+ what happens next is theirs. While nothing else listens, neither does the SDK: Node
120
+ raises the rejection as an uncaught exception (in its default mode), and that is
121
+ reported like any other crash.
122
+
123
+ An app that has taken uncaught exceptions over altogether
124
+ (`process.setUncaughtExceptionCaptureCallback()`, which is also what a `domain` with an
125
+ error handler does) is handed each one as it comes, and the SDK reports it. A
126
+ rejection inside such a domain goes to the domain and to nobody else, and is not
127
+ reported.
128
+
129
+ **A listener of yours that ends the process at once** (`process.exit(1)` in the
130
+ listener itself, after logging) leaves the report no time to leave: nothing is sent.
131
+ The SDK does not hold a process back that your code has decided to end. Give it a
132
+ moment, as you would for your own logs: end the process from a `setTimeout` of a
133
+ second or so, or let it end by itself.
134
+
135
+ So whatever decides by asking who listens gets the answer it gets without the SDK:
136
+
137
+ - **A process manager** such as PM2 in cluster mode, which ends a crashed process and
138
+ starts a new one unless your app has a listener of its own, still does. PM2 ends the
139
+ process at once, so the SDK's report of that crash may not have left.
140
+ - **Another crash reporter** such as Sentry still ends the process once its own report
141
+ has left, which usually leaves time for this one's too.
142
+ - **A promise library** that raises `unhandledRejection` for its own promises
143
+ (Bluebird, Q, zone.js) prints or keeps quiet as it does by itself.
144
+ - **A test runner** that passes a rejection on to the listeners behind its own (Mocha)
145
+ finds the ones your code added and no other.
146
+
147
+ Which rejections are reported follows from that:
148
+
149
+ | Node was started with | A rejection nobody handled is reported |
150
+ |---|---|
151
+ | nothing (the default), or `--unhandled-rejections=throw` | as the crash it becomes, or when something listens for `unhandledRejection` |
152
+ | `--unhandled-rejections=strict` | as the crash it becomes |
153
+ | `--unhandled-rejections=warn` or `warn-with-error-code` | from Node's warning about it, or when something listens |
154
+ | `--unhandled-rejections=none` | only when something listens: Node tells nobody else |
155
+
156
+ The mode is read from the command line and from `NODE_OPTIONS` as they are when the
157
+ SDK is first loaded (not from a `node.config.json`). It decides what is reported, and
158
+ how a program that failed as it started is handed back to Node. An app that changes
159
+ `NODE_OPTIONS` before it loads the SDK can be read wrongly, and so can a worker thread,
160
+ which is given its parent's copy of the variable while Node keeps to the mode the
161
+ process was started in. Rejections may then go unreported; a program that fails as it
162
+ starts still ends as it does without the SDK, with Node's warning about it printed
163
+ first where Node only warns.
164
+
165
+ A rejection of a promise library's own promise is reported when something listens for
166
+ `unhandledRejection`, in any mode but `strict`. (zone.js from 0.14 on tells listeners
167
+ that there was a rejection and not what it was, so there is nothing to report.) To
168
+ have the SDK told of every rejection, add a listener of your own; in the default mode
169
+ that also means the process no longer ends over one, which is Node's rule and not the
170
+ SDK's.
171
+
172
+ What does differ from a process without the SDK:
173
+
174
+ - **The program runs on while the report of a crash leaves**, for 2 seconds at most:
175
+ timers fire, requests are answered, and Node goes on to do what it would have done
176
+ next (a pending rejection is raised, a warning printed). A listener for
177
+ `uncaughtException` that is added in that time is handed the crash, and decides
178
+ what becomes of the process. If the program ends in that time by itself (a shutdown
179
+ handler that calls `process.exit(0)`), the SDK prints the error and sets the exit
180
+ code to 1, as the crash would have.
181
+ - Above an uncaught exception, Node prints the line of source it was thrown from.
182
+ Handed back by the SDK, the error is thrown from the SDK's file, so that is the line
183
+ shown. Above an unhandled rejection Node shows a line of its own
184
+ (`node:internal/process/promises`), where it shows the line that made the error as
185
+ long as nothing has read the error's stack; the SDK has read it, to report it. The
186
+ error, its message and its stack are as they were.
187
+ - A listener for `uncaughtExceptionMonitor` sees a crash that the SDK held back twice:
188
+ when it happened, and when the SDK hands it back.
189
+ - With `--unhandled-rejections=strict`, Node also prints its warning about the
190
+ rejection before the process ends. If your app listens for `unhandledRejection` in
191
+ that mode (and not for `uncaughtException`), the process ends at once, as it does
192
+ without the SDK, and the rejection is not reported: there is no moment for a report
193
+ to leave in.
194
+ - Two crashes are left to Node and not reported. A process started with
195
+ `--abort-on-uncaught-exception` aborts before any JavaScript is told. And an error
196
+ thrown while the process is already exiting (in an `exit` listener) ends it at once:
197
+ there is no later moment for a report to leave in.
198
+ - An `uncaughtException` event that your code emits by hand is not reported: only
199
+ what Node raises is. An `unhandledRejection` event emitted by hand is reported when
200
+ something listens for it, as a promise library's is.
201
+ - Under Next.js 16, which keeps your listeners for rejections in a list of its own and
202
+ prints a rejection when that list is empty: a listener that your code puts in front
203
+ with `prependOnceListener` after `init()` has left the list by the time the SDK is
204
+ asked, and the line Next prints for an empty list is printed although yours ran.
205
+
206
+ Bun deals with these errors in its own way, and this package is tested on it only in
207
+ passing. What the SDK does there:
208
+
209
+ - **Left to itself** (no `--unhandled-rejections`), Bun ends a process over an
210
+ unhandled rejection without raising an exception first. So the SDK listens for
211
+ rejections all the time, holds one that nobody else listens for until its report
212
+ has left, then steps aside and gives it back to Bun. The process ends with exit
213
+ code 1 and the error is reported. A listener of yours that is in front of the
214
+ SDK's (`prependListener`, `prependOnceListener`) has been told of a rejection
215
+ before the SDK is, and the rejection is left to it, also when it has gone by
216
+ then (added with `prependOnceListener`, or a test runner that steps aside to
217
+ pass the rejection on). Bun never says that a listener has been removed, so one
218
+ put in front and later taken away with `off()` is noticed one rejection late:
219
+ that rejection is reported, and the process does not end over it.
220
+ - **Started with `--unhandled-rejections`** (on the command line or in `BUN_OPTIONS`;
221
+ Bun does not read `NODE_OPTIONS`), Bun raises, warns or ends the process as Node
222
+ does in that mode, and the SDK does what it does on Node, with these differences:
223
+ - Bun never says that a listener has been removed (it has no `removeListener`
224
+ event). With `throw`, a listener of yours for `unhandledRejection` added with
225
+ `once()` is seen to have gone as soon as Bun is done with the rejection it was
226
+ called for, and Bun deals with the next ones itself. Otherwise (one taken away
227
+ with `off()` or `removeAllListeners()`, or added with `once()` in another mode)
228
+ the SDK finds out at the next rejection: it reports that one and gives it back
229
+ to Bun at once, which then does with it what it does when nobody listens (a
230
+ listener of yours added after it is not handed it). Bun deals with the one given
231
+ back after the other rejections of that turn. With `throw`, a listener of yours
232
+ for `uncaughtException` is then handed those first, and one that ends the
233
+ process with a code taken from the first error it is handed can end it with
234
+ another code. Until then, code that asks who listens (a promise library,
235
+ `process.listeners()`) counts the SDK's listener, and a promise library's
236
+ rejection in that time is reported and not printed by the library. A listener
237
+ that your code puts in front of the SDK's (`prependListener`) and then takes away
238
+ is noticed one rejection late: that rejection is reported, and not given back.
239
+ - Where Bun only warns (`warn`, `warn-with-error-code`), a rejection is reported
240
+ only when something listens for it. Bun prints a warning only while nothing
241
+ listens for warnings, so the SDK does not listen for them there.
242
+ - With `strict`, Bun tells your listener for rejections about a rejection after
243
+ raising it, also when nothing listens for `uncaughtException`. Node ends the
244
+ process first in that case; Bun ends it once your listener has run, and the
245
+ report may not have left by then. If your listener throws the rejection again,
246
+ it is reported once, whatever it was rejected with.
247
+
248
+ What Bun prints can differ from what it prints without the SDK: above an error it
249
+ shows where the SDK handed it back and not your own frames, and of several rejections
250
+ in one turn it prints one, which need not be the first. And if the program calls `process.exit(0)` while a report
251
+ is on its way, the exit code stays 0 there.
252
+
253
+ ## Settings in Node.js
254
+
255
+ `CATCH_API_KEY`, `CATCH_VERSION`, `CATCH_ENVIRONMENT` and `CATCH_BASE_URL` are used for
256
+ whatever `init()` was not given. They are read when an event is sent, so it does not
257
+ matter whether your `.env` file is loaded before or after the import.
258
+
259
+ ## The access key
260
+
261
+ The key names your app. It is not a secret: in a browser anyone can read it. It only
262
+ lets events be sent.
263
+
264
+ ## License
265
+
266
+ Apache-2.0
@@ -0,0 +1,14 @@
1
+ /** What the server said: its status, and how long it asked us to wait, if it did. */
2
+ export type Answer = {
3
+ status: number;
4
+ retryAfterSeconds?: number;
5
+ };
6
+ /**
7
+ * POST one event. Resolves with the status for any answer at all and rejects
8
+ * only when there was none (offline, blocked, timed out).
9
+ *
10
+ * The body of the answer is not read. An earlier version parsed it as JSON and
11
+ * treated a body it couldn't parse as a failed send, so an event the server
12
+ * had accepted with an empty answer was sent again and again.
13
+ */
14
+ export declare function post(url: string, body: unknown): Promise<Answer>;
@@ -0,0 +1,23 @@
1
+ export declare const setBaseUrl: (newUrl: string) => void;
2
+ export declare const getBaseUrl: () => string;
3
+ export declare const setKey: (newKey: string) => void;
4
+ export declare const getKey: () => string;
5
+ export declare const setVersion: (newVersion: string) => void;
6
+ export declare const getVersion: () => string;
7
+ export declare const setEnvironment: (newEnvironment: string) => void;
8
+ export declare const getEnvironment: () => string;
9
+ export declare const setTrackActivity: (on: boolean) => void;
10
+ export declare const getTrackActivity: () => boolean;
11
+ export declare const setRememberVisitor: (on: boolean) => void;
12
+ export declare const getRememberVisitor: () => boolean;
13
+ export declare const markStarted: () => void;
14
+ export declare const hasStarted: () => boolean;
15
+ export declare const getMeta: () => {
16
+ runtime: string;
17
+ userAgent?: undefined;
18
+ language?: undefined;
19
+ } | {
20
+ userAgent: string;
21
+ language: string;
22
+ runtime: string;
23
+ };
@@ -0,0 +1,2 @@
1
+ import type { LogFunction, LogActivityFunction } from "../log";
2
+ export declare const init: (log: LogFunction, logActivity: LogActivityFunction) => void;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Remove what is in storage under this SDK's keys. Called when the app turns
3
+ * `rememberVisitor` off: "store nothing" includes not leaving ids behind. What
4
+ * this page itself set is kept, for the page only.
5
+ */
6
+ export declare const forgetStoredIds: () => void;
7
+ export declare const getUserId: () => string;
8
+ /** Remember the app's id for the signed-in user. An empty id forgets it. */
9
+ export declare const setUserId: (id: string) => void;
10
+ export declare const identify: (id: string) => void;
11
+ export declare const generateUUID: () => string;
12
+ /**
13
+ * The anonymous id for this browser. Kept across visits unless the app turned
14
+ * that off (`rememberVisitor: false`), in which case it lasts for this page.
15
+ */
16
+ export declare const getVisitorId: () => string;
@@ -0,0 +1,19 @@
1
+ import { log } from "./log.js";
2
+ export interface InitOptions {
3
+ /**
4
+ * Say that the site is in use: a "ping" is sent when the visitor clicks, types
5
+ * or touches, at most once per five minutes, and the dashboard shows the app as
6
+ * live before it has sent an error. Browser only. Default true.
7
+ */
8
+ trackActivity?: boolean;
9
+ /**
10
+ * Keep the anonymous visitor id, and the user id given to `identify`, in the
11
+ * browser's storage, so the same browser counts as the same visitor on its
12
+ * next visit. When false both last for the page only, nothing is stored, and
13
+ * what an earlier visit stored is removed. Browser only. Default true.
14
+ */
15
+ rememberVisitor?: boolean;
16
+ }
17
+ declare const init: (givenKey?: string, givenVersion?: string, givenEnvironment?: string, givenBaseUrl?: string, options?: InitOptions) => void;
18
+ declare const identify: (userId: string) => void;
19
+ export { init, identify, log };
@@ -0,0 +1,3 @@
1
+ export { init, identify, log } from './core.js';
2
+ export type { InitOptions } from './core.js';
3
+ export type { LogFunction } from './log.js';
@@ -0,0 +1,2 @@
1
+ const t=Symbol.for("catch.dev/page-hooks");let e=0;async function n(t,n){const r=JSON.stringify(n),o=(i=r,"undefined"!=typeof TextEncoder?(new TextEncoder).encode(i).length:3*i.length);var i;const c=e+o<=16384;let a;c&&(e+=o);try{a=await async function(t,e,n){const r="undefined"!=typeof AbortController?new AbortController:void 0,o=r&&setTimeout((()=>r.abort()),1e4);try{return await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:e,credentials:"omit",keepalive:n,signal:r?.signal})}finally{void 0!==o&&clearTimeout(o)}}(t,r,c)}finally{c&&(e-=o)}const s=Number(a.headers?.get?.("retry-after"));return{status:a.status,retryAfterSeconds:Number.isFinite(s)&&s>0?s:void 0}}const r=function(){if("undefined"==typeof document||"undefined"==typeof Document)return null;try{const t=Object.getOwnPropertyDescriptor(Document.prototype,"currentScript")?.get,e=t?t.call(document):null;return e instanceof HTMLScriptElement?e:null}catch{return null}}(),o=t=>r&&r.getAttribute(t)||"";let i=o("data-url").replace(/\/+$/,"")||"https://api.catch.dev",c=`${i}/api/v1/event`,a=o("data-key"),s=o("data-version"),u=o("data-environment")||"unset",f="off"!==o("data-activity"),d="off"!==o("data-remember-visitor");const l=()=>c,y=()=>a,m=()=>s,p=()=>u,g=()=>d;let v=!1;const w=()=>"undefined"==typeof window||"undefined"==typeof navigator?{runtime:"server-render"}:{userAgent:navigator.userAgent,language:navigator.language,runtime:"browser"},x="catchdev.visitorId",h="catchdev.userId",b={},S=new Set,I=()=>"undefined"!=typeof window,k=()=>v&&g();function D(t,e){try{return window.localStorage.setItem(t,e),window.localStorage.getItem(t)===e}catch{return!1}}function A(t){if(!I())return"";if(k())try{const e=window.localStorage.getItem(t);if(null!==e){if(t===h&&S.has(t)&&b[t]){const e=b[t];return D(t,e)&&S.delete(t),e}return b[t]!==e&&delete b[t],S.delete(t),e}const n=b[t];return n?S.has(t)?(D(t,n)&&S.delete(t),n):(delete b[t],""):""}catch{}return b[t]??""}function O(t,e){I()&&(b[t]=e,k()&&D(t,e)?S.delete(t):S.add(t))}const T=()=>A(h),j=t=>{t?O(h,t):function(t){if(delete b[t],S.delete(t),I())try{window.localStorage.removeItem(t)}catch{}}(h)},E=()=>{if(!I())return"";let t=A(x);return t||(t="undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})),O(x,t)),t},B=18e5,M=[];let U,L=0;const N=(t,e)=>t.notBefore<=e||t.notBefore-e>B;async function $(t){let e=0;try{const r=await n(t.url,t.body);if(r.status>=200&&r.status<300)return;if(r.status>=400&&r.status<500&&408!==r.status&&429!==r.status)return;e=1e3*(r.retryAfterSeconds??0)}catch{}if(t.attempts+=1,t.attempts>=5)return;const r=6e4*2**(t.attempts-1),o=Math.min(Math.max(r,e),B);t.notBefore=Date.now()+o,M.push(t),M.length>30&&M.shift(),C()}function C(){if(0===M.length)return;const t=Date.now(),e=Math.min(...M.map((e=>N(e,t)?t:e.notBefore)));if(void 0!==U){if(L<=e)return;clearTimeout(U)}L=e,U=setTimeout(J,e-t),U.unref?.()}async function J(){U=void 0;const t=Date.now(),e=M.filter((e=>N(e,t)));for(const t of e)M.splice(M.indexOf(t),1);for(const t of e)await $(t);C()}let P=0,V=0;function F(t){if(null==t)return"";if("string"==typeof t)return t;try{return"object"==typeof t?JSON.stringify(t):String(t)}catch{return""}}function H(t){if("string"==typeof t)return t;if(null==t)return"Error";if("object"!=typeof t)return String(t);const e=t;return F(e.message??e.type??"Error")}function q(t){const e={};for(const[n,r]of Object.entries(t))null!=r&&""!==r&&(e[n]=F(r));return e}const z=async(t,e,n,r,o,i={})=>{try{if(!y())return!1;if(!function(){const t=Date.now();return(t-P>=6e4||t<P)&&(P=t,V=0),V+=1,V<=120}())return!1;const c=function(t,e,n,r,o,i){return{message:H(t),source:F(e),line:F(n),column:F(r),stack:F(o?.stack),time:(new Date).toISOString(),key:y(),version:m(),environment:p(),meta:q({visitorId:E(),userId:T(),...w(),...i})}}(t,e,n,r,o,i);return $({url:l(),body:c,attempts:0,notBefore:0}),!0}catch{return!1}};let G=0;const K=()=>{if(!f)return;const t=Date.now();if(t-G<3e5&&t>=G)return;if("browser"!==w().runtime)return;if(!y())return;G=t;const e={type:"activity",message:"ping",source:"",line:"",column:"",stack:"",time:(new Date).toISOString(),key:y(),version:m(),environment:p(),meta:{}};$({url:l(),body:e,attempts:0,notBefore:0})};let Q=!1;const R=(e,n,r,o,l={})=>{var y;e&&(a=e),n&&(s=n),r&&(u=r),o&&(i=o.replace(/\/+$/,""),c=`${i}/api/v1/event`),void 0!==l.trackActivity&&(y=l.trackActivity,f=y),void 0!==l.rememberVisitor&&(t=>{d=t})(l.rememberVisitor),v=!0,g()||(()=>{if(I())for(const t of[x,h]){try{window.localStorage.removeItem(t)}catch{}b[t]&&S.add(t)}})(),Q||(Q=!0,((e,n)=>{if("undefined"==typeof window||"undefined"==typeof document)return;const r=window;if(r[t])return;r[t]=!0;const o=t=>{try{t()}catch{}};window.addEventListener("error",(t=>{o((()=>{e(t.message,t.filename,t.lineno,t.colno,t.error)}))})),window.addEventListener("unhandledrejection",(t=>{o((()=>{const n=t.reason,r="object"==typeof n&&null!==n&&"string"==typeof n.message?n:void 0,o=r?r.message:"string"==typeof n?n:"Unhandled promise rejection";e(o,"",void 0,void 0,r)}))}));const i=()=>o(n);for(const t of["click","keydown","touchstart"])document.addEventListener(t,i,{passive:!0,capture:!0})})(z,K))},W=t=>{j(t),K()};export{W as identify,R as init,z as log};
2
+ //# sourceMappingURL=index.js.map