/
vue.ts
447 lines (388 loc) · 14.5 KB
/
vue.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
import { EventProcessor, Hub, Integration, IntegrationClass, Scope, Span, Transaction } from '@sentry/types';
import { basename, getGlobalObject, logger, timestampWithMs } from '@sentry/utils';
/**
* Used to extract Tracing integration from the current client,
* without the need to import `Tracing` itself from the @sentry/apm package.
* @deprecated as @sentry/tracing should be used over @sentry/apm.
*/
const TRACING_GETTER = ({
id: 'Tracing',
} as any) as IntegrationClass<Integration>;
/**
* Used to extract BrowserTracing integration from @sentry/tracing
*/
const BROWSER_TRACING_GETTER = ({
id: 'BrowserTracing',
} as any) as IntegrationClass<Integration>;
/** Global Vue object limited to the methods/attributes we require */
interface VueInstance {
config: {
errorHandler?(error: Error, vm?: ViewModel, info?: string): void; // tslint:disable-line:completed-docs
};
mixin(hooks: { [key: string]: () => void }): void; // tslint:disable-line:completed-docs
util?: {
warn(...input: any): void; // tslint:disable-line:completed-docs
};
}
/** Representation of Vue component internals */
interface ViewModel {
[key: string]: any;
$root: object;
$options: {
[key: string]: any;
name?: string;
propsData?: { [key: string]: any };
_componentTag?: string;
__file?: string;
$_sentryPerfHook?: boolean;
};
$once(hook: string, cb: () => void): void; // tslint:disable-line:completed-docs
}
// tslint:enable:completed-docs
/** Vue Integration configuration */
interface IntegrationOptions {
/** Vue instance to be used inside the integration */
Vue: VueInstance;
/**
* When set to `false`, Sentry will suppress reporting of all props data
* from your Vue components for privacy concerns.
*/
attachProps: boolean;
/**
* When set to `true`, original Vue's `logError` will be called as well.
* https://github.com/vuejs/vue/blob/c2b1cfe9ccd08835f2d99f6ce60f67b4de55187f/src/core/util/error.js#L38-L48
*/
logErrors: boolean;
/**
* When set to `true`, enables tracking of components lifecycle performance.
* It requires `Tracing` integration to be also enabled.
*/
tracing: boolean;
/** {@link TracingOptions} */
tracingOptions: TracingOptions;
}
/** Vue specific configuration for Tracing Integration */
interface TracingOptions {
/**
* Decides whether to track components by hooking into its lifecycle methods.
* Can be either set to `boolean` to enable/disable tracking for all of them.
* Or to an array of specific component names (case-sensitive).
*/
trackComponents: boolean | string[];
/** How long to wait until the tracked root activity is marked as finished and sent of to Sentry */
timeout: number;
/**
* List of hooks to keep track of during component lifecycle.
* Available hooks: 'activate' | 'create' | 'destroy' | 'mount' | 'update'
* Based on https://vuejs.org/v2/api/#Options-Lifecycle-Hooks
*/
hooks: Operation[];
}
/** Optional metadata attached to Sentry Event */
interface Metadata {
[key: string]: any;
componentName?: string;
propsData?: { [key: string]: any };
lifecycleHook?: string;
}
// https://vuejs.org/v2/api/#Options-Lifecycle-Hooks
type Hook =
| 'activated'
| 'beforeCreate'
| 'beforeDestroy'
| 'beforeMount'
| 'beforeUpdate'
| 'created'
| 'deactivated'
| 'destroyed'
| 'mounted'
| 'updated';
type Operation = 'activate' | 'create' | 'destroy' | 'mount' | 'update';
// Mappings from operation to corresponding lifecycle hook.
const HOOKS: { [key in Operation]: Hook[] } = {
activate: ['activated', 'deactivated'],
create: ['beforeCreate', 'created'],
destroy: ['beforeDestroy', 'destroyed'],
mount: ['beforeMount', 'mounted'],
update: ['beforeUpdate', 'updated'],
};
const COMPONENT_NAME_REGEXP = /(?:^|[-_/])(\w)/g;
const ROOT_COMPONENT_NAME = 'root';
const ANONYMOUS_COMPONENT_NAME = 'anonymous component';
/** JSDoc */
export class Vue implements Integration {
/**
* @inheritDoc
*/
public name: string = Vue.id;
/**
* @inheritDoc
*/
public static id: string = 'Vue';
private readonly _options: IntegrationOptions;
/**
* Cache holding already processed component names
*/
private readonly _componentsCache: { [key: string]: string } = {};
private _rootSpan?: Span;
private _rootSpanTimer?: ReturnType<typeof setTimeout>;
private _tracingActivity?: number;
/**
* @inheritDoc
*/
public constructor(options: Partial<IntegrationOptions>) {
this._options = {
Vue: getGlobalObject<any>().Vue, // tslint:disable-line:no-unsafe-any
attachProps: true,
logErrors: false,
tracing: false,
...options,
tracingOptions: {
hooks: ['mount', 'update'],
timeout: 2000,
trackComponents: false,
...options.tracingOptions,
},
};
}
/**
* Extract component name from the ViewModel
*/
private _getComponentName(vm: ViewModel): string {
// Such level of granularity is most likely not necessary, but better safe than sorry. — Kamil
if (!vm) {
return ANONYMOUS_COMPONENT_NAME;
}
if (vm.$root === vm) {
return ROOT_COMPONENT_NAME;
}
if (!vm.$options) {
return ANONYMOUS_COMPONENT_NAME;
}
if (vm.$options.name) {
return vm.$options.name;
}
if (vm.$options._componentTag) {
return vm.$options._componentTag;
}
// injected by vue-loader
if (vm.$options.__file) {
const unifiedFile = vm.$options.__file.replace(/^[a-zA-Z]:/, '').replace(/\\/g, '/');
const filename = basename(unifiedFile, '.vue');
return (
this._componentsCache[filename] ||
(this._componentsCache[filename] = filename.replace(COMPONENT_NAME_REGEXP, (_, c: string) =>
c ? c.toUpperCase() : '',
))
);
}
return ANONYMOUS_COMPONENT_NAME;
}
/** Keep it as attribute function, to keep correct `this` binding inside the hooks callbacks */
private readonly _applyTracingHooks = (vm: ViewModel, getCurrentHub: () => Hub) => {
// Don't attach twice, just in case
if (vm.$options.$_sentryPerfHook) {
return;
}
vm.$options.$_sentryPerfHook = true;
const name = this._getComponentName(vm);
const rootMount = name === ROOT_COMPONENT_NAME;
const spans: { [key: string]: Span } = {};
// Render hook starts after once event is emitted,
// but it ends before the second event of the same type.
//
// Because of this, we start measuring inside the first event,
// but finish it before it triggers, to skip the event emitter timing itself.
const rootHandler = (hook: Hook) => {
const now = timestampWithMs();
// On the first handler call (before), it'll be undefined, as `$once` will add it in the future.
// However, on the second call (after), it'll be already in place.
if (this._rootSpan) {
this._finishRootSpan(now, getCurrentHub);
} else {
vm.$once(`hook:${hook}`, () => {
// Create an activity on the first event call. There'll be no second call, as rootSpan will be in place,
// thus new event handler won't be attached.
// We do this whole dance with `TRACING_GETTER` to prevent `@sentry/apm` from becoming a peerDependency.
// We also need to ask for the `.constructor`, as `pushActivity` and `popActivity` are static, not instance methods.
// tslint:disable-next-line: deprecation
const tracingIntegration = getCurrentHub().getIntegration(TRACING_GETTER);
if (tracingIntegration) {
// tslint:disable-next-line:no-unsafe-any
this._tracingActivity = (tracingIntegration as any).constructor.pushActivity('Vue Application Render');
// tslint:disable-next-line:no-unsafe-any
const transaction = (tracingIntegration as any).constructor.getTransaction();
if (transaction) {
// tslint:disable-next-line:no-unsafe-any
this._rootSpan = transaction.startChild({
description: 'Application Render',
op: 'Vue',
});
}
// Use functionality from @sentry/tracing
} else {
const activeTransaction = getActiveTransaction(getCurrentHub());
if (activeTransaction) {
this._rootSpan = activeTransaction.startChild({
description: 'Application Render',
op: 'Vue',
});
}
}
});
}
};
const childHandler = (hook: Hook, operation: Operation) => {
// Skip components that we don't want to track to minimize the noise and give a more granular control to the user
const shouldTrack = Array.isArray(this._options.tracingOptions.trackComponents)
? this._options.tracingOptions.trackComponents.indexOf(name) > -1
: this._options.tracingOptions.trackComponents;
if (!this._rootSpan || !shouldTrack) {
return;
}
const now = timestampWithMs();
const span = spans[operation];
// On the first handler call (before), it'll be undefined, as `$once` will add it in the future.
// However, on the second call (after), it'll be already in place.
if (span) {
span.finish();
this._finishRootSpan(now, getCurrentHub);
} else {
vm.$once(`hook:${hook}`, () => {
if (this._rootSpan) {
spans[operation] = this._rootSpan.startChild({
description: `Vue <${name}>`,
op: operation,
});
}
});
}
};
// Each compomnent has it's own scope, so all activities are only related to one of them
this._options.tracingOptions.hooks.forEach(operation => {
// Retrieve corresponding hooks from Vue lifecycle.
// eg. mount => ['beforeMount', 'mounted']
const internalHooks = HOOKS[operation];
if (!internalHooks) {
logger.warn(`Unknown hook: ${operation}`);
return;
}
internalHooks.forEach(internalHook => {
const handler = rootMount
? rootHandler.bind(this, internalHook)
: childHandler.bind(this, internalHook, operation);
const currentValue = vm.$options[internalHook];
if (Array.isArray(currentValue)) {
vm.$options[internalHook] = [handler, ...currentValue];
} else if (typeof currentValue === 'function') {
vm.$options[internalHook] = [handler, currentValue];
} else {
vm.$options[internalHook] = [handler];
}
});
});
};
/** Finish top-level span and activity with a debounce configured using `timeout` option */
private _finishRootSpan(timestamp: number, getCurrentHub: () => Hub): void {
if (this._rootSpanTimer) {
clearTimeout(this._rootSpanTimer);
}
this._rootSpanTimer = setTimeout(() => {
if (this._tracingActivity) {
// We do this whole dance with `TRACING_GETTER` to prevent `@sentry/apm` from becoming a peerDependency.
// We also need to ask for the `.constructor`, as `pushActivity` and `popActivity` are static, not instance methods.
// tslint:disable-next-line: deprecation
const tracingIntegration = getCurrentHub().getIntegration(TRACING_GETTER);
if (tracingIntegration) {
// tslint:disable-next-line:no-unsafe-any
(tracingIntegration as any).constructor.popActivity(this._tracingActivity);
}
}
// We should always finish the span, only should pop activity if using @sentry/apm
if (this._rootSpan) {
this._rootSpan.finish(timestamp);
}
}, this._options.tracingOptions.timeout);
}
/** Inject configured tracing hooks into Vue's component lifecycles */
private _startTracing(getCurrentHub: () => Hub): void {
const applyTracingHooks = this._applyTracingHooks;
this._options.Vue.mixin({
beforeCreate(this: ViewModel): void {
// tslint:disable-next-line: deprecation
if (getCurrentHub().getIntegration(TRACING_GETTER) || getCurrentHub().getIntegration(BROWSER_TRACING_GETTER)) {
// `this` points to currently rendered component
applyTracingHooks(this, getCurrentHub);
} else {
logger.error('Vue integration has tracing enabled, but Tracing integration is not configured');
}
},
});
}
/** Inject Sentry's handler into owns Vue's error handler */
private _attachErrorHandler(getCurrentHub: () => Hub): void {
const currentErrorHandler = this._options.Vue.config.errorHandler; // tslint:disable-line:no-unbound-method
this._options.Vue.config.errorHandler = (error: Error, vm?: ViewModel, info?: string): void => {
const metadata: Metadata = {};
if (vm) {
try {
metadata.componentName = this._getComponentName(vm);
if (this._options.attachProps) {
metadata.propsData = vm.$options.propsData;
}
} catch (_oO) {
logger.warn('Unable to extract metadata from Vue component.');
}
}
if (info) {
metadata.lifecycleHook = info;
}
if (getCurrentHub().getIntegration(Vue)) {
// Capture exception in the next event loop, to make sure that all breadcrumbs are recorded in time.
setTimeout(() => {
getCurrentHub().withScope(scope => {
scope.setContext('vue', metadata);
getCurrentHub().captureException(error);
});
});
}
if (typeof currentErrorHandler === 'function') {
currentErrorHandler.call(this._options.Vue, error, vm, info);
}
if (this._options.logErrors) {
if (this._options.Vue.util) {
this._options.Vue.util.warn(`Error in ${info}: "${error.toString()}"`, vm);
}
console.error(error); // tslint:disable-line:no-console
}
};
}
/**
* @inheritDoc
*/
public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {
if (!this._options.Vue) {
logger.error('Vue integration is missing a Vue instance');
return;
}
this._attachErrorHandler(getCurrentHub);
if (this._options.tracing) {
this._startTracing(getCurrentHub);
}
}
}
// tslint:disable-next-line: completed-docs
interface HubType extends Hub {
// tslint:disable-next-line: completed-docs
getScope?(): Scope | undefined;
}
/** Grabs active transaction off scope */
export function getActiveTransaction<T extends Transaction>(hub: HubType): T | undefined {
if (hub && hub.getScope) {
const scope = hub.getScope() as Scope;
if (scope) {
return scope.getTransaction() as T | undefined;
}
}
return undefined;
}