Skip to content
RouteSpear
Documentation
Documentation menu

Node.js SDK API reference

Every Node SDK method, options object, return value and host-runtime difference.

Select language Node.js (node). The operator must enable host interpreters and allowlist node or nodejs. The RouteSpear SDK is already bundled with the script plugin. Before each run the agent writes the module and sets NODE_PATH for that process. You do not run npm install, copy SDK files or configure a module path on the machine. Node.js itself can be an enabled managed runtime or an interpreter installed and allowlisted by the host operator. The editor’s starter script includes:

const rs = require('routespear');

This is a CommonJS module. It supplies metrics, timing, args, context and secrets. It does not supply the built-in engine’s rs.http, rs.dns, rs.net, rs.sleep, rs.now or rs.log. Use Node APIs or packages already installed on the host; package installation is not part of a run. The availability of global fetch depends on the installed Node version.

Metric APIs

All emitters synchronously write a single stdout line using fs.writeSync and return undefined. They do not confirm downstream ingestion. Their arguments are the same as the built-in JavaScript metric APIs:

Method Full signature Options/defaults
rs.emit emit(metric) Complete raw wire object; no schema normalization.
rs.gauge gauge(name, value, opts = {}) unit: '', labels omitted.
rs.counter counter(name, value, opts = {}) unit: 'count', cumulative: false, labels omitted.
rs.duration duration(name, ms, opts = {}) labels; fixed ms unit.
rs.ratio ratio(name, value, opts = {}) labels; fixed ratio unit, value 0–1.
rs.bool bool(name, value, opts = {}) labels; JavaScript truthiness maps to 1/0.
rs.distribution distribution(name, values, opts = {}) unit: '', optional bounds and labels; iterable values are converted with Number.
rs.timer timer(name, opts = {}) Optional labels; returns an emitting stop function.

Numeric scalar inputs are converted with Number; provide actual finite values. Labels are stringified. Empty/omitted distribution bounds use the standard bucket array. JSON.stringify can turn non-finite values into null, but that does not make the resulting metric valid. Review the output contract.

rs.timer uses process.hrtime.bigint(). Call the returned function to emit a duration and receive elapsed milliseconds. Each call measures from the original start and emits again. It is not a context manager; use finally deliberately.

Run APIs

Method Return / failure behavior
rs.args() Cached parsed stdin JSON; empty input returns {}, malformed JSON throws.
rs.context() Cached context object with normalized agent, test, run and label objects; invalid/missing context falls back to empty sections.
rs.target() Target string or ''.
rs.testId() Check ID string or ''.
rs.timeoutMs() Numeric runtime budget in milliseconds, or 0 if unavailable/invalid. Not a remaining-time counter.
rs.secret(name) Credential value from the declared map; missing name throws. File and JSON errors propagate.

Arguments and credentials are read synchronously on first use. Do not consume stdin before rs.args(). Never log a credential, include it in labels or paste it into chat. See context and credential mapping.

Complete metric example

This sample processes supplied fixture values. Replace them with real observations for a production check. Args: {"depth":12,"request_count":4,"samples_ms":[12,18,22]}.

const rs = require('routespear');
const settings = rs.args();
const labels = { site: rs.context().agent.labels.site || 'unknown' };
const stop = rs.timer('process_ms', { labels });
try {
  rs.gauge('queue_depth', settings.depth, { unit: 'count', labels });
  rs.counter('processed', settings.request_count, { labels });
  rs.distribution('sample_ms', settings.samples_ms, { unit: 'ms', bounds: [10, 20, 50], labels });
  rs.bool('within_limit', Math.max(...settings.samples_ms) < 50, { labels });
} finally {
  stop();
}
console.error('Processed supplied sample input');

Asynchronous work and errors

Node can perform asynchronous work, but the invocation still has a hard wall-clock deadline. Await the work in an async function, attach an error handler, and explicitly bound network calls. rs.timer does not enforce a timeout.

Use console.error for diagnostics. console.log writes non-metric stdout and counts as malformed output. A thrown exception or a nonzero process exit is a script failure; it is not automatically a custom boolean metric. Emit only the measurements that actually occurred and let configuration errors remain visible.

Source implementation: agent/plugins/script/internal/sdk/files/routespear.js.

Screenshot