Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,18 @@ To use the CJS patch you can run your Node.js application with the `--require` f
node --require cjs-patch.js your-app.js
```

## Debugging

The [debug module](https://www.npmjs.com/package/debug) is used to provide
insight into the patching process. Set `DEBUG='@apm-js-collab*'` to view these
logs.

Additionally, any patched files can be written out by enabling dump mode. This
is done by setting the environment variable `TRACING_DUMP` to any value. By
default, it will write out file to the system's temporary directory as the
parent directory. The target parent directory can be configured by setting
the `TRACING_DUMP_DIR` environment variable to an absolute path. In either
case, the resolved filename of the module being patched is appended. For
example, if we are patching `lib/index.js` in the `foo` package, and we set
a base directory of `/tmp/dump/`, then the patched code will be written to
`/tmp/dump/foo/lib/index.js`.
19 changes: 19 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ class ModulePatch {
try {
const transformedCode = transformer.transform(content, 'unknown')
args[0] = transformedCode?.code
if (process.env.TRACING_DUMP) {
dump(args[0], filename)
}
} catch (error) {
debug('Error transforming module %s: %o', filename, error)
} finally {
Expand All @@ -63,5 +66,21 @@ class ModulePatch {
}
}

function dump(code, filename) {
const os = require('node:os')
const path = require('node:path')
const fs = require('node:fs')

const base = process.env.TRACING_DUMP_DIR ?? os.tmpdir()
const dirname = path.dirname(filename)
const basename = path.basename(filename)
const targetDir = path.join(base, dirname)
const targetFile = path.join(targetDir, basename)

debug('Dumping patched code to: %s', targetFile)
fs.mkdirSync(targetDir, { recursive: true })
fs.writeFileSync(targetFile, code)
}

module.exports = ModulePatch

Loading