Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert @bugsnag/plugin-browser-request to TypeScript #2236

Merged
18 changes: 15 additions & 3 deletions packages/plugin-browser-request/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
{
"name": "@bugsnag/plugin-browser-request",
"version": "8.1.1",
"main": "request.js",
"main": "dist/request.js",
"types": "dist/types/request.d.ts",
"exports": {
".": {
"types": "./dist/types/request.d.ts",
"default": "./dist/request.js",
"import": "./dist/request.mjs"
}
},
"description": "@bugsnag/js plugin to set request info in browsers",
"homepage": "https://www.bugsnag.com/",
"repository": {
Expand All @@ -12,15 +20,19 @@
"access": "public"
},
"files": [
"*.js"
"dist"
],
"scripts": {},
"author": "Bugsnag",
"license": "MIT",
"devDependencies": {
"@bugsnag/core": "^8.1.1"
},
"peerDependencies": {
"@bugsnag/core": "^8.0.0"
},
"scripts": {
"build": "npm run build:npm",
"build:npm": "rollup --config rollup.config.npm.mjs",
"clean": "rm -rf dist/*"
}
}
6 changes: 6 additions & 0 deletions packages/plugin-browser-request/rollup.config.npm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import createRollupConfig from "../../.rollup/index.mjs";

export default createRollupConfig({
input: "src/request.ts",
external: ['@bugsnag/core/lib/es-utils/assign']
});
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
const assign = require('@bugsnag/core/lib/es-utils/assign')
import { Plugin } from '@bugsnag/core'
import assign from '@bugsnag/core/lib/es-utils/assign'

/*
* Sets the event request: { url } to be the current href
*/
module.exports = (win = window) => ({
export default (win = window): Plugin => ({
load: (client) => {
client.addOnError(event => {
if (event.request && event.request.url) return
event.request = assign({}, event.request, { url: win.location.href })
// @ts-expect-error second parameter is private API
}, true)
}
})
2 changes: 1 addition & 1 deletion packages/plugin-browser-request/test/request.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import plugin from '../'
import plugin from '../src/request'

import Client, { EventDeliveryPayload } from '@bugsnag/core/client'

Expand Down
7 changes: 7 additions & 0 deletions packages/plugin-browser-request/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"include": ["src/**/*.ts"],
"compilerOptions": {
"target": "ES2020"
}
}
2 changes: 1 addition & 1 deletion packages/plugin-window-onerror/test/onerror.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable jest/no-commented-out-tests */

import plugin from '../'
import plugin from '../src/onerror'

import Client, { EventDeliveryPayload } from '@bugsnag/core/client'

Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-window-unhandled-rejection/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"access": "public"
},
"files": [
"*.js"
"dist"
],
"author": "Bugsnag",
"license": "MIT",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import createRollupConfig from '../../.rollup/index.mjs'

export default createRollupConfig({
input: 'src/unhandled-rejection.ts'
input: 'src/unhandled-rejection.ts',
external: ['@bugsnag/core/lib/iserror', '@bugsnag/core/lib/es-utils/map']
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Stackframe } from 'packages/core/types'

// The stack parser on bluebird stacks in FF get a suprious first frame:
//
// Error: derp
// b@http://localhost:5000/bluebird.html:22:24
// a@http://localhost:5000/bluebird.html:18:9
// @http://localhost:5000/bluebird.html:14:9
//
// results in
// […]
// 0: Object { file: "Error: derp", method: undefined, lineNumber: undefined, … }
// 1: Object { file: "http://localhost:5000/bluebird.html", method: "b", lineNumber: 22, … }
// 2: Object { file: "http://localhost:5000/bluebird.html", method: "a", lineNumber: 18, … }
// 3: Object { file: "http://localhost:5000/bluebird.html", lineNumber: 14, columnNumber: 9, … }
//
// so the following reduce/accumulator function removes such frames
//
// Bluebird pads method names with spaces so trim that too…

// https://github.com/petkaantonov/bluebird/blob/b7f21399816d02f979fe434585334ce901dcaf44/src/debuggability.js#L568-L571
const fixBluebirdStacktrace = (error: PromiseRejectionEvent['reason']) => (frame: Stackframe) => {
if (frame.file === error.toString()) return
if (frame.method) {
frame.method = frame.method.replace(/^\s+/, '')
}
}

export default fixBluebirdStacktrace
Original file line number Diff line number Diff line change
@@ -1,82 +1,96 @@
import { Plugin, Stackframe } from '@bugsnag/core'
import { Client, Logger, Plugin } from '@bugsnag/core'
import map from '@bugsnag/core/lib/es-utils/map'
import isError from '@bugsnag/core/lib/iserror'
import fixBluebirdStacktrace from './fix-bluebird-stacktrace'

type Listener = (evt: PromiseRejectionEvent) => void

let _listener: Listener | null

interface InternalClient extends Client {
_config: {
autoDetectErrors: boolean
enabledErrorTypes: {
unhandledRejections: boolean
}
reportUnhandledPromiseRejectionsAsHandled: boolean
}
_logger: Logger
}

interface BluebirdPromiseRejectionEvent {
detail?: {
reason: PromiseRejectionEvent['reason']
promise: PromiseRejectionEvent['promise']
}
}

/*
* Automatically notifies Bugsnag when window.onunhandledrejection is called
*/
export default (win = window): Plugin => {
const plugin: Plugin = {
load: (client) => {
// @ts-expect-error _config is private API
if (!client._config.autoDetectErrors || !client._config.enabledErrorTypes.unhandledRejections) return
const listener = (evt: PromiseRejectionEvent) => {
let error = evt.reason
const internalClient = client as InternalClient

if (!internalClient._config.autoDetectErrors || !internalClient._config.enabledErrorTypes.unhandledRejections) return
const listener: Listener = (ev) => {
const bluebirdEvent = ev as BluebirdPromiseRejectionEvent

let error = ev.reason
let isBluebird = false

// accessing properties on evt.detail can throw errors (see #394)
try {
// @ts-expect-error detail does not exist on type PromiseRejectionEvent
if (evt.detail && evt.detail.reason) {
// @ts-expect-error detail does not exist on type PromiseRejectionEvent
error = evt.detail.reason
if (bluebirdEvent.detail && bluebirdEvent.detail.reason) {
error = bluebirdEvent.detail.reason
isBluebird = true
}
} catch (e) {}

// Report unhandled promise rejections as handled if the user has configured it
// @ts-expect-error _config is private API
const unhandled = !client._config.reportUnhandledPromiseRejectionsAsHandled

const event = client.Event.create(error, false, {
const event = internalClient.Event.create(error, false, {
severity: 'error',
unhandled,
// Report unhandled promise rejections as handled when set by config
unhandled: !internalClient._config.reportUnhandledPromiseRejectionsAsHandled,
severityReason: { type: 'unhandledPromiseRejection' }
// @ts-expect-error _logger is private API
}, 'unhandledrejection handler', 1, client._logger)
}, 'unhandledrejection handler', 1, internalClient._logger)

if (isBluebird) {
map(event.errors[0].stacktrace, fixBluebirdStacktrace(error))
}

client._notify(event, (event) => {
internalClient._notify(event, (event) => {
if (isError(event.originalError) && !event.originalError.stack) {
event.addMetadata('unhandledRejection handler', {
[Object.prototype.toString.call(event.originalError)]: {
name: event.originalError.name,
message: event.originalError.message,
// @ts-expect-error Property 'code' does not exist on type 'Error'
// @ts-expect-error Optional NodeJS error property
code: event.originalError.code
}
})
}
})
}
if ('addEventListener' in win) {
if (typeof win.addEventListener === 'function') {
win.addEventListener('unhandledrejection', listener)
} else {
// @ts-expect-error onunhandledrejection does not exist on type never
// @ts-expect-error IE8 onunhandledrejection does not match the signature of the modern listener
win.onunhandledrejection = (reason, promise) => {
// @ts-expect-error detail does not exist on type PromiseRejectionEvent
listener({ detail: { reason, promise } })
listener({ detail: { reason, promise } } as unknown as PromiseRejectionEvent)
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tomlongridge have we officially dropped support for IE8 now? this block can go if so 🔥

_listener = listener
}
}

// @ts-expect-error cannot find name 'process'
if (process.env.NODE_ENV !== 'production') {
plugin.destroy = (win = window) => {
if (_listener) {
if ('addEventListener' in win) {
if (typeof win.removeEventListener === 'function') {
win.removeEventListener('unhandledrejection', _listener)
} else {
(win as Window).onunhandledrejection = null
win.onunhandledrejection = null
}
}
_listener = null
Expand All @@ -85,28 +99,3 @@ export default (win = window): Plugin => {

return plugin
}

// The stack parser on bluebird stacks in FF get a suprious first frame:
//
// Error: derp
// b@http://localhost:5000/bluebird.html:22:24
// a@http://localhost:5000/bluebird.html:18:9
// @http://localhost:5000/bluebird.html:14:9
//
// results in
// […]
// 0: Object { file: "Error: derp", method: undefined, lineNumber: undefined, … }
// 1: Object { file: "http://localhost:5000/bluebird.html", method: "b", lineNumber: 22, … }
// 2: Object { file: "http://localhost:5000/bluebird.html", method: "a", lineNumber: 18, … }
// 3: Object { file: "http://localhost:5000/bluebird.html", lineNumber: 14, columnNumber: 9, … }
//
// so the following reduce/accumulator function removes such frames
//
// Bluebird pads method names with spaces so trim that too…
// https://github.com/petkaantonov/bluebird/blob/b7f21399816d02f979fe434585334ce901dcaf44/src/debuggability.js#L568-L571
const fixBluebirdStacktrace = (error: PromiseRejectionEvent['reason']) => (frame: Stackframe) => {
if (frame.file === error.toString()) return
if (frame.method) {
frame.method = frame.method.replace(/^\s+/, '')
}
}
1 change: 1 addition & 0 deletions packages/plugin-window-unhandled-rejection/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"extends": "../../tsconfig.json",
"include": ["src/**/*.ts"],
"compilerOptions": {
"types": ["node"],
"target": "ES2020"
}
}
Expand Down
1 change: 0 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@
"packages/plugin-strip-query-string",
"packages/plugin-strip-project-root",
"packages/plugin-interaction-breadcrumbs",
"packages/plugin-browser-request",
"packages/plugin-simple-throttle",
"packages/plugin-intercept",
"packages/plugin-node-unhandled-rejection",
Expand Down
Loading