@ohbug/node 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,30 @@
1
+ import { OhbugBaseDetail, OhbugClient, OhbugConfig } from "@ohbug/types";
2
+
3
+ //#region src/client.d.ts
4
+ interface OhbugNodeClient {
5
+ __client: OhbugClient | null;
6
+ setup: (config: OhbugConfig) => OhbugClient;
7
+ }
8
+ declare const NodeClient: OhbugNodeClient;
9
+ //#endregion
10
+ //#region src/handle/uncaughtExceptionHandler.d.ts
11
+ interface UncaughtExceptionDetail extends OhbugBaseDetail {
12
+ name: string;
13
+ stack?: string;
14
+ origin?: string;
15
+ }
16
+ //#endregion
17
+ //#region src/handle/unhandledRejectionHandler.d.ts
18
+ interface UnhandledRejectionDetail extends OhbugBaseDetail {
19
+ name?: string;
20
+ stack?: string;
21
+ }
22
+ //#endregion
23
+ //#region src/handle/unknownErrorHandler.d.ts
24
+ interface UnknownErrorDetail extends OhbugBaseDetail {
25
+ name?: string;
26
+ stack?: string;
27
+ }
28
+ //#endregion
29
+ export { type UncaughtExceptionDetail, type UnhandledRejectionDetail, type UnknownErrorDetail, NodeClient as default };
30
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1,248 @@
1
+ import { Client, EventTypes, defineExtension } from "@ohbug/core";
2
+ import { getCircularReplacer, getGlobal, getOhbugObject, replace, safeCall } from "@ohbug/utils";
3
+ import os from "node:os";
4
+ //#region src/capture/captureConsole.ts
5
+ const levels = [
6
+ "log",
7
+ "info",
8
+ "warn",
9
+ "error"
10
+ ];
11
+ const consoleOriginal = {
12
+ log: console.log,
13
+ info: console.info,
14
+ warn: console.warn,
15
+ error: console.error
16
+ };
17
+ let captured = false;
18
+ function captureConsole() {
19
+ if (captured) return;
20
+ captured = true;
21
+ const { client } = getOhbugObject();
22
+ levels.forEach((level) => {
23
+ consoleOriginal[level] = replace(console, level, (origin) => function call(...args) {
24
+ if (!args.some((arg) => typeof arg === "string" && arg.includes("Ohbug"))) client.addAction(`console.${level}`, args, "console");
25
+ return origin.apply(this, args);
26
+ });
27
+ });
28
+ }
29
+ function removeCaptureConsole() {
30
+ if (!captured) return;
31
+ captured = false;
32
+ if (console) levels.forEach((level) => {
33
+ console[level] = consoleOriginal[level];
34
+ });
35
+ }
36
+ //#endregion
37
+ //#region src/handle/uncaughtExceptionHandler.ts
38
+ async function uncaughtExceptionHandler(error, origin) {
39
+ const detail = {
40
+ name: error?.name ?? "Error",
41
+ message: error?.message ?? String(error),
42
+ stack: error?.stack,
43
+ origin
44
+ };
45
+ const { client } = getOhbugObject();
46
+ const event = client.createEvent({
47
+ category: "error",
48
+ type: EventTypes.UNCAUGHT_ERROR,
49
+ detail
50
+ });
51
+ await client.notify(event);
52
+ }
53
+ //#endregion
54
+ //#region src/capture/captureUncaughtException.ts
55
+ const SHUTDOWN_TIMEOUT = 2e3;
56
+ let exiting = false;
57
+ function listener$1(error, origin) {
58
+ let notifyPromise;
59
+ try {
60
+ notifyPromise = uncaughtExceptionHandler(error, origin);
61
+ } catch {
62
+ return;
63
+ }
64
+ if (exiting) return;
65
+ let client;
66
+ try {
67
+ ({client} = getOhbugObject());
68
+ } catch {
69
+ return;
70
+ }
71
+ if (process.listeners("uncaughtException").filter((l) => l !== listener$1).length === 0) {
72
+ exiting = true;
73
+ client.__logger.error("No other uncaughtException listeners detected. Exiting process.");
74
+ notifyPromise.finally(() => {
75
+ process.exit(1);
76
+ });
77
+ setTimeout(() => {
78
+ process.exit(1);
79
+ }, SHUTDOWN_TIMEOUT).unref();
80
+ }
81
+ }
82
+ function captureUncaughtException() {
83
+ exiting = false;
84
+ process.on("uncaughtException", listener$1);
85
+ }
86
+ function removeCaptureUncaughtException() {
87
+ process.removeListener("uncaughtException", listener$1);
88
+ exiting = false;
89
+ }
90
+ //#endregion
91
+ //#region src/handle/unhandledRejectionHandler.ts
92
+ function unhandledRejectionHandler(reason, _promise) {
93
+ const detail = {
94
+ name: reason instanceof Error ? reason.name : "UnhandledRejection",
95
+ message: reason instanceof Error ? reason.message : String(reason),
96
+ stack: reason instanceof Error ? reason.stack : void 0
97
+ };
98
+ const { client } = getOhbugObject();
99
+ const event = client.createEvent({
100
+ category: "error",
101
+ type: EventTypes.UNHANDLEDREJECTION_ERROR,
102
+ detail
103
+ });
104
+ client.notify(event).catch(() => {});
105
+ }
106
+ //#endregion
107
+ //#region src/capture/captureUnhandledRejection.ts
108
+ function listener(reason, promise) {
109
+ unhandledRejectionHandler(reason, promise);
110
+ }
111
+ function captureUnhandledRejection() {
112
+ process.on("unhandledRejection", listener);
113
+ }
114
+ function removeCaptureUnhandledRejection() {
115
+ process.removeListener("unhandledRejection", listener);
116
+ }
117
+ //#endregion
118
+ //#region src/capture/index.ts
119
+ function captureProcess() {
120
+ captureUncaughtException();
121
+ captureUnhandledRejection();
122
+ }
123
+ function removeCaptureProcess() {
124
+ removeCaptureUncaughtException();
125
+ removeCaptureUnhandledRejection();
126
+ }
127
+ function handleCapture() {
128
+ captureProcess();
129
+ captureConsole();
130
+ }
131
+ //#endregion
132
+ //#region src/destroy.ts
133
+ function destroy() {
134
+ removeCaptureProcess();
135
+ removeCaptureConsole();
136
+ removeBeforeExitListener();
137
+ }
138
+ function beforeExitListener() {
139
+ destroy();
140
+ }
141
+ function removeBeforeExitListener() {
142
+ process.removeListener("beforeExit", beforeExitListener);
143
+ }
144
+ function handleDestroy() {
145
+ process.on("beforeExit", beforeExitListener);
146
+ }
147
+ //#endregion
148
+ //#region src/device.ts
149
+ function detectRuntime() {
150
+ if (typeof process !== "undefined" && process.versions?.bun) return {
151
+ name: "bun",
152
+ version: process.versions.bun
153
+ };
154
+ return {
155
+ name: "node",
156
+ version: process.version
157
+ };
158
+ }
159
+ let cachedStatic = null;
160
+ function getStaticDeviceInfo() {
161
+ if (cachedStatic) return cachedStatic;
162
+ const runtime = detectRuntime();
163
+ cachedStatic = {
164
+ runtime: runtime.name,
165
+ runtimeVersion: runtime.version,
166
+ platform: process.platform,
167
+ arch: process.arch,
168
+ osType: safeCall(() => os.type(), "unknown"),
169
+ osRelease: safeCall(() => os.release(), "unknown"),
170
+ hostname: safeCall(() => os.hostname(), "unknown"),
171
+ pid: process.pid
172
+ };
173
+ return cachedStatic;
174
+ }
175
+ const device = () => ({
176
+ ...getStaticDeviceInfo(),
177
+ memoryUsage: safeCall(() => process.memoryUsage(), void 0),
178
+ uptime: safeCall(() => process.uptime(), 0)
179
+ });
180
+ //#endregion
181
+ //#region src/extension.ts
182
+ const extension = defineExtension({
183
+ name: "OhbugNode",
184
+ onSetup: () => {
185
+ handleCapture();
186
+ handleDestroy();
187
+ }
188
+ });
189
+ //#endregion
190
+ //#region src/notifier.ts
191
+ async function notifier(event) {
192
+ const { client } = getOhbugObject();
193
+ const url = client.__config.endpoint;
194
+ const json = JSON.stringify(event, getCircularReplacer());
195
+ const response = await fetch(url, {
196
+ method: "POST",
197
+ headers: { "Content-Type": "application/json;charset=UTF-8" },
198
+ body: json
199
+ });
200
+ if (!response.ok) client.__logger.warn(`@ohbug/node notifier: server responded with ${response.status}`);
201
+ return response;
202
+ }
203
+ //#endregion
204
+ //#region src/version.ts
205
+ const version = "0.0.1";
206
+ //#endregion
207
+ //#region src/client.ts
208
+ function createClient(config, handleDestroy) {
209
+ const global = getGlobal();
210
+ const client = new Client({
211
+ sdk: {
212
+ platform: "ohbug-node",
213
+ version
214
+ },
215
+ config,
216
+ device,
217
+ notifier: config.notifier ?? notifier,
218
+ destroy: handleDestroy
219
+ });
220
+ global.__OHBUG__ = { client };
221
+ client.use(extension);
222
+ client.__logger.info(`@ohbug/node: Detected Ohbug v${version}`);
223
+ return client;
224
+ }
225
+ const NodeClient = {
226
+ __client: null,
227
+ setup(config) {
228
+ function destroyClient() {
229
+ const global = getGlobal();
230
+ destroy();
231
+ NodeClient.__client = null;
232
+ global.__OHBUG__ = void 0;
233
+ }
234
+ if (NodeClient.__client) {
235
+ NodeClient.__client.__logger?.warn("setup() has been called. Ignored.");
236
+ return NodeClient.__client;
237
+ }
238
+ NodeClient.__client = createClient(config, destroyClient);
239
+ return NodeClient.__client;
240
+ }
241
+ };
242
+ //#endregion
243
+ //#region src/index.ts
244
+ var src_default = NodeClient;
245
+ //#endregion
246
+ export { src_default as default };
247
+
248
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["listener"],"sources":["../src/capture/captureConsole.ts","../src/handle/uncaughtExceptionHandler.ts","../src/capture/captureUncaughtException.ts","../src/handle/unhandledRejectionHandler.ts","../src/capture/captureUnhandledRejection.ts","../src/capture/index.ts","../src/destroy.ts","../src/device.ts","../src/extension.ts","../src/notifier.ts","../src/version.ts","../src/client.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable no-console */\n\nimport { getOhbugObject, replace } from \"@ohbug/utils\";\n\ntype Level = \"log\" | \"info\" | \"warn\" | \"error\";\nconst levels: Level[] = [\"log\", \"info\", \"warn\", \"error\"];\nconst consoleOriginal: Record<Level, any> = {\n log: console.log,\n info: console.info,\n warn: console.warn,\n error: console.error,\n};\n\n// 幂等保护:防止重复调用 captureConsole 导致 consoleOriginal 被覆盖为包装后的函数\nlet captured = false;\n\nexport function captureConsole() {\n if (captured) return;\n captured = true;\n\n const { client } = getOhbugObject();\n levels.forEach((level) => {\n consoleOriginal[level] = replace(\n console,\n level,\n (origin) =>\n function call(this: any, ...args: any[]) {\n const isOhbugConsole = args.some(\n (arg) => typeof arg === \"string\" && arg.includes(\"Ohbug\"),\n );\n if (!isOhbugConsole) {\n client.addAction(`console.${level}`, args, \"console\");\n }\n\n return origin.apply(this, args);\n },\n );\n });\n}\n\nexport function removeCaptureConsole() {\n if (!captured) return;\n captured = false;\n\n if (console) {\n levels.forEach((level) => {\n console[level] = consoleOriginal[level];\n });\n }\n}\n","import { EventTypes } from \"@ohbug/core\";\nimport type { OhbugBaseDetail } from \"@ohbug/types\";\nimport { getOhbugObject } from \"@ohbug/utils\";\n\nexport interface UncaughtExceptionDetail extends OhbugBaseDetail {\n name: string;\n stack?: string;\n origin?: string;\n}\n\nexport async function uncaughtExceptionHandler(error: Error, origin: string) {\n const detail: UncaughtExceptionDetail = {\n name: error?.name ?? \"Error\",\n message: error?.message ?? String(error),\n stack: error?.stack,\n origin,\n };\n\n const { client } = getOhbugObject();\n const event = client.createEvent<UncaughtExceptionDetail>({\n category: \"error\",\n type: EventTypes.UNCAUGHT_ERROR,\n detail,\n });\n await client.notify(event);\n}\n","import { getOhbugObject } from \"@ohbug/utils\";\n\nimport { uncaughtExceptionHandler } from \"../handle/uncaughtExceptionHandler\";\n\n// 参考 Sentry:确保事件发送后,进程正常退出。\n// 注册了 uncaughtException 监听器后,Node 不会自动退出进程。\n// 如果用户没有注册其他监听器,由我们负责退出进程。\n// 给 notifier 2 秒的时间来 flush 事件,然后强制退出。\nconst SHUTDOWN_TIMEOUT = 2000;\n\n// 重入保护:防止多个快速连续的异常触发竞争的 process.exit 调用\nlet exiting = false;\n\nfunction listener(error: Error, origin: string) {\n let notifyPromise: Promise<void>;\n try {\n notifyPromise = uncaughtExceptionHandler(error, origin);\n } catch {\n // client 已销毁或未初始化,无法上报\n return;\n }\n\n if (exiting) return;\n\n let client;\n try {\n ({ client } = getOhbugObject());\n } catch {\n return;\n }\n\n const listeners = process.listeners(\"uncaughtException\").filter((l) => l !== listener);\n if (listeners.length === 0) {\n exiting = true;\n client.__logger.error(\"No other uncaughtException listeners detected. Exiting process.\");\n // 等待 notify 完成后退出,设置超时兜底防止 hang\n void notifyPromise.finally(() => {\n process.exit(1);\n });\n setTimeout(() => {\n process.exit(1);\n }, SHUTDOWN_TIMEOUT).unref();\n }\n}\n\nexport function captureUncaughtException() {\n exiting = false;\n process.on(\"uncaughtException\", listener);\n}\n\nexport function removeCaptureUncaughtException() {\n process.removeListener(\"uncaughtException\", listener);\n exiting = false;\n}\n","import { EventTypes } from \"@ohbug/core\";\nimport type { OhbugBaseDetail } from \"@ohbug/types\";\nimport { getOhbugObject } from \"@ohbug/utils\";\n\nexport interface UnhandledRejectionDetail extends OhbugBaseDetail {\n name?: string;\n stack?: string;\n}\n\nexport function unhandledRejectionHandler(reason: unknown, _promise: Promise<unknown>) {\n const detail: UnhandledRejectionDetail = {\n name: reason instanceof Error ? reason.name : \"UnhandledRejection\",\n message: reason instanceof Error ? reason.message : String(reason),\n stack: reason instanceof Error ? reason.stack : undefined,\n };\n\n const { client } = getOhbugObject();\n const event = client.createEvent<UnhandledRejectionDetail>({\n category: \"error\",\n type: EventTypes.UNHANDLEDREJECTION_ERROR,\n detail,\n });\n client.notify(event).catch(() => {});\n}\n","import { unhandledRejectionHandler } from \"../handle/unhandledRejectionHandler\";\n\nfunction listener(reason: unknown, promise: Promise<unknown>) {\n unhandledRejectionHandler(reason, promise);\n}\n\nexport function captureUnhandledRejection() {\n process.on(\"unhandledRejection\", listener);\n}\n\nexport function removeCaptureUnhandledRejection() {\n process.removeListener(\"unhandledRejection\", listener);\n}\n","import { captureConsole, removeCaptureConsole } from \"./captureConsole\";\nimport {\n captureUncaughtException,\n removeCaptureUncaughtException,\n} from \"./captureUncaughtException\";\nimport {\n captureUnhandledRejection,\n removeCaptureUnhandledRejection,\n} from \"./captureUnhandledRejection\";\n\nexport { removeCaptureConsole };\n\nexport function captureProcess() {\n captureUncaughtException();\n captureUnhandledRejection();\n}\n\nexport function removeCaptureProcess() {\n removeCaptureUncaughtException();\n removeCaptureUnhandledRejection();\n}\n\nexport function handleCapture() {\n captureProcess();\n captureConsole();\n}\n","import { removeCaptureConsole, removeCaptureProcess } from \"./capture\";\n\nexport function destroy() {\n removeCaptureProcess();\n removeCaptureConsole();\n removeBeforeExitListener();\n}\n\nfunction beforeExitListener() {\n destroy();\n}\n\nfunction removeBeforeExitListener() {\n process.removeListener(\"beforeExit\", beforeExitListener);\n}\n\nexport function handleDestroy() {\n process.on(\"beforeExit\", beforeExitListener);\n}\n","import os from \"node:os\";\n\nimport type { OhbugGetDevice } from \"@ohbug/types\";\nimport { safeCall } from \"@ohbug/utils\";\n\nfunction detectRuntime(): { name: string; version: string } {\n if (typeof process !== \"undefined\" && process.versions?.bun) {\n return { name: \"bun\", version: process.versions.bun };\n }\n return { name: \"node\", version: process.version };\n}\n\n// Static fields are cached — they never change during the process lifetime.\nlet cachedStatic: Record<string, unknown> | null = null;\n\nfunction getStaticDeviceInfo() {\n if (cachedStatic) return cachedStatic;\n const runtime = detectRuntime();\n cachedStatic = {\n runtime: runtime.name,\n runtimeVersion: runtime.version,\n platform: process.platform,\n arch: process.arch,\n osType: safeCall(() => os.type(), \"unknown\"),\n osRelease: safeCall(() => os.release(), \"unknown\"),\n hostname: safeCall(() => os.hostname(), \"unknown\"),\n pid: process.pid,\n };\n return cachedStatic;\n}\n\nexport const device: OhbugGetDevice = () => ({\n ...getStaticDeviceInfo(),\n memoryUsage: safeCall(() => process.memoryUsage(), undefined),\n uptime: safeCall(() => process.uptime(), 0),\n});\n","import { defineExtension } from \"@ohbug/core\";\n\nimport { handleCapture } from \"./capture\";\nimport { handleDestroy } from \"./destroy\";\n\nexport const extension = defineExtension({\n name: \"OhbugNode\",\n onSetup: () => {\n handleCapture();\n handleDestroy();\n },\n});\n","import type { OhbugEventWithMethods } from \"@ohbug/types\";\nimport { getCircularReplacer, getOhbugObject } from \"@ohbug/utils\";\n\nexport async function notifier<D>(event: OhbugEventWithMethods<D>) {\n const { client } = getOhbugObject();\n const url = client.__config.endpoint!;\n const json = JSON.stringify(event, getCircularReplacer());\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json;charset=UTF-8\" },\n body: json,\n });\n\n if (!response.ok) {\n client.__logger.warn(`@ohbug/node notifier: server responded with ${response.status}`);\n }\n\n return response;\n}\n","declare const __VERSION__: string;\nexport const version: string = __VERSION__;\n","import { Client } from \"@ohbug/core\";\nimport type { OhbugClient, OhbugConfig, OhbugSDK } from \"@ohbug/types\";\nimport { getGlobal } from \"@ohbug/utils\";\n\nimport { destroy } from \"./destroy\";\nimport { device } from \"./device\";\nimport { extension } from \"./extension\";\nimport { notifier } from \"./notifier\";\nimport { version } from \"./version\";\n\ninterface OhbugNodeClient {\n __client: OhbugClient | null;\n setup: (config: OhbugConfig) => OhbugClient;\n}\n\nfunction createClient(config: OhbugConfig, handleDestroy: () => void) {\n const global = getGlobal<typeof globalThis>();\n\n const sdk: OhbugSDK = {\n platform: \"ohbug-node\",\n version,\n };\n const client = new Client({\n sdk,\n config,\n device,\n notifier: config.notifier ?? notifier,\n destroy: handleDestroy,\n });\n\n global.__OHBUG__ = { client };\n client.use(extension);\n client.__logger.info(`@ohbug/node: Detected Ohbug v${version}`);\n return client;\n}\n\nexport const NodeClient: OhbugNodeClient = {\n __client: null,\n setup(config: OhbugConfig) {\n function destroyClient() {\n const global = getGlobal<typeof globalThis>();\n\n destroy();\n NodeClient.__client = null;\n // @ts-expect-error noop\n global.__OHBUG__ = undefined;\n }\n\n if (NodeClient.__client) {\n NodeClient.__client.__logger?.warn(\"setup() has been called. Ignored.\");\n return NodeClient.__client;\n }\n\n NodeClient.__client = createClient(config, destroyClient);\n return NodeClient.__client;\n },\n};\n","import { NodeClient } from \"./client\";\n\nexport type {\n UncaughtExceptionDetail,\n UnhandledRejectionDetail,\n UnknownErrorDetail,\n} from \"./handle\";\n\nexport default NodeClient;\n"],"mappings":";;;;AAKA,MAAM,SAAkB;CAAC;CAAO;CAAQ;CAAQ;CAAQ;AACxD,MAAM,kBAAsC;CAC1C,KAAK,QAAQ;CACb,MAAM,QAAQ;CACd,MAAM,QAAQ;CACd,OAAO,QAAQ;CAChB;AAGD,IAAI,WAAW;AAEf,SAAgB,iBAAiB;AAC/B,KAAI,SAAU;AACd,YAAW;CAEX,MAAM,EAAE,WAAW,gBAAgB;AACnC,QAAO,SAAS,UAAU;AACxB,kBAAgB,SAAS,QACvB,SACA,Q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AAW,WAAW;AAEtB,UAAO,YAAY,KAAA;;AAGrB,MAAI,WAAW,UAAU;AACvB,cAAW,SAAS,UAAU,KAAK,oCAAoC;AACvE,UAAO,WAAW;;AAGpB,aAAW,WAAW,aAAa,QAAQ,cAAc;AACzD,SAAO,WAAW;;CAErB;;;AChDD,IAAA,cAAe"}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@ohbug/node",
3
+ "version": "0.0.1",
4
+ "description": "Ohbug SDK for Node.js and Bun",
5
+ "homepage": "https://github.com/ohbug-org/ohbug#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/ohbug-org/ohbug/issues"
8
+ },
9
+ "license": "Apache-2.0",
10
+ "author": {
11
+ "name": "xinyao",
12
+ "email": "hi@xinyao.me"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/ohbug-org/ohbug.git"
17
+ },
18
+ "funding": "https://github.com/sponsors/xinyao27",
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "types": "dist/index.d.mts",
25
+ "exports": {
26
+ ".": "./dist/index.mjs",
27
+ "./package.json": "./package.json"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dependencies": {
33
+ "@ohbug/core": "2.2.3",
34
+ "@ohbug/utils": "2.0.10",
35
+ "@ohbug/types": "2.2.2"
36
+ },
37
+ "engines": {
38
+ "node": ">=18"
39
+ },
40
+ "scripts": {
41
+ "dev": "vp pack --watch"
42
+ }
43
+ }