Skip to content

Commit 3912e19

Browse files
authored
Add ability to dump patched code (#9)
1 parent 6811c09 commit 3912e19

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,18 @@ To use the CJS patch you can run your Node.js application with the `--require` f
7777
node --require cjs-patch.js your-app.js
7878
```
7979
80+
## Debugging
81+
82+
The [debug module](https://www.npmjs.com/package/debug) is used to provide
83+
insight into the patching process. Set `DEBUG='@apm-js-collab*'` to view these
84+
logs.
85+
86+
Additionally, any patched files can be written out by enabling dump mode. This
87+
is done by setting the environment variable `TRACING_DUMP` to any value. By
88+
default, it will write out file to the system's temporary directory as the
89+
parent directory. The target parent directory can be configured by setting
90+
the `TRACING_DUMP_DIR` environment variable to an absolute path. In either
91+
case, the resolved filename of the module being patched is appended. For
92+
example, if we are patching `lib/index.js` in the `foo` package, and we set
93+
a base directory of `/tmp/dump/`, then the patched code will be written to
94+
`/tmp/dump/foo/lib/index.js`.

index.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ class ModulePatch {
4141
try {
4242
const transformedCode = transformer.transform(content, 'unknown')
4343
args[0] = transformedCode?.code
44+
if (process.env.TRACING_DUMP) {
45+
dump(args[0], filename)
46+
}
4447
} catch (error) {
4548
debug('Error transforming module %s: %o', filename, error)
4649
} finally {
@@ -63,5 +66,21 @@ class ModulePatch {
6366
}
6467
}
6568

69+
function dump(code, filename) {
70+
const os = require('node:os')
71+
const path = require('node:path')
72+
const fs = require('node:fs')
73+
74+
const base = process.env.TRACING_DUMP_DIR ?? os.tmpdir()
75+
const dirname = path.dirname(filename)
76+
const basename = path.basename(filename)
77+
const targetDir = path.join(base, dirname)
78+
const targetFile = path.join(targetDir, basename)
79+
80+
debug('Dumping patched code to: %s', targetFile)
81+
fs.mkdirSync(targetDir, { recursive: true })
82+
fs.writeFileSync(targetFile, code)
83+
}
84+
6685
module.exports = ModulePatch
6786

0 commit comments

Comments
 (0)