-
Notifications
You must be signed in to change notification settings - Fork 309
/
index.js
189 lines (159 loc) · 5.51 KB
/
index.js
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
'use strict'
/* eslint-disable no-console */
const instrumentations = require('../datadog-instrumentations/src/helpers/instrumentations.js')
const hooks = require('../datadog-instrumentations/src/helpers/hooks.js')
const extractPackageAndModulePath = require('../datadog-instrumentations/src/utils/src/extract-package-and-module-path')
for (const hook of Object.values(hooks)) {
if (typeof hook === 'object') {
hook.fn()
} else {
hook()
}
}
const modulesOfInterest = new Set()
for (const instrumentation of Object.values(instrumentations)) {
for (const entry of instrumentation) {
if (!entry.file) {
modulesOfInterest.add(entry.name) // e.g. "redis"
} else {
modulesOfInterest.add(`${entry.name}/${entry.file}`) // e.g. "redis/my/file.js"
}
}
}
const INSTRUMENTED = Object.keys(instrumentations)
const RAW_BUILTINS = require('module').builtinModules
const CHANNEL = 'dd-trace:bundler:load'
const path = require('path')
const fs = require('fs')
const builtins = new Set()
for (const builtin of RAW_BUILTINS) {
builtins.add(builtin)
builtins.add(`node:${builtin}`)
}
const DEBUG = !!process.env.DD_TRACE_DEBUG
// We don't want to handle any built-in packages
// Those packages will still be handled via RITM
// Attempting to instrument them would fail as they have no package.json file
for (const pkg of INSTRUMENTED) {
if (builtins.has(pkg)) continue
if (pkg.startsWith('node:')) continue
modulesOfInterest.add(pkg)
}
module.exports.name = 'datadog-esbuild'
module.exports.setup = function (build) {
const externalModules = new Set(build.initialOptions.external || [])
build.onResolve({ filter: /.*/ }, args => {
if (externalModules.has(args.path)) {
// Internal Node.js packages will still be instrumented via require()
if (DEBUG) console.log(`EXTERNAL: ${args.path}`)
return
}
// TODO: Should this also check for namespace === 'file'?
if (args.path.startsWith('.') && !args.importer.includes('node_modules/')) {
// This is local application code, not an instrumented package
if (DEBUG) console.log(`LOCAL: ${args.path}`)
return
}
// TODO: Should this also check for namespace === 'file'?
if (args.path.startsWith('@') && !args.importer.includes('node_modules/')) {
// This is the Next.js convention for loading local files
if (DEBUG) console.log(`@LOCAL: ${args.path}`)
return
}
let fullPathToModule
try {
fullPathToModule = dotFriendlyResolve(args.path, args.resolveDir)
} catch (err) {
if (DEBUG) {
console.warn(`Warning: Unable to find "${args.path}".` +
"Unless it's dead code this could cause a problem at runtime.")
}
return
}
const extracted = extractPackageAndModulePath(fullPathToModule)
const internal = builtins.has(args.path)
if (args.namespace === 'file' && (
modulesOfInterest.has(args.path) || modulesOfInterest.has(`${extracted.pkg}/${extracted.path}`))
) {
// The file namespace is used when requiring files from disk in userland
let pathToPackageJson
try {
// we can't use require.resolve('pkg/package.json') as ESM modules don't make the file available
pathToPackageJson = require.resolve(`${extracted.pkg}`, { paths: [args.resolveDir] })
pathToPackageJson = extractPackageAndModulePath(pathToPackageJson).pkgJson
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
if (!internal) {
if (DEBUG) {
console.warn(`Warning: Unable to find "${extracted.pkg}/package.json".` +
"Unless it's dead code this could cause a problem at runtime.")
}
}
return
} else {
throw err
}
}
const packageJson = JSON.parse(fs.readFileSync(pathToPackageJson).toString())
if (DEBUG) console.log(`RESOLVE: ${args.path}@${packageJson.version}`)
// https://esbuild.github.io/plugins/#on-resolve-arguments
return {
path: fullPathToModule,
pluginData: {
version: packageJson.version,
pkg: extracted.pkg,
path: extracted.path,
full: fullPathToModule,
raw: args.path,
pkgOfInterest: true,
internal
}
}
}
})
build.onLoad({ filter: /.*/ }, args => {
if (!args.pluginData?.pkgOfInterest) {
return
}
const data = args.pluginData
if (DEBUG) console.log(`LOAD: ${data.pkg}@${data.version}, pkg "${data.path}"`)
const pkgPath = data.raw !== data.pkg
? `${data.pkg}/${data.path}`
: data.pkg
// Read the content of the module file of interest
const fileCode = fs.readFileSync(args.path, 'utf8')
const contents = `
(function() {
${fileCode}
})(...arguments);
{
const dc = require('dc-polyfill');
const ch = dc.channel('${CHANNEL}');
const mod = module.exports
const payload = {
module: mod,
version: '${data.version}',
package: '${data.pkg}',
path: '${pkgPath}'
};
ch.publish(payload);
module.exports = payload.module;
}
`
// https://esbuild.github.io/plugins/#on-load-results
return {
contents,
loader: 'js',
resolveDir: path.dirname(args.path)
}
})
}
// @see https://github.com/nodejs/node/issues/47000
function dotFriendlyResolve (path, directory) {
if (path === '.') {
path = './'
} else if (path === '..') {
path = '../'
}
return require.resolve(path, { paths: [directory] })
}