# Insight scripts

> The `insight` object available to scripts loaded with Elide's `--insights` flag: the `source`, `enter` and `return` events, their filters, and what each handler receives.

An Insight script runs before the program and subscribes to its execution events. Load one with the repeatable
`--insights <FILE>` option:

```bash
elide run --insights=trace.js app.js
```

```javascript
// trace.js
insight.on("enter", (ctx, frame) => {
  console.log("enter", ctx.name, JSON.stringify(frame));
}, { roots: true, rootNameFilter: "add" });

insight.on("return", (ctx, frame) => {
  console.log("return", ctx.name, ctx.returnValue(frame));
}, { roots: true, rootNameFilter: "add" });
```

For `function add(a, b) { return a + b; }` called as `add(1, 2)`, this prints `enter add {"a":1,"b":2,"this":{}}` and
`return add 3`.

## Events

| Event    | Fires when                          | Handler arguments |
| -------- | ----------------------------------- | ----------------- |
| `source` | a source file is loaded             | `(source)` with `name`, `characters`, `uri` |
| `enter`  | a matching function, statement or expression starts | `(ctx, frame)` |
| `return` | a matching function, statement or expression ends   | `(ctx, frame)` |

`insight.on(event, handler, filter)` registers a handler for the whole run; `insight.off` is not supported.
`insight.id` and `insight.version` identify the API.

## Filters

`enter` and `return` need at least one of `roots`, `statements` or `expressions`.

| Key              | Value                                                   |
| ---------------- | ------------------------------------------------------- |
| `roots`          | `true` to match function entries                        |
| `statements`     | `true` to match each statement                          |
| `expressions`    | `true` to match each expression                         |
| `rootNameFilter` | a regular expression string matched against the function name |
| `sourceFilter`   | a function `(source) => boolean`; also filters `source` events |

## Context and frame

| Member                  | Value                                         |
| ----------------------- | --------------------------------------------- |
| `ctx.name`              | function name                                 |
| `ctx.source.name`       | file name                                     |
| `ctx.line`, `ctx.column` | start position                               |
| `ctx.characters`        | source text of the matched node               |
| `ctx.returnValue(frame)` | value returned (in `return` handlers)        |
| `frame`                 | local variables and `this`, by name           |

For profiling and a guided example, see [Debugging](https://elide.help/docs/debugging).
