> For the complete documentation index, see [llms.txt](https://triton.pharos.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://triton.pharos.ai/instrumentation-skills/instrument-lwc.md).

# Instrument LWC

The instrument-lwc skill adds Triton logging to a Lightning Web Component — timed backend calls with span context and transaction stitching to Apex.

The **instrument-lwc** skill reads a Lightning Web Component, adds the `c/triton` logger, and instruments its imperative Apex calls, `@wire` adapters, event handlers, and error paths — preferring `timeBackendCall` so backend calls are timed and carry span context automatically. Then it shows you the diff and, if you want, deploys the whole component directory.

{% hint style="info" %}
**Invocation is agent-specific.** In agents that support slash commands (Claude Code, Cursor) you invoke it as `/pharos:instrument-lwc <path>`; in others you point the agent at this skill and give it the path. See [Running these in your agent](https://triton.pharos.ai/instrumentation-skills.md#running-these-in-your-agent).
{% endhint %}

## Usage

{% code lineNumbers="true" %}

```bash
/pharos:instrument-lwc <path> [--area <Area>] [--type <Type>] [--perf essential|standard|deep] [--deploy]
```

{% endcode %}

| Argument   | Required | Meaning                                                                                                                                                                                                                                                                                                                                                                      |
| ---------- | :------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<path>`   |     ✅    | The component **directory** (e.g. `force-app/main/default/lwc/myComponent/`) or the `.js` file directly. If a directory is given, the skill finds `<componentName>.js`.                                                                                                                                                                                                      |
| `--area`   |          | The feature's area. Inferred from the code and matched to the paired Apex controller if omitted. Any string works, exactly as in Apex and Flow, so the skill reuses the Apex area verbatim (`.area('OrderEntry')`). The `AREA` constants (`ACCOUNTS`, `COMMUNITY`, `LEAD_CONVERSION`, `OPPORTUNITY_MANAGEMENT`, `REST_API`) land as the Apex names (`Accounts` … `RestAPI`). |
| `--type`   |          | A `TYPE` constant: `BACKEND`, `FRONTEND`, `BACKEND_CALL`, `COMPONENT_LIFECYCLE`, `COMPONENT_RENDER`, `USER_INTERACTION`, `PERFORMANCE`. Defaults to `FRONTEND`.                                                                                                                                                                                                              |
| `--perf`   |          | How much profiling to add: `essential` (default), `standard`, or `deep`. See [Performance tiers](#performance-tiers).                                                                                                                                                                                                                                                        |
| `--deploy` |          | Deploy the component directory after you accept the diff.                                                                                                                                                                                                                                                                                                                    |

{% hint style="info" %}
The import is `import Triton, { TYPE, AREA, LEVEL } from 'c/triton';`. `new Triton()` returns a **module-scoped singleton** that already starts/resumes a transaction (from `sessionStorage`) on construction — so a transaction is always active, and every log builder is auto-stamped with the current `transactionId`. That's why LWC-originated logs correlate automatically.
{% endhint %}

## What it instruments

The skill reads the `.js` file (and the `.html` template for context), then identifies the existing Triton import, lifecycle hooks, `@wire` adapters, imperative Apex calls, `handle*` event handlers, and existing error handling.

### The import and the bound instance

It adds the import, then a class-level `triton` property bound once — **`constructor` is preferred** because it covers `@wire` (which fires early); `connectedCallback` is acceptable for purely imperative components. It **always** calls `bindToComponent`.

{% code lineNumbers="true" %}

```javascript
import Triton, { TYPE, AREA, LEVEL } from 'c/triton';

// ...

triton;

constructor() {
    super();
    this.triton = new Triton().bindToComponent('myComponent');
    this.triton.setTemplate(
        this.triton.makeBuilder()
            .type(TYPE.FRONTEND)
            .area(AREA.ACCOUNTS)   // the paired Apex controller's area: an AREA constant or the same string; omit if none
    );
}
```

{% endcode %}

{% hint style="warning" %}
`new Triton()` returns the shared singleton and binds it to this component — it does **not** create an isolated instance, and it **already** starts/resumes a transaction, so the skill never calls `startTransaction()` in the constructor. Logs are created with `this.triton.fromTemplate()`, which clones the template and stamps the current `transactionId`.
{% endhint %}

Where the paired Apex code uses an area that isn't one of the `AREA` constants, the skill passes that string as-is (`.area('OrderEntry')`), and the server keeps it. Only when the feature has no area at all does it omit `.area(...)`; those logs record under `LWC`.

### Instrumenting imperative Apex calls — `timeBackendCall` preferred

`timeBackendCall` auto-logs start / success / failure with duration **and span context**, so the backend call and everything it does nest cleanly under one span. Only the rethrow needs handling:

{% code lineNumbers="true" %}

```javascript
async handleSave() {
    try {
        const result = await this.triton.timeBackendCall('saveRecord', () =>
            saveRecord({
                recordId: this.recordId,
                transactionId: this.triton.transactionId   // Option A stitching; omit if using withCache
            })
        ).execute();
        // ...use result
    } catch (error) {
        // timeBackendCall already logged the failure; handle UI state here
    }
}
```

{% endcode %}

Use `.withoutRethrow()` to swallow, or `.withCustomErrorHandler(fn)` for custom handling. When not using `timeBackendCall`, the skill falls back to a manual `try/catch` with `this.triton.log(...)` on success and `this.triton.logNow(this.triton.exception(error))` on failure. `.exception(error)` — on `this.triton` or on any builder — sets `ERROR`, so the server opens an issue, exactly like Apex's `.exception(e)`. `logNow` and `flush` never reject: if the server can't take the logs they're kept for the next flushes and dropped after three failures in a row, so awaiting them can't derail your catch block.

### Transaction stitching to Apex

LWC logs are already correlated. To extend the **same** transaction into your Apex controller, the skill uses **one** of two mechanisms — and never invents an Apex parameter:

* **Option A — pass the id** *only when the Apex method declares it.* The Apex side (see [Instrument Apex](https://triton.pharos.ai/instrumentation-skills/instrument-apex.md)) resumes a param named `transactionId`. Passing a key the Apex signature doesn't declare fails at runtime.
* **Option B — platform cache.** Leave the Apex call unchanged and have the Apex method call `Triton.withCache()`; the id rides platform cache with no param threading.

It never starts or stops a transaction inside a handler — that would split a component's logs across transactions and `stopTransaction()` clears the shared id. For a genuine multi-step wizard, it uses `this.triton.enterStep()` to segment logical steps within the one transaction.

### Wires, handlers, milestones, and errors

* **`@wire` adapters** — errors are logged from the callback with `this.triton.logNow(...)`.
* **Event handlers** (`handle*`) — get DEBUG-level entry logging (`this.triton.debug(TYPE.FRONTEND, AREA.X)`), reserving INFO for business milestones.
* **Business milestones** (save, submit, approve) — get INFO logging at completion with `.relatedObjects([this.recordId])`.
* **Error handlers** — every existing `catch` uses `logNow` (immediate) so the error persists before UI state changes; `log` is reserved for buffered debug/info.
* **`disconnectedCallback` flush** — optional belt-and-suspenders; flushing is already automatic.

### Performance tiers

`--perf` sets how much profiling the skill adds. Each tier includes the ones before it:

| `--perf`              | Adds                                                                                                                        | Records log at                              |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
| `essential` (default) | `timeBackendCall` around imperative Apex calls, `timeUserInteraction` around `handle*` handlers                             | `FINE`; a failure at `ERROR`, with an issue |
| `standard`            | `trackComponentLifecycle` in `connectedCallback` / `disconnectedCallback`, and custom marks around notable client-side work | lifecycle at `FINER`, marks at `FINE`       |
| `deep`                | `trackComponentRender` in `renderedCallback`                                                                                | `FINEST`                                    |

Profiling records inherit the Area from the component's template, so the skill sets the template first. Because each tier maps to a level, one `Log_Level__mdt` threshold picks the tier you keep: a production LWC rule at `INFO` or stricter drops everything but failures, `FINE` keeps the essential tier, and render tracking should run at `FINEST` only mid-investigation. When it adds render tracking, the skill says so in the diff.

## Review the diff

The skill presents a summary — the bind and template, the stitching mechanism, and counts of instrumented Apex calls, error handlers, and event handlers — then the key changes. Answer **`yes`** to apply, **`modify`** for corrections, or **`skip`** to write nothing.

## Deploy

The `.js` content is written back to the original file. Because an LWC's HTML and metadata must deploy together, deploy targets the **entire component directory**:

{% code lineNumbers="true" %}

```bash
sf project deploy start --source-dir <component-directory> --json
# or:
sfdx force:source:deploy -p <component-directory> --json
```

{% endcode %}

A `"status": "Succeeded"` confirms the component deployed; failures show the failures table without reverting your file.

## Where to go next

* [Instrument Apex](https://triton.pharos.ai/instrumentation-skills/instrument-apex.md) — the controller that resumes the id this component passes.
* [Instrument the Org](https://triton.pharos.ai/instrumentation-skills/instrument-org.md) — run this skill across every component at once.
* [Logging in LWC](https://triton.pharos.ai/beyond-apex/lwc.md) · [LWC and Apex](https://triton.pharos.ai/beyond-apex/lwc-and-apex.md) — the hand-written patterns the skill automates.
* [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing.md) — how `timeBackendCall`'s span context maps to OpenTelemetry spans.
