@devmoods/sentry 0.2.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.
@@ -0,0 +1,210 @@
1
+ /* eslint-disable */
2
+ var addSorting = (function() {
3
+ 'use strict';
4
+ var cols,
5
+ currentSort = {
6
+ index: 0,
7
+ desc: false
8
+ };
9
+
10
+ // returns the summary table element
11
+ function getTable() {
12
+ return document.querySelector('.coverage-summary');
13
+ }
14
+ // returns the thead element of the summary table
15
+ function getTableHeader() {
16
+ return getTable().querySelector('thead tr');
17
+ }
18
+ // returns the tbody element of the summary table
19
+ function getTableBody() {
20
+ return getTable().querySelector('tbody');
21
+ }
22
+ // returns the th element for nth column
23
+ function getNthColumn(n) {
24
+ return getTableHeader().querySelectorAll('th')[n];
25
+ }
26
+
27
+ function onFilterInput() {
28
+ const searchValue = document.getElementById('fileSearch').value;
29
+ const rows = document.getElementsByTagName('tbody')[0].children;
30
+
31
+ // Try to create a RegExp from the searchValue. If it fails (invalid regex),
32
+ // it will be treated as a plain text search
33
+ let searchRegex;
34
+ try {
35
+ searchRegex = new RegExp(searchValue, 'i'); // 'i' for case-insensitive
36
+ } catch (error) {
37
+ searchRegex = null;
38
+ }
39
+
40
+ for (let i = 0; i < rows.length; i++) {
41
+ const row = rows[i];
42
+ let isMatch = false;
43
+
44
+ if (searchRegex) {
45
+ // If a valid regex was created, use it for matching
46
+ isMatch = searchRegex.test(row.textContent);
47
+ } else {
48
+ // Otherwise, fall back to the original plain text search
49
+ isMatch = row.textContent
50
+ .toLowerCase()
51
+ .includes(searchValue.toLowerCase());
52
+ }
53
+
54
+ row.style.display = isMatch ? '' : 'none';
55
+ }
56
+ }
57
+
58
+ // loads the search box
59
+ function addSearchBox() {
60
+ var template = document.getElementById('filterTemplate');
61
+ var templateClone = template.content.cloneNode(true);
62
+ templateClone.getElementById('fileSearch').oninput = onFilterInput;
63
+ template.parentElement.appendChild(templateClone);
64
+ }
65
+
66
+ // loads all columns
67
+ function loadColumns() {
68
+ var colNodes = getTableHeader().querySelectorAll('th'),
69
+ colNode,
70
+ cols = [],
71
+ col,
72
+ i;
73
+
74
+ for (i = 0; i < colNodes.length; i += 1) {
75
+ colNode = colNodes[i];
76
+ col = {
77
+ key: colNode.getAttribute('data-col'),
78
+ sortable: !colNode.getAttribute('data-nosort'),
79
+ type: colNode.getAttribute('data-type') || 'string'
80
+ };
81
+ cols.push(col);
82
+ if (col.sortable) {
83
+ col.defaultDescSort = col.type === 'number';
84
+ colNode.innerHTML =
85
+ colNode.innerHTML + '<span class="sorter"></span>';
86
+ }
87
+ }
88
+ return cols;
89
+ }
90
+ // attaches a data attribute to every tr element with an object
91
+ // of data values keyed by column name
92
+ function loadRowData(tableRow) {
93
+ var tableCols = tableRow.querySelectorAll('td'),
94
+ colNode,
95
+ col,
96
+ data = {},
97
+ i,
98
+ val;
99
+ for (i = 0; i < tableCols.length; i += 1) {
100
+ colNode = tableCols[i];
101
+ col = cols[i];
102
+ val = colNode.getAttribute('data-value');
103
+ if (col.type === 'number') {
104
+ val = Number(val);
105
+ }
106
+ data[col.key] = val;
107
+ }
108
+ return data;
109
+ }
110
+ // loads all row data
111
+ function loadData() {
112
+ var rows = getTableBody().querySelectorAll('tr'),
113
+ i;
114
+
115
+ for (i = 0; i < rows.length; i += 1) {
116
+ rows[i].data = loadRowData(rows[i]);
117
+ }
118
+ }
119
+ // sorts the table using the data for the ith column
120
+ function sortByIndex(index, desc) {
121
+ var key = cols[index].key,
122
+ sorter = function(a, b) {
123
+ a = a.data[key];
124
+ b = b.data[key];
125
+ return a < b ? -1 : a > b ? 1 : 0;
126
+ },
127
+ finalSorter = sorter,
128
+ tableBody = document.querySelector('.coverage-summary tbody'),
129
+ rowNodes = tableBody.querySelectorAll('tr'),
130
+ rows = [],
131
+ i;
132
+
133
+ if (desc) {
134
+ finalSorter = function(a, b) {
135
+ return -1 * sorter(a, b);
136
+ };
137
+ }
138
+
139
+ for (i = 0; i < rowNodes.length; i += 1) {
140
+ rows.push(rowNodes[i]);
141
+ tableBody.removeChild(rowNodes[i]);
142
+ }
143
+
144
+ rows.sort(finalSorter);
145
+
146
+ for (i = 0; i < rows.length; i += 1) {
147
+ tableBody.appendChild(rows[i]);
148
+ }
149
+ }
150
+ // removes sort indicators for current column being sorted
151
+ function removeSortIndicators() {
152
+ var col = getNthColumn(currentSort.index),
153
+ cls = col.className;
154
+
155
+ cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, '');
156
+ col.className = cls;
157
+ }
158
+ // adds sort indicators for current column being sorted
159
+ function addSortIndicators() {
160
+ getNthColumn(currentSort.index).className += currentSort.desc
161
+ ? ' sorted-desc'
162
+ : ' sorted';
163
+ }
164
+ // adds event listeners for all sorter widgets
165
+ function enableUI() {
166
+ var i,
167
+ el,
168
+ ithSorter = function ithSorter(i) {
169
+ var col = cols[i];
170
+
171
+ return function() {
172
+ var desc = col.defaultDescSort;
173
+
174
+ if (currentSort.index === i) {
175
+ desc = !currentSort.desc;
176
+ }
177
+ sortByIndex(i, desc);
178
+ removeSortIndicators();
179
+ currentSort.index = i;
180
+ currentSort.desc = desc;
181
+ addSortIndicators();
182
+ };
183
+ };
184
+ for (i = 0; i < cols.length; i += 1) {
185
+ if (cols[i].sortable) {
186
+ // add the click event handler on the th so users
187
+ // dont have to click on those tiny arrows
188
+ el = getNthColumn(i).querySelector('.sorter').parentElement;
189
+ if (el.addEventListener) {
190
+ el.addEventListener('click', ithSorter(i));
191
+ } else {
192
+ el.attachEvent('onclick', ithSorter(i));
193
+ }
194
+ }
195
+ }
196
+ }
197
+ // adds sorting functionality to the UI
198
+ return function() {
199
+ if (!getTable()) {
200
+ return;
201
+ }
202
+ cols = loadColumns();
203
+ loadData();
204
+ addSearchBox();
205
+ addSortIndicators();
206
+ enableUI();
207
+ };
208
+ })();
209
+
210
+ window.addEventListener('load', addSorting);
@@ -0,0 +1,25 @@
1
+ import { type LoggerAdapter } from '@devmoods/observability';
2
+ import * as Sentry from '@sentry/node';
3
+ import { type ErrorRequestHandler } from 'express';
4
+ declare module '@devmoods/config' {
5
+ interface Config extends ConfigFromDefs<typeof sentryConfig> {
6
+ }
7
+ }
8
+ export declare const sentryConfig: import("@devmoods/config").Defs<{
9
+ SENTRY_DSN: string;
10
+ SENTRY_TRACES_SAMPLE_RATE: number;
11
+ SENTRY_PROFILES_SAMPLE_RATE: number;
12
+ SENTRY_EVENT_LOOP_THRESHOLD: number;
13
+ }>;
14
+ export type { Sentry };
15
+ export interface SentryOptions extends Sentry.NodeOptions {
16
+ }
17
+ export declare function initSentry(options?: SentryOptions): Promise<void>;
18
+ export declare function closeSentry(): Promise<void>;
19
+ export declare function sentryOptions(options?: SentryOptions): Promise<SentryOptions>;
20
+ export declare function sentryErrorHandler(options?: Sentry.NodeOptions): ErrorRequestHandler;
21
+ export declare class SentryLoggerAdapter implements LoggerAdapter {
22
+ constructor();
23
+ captureError(error: Error | null, attributes?: Record<string, any>): void;
24
+ write(log: Record<string, any>): boolean;
25
+ }
package/dist/index.js ADDED
@@ -0,0 +1,87 @@
1
+ import { config, define, t } from '@devmoods/config';
2
+ import {} from '@devmoods/observability';
3
+ import * as Sentry from '@sentry/node';
4
+ import {} from 'express';
5
+ export const sentryConfig = define({
6
+ SENTRY_DSN: t.string(),
7
+ SENTRY_TRACES_SAMPLE_RATE: t.number(0.3),
8
+ SENTRY_PROFILES_SAMPLE_RATE: t.number(0.3),
9
+ SENTRY_EVENT_LOOP_THRESHOLD: t.number(750),
10
+ });
11
+ /* c8 ignore start */
12
+ export async function initSentry(options = {}) {
13
+ Sentry.init(await sentryOptions(options));
14
+ }
15
+ export async function closeSentry() {
16
+ await Sentry.close(5000);
17
+ }
18
+ /* c8 ignore end */
19
+ /**
20
+ * Safely imports native Sentry integrations if available.
21
+ * Returns null if native modules are not available (e.g., on unsupported Node.js versions).
22
+ */
23
+ async function getNativeIntegrations() {
24
+ const integrations = [];
25
+ /* v8 ignore next -- @preserve */
26
+ try {
27
+ const { nodeProfilingIntegration } = await import('@sentry/profiling-node');
28
+ integrations.push(nodeProfilingIntegration());
29
+ }
30
+ catch {
31
+ // Native profiling integration not available
32
+ }
33
+ /* v8 ignore next -- @preserve */
34
+ try {
35
+ const { eventLoopBlockIntegration } = await import('@sentry/node-native');
36
+ integrations.push(eventLoopBlockIntegration({
37
+ threshold: config.SENTRY_EVENT_LOOP_THRESHOLD,
38
+ }));
39
+ }
40
+ catch {
41
+ // Native event loop integration not available
42
+ }
43
+ return integrations;
44
+ }
45
+ export async function sentryOptions(options = {}) {
46
+ const nativeIntegrations = await getNativeIntegrations();
47
+ return {
48
+ dsn: config.SENTRY_DSN,
49
+ tracesSampleRate: config.SENTRY_TRACES_SAMPLE_RATE,
50
+ profileSessionSampleRate: config.SENTRY_PROFILES_SAMPLE_RATE,
51
+ integrations: nativeIntegrations,
52
+ enableLogs: true,
53
+ ...options,
54
+ };
55
+ }
56
+ export function sentryErrorHandler(options = {}) {
57
+ return Sentry.expressErrorHandler({
58
+ shouldHandleError() {
59
+ return process.env.NODE_ENV === 'production';
60
+ },
61
+ ...options,
62
+ });
63
+ }
64
+ export class SentryLoggerAdapter {
65
+ constructor() { }
66
+ captureError(error, attributes) {
67
+ /* v8 ignore next -- @preserve */
68
+ if (error == null) {
69
+ return;
70
+ }
71
+ /* v8 ignore next -- @preserve */
72
+ if (Sentry.isInitialized()) {
73
+ Sentry.captureException(error, {
74
+ tags: attributes,
75
+ });
76
+ }
77
+ }
78
+ write(log) {
79
+ const { message, ...attributes } = log;
80
+ /* v8 ignore next -- @preserve */
81
+ if (Sentry.isInitialized()) {
82
+ const fn = log.level;
83
+ Sentry.logger[fn](message, attributes);
84
+ }
85
+ return true;
86
+ }
87
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import { loadConfig } from '@devmoods/config';
2
+ import { sentryConfig } from './index.js';
3
+ loadConfig(sentryConfig);
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@devmoods/sentry",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ }
14
+ },
15
+ "scripts": {
16
+ "clean": "rm -rf dist",
17
+ "lint": "eslint",
18
+ "test": "vitest",
19
+ "test:coverage": "pnpm run test --coverage",
20
+ "build": "pnpm run clean && tsgo",
21
+ "prepublishOnly": "pnpm run clean && pnpm run build"
22
+ },
23
+ "dependencies": {
24
+ "@devmoods/config": "0.2.3",
25
+ "@devmoods/observability": "0.2.0",
26
+ "@sentry/node": "^10.48.0",
27
+ "@sentry/node-native": "^10.48.0",
28
+ "@sentry/profiling-node": "^10.48.0",
29
+ "express": "^4.21.2"
30
+ },
31
+ "peerDependencies": {
32
+ "express": ">=4.21.2 <5.0.0"
33
+ },
34
+ "gitHead": "ea4f51756aca98bd050cf98128bf4d4b3da1bf38"
35
+ }
@@ -0,0 +1,28 @@
1
+ import { overrideConfig } from '@devmoods/config';
2
+
3
+ import { sentryOptions } from '../index.js';
4
+
5
+ test('sentryOptions', async () => {
6
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
7
+
8
+ const reset = overrideConfig({
9
+ SENTRY_DSN: 'https://example.com/sentry',
10
+ SENTRY_TRACES_SAMPLE_RATE: 0.3,
11
+ SENTRY_PROFILES_SAMPLE_RATE: 0.3,
12
+ SENTRY_EVENT_LOOP_THRESHOLD: 750,
13
+ });
14
+
15
+ const options = await sentryOptions();
16
+
17
+ expect(options).toEqual(
18
+ expect.objectContaining({
19
+ dsn: 'https://example.com/sentry',
20
+ enableLogs: true,
21
+ integrations: expect.any(Array),
22
+ profileSessionSampleRate: 0.3,
23
+ tracesSampleRate: 0.3,
24
+ }),
25
+ );
26
+
27
+ reset();
28
+ });
package/src/index.ts ADDED
@@ -0,0 +1,122 @@
1
+ import { config, define, t, type ConfigFromDefs } from '@devmoods/config';
2
+ import { type LoggerAdapter } from '@devmoods/observability';
3
+ import * as Sentry from '@sentry/node';
4
+ import { type ErrorRequestHandler } from 'express';
5
+
6
+ declare module '@devmoods/config' {
7
+ interface Config extends ConfigFromDefs<typeof sentryConfig> {}
8
+ }
9
+
10
+ export const sentryConfig = define({
11
+ SENTRY_DSN: t.string(),
12
+ SENTRY_TRACES_SAMPLE_RATE: t.number(0.3),
13
+ SENTRY_PROFILES_SAMPLE_RATE: t.number(0.3),
14
+ SENTRY_EVENT_LOOP_THRESHOLD: t.number(750),
15
+ });
16
+
17
+ export type { Sentry };
18
+
19
+ export interface SentryOptions extends Sentry.NodeOptions {}
20
+
21
+ /* c8 ignore start */
22
+ export async function initSentry(options: SentryOptions = {}) {
23
+ Sentry.init(await sentryOptions(options));
24
+ }
25
+
26
+ export async function closeSentry() {
27
+ await Sentry.close(5000);
28
+ }
29
+ /* c8 ignore end */
30
+
31
+ /**
32
+ * Safely imports native Sentry integrations if available.
33
+ * Returns null if native modules are not available (e.g., on unsupported Node.js versions).
34
+ */
35
+ async function getNativeIntegrations() {
36
+ const integrations = [];
37
+
38
+ /* v8 ignore next -- @preserve */
39
+ try {
40
+ const { nodeProfilingIntegration } = await import('@sentry/profiling-node');
41
+ integrations.push(nodeProfilingIntegration());
42
+ } catch {
43
+ // Native profiling integration not available
44
+ }
45
+
46
+ /* v8 ignore next -- @preserve */
47
+ try {
48
+ const { eventLoopBlockIntegration } = await import('@sentry/node-native');
49
+ integrations.push(
50
+ eventLoopBlockIntegration({
51
+ threshold: config.SENTRY_EVENT_LOOP_THRESHOLD,
52
+ }),
53
+ );
54
+ } catch {
55
+ // Native event loop integration not available
56
+ }
57
+
58
+ return integrations;
59
+ }
60
+
61
+ export async function sentryOptions(
62
+ options: SentryOptions = {},
63
+ ): Promise<SentryOptions> {
64
+ const nativeIntegrations = await getNativeIntegrations();
65
+
66
+ return {
67
+ dsn: config.SENTRY_DSN,
68
+ tracesSampleRate: config.SENTRY_TRACES_SAMPLE_RATE,
69
+ profileSessionSampleRate: config.SENTRY_PROFILES_SAMPLE_RATE,
70
+ integrations: nativeIntegrations,
71
+ enableLogs: true,
72
+ ...options,
73
+ };
74
+ }
75
+
76
+ export function sentryErrorHandler(
77
+ options: Sentry.NodeOptions = {},
78
+ ): ErrorRequestHandler {
79
+ return Sentry.expressErrorHandler({
80
+ shouldHandleError() {
81
+ return process.env.NODE_ENV === 'production';
82
+ },
83
+ ...options,
84
+ }) as unknown as ErrorRequestHandler;
85
+ }
86
+
87
+ export class SentryLoggerAdapter implements LoggerAdapter {
88
+ constructor() {}
89
+
90
+ captureError(error: Error | null, attributes?: Record<string, any>) {
91
+ /* v8 ignore next -- @preserve */
92
+ if (error == null) {
93
+ return;
94
+ }
95
+
96
+ /* v8 ignore next -- @preserve */
97
+ if (Sentry.isInitialized()) {
98
+ Sentry.captureException(error, {
99
+ tags: attributes,
100
+ });
101
+ }
102
+ }
103
+
104
+ write(log: Record<string, any>) {
105
+ const { message, ...attributes } = log;
106
+
107
+ /* v8 ignore next -- @preserve */
108
+ if (Sentry.isInitialized()) {
109
+ const fn = log.level as
110
+ | 'trace'
111
+ | 'debug'
112
+ | 'info'
113
+ | 'warn'
114
+ | 'error'
115
+ | 'fatal';
116
+
117
+ Sentry.logger[fn](message, attributes);
118
+ }
119
+
120
+ return true;
121
+ }
122
+ }
@@ -0,0 +1,5 @@
1
+ import { loadConfig } from '@devmoods/config';
2
+
3
+ import { sentryConfig } from './index.js';
4
+
5
+ loadConfig(sentryConfig);
package/tsconfig.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "extends": "../../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src",
6
+ "declaration": true,
7
+ "noEmit": false
8
+ },
9
+ "include": ["src/**/*"],
10
+ "exclude": ["dist", "node_modules", "**/*.test.ts", "**/*.spec.ts"]
11
+ }
@@ -0,0 +1,14 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ setupFiles: ['./src/setupTests.ts'],
6
+ globals: true,
7
+ restoreMocks: true,
8
+ coverage: {
9
+ thresholds: {
10
+ 100: true,
11
+ },
12
+ },
13
+ },
14
+ });