-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathmain.ts
More file actions
217 lines (188 loc) · 6.93 KB
/
Copy pathmain.ts
File metadata and controls
217 lines (188 loc) · 6.93 KB
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
import type { LogsInitConfiguration } from '@datadog/browser-logs'
import type { RumInitConfiguration } from '@datadog/browser-rum'
import type { Settings } from '../common/extension.types'
import { EventListeners } from '../common/eventListeners'
import { DEV_LOGS_URL, DEV_RUM_SLIM_URL, DEV_RUM_URL } from '../common/packagesUrlConstants'
import { SESSION_STORAGE_SETTINGS_KEY } from '../common/sessionKeyConstant'
const windowWithSdkGlobals = window as Window & {
DD_RUM?: SdkPublicApi
DD_LOGS?: SdkPublicApi
__ddBrowserSdkExtensionCallback?: (message: unknown) => void
}
interface SdkPublicApi {
[key: string]: (...args: any[]) => unknown
}
export function main() {
// Prevent multiple executions when the devetools are reconnecting
if (windowWithSdkGlobals.__ddBrowserSdkExtensionCallback) {
return
}
sendEventsToExtension()
const settings = getSettings()
if (
settings &&
// Avoid instrumenting SDK global variables if the SDKs are already loaded.
// This happens when the page is loaded and then the devtools are opened.
noBrowserSdkLoaded()
) {
const ddRumGlobal = instrumentGlobal('DD_RUM')
const ddLogsGlobal = instrumentGlobal('DD_LOGS')
if (settings.debugMode) {
setDebug(ddRumGlobal)
setDebug(ddLogsGlobal)
}
if (settings.rumConfigurationOverride) {
overrideInitConfiguration(ddRumGlobal, settings.rumConfigurationOverride)
}
if (settings.logsConfigurationOverride) {
overrideInitConfiguration(ddLogsGlobal, settings.logsConfigurationOverride)
}
if (settings.useDevBundles === 'npm') {
injectDevBundle(settings.useRumSlim ? DEV_RUM_SLIM_URL : DEV_RUM_URL, ddRumGlobal)
injectDevBundle(DEV_LOGS_URL, ddLogsGlobal)
}
}
}
function sendEventsToExtension() {
// This script is executed in the "main" execution world, the same world as the webpage. Thus, it
// can define a global callback variable to listen to SDK events.
windowWithSdkGlobals.__ddBrowserSdkExtensionCallback = (message: unknown) => {
// Relays any message to the "isolated" content-script via a custom event.
window.dispatchEvent(
new CustomEvent('__ddBrowserSdkMessage', {
detail: message,
})
)
}
}
function getSettings() {
try {
// sessionStorage access throws in sandboxed iframes
const stringSettings = sessionStorage.getItem(SESSION_STORAGE_SETTINGS_KEY)
// JSON.parse throws if the stringSettings is not a valid JSON
return JSON.parse(stringSettings || 'null') as Settings | null
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error getting settings', error)
}
}
function noBrowserSdkLoaded() {
return !windowWithSdkGlobals.DD_RUM && !windowWithSdkGlobals.DD_LOGS
}
function injectDevBundle(url: string, global: GlobalInstrumentation) {
loadSdkScriptFromURL(url)
const devInstance = global.get() as SdkPublicApi
if (devInstance) {
global.onSet((sdkInstance) => proxySdk(sdkInstance, devInstance))
global.returnValue(devInstance)
}
}
function setDebug(global: GlobalInstrumentation) {
global.onSet((sdkInstance) => {
// Ensure the sdkInstance has a '_setDebug' method, excluding async stubs.
if ('_setDebug' in sdkInstance) {
sdkInstance._setDebug(true)
}
})
}
function overrideInitConfiguration(
global: GlobalInstrumentation,
configurationOverride: Partial<RumInitConfiguration | LogsInitConfiguration>
) {
global.onSet((sdkInstance) => {
// Ensure the sdkInstance has an 'init' method, excluding async stubs.
if ('init' in sdkInstance) {
const originalInit = sdkInstance.init
sdkInstance.init = (config: RumInitConfiguration | LogsInitConfiguration) => {
originalInit({
...config,
...restoreFunctions(config, configurationOverride),
allowedTrackingOrigins: [location.origin],
})
}
}
})
}
type SDKInitConfiguration = RumInitConfiguration | LogsInitConfiguration
function restoreFunctions(
original: SDKInitConfiguration,
override: Partial<SDKInitConfiguration>
): Partial<SDKInitConfiguration> {
// Clone the override to avoid mutating the input
const result = (Array.isArray(override) ? [...override] : { ...override }) as Record<string, unknown>
// Add back any missing functions from original
for (const key in original) {
if (!Object.prototype.hasOwnProperty.call(original, key)) {
continue
}
const originalValue = original[key as keyof typeof original]
const resultValue = result[key]
// If it's a function and missing in result, restore it
if (typeof originalValue === 'function' && !(key in result)) {
result[key] = originalValue
}
// If both are objects, recurse to restore functions at deeper levels
else if (
key in result &&
originalValue &&
typeof originalValue === 'object' &&
!Array.isArray(originalValue) &&
resultValue &&
typeof resultValue === 'object' &&
!Array.isArray(resultValue)
) {
result[key] = restoreFunctions(originalValue as SDKInitConfiguration, resultValue)
}
}
return result
}
function loadSdkScriptFromURL(url: string) {
const xhr = new XMLHttpRequest()
try {
xhr.open('GET', url, false) // `false` makes the request synchronous
xhr.send()
} catch (error) {
// eslint-disable-next-line no-console
console.error(`[DD Browser SDK extension] Error while loading ${url}:`, error)
return
}
if (xhr.status === 200) {
let sdkCode = xhr.responseText
// Webpack chunks are loaded via ESM dynamic imports with relative paths (e.g. `import('./chunks/...')`).
// Since this script is injected inline rather than loaded via `<script src>`, relative import()
// paths would resolve against the page URL instead of the SDK URL. Replace them with absolute URLs.
const baseUrl = url.slice(0, url.lastIndexOf('/') + 1)
sdkCode = sdkCode.replaceAll(/\bimport\(['"]\.\/['"]/g, `import('${baseUrl}'`)
const script = document.createElement('script')
script.type = 'text/javascript'
script.text = sdkCode
document.documentElement.prepend(script)
}
}
type GlobalInstrumentation = ReturnType<typeof instrumentGlobal>
function instrumentGlobal(global: 'DD_RUM' | 'DD_LOGS') {
const eventListeners = new EventListeners<SdkPublicApi>()
let returnedInstance: SdkPublicApi | undefined
let lastInstance: SdkPublicApi | undefined
Object.defineProperty(window, global, {
set(sdkInstance: SdkPublicApi) {
eventListeners.notify(sdkInstance)
lastInstance = sdkInstance
},
get(): SdkPublicApi | undefined {
return returnedInstance ?? lastInstance
},
})
return {
get: () => windowWithSdkGlobals[global],
onSet: (callback: (sdkInstance: SdkPublicApi) => void) => {
eventListeners.subscribe(callback)
},
returnValue: (sdkInstance: SdkPublicApi) => {
returnedInstance = sdkInstance
},
}
}
function proxySdk(target: SdkPublicApi, root: SdkPublicApi) {
Object.assign(target, root)
}