# `@contrast/patcher`

Advanced monkey patching: registers hooks to run before, around, and after
functions, methods, and class constructors.

## Usage

`@contrast/agentify` composes the patcher onto core as `core.patcher`.

```javascript
// patch a method in place; returns the object
core.patcher.patch(obj, 'method', {
  name: 'lib.obj.method',
  patchType: 'assess-dataflow-source',
  pre(data) {},
  around(next, data) { return next(data); },
  post(data) {},
});

// patch a function (or class constructor) directly; returns the patched function
const patched = core.patcher.patch(fn, { name: 'lib.fn', patchType: 'protect-input-analysis', post(data) {} });
```

### Options

- `name` (required): identifies the patched function, e.g. `'http.Server.prototype.emit'`.
- `patchType` (required): the category of instrumentation, e.g. `assess-dataflow-source` or `protect-input-analysis`.
- `pre(data)`: runs before the original.
- `around(next, data)`: wraps the original. Call `next(data)` with the `data` the hook received to run it (or the next `around` hook) and return its result. Nothing is allocated per call, however many `around` hooks there are.
- `post(data)`: runs after the original. `data.result` holds the return value, and assigning to it changes what the caller receives.

Set `CSI_PATCHER_STRICT_AROUND=1` in tests to make every `around` hook fail with
an error that names it unless it calls `next(data)` with the `data` it received.
It is off in production and costs nothing when off. The repo's unit and
integration tests turn it on, and `CSI_PATCHER_STRICT_AROUND=0` turns it off
there.

Hook data includes `args`, `obj` (the `this` value), `orig` (the original
function), `hooked` (the patched function), `name`, and `funcKey`.

Hooks are keyed by `` `${patchType}:${name}` ``. Patching the same function again
with the same key is ignored, so different features can hook one function by
using different `patchType` values.

`unpatch(fn, name, patchType)` removes one hook, `unwrap(fn)` returns the
original function, and `isContrastHooked(fn)` reports whether a function is
patched. Type definitions are in `lib/index.d.ts`.
