Skip to content

Commit 2083f12

Browse files
authored
Merge pull request #2382 from bugsnag/plat-13682
convert @bugsnag/plugin-inline-script-content to TypeScript and rollup
2 parents e3328f6 + dae4b89 commit 2083f12

44 files changed

Lines changed: 239 additions & 805 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

packages/browser/src/bugsnag.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
import { BugsnagStatic, Config, Client, schema as baseConfig } from '@bugsnag/core'
22

3-
import map from '@bugsnag/core/lib/es-utils/map'
4-
import keys from '@bugsnag/core/lib/es-utils/keys'
5-
import assign from '@bugsnag/core/lib/es-utils/assign'
6-
73
// extend the base config schema with some browser-specific options
84
import browserConfig from './config'
95

@@ -18,7 +14,6 @@ import pluginConsoleBreadcrumbs from '@bugsnag/plugin-console-breadcrumbs'
1814
import pluginNetworkBreadcrumbs from '@bugsnag/plugin-network-breadcrumbs'
1915
import pluginNavigationBreadcrumbs from '@bugsnag/plugin-navigation-breadcrumbs'
2016
import pluginInteractionBreadcrumbs from '@bugsnag/plugin-interaction-breadcrumbs'
21-
// @ts-ignore
2217
import pluginInlineScriptContent from '@bugsnag/plugin-inline-script-content'
2318
import pluginSession from '@bugsnag/plugin-browser-session'
2419
import pluginIp from '@bugsnag/plugin-client-ip'
@@ -32,7 +27,7 @@ const name = 'Bugsnag JavaScript'
3227
const version = '__BUGSNAG_NOTIFIER_VERSION__'
3328
const url = 'https://github.com/bugsnag/bugsnag-js'
3429

35-
const schema = assign({}, baseConfig, browserConfig)
30+
const schema = { ...baseConfig, ...browserConfig }
3631

3732
export interface BrowserConfig extends Config {
3833
maxEvents?: number
@@ -62,6 +57,7 @@ type BrowserClient = Partial<Client> & {
6257

6358
const notifier: BrowserClient = {
6459
_client: null,
60+
// @ts-expect-error
6561
createClient: (opts) => {
6662
// handle very simple use case where user supplies just the api key as a string
6763
if (typeof opts === 'string') opts = { apiKey: opts }
@@ -89,9 +85,11 @@ const notifier: BrowserClient = {
8985
]
9086

9187
// configure a client with user supplied options
88+
// @ts-expect-error
9289
const bugsnag = new Client(opts, schema, internalPlugins, { name, version, url });
9390

9491
// set delivery based on browser capability (IE 8+9 have an XDomainRequest object)
92+
// @ts-expect-error
9593
(bugsnag as BrowserClient)._setDelivery?.(window.XDomainRequest ? dXDomainRequest : dXMLHttpRequest)
9694

9795
bugsnag._logger.debug('Loaded!')
@@ -114,21 +112,22 @@ const notifier: BrowserClient = {
114112
}
115113
}
116114

117-
type Method = keyof typeof Client.prototype
118-
119-
const clientMethods = Object.getOwnPropertyNames(Client.prototype).concat(['resetEventCount']) as Method[]
115+
const clientMethods = Object.getOwnPropertyNames(Client.prototype).concat(['resetEventCount'])
120116

121-
map(clientMethods, (m) => {
122-
if (/^_/.test(m)) return
117+
clientMethods.map((m) => {
118+
if (/^_/.test(m) || m === 'constructor') return
119+
// @ts-expect-error
123120
notifier[m] = function () {
124121
if (!notifier._client) return console.log(`Bugsnag.${m}() was called before Bugsnag.start()`)
125122
notifier._client._depth += 1
123+
// @ts-expect-error
126124
const ret = notifier._client[m].apply(notifier._client, arguments)
127125
notifier._client._depth -= 1
128126
return ret
129127
}
130128
})
131129

130+
// @ts-expect-error
132131
const Bugsnag = notifier as BrowserBugsnagStatic
133132

134133
export default Bugsnag

packages/browser/test/index.test.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,12 @@ function mockFetch (onSessionSend?: SendCallback, onNotifySend?: SendCallback) {
3131
const session = makeMockXHR(onSessionSend)
3232
const notify = makeMockXHR(onNotifySend)
3333

34-
// @ts-ignore
34+
// @ts-expect-error
3535
window.XMLHttpRequest = jest.fn()
3636
.mockImplementationOnce(() => session)
3737
.mockImplementationOnce(() => notify)
3838
.mockImplementation(() => makeMockXHR(() => {}))
39-
// @ts-ignore
39+
// @ts-expect-error
4040
window.XMLHttpRequest.DONE = DONE
4141

4242
return { session, notify }
@@ -102,7 +102,7 @@ describe('browser notifier', () => {
102102
type: 'state',
103103
message: 'Bugsnag loaded'
104104
}))
105-
expect(event.originalError.message).toBe('123')
105+
expect((event.originalError as Error).message).toBe('123')
106106
})
107107
})
108108

@@ -204,7 +204,7 @@ describe('browser notifier', () => {
204204
done(err)
205205
}
206206
expect(event.breadcrumbs.length).toBe(0)
207-
expect(event.originalError.message).toBe('123')
207+
expect((event.originalError as Error).message).toBe('123')
208208
expect(event.getMetadata('debug')).toEqual({ foo: 'bar' })
209209
done()
210210
})
@@ -235,6 +235,7 @@ describe('browser notifier', () => {
235235
it('resets events on pushState', () => {
236236
const Bugsnag = getBugsnag()
237237
const client = Bugsnag.createClient('API_KEY')
238+
// @ts-expect-error
238239
const resetEventCount = jest.spyOn(client, 'resetEventCount')
239240

240241
window.history.pushState('', '', 'new-url')
@@ -247,6 +248,7 @@ describe('browser notifier', () => {
247248
it('does not reset events on replaceState', () => {
248249
const Bugsnag = getBugsnag()
249250
const client = Bugsnag.createClient('API_KEY')
251+
// @ts-expect-error
250252
const resetEventCount = jest.spyOn(client, 'resetEventCount')
251253

252254
window.history.replaceState('', '', 'new-url')
@@ -274,12 +276,10 @@ describe('browser notifier', () => {
274276

275277
describe('payload checksum behavior (Bugsnag-Integrity header)', () => {
276278
beforeEach(() => {
277-
// @ts-ignore
278279
window.isSecureContext = true
279280
})
280281

281282
afterEach(() => {
282-
// @ts-ignore
283283
window.isSecureContext = false
284284
})
285285

packages/core/package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22
"name": "@bugsnag/core",
33
"main": "./dist/index.cjs",
44
"version": "8.2.0",
5-
"types": "types/index.d.ts",
5+
"types": "./dist/types/index.d.ts",
66
"exports": {
77
".": {
8-
"types": "./types/index.d.ts",
8+
"types": "./dist/types/index.d.ts",
99
"import": "./dist/index.mjs",
1010
"default": "./dist/index.cjs"
1111
},

packages/core/src/client.ts

Lines changed: 15 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -2,66 +2,21 @@ import configSchema from './config'
22
import Event from './event'
33
import Breadcrumb from './breadcrumb'
44
import Session from './session'
5-
import map from './lib/es-utils/map'
65
import includes from './lib/es-utils/includes'
76
import filter from './lib/es-utils/filter'
87
import reduce from './lib/es-utils/reduce'
9-
import keys from './lib/es-utils/keys'
108
import assign from './lib/es-utils/assign'
119
import runCallbacks from './lib/callback-runner'
1210
import metadataDelegate from './lib/metadata-delegate'
1311
import runSyncCallbacks from './lib/sync-callback-runner'
1412
import BREADCRUMB_TYPES from './lib/breadcrumb-types'
1513
import { add, clear, merge } from './lib/feature-flag-delegate'
16-
import { App, BreadcrumbType, Config, Device, FeatureFlag, OnBreadcrumbCallback, OnErrorCallback, OnSessionCallback, Plugin, User } from './common'
14+
import { BreadcrumbType, Config, Delivery, FeatureFlag, LoggerConfig, NotifiableError, Notifier, OnBreadcrumbCallback, OnErrorCallback, OnSessionCallback, Plugin, SessionDelegate, User } from './common'
1715

1816
const noop = () => {}
19-
20-
interface LoggerConfig {
21-
debug: (msg: any) => void
22-
info: (msg: any) => void
23-
warn: (msg: any) => void
24-
error: (msg: any, err?: unknown) => void
25-
}
26-
27-
interface Notifier {
28-
name: string
29-
version: string
30-
url: string
31-
}
32-
33-
interface EventDeliveryPayload {
34-
apiKey: string
35-
notifier: Notifier
36-
events: Event[]
37-
}
38-
39-
interface SessionDeliveryPayload {
40-
notifier?: Notifier
41-
device?: Device
42-
app?: App
43-
sessions?: Array<{
44-
id: string
45-
startedAt: Date
46-
user?: User
47-
}>
48-
}
49-
50-
interface Delivery {
51-
sendEvent(payload: EventDeliveryPayload, cb: (err?: Error | null) => void): void
52-
sendSession(session: SessionDeliveryPayload, cb: (err?: Error | null) => void): void
53-
}
54-
55-
export interface SessionDelegate<T extends Config = Config> {
56-
startSession: (client: Client<T>, session: Session) => Client
57-
pauseSession: (client: Client<T>) => void
58-
resumeSession: (client: Client<T>) => Client
59-
}
60-
6117
export default class Client<T extends Config = Config> {
62-
private readonly _notifier?: Notifier
63-
// This ought to be Required<T> but the current version of TypeScript doesn't seem to like it
64-
public readonly _config: Required<Config>
18+
public readonly _notifier?: Notifier
19+
public readonly _config: T & Required<Config>
6520
private readonly _schema: any
6621

6722
public _delivery: Delivery
@@ -87,13 +42,14 @@ export default class Client<T extends Config = Config> {
8742
b: OnBreadcrumbCallback[]
8843
}
8944

90-
private readonly Client: typeof Client
91-
private readonly Event: typeof Event
92-
private readonly Breadcrumb: typeof Breadcrumb
93-
private readonly Session: typeof Session
45+
public readonly Client: typeof Client
46+
public readonly Event: typeof Event
47+
public readonly Breadcrumb: typeof Breadcrumb
48+
public readonly Session: typeof Session
9449

95-
private readonly _depth: number
50+
public _depth: number
9651

52+
public _pausedSession?: Session | null
9753
public _sessionDelegate?: SessionDelegate
9854

9955
constructor (configuration: T, schema = configSchema, internalPlugins: Plugin<T>[] = [], notifier?: Notifier) {
@@ -139,7 +95,7 @@ export default class Client<T extends Config = Config> {
13995
this.Session = Session
14096

14197
this._config = this._configure(configuration, internalPlugins)
142-
map(internalPlugins.concat(this._config.plugins), pl => {
98+
internalPlugins.concat(this._config.plugins).map(pl => {
14399
if (pl) this._loadPlugin(pl)
144100
})
145101

@@ -195,7 +151,7 @@ export default class Client<T extends Config = Config> {
195151
this._context = c
196152
}
197153

198-
_configure (opts: T, internalPlugins: Plugin[]) {
154+
_configure (opts: T, internalPlugins: Plugin<T>[]) {
199155
const schema = reduce(internalPlugins, (schema, plugin) => {
200156
if (plugin && plugin.configSchema) return assign({}, schema, plugin.configSchema)
201157
return schema
@@ -207,7 +163,7 @@ export default class Client<T extends Config = Config> {
207163
}
208164

209165
// accumulate configuration and error messages
210-
const { errors, config } = reduce(keys(schema), (accum, key: keyof typeof opts) => {
166+
const { errors, config } = reduce(Object.keys(schema) as unknown as (keyof T)[], (accum, key: keyof typeof opts) => {
211167
const defaultValue = schema[key].defaultValue(opts[key])
212168

213169
if (opts[key] !== undefined) {
@@ -249,7 +205,7 @@ export default class Client<T extends Config = Config> {
249205
if (config.onSession) this._cbs.s = this._cbs.s.concat(config.onSession)
250206

251207
// finally warn about any invalid config where we fell back to the default
252-
if (keys(errors).length) {
208+
if (Object.keys(errors).length) {
253209
this._logger.warn(generateConfigErrorMessage(errors, opts))
254210
}
255211

@@ -369,7 +325,7 @@ export default class Client<T extends Config = Config> {
369325
return types === null || includes(types, type)
370326
}
371327

372-
notify (maybeError: Error, onError?: OnErrorCallback, postReportCallback: (err: Error | null | undefined, event: Event) => void = noop) {
328+
notify (maybeError: NotifiableError, onError?: OnErrorCallback, postReportCallback: (err: Error | null | undefined, event: Event) => void = noop) {
373329
const event = Event.create(maybeError, true, undefined, 'notify()', this._depth + 1, this._logger)
374330
this._notify(event, onError, postReportCallback)
375331
}
@@ -411,11 +367,8 @@ export default class Client<T extends Config = Config> {
411367

412368
if (this._isBreadcrumbTypeEnabled('error')) {
413369
// only leave a crumb for the error if actually got sent
414-
// @ts-ignore
415370
Client.prototype.leaveBreadcrumb.call(this, event.errors[0].errorClass, {
416-
// @ts-ignore
417371
errorClass: event.errors[0].errorClass,
418-
// @ts-ignore
419372
errorMessage: event.errors[0].errorMessage,
420373
severity: event.severity
421374
}, 'error')
@@ -447,7 +400,7 @@ export default class Client<T extends Config = Config> {
447400

448401
const generateConfigErrorMessage = (errors: Record<string, Error>, rawInput: Config) => {
449402
const er = new Error(
450-
`Invalid configuration\n${map(keys(errors), key => ` - ${key} ${errors[key]}, got ${stringify(rawInput[key])}`).join('\n\n')}`)
403+
`Invalid configuration\n${(Object.keys(errors) as unknown as (keyof Config)[]).map(key => ` - ${key} ${errors[key]}, got ${stringify(rawInput[key])}`).join('\n\n')}`)
451404
return er
452405
}
453406

packages/core/src/common.ts

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,6 @@ export interface Logger {
6060
error: (...args: any[]) => void
6161
}
6262

63-
export interface SessionDelegate {
64-
startSession: (client: Client) => Client
65-
}
66-
6763
export interface EventPayload {
6864
apiKey: string
6965
notifier: {
@@ -157,4 +153,57 @@ export interface Stackframe {
157153
export interface FeatureFlag {
158154
name: string
159155
variant?: string | null
156+
}
157+
158+
export interface LoggerConfig {
159+
debug: (msg: any) => void
160+
info: (msg: any) => void
161+
warn: (msg: any) => void
162+
error: (msg: any, err?: unknown) => void
163+
}
164+
165+
export interface Notifier {
166+
name: string
167+
version: string
168+
url: string
169+
}
170+
171+
export interface EventDeliveryPayload {
172+
apiKey: string
173+
notifier: Notifier
174+
events: Event[]
175+
}
176+
177+
export interface SessionDeliveryPayload {
178+
notifier?: Notifier
179+
device?: Device
180+
app?: App
181+
sessions?: Array<{
182+
id: string
183+
startedAt: Date
184+
user?: User
185+
}>
186+
}
187+
export interface Delivery {
188+
sendEvent(payload: EventDeliveryPayload, cb: (err?: Error | null) => void): void
189+
sendSession(session: SessionDeliveryPayload, cb: (err?: Error | null) => void): void
190+
}
191+
192+
export interface SessionDelegate<T extends Config = Config> {
193+
startSession: (client: Client<T>, session: Session) => Client
194+
pauseSession: (client: Client<T>) => void
195+
resumeSession: (client: Client<T>) => Client
196+
}
197+
198+
export interface BugsnagStatic extends Client {
199+
start(apiKeyOrOpts: string | Config): Client
200+
createClient(apiKeyOrOpts: string | Config): Client
201+
isStarted(): boolean
202+
}
203+
204+
export interface BugsnagError {
205+
errorClass: string
206+
errorMessage: string
207+
type: string
208+
stacktrace: Stackframe[]
160209
}

0 commit comments

Comments
 (0)