Browse documentation

Reference

JavaScript SDK API

Functions, classes, options, parameters, and return values for the Teml JavaScript and TypeScript SDK.

This is the application-developer API for @teml/sdk 0.1.x. Import optional capabilities from their documented subpaths so replay, React, and provider-specific code stays out of the base bundle.

Use a key with ingest:write for traces, metrics, logs, and errors. Add analytics:write for identity, groups, diagnostic events, and flag exposure events; flags:read for decisions; and replay:write for replay.

Initialize the core client

import { init, TemlClient } from '@teml/sdk';

const teml = await init({
  apiKey: process.env.TEML_API_KEY,
  serviceName: 'orders-api',
});

// Equivalent lifecycle with explicit construction:
const second = await new TemlClient(options).start();
await second.stop();
API Parameters Returns Behavior
init(options?) TemlOptions Promise<TemlClient> Creates, validates, starts, and returns one client. Recommended entry point.
new TemlClient(options?) TemlOptions TemlClient Creates an unstarted client. Call start() before recording.
start() Promise<TemlClient> Validates configuration and starts OTLP transports. Repeated calls return the same client.
stop() Promise<void> Flushes transports, removes installed hooks, and releases resources. Safe to repeat.
registerShutdownHook(hook) cleanup function void Registers a cleanup that stop() invokes once. Framework integrations use this to remove installed handlers.
isRunning() boolean Reports whether the client currently accepts telemetry.
getConfig() ResolvedConfig Returns a defensive copy of the resolved configuration for diagnostics. It includes sensitive headers; do not log it.
health() HealthStatus Returns healthy, degraded, or stopped, recent internal errors, uptime, and signal counters.
stats() ClientStats Returns processed, dropped, and failed-export counters plus timing data.

Keep one client per application process or browser page. Always await stop() during graceful server shutdown.

TemlOptions

Explicit options override environment values. Required values have no usable default.

Option Type Default/environment Purpose
apiKey string TEML_API_KEY; required Project-scoped Teml API key.
serviceName string OTEL_SERVICE_NAME; required Logical application or service name.
serviceVersion string OTEL_SERVICE_VERSION; 0.0.0 Deployed version.
environment string TEML_ENVIRONMENT; runtime-derived Deployment environment such as production.
release string TEML_RELEASE, then real serviceVersion Release used for regression detection and source maps.
dist string TEML_DIST; empty Artifact/build discriminator within a release.
endpoint string TEML_ENDPOINT; https://api.teml.io Base API and OTLP URL.
protocol 'http' http JavaScript supports OTLP over HTTP only.
enableTraces boolean TEML_ENABLE_TRACES; true Enable trace export.
enableMetrics boolean TEML_ENABLE_METRICS; true Enable metric export.
enableLogs boolean TEML_ENABLE_LOGS; true Enable log export.
enableErrorCapture boolean TEML_ENABLE_ERROR_CAPTURE; true Enable captureError and captureMessage.
enableFetchTracing boolean true Browser only: instrument fetch/XHR and inject trace headers. Disabling it does both.
propagateTraceHeaderCorsUrls (string | RegExp)[] empty Browser cross-origin destinations allowed to receive trace and identity headers.
propagateTraceHeaderUrls (string | RegExp)[] TEML_PROPAGATE_TRACE_HEADER_URLS; empty Node HTTP(S) destinations allowed to receive trace and identity headers.
traceSampleRate number OTEL_TRACES_SAMPLER_ARG; 0.1 production, 1 development Trace sampling in the inclusive range 0–1.
errorSampleRate number TEML_ERROR_SAMPLE_RATE; 1 Non-fatal captured-error sampling in the inclusive range 0–1.
attachStackTrace boolean TEML_ATTACH_STACK_TRACE; true Parse and attach error stack frames.
maxStackTraceFrames number TEML_MAX_STACK_TRACE_FRAMES; 50 Maximum captured frames.
batchSize number OTEL_BSP_MAX_EXPORT_BATCH_SIZE; 512 Maximum items per export batch.
batchTimeout number OTEL_BSP_SCHEDULE_DELAY; 5000 ms Maximum delay before a trace/log batch flushes.
maxQueueSize number OTEL_BSP_MAX_QUEUE_SIZE; 2048 Queue capacity before signals are dropped. Must be at least batchSize.
exportTimeout number OTEL_BSP_EXPORT_TIMEOUT; 30000 ms Per-export deadline.
metricExportInterval number OTEL_METRIC_EXPORT_INTERVAL; 60000 ms Metric push interval; raised to at least exportTimeout.
shutdownTimeout number OTEL_BSP_SHUTDOWN_TIMEOUT; 5000 ms Graceful shutdown deadline.
resourceAttributes Record<string,string> empty Extra OpenTelemetry resource attributes.
headers Record<string,string> empty Extra headers on exports. Do not expose secrets in browser builds.
debug boolean TEML_DEBUG; false Enable SDK diagnostic logs.

Traces, metrics, logs, and AI operations

Method Parameters Returns Behavior
tracer property OpenTelemetry Tracer Access the underlying tracer for advanced instrumentation.
startSpan(name, options?) name; OTel SpanOptions OTel Span Starts a span. The caller must call span.end(). Returns a no-op span before startup.
recordMetric(name, value, labels?) metric name; number; string labels void Records one histogram observation. Invalid calls increment dropped-metric stats rather than throwing.
logEvent(level, message, attrs?) debug | info | warn | error | silent; message; attributes void Emits one structured OTel log. Complex attribute values are JSON-stringified.
recordLLMCall(options) LLMCallOptions void Records one completed model call as a gen_ai client span.
recordToolCall(options) ToolCallOptions void Records one completed agent tool/function call.
startAgentRun(options) AgentRunOptions { span, context } Starts an invoke_agent span. Run child work in the returned OTel context and end the span.

LLMCallOptions.model is required. Optional fields are responseModel, provider, operation, token counts (inputTokens, outputTokens, reasoningTokens, cacheReadTokens, cacheWriteTokens), costUsd, finishReason, startTime, endTime, and isError. messages and output opt into prompt/completion content capture.

ToolCallOptions.name is required. Optional fields are type, callId, conversationId, agentName, isError, arguments, and result. Arguments and results can contain sensitive data; omit them unless content capture is approved.

Errors, messages, users, and breadcrumbs

Method Parameters Returns Behavior
captureError(error, options?) Error; CaptureOptions string Sends an error span and returns its generated ID. Returns '' when capture is unavailable or sampled out.
captureMessage(message, level?, options?) message; ErrorLevel; CaptureOptions string Captures a diagnostic message. Only error and fatal produce error status.
addBreadcrumb(category, message, options?) strings; BreadcrumbOptions void Buffers context for the next captured error, then clears the buffer. Capacity is 100.
setUser(user) TemlUser void Sets global error user context. Prefer identify for the cross-signal identity spine.
clearUser() void Removes global error user context.

CaptureOptions accepts tags: Record<string,string>, extra: Record<string,unknown>, user, stackTrace, level, and fingerprint. A fingerprint is a string or string array; commas are the component delimiter, and {{default}} includes automatic grouping.

TemlUser accepts id, email, username, ipAddress, segment, and data. Breadcrumb options accept level and data.

Identity and accounts

Method Parameters Returns Behavior
identify(distinctId, properties?) stable ID; person properties void Switches shared identity and sends a best-effort identify event. Empty IDs are ignored.
group(groupType, groupKey, properties?) group type; stable key; group properties void Associates the current person with an account and sends $groupidentify.
reset() void Logout: rotates anonymous identity and session, clears groups, and clears global user context.
getSessionId() string Returns the shared session ID, rotating it after its idle/max duration.

For concurrent Node requests, use contextWithDistinctId(ctx, id) and distinctIdFromContext(ctx) instead of changing process-wide identity. adoptDistinctIdFromBaggage must be used only after an authenticated gateway has replaced untrusted inbound baggage.

Diagnostic events: @teml/sdk/analytics

import { AnalyticsClient } from '@teml/sdk/analytics';

const events = new AnalyticsClient({
  endpoint: 'https://api.teml.io',
  apiKey: process.env.TEML_API_KEY!,
});
API Parameters Returns Behavior
new AnalyticsClient(options) endpoint, API key, optional flushAt, flushInterval, fetchImpl, identity AnalyticsClient Creates a batching event client. Defaults: flush at 20 events or 5 seconds.
getDistinctId() string Current shared known or anonymous ID.
capture(event, properties?) name; properties void Queues one diagnostic event with identity, groups, session, timestamp, and dedup ID.
identify(distinctId, personProps?) ID; person properties void Queues identity merge, switches identity, and starts a flush.
group(type, key, properties?) group type/key; properties void Records membership and a group identify event.
reset() void Rotates anonymous identity and session.
flush({ keepalive? }?) optional browser keepalive Promise<void> Sends queued events in server-safe chunks and requeues transient failures.
stop({ keepalive? }?) optional browser keepalive Promise<void> Stops timers/listeners and flushes remaining events. Further capture calls fail.

Feature flags: @teml/sdk/analytics

FlagsClient needs flags:read. Its default exposure sender also needs analytics:write.

API Parameters Returns Behavior
new FlagsClient(options, capture?) endpoint, API key, optional fetch/bootstrap; optional exposure callback FlagsClient Creates an in-memory decision client. Bootstrap avoids the first network call.
reload(distinctId, personProperties?, groups?) person ID; properties; group map Promise<void> Calls /api/v1/decide, replaces cached flags/payloads, and resets exposure dedup when identity changes.
getFeatureFlag(key) flag key boolean | string | undefined Returns a decision and emits one deduplicated exposure for that key/value.
isFeatureEnabled(key) flag key boolean True for true or a non-empty string variant.
getFeatureFlagPayload(key) flag key unknown Returns the payload from the latest decision.
allFlags() Record<string, boolean | string> Returns a copy of every cached decision.
hadEvaluationErrors() boolean Reports whether the server used a fallback during the latest evaluation.
reset() void Clears only the per-key/value exposure dedup set. Cached decisions and payloads remain available until the next reload.

Browser decisions reveal flag configuration to the client. Never store secrets in flag rules or payloads.

Replay: @teml/sdk/replay

startReplay(options) starts rrweb recording and returns a synchronous stop function. The stop function removes hooks and flushes the buffered tail.

Option Type/default Purpose
endpoint, apiKey required strings Replay endpoint and key with replay:write.
sessionId, distinctId optional strings Override shared session/person linkage.
maxEvents number; 50 Flush threshold.
flushMs number; 5000 Time-based flush interval.
maskAllInputs boolean; true Mask input values in the DOM recording.
captureConsole boolean; true Record console events. Disable unless required.
captureNetwork boolean; true Record fetch/XHR metadata and bodies. Disable unless required.
maxBodyBytes number; 10240 Per-body truncation limit.
maxNetworkEvents, maxConsoleEvents number; 1000 Per-session event caps.
fetchImpl typeof fetch Test/SSR transport override.

shouldFlush(...) and buildChunkBody(...) are exported pure helpers for custom/testing use; most applications should call only startReplay.

Node, browser, Express, and React

Import/API Parameters Returns Behavior
@teml/sdk/node initNode(options?) TemlOptions Promise<TemlClient> Starts the client and installs Node HTTP/process handlers.
registerProcessHandlers(client) client cleanup function Installs uncaught exception, rejection, and shutdown handlers.
setupNodePropagation(trustedUrls?) string/regular-expression destination allowlist void Installs W3C trace/baggage propagation and Node HTTP instrumentation. Preload @teml/sdk/node/register before node:http for outbound patching.
temlExpressMiddleware(client, options?) client; ExpressMiddlewareOptions Express handler Creates request spans and extracts trace context. Identity baggage is ignored unless explicitly trusted.
temlExpressErrorHandler(client) client Express error handler Captures route errors and must be registered after routes.
@teml/sdk/browser initBrowser(options?) TemlOptions Promise<TemlClient> Starts browser transport, global handlers, and fetch/XHR propagation.
registerBrowserHandlers(client) client cleanup function Installs global error/rejection and lifecycle flush handlers.
TemlProvider client, children React node Exposes the client through React context.
useTeml() TemlClient Reads the provider client; throws outside TemlProvider.
useSpan(name) span name { span, endSpan } Creates a component-lifetime span and ends it on unmount.
TemlErrorBoundary client, children, optional fallback/hooks React component Captures render errors while preserving custom fallback behavior.

ExpressMiddlewareOptions supports ignorePaths, safe recordHeaders, trustIncomingIdentity, and spanNameHook. Sensitive headers are redacted even when requested.

LLM wrappers and source maps

API Parameters Returns Behavior
wrapOpenAI(client, teml, options?) OpenAI client; Teml client; { captureContent? } same OpenAI client Instruments non-streaming chat.completions.create calls in place. Idempotent.
wrapAnthropic(client, teml, options?) Anthropic client; Teml client; { captureContent? } same Anthropic client Instruments non-streaming messages.create calls in place. Idempotent.
uploadSourceMap(options) release, dist, filename, content, endpoint, API key, optional fetch Promise<void> Uploads one source map. CI should normally use teml symbols upload-sourcemap.
collectSourceMaps(directory, fs) directory; required filesystem facade CollectedSourceMap[] Finds .map files for a custom uploader. The packaged CLI supplies the Node filesystem adapter.

Both LLM wrappers pass streaming calls through without automatic spans. captureContent defaults to false and can record sensitive prompts and completions.

Validation and utility exports

These root exports support framework authors and custom integrations. Normal applications should prefer init, TemlClient, and the documented subpath clients.

API Parameters Returns/behavior
resolveConfig(options?) partial TemlOptions Resolves environment values, defaults, and explicit options into ResolvedConfig. It does not validate required values.
validateConfig(config) resolved config void; throws for missing credentials/service identity, invalid URL/protocol/rates, or inconsistent batching/timeouts.
validateAPIKey(key) string void; throws when the key does not match the supported API-key shape.
isAPIKeyFormat(value) string Boolean shape check without throwing.
maskAPIKey(key) string Log-safe prefix plus last four characters. Never use the result for authentication.
generateErrorId() Hyphenless random error/message ID.
parseStackTrace(error, maxFrames=50) Error; limit StackFrame[] parsed from V8, Firefox, or Safari stacks.
formatStackTrace(frames) StackFrame[] OpenTelemetry stacktrace string.
framesToSerializable(frames) camel-case frames Backend wire frames with in_app.
resolveCaptureOptions(options?, defaultLevel='error') capture options/default level Capture defaults used by custom capture implementations.
new UserManager() Mutable global error-user holder with setUser, getUser, and clearUser; values are copied.
userToAttributes(user) TemlUser Flat OpenTelemetry enduser.* and user.data.* string attributes.
new IdentityManager(storage?) optional Web Storage-like adapter Identity holder with getDistinctId, getAnonId, identify, group, getGroups, and reset.
sharedIdentity() Process/page-wide IdentityManager shared by core signals and analytics.
contextWithDistinctId(ctx, id) OTel context and ID New context carrying request-local identity and W3C baggage.
distinctIdFromContext(ctx) OTel context Request-local ID or undefined.
adoptDistinctIdFromBaggage(ctx) trusted OTel context New context that promotes baggage identity; authenticate first.
new BreadcrumbBuffer(capacity=100) positive capacity Ring buffer with size, isEmpty, add, serialize, and clear.
createTransport(config) validated ResolvedConfig TransportComponents containing enabled OTel providers and signal handles.
shutdownTransport(components, timeoutMs) components/deadline Promise<void>; shuts down all providers and reports aggregated failures.

The Node subpath additionally exports removeDistinctIdFromBaggage(ctx) for stripping an inbound Teml identity member while retaining trace context, plus the request-context helpers listed above.