-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathpreprocessors.ts
136 lines (111 loc) · 5.48 KB
/
preprocessors.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
import MagicString from 'magic-string';
import type { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
import type { ComponentTrackingInitOptions, SentryPreprocessorGroup, TrackComponentOptions } from './types';
export const defaultComponentTrackingOptions: Required<ComponentTrackingInitOptions> = {
trackComponents: true,
trackInit: true,
trackUpdates: false,
};
export const FIRST_PASS_COMPONENT_TRACKING_PREPROC_ID = 'FIRST_PASS_COMPONENT_TRACKING_PREPROCESSOR';
/**
* Svelte Preprocessor to inject Sentry performance monitoring related code
* into Svelte components.
*/
export function componentTrackingPreprocessor(options?: ComponentTrackingInitOptions): PreprocessorGroup {
const mergedOptions = { ...defaultComponentTrackingOptions, ...options };
const visitedFiles = new Set<string>();
const visitedFilesMarkup = new Set<string>();
const preprocessor: PreprocessorGroup = {
// This markup hook is called once per .svelte component file, before the `script` hook is called
// We use it to check if the passed component has a <script> tag. If it doesn't, we add one to inject our
// code later on, when the `script` hook is executed.
markup: ({ content, filename }) => {
const finalFilename = filename || 'unknown';
const shouldInject = shouldInjectFunction(mergedOptions.trackComponents, finalFilename, {}, visitedFilesMarkup);
if (shouldInject && !hasScriptTag(content)) {
// Insert a <script> tag into the component file where we can later on inject our code.
// We have to add a placeholder to the script tag because for empty script tags,
// the `script` preprocessor hook won't be called
// Note: The space between <script> and </script> is important! Without any content,
// the `script` hook wouldn't be executed for the added script tag.
const s = new MagicString(content);
s.prepend('<script>\n</script>\n');
return { code: s.toString(), map: s.generateMap().toString() };
}
return { code: content };
},
// This script hook is called whenever a Svelte component's <script> content is preprocessed.
// `content` contains the script code as a string
script: ({ content, filename, attributes }) => {
// TODO: Not sure when a filename could be undefined. Using this 'unknown' fallback for the time being
const finalFilename = filename || 'unknown';
if (!shouldInjectFunction(mergedOptions.trackComponents, finalFilename, attributes, visitedFiles)) {
return { code: content };
}
const { trackInit, trackUpdates } = mergedOptions;
const trackComponentOptions: TrackComponentOptions = {
trackInit,
trackUpdates,
componentName: getBaseName(finalFilename),
};
const importStmt = 'import { trackComponent } from "@sentry/svelte";\n';
const functionCall = `trackComponent(${JSON.stringify(trackComponentOptions)});\n`;
const s = new MagicString(content);
s.prepend(functionCall).prepend(importStmt);
const updatedCode = s.toString();
const updatedSourceMap = s.generateMap().toString();
return { code: updatedCode, map: updatedSourceMap };
},
};
const sentryPreprocessor: SentryPreprocessorGroup = {
...preprocessor,
sentryId: FIRST_PASS_COMPONENT_TRACKING_PREPROC_ID,
};
return sentryPreprocessor;
}
function shouldInjectFunction(
trackComponents: Required<ComponentTrackingInitOptions['trackComponents']>,
filename: string,
attributes: Record<string, string | boolean>,
visitedFiles: Set<string>,
): boolean {
// We do cannot inject our function multiple times into the same component
// This can happen when a component has multiple <script> blocks
if (visitedFiles.has(filename)) {
return false;
}
visitedFiles.add(filename);
// We can't inject our function call into <script context="module"> blocks
// because the code inside is not executed when the component is instantiated but
// when the module is first imported.
// see: https://svelte.dev/docs#component-format-script-context-module
if (attributes.context === 'module') {
return false;
}
if (!trackComponents) {
return false;
}
if (Array.isArray(trackComponents)) {
const componentName = getBaseName(filename);
return trackComponents.some(allowed => allowed === componentName);
}
return true;
}
function getBaseName(filename: string): string {
const segments = filename.split('/');
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return segments[segments.length - 1]!.replace('.svelte', '');
}
function hasScriptTag(content: string): boolean {
// This regex is taken from the Svelte compiler code.
// They use this regex to find matching script tags that are passed to the `script` preprocessor hook:
// https://github.com/sveltejs/svelte/blob/bb83eddfc623437528f24e9fe210885b446e72fa/src/compiler/preprocess/index.ts#L144
// However, we remove the first part of the regex to not match HTML comments
const scriptTagRegex = /<script(\s[^]*?)?(?:>([^]*?)<\/script\s*>|\/>)/gi;
// Regex testing is not a super safe way of checking for the presence of a <script> tag in the Svelte
// component file but I think we can use it as a start.
// A case that is not covered by regex-testing HTML is e.g. nested <script> tags but I cannot
// think of why one would do this in Svelte components. For instance, the Svelte compiler errors
// when there's more than one top-level script tag.
return scriptTagRegex.test(content);
}