@grow-codes/grafana-loki 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts ADDED
@@ -0,0 +1,1348 @@
1
+ import { L as LokiError, A as Attributes, a as LogRecord, b as AttrValue, c as LogClient, S as Severity, d as LogExporter, E as ExportOptions, e as ExportResult, B as BaseLogQueryClient, f as LogSearchOptions, g as LogSearchResult, T as TailOptions, h as TailHandle, H as HealthStatus, i as BatchingLogClientOptions, j as BatchingLogClient } from './query-CofVHbt1.js';
2
+ export { k as AuthenticationError, l as BatchOptions, m as BatchProcessor, n as BatchStats, C as CancelledError, o as ConfigError, p as ConflictError, D as DEFAULT_BATCH_OPTIONS, q as DEFAULT_REDACT_KEYS, r as DropPolicy, s as DropReason, t as ErrorCode, u as ErrorDetails, v as LogInput, w as LogQueryClient, x as LogSink, y as Logger, z as LoggerOptions, N as NotFoundError, P as PermissionDeniedError, R as RateLimitError, F as RedactionOptions, G as RedactionProcessor, I as ResolvedBatchOptions, J as TimeoutError, U as UnavailableError, K as UnsupportedError, M as UnsupportedLogQueryClient, V as ValidationError, W as WaitForLogOptions, O as canonicalSeverity, Q as codeForStatus, X as errorForCode, Y as errorForStatus, Z as healthStatus, _ as isHealthyWord, $ as isLokiError, a0 as parseSeverity, a1 as pollTail, a2 as probeHealth, a3 as reasonForCode, a4 as resolveBatchOptions, a5 as severityText, a6 as waitForLog } from './query-CofVHbt1.js';
3
+ import { Dispatcher } from 'undici';
4
+ import { Writable } from 'node:stream';
5
+
6
+ /** Throws {@link CancelledError} when the signal is already aborted. */
7
+ declare function throwIfAborted(signal: AbortSignal | undefined, operation: string): void;
8
+ /**
9
+ * Resolves after `ms` milliseconds; rejects with {@link CancelledError} when `signal` aborts
10
+ * first. The timer does not keep the process alive.
11
+ */
12
+ declare function sleep(ms: number, signal?: AbortSignal, operation?: string): Promise<void>;
13
+
14
+ /** Replacement text for every redacted value. */
15
+ declare const REDACTED = "[REDACTED]";
16
+ declare const INSPECT$1: unique symbol;
17
+ /** Field and query parameter name substrings that make a value sensitive (case-insensitive). */
18
+ declare const SENSITIVE_FIELD_PARTS: readonly string[];
19
+ /** Minimum length of a known secret value that {@link redactText} replaces. */
20
+ declare const MIN_SECRET_LENGTH = 4;
21
+ /** True when a header with this name must be redacted (SPEC §2.6). */
22
+ declare function isSensitiveHeader(name: string): boolean;
23
+ /** True when a field or query parameter with this name must be redacted (SPEC §2.6). */
24
+ declare function isSensitiveField(name: string, extraKeys?: readonly string[]): boolean;
25
+ /** Header input accepted by {@link redactHeaders}. */
26
+ type HeadersInput = Readonly<Record<string, string | readonly string[] | undefined>> | Iterable<readonly [string, string]>;
27
+ /** Returns a copy of the headers with every sensitive value replaced by {@link REDACTED}. */
28
+ declare function redactHeaders(headers: HeadersInput): Record<string, string>;
29
+ /** Redacts credentials in the user-info part and the values of sensitive query parameters. */
30
+ declare function redactUrl(url: string | URL): string;
31
+ /**
32
+ * Returns a deep copy of `value` in which every map entry whose key is sensitive is replaced by
33
+ * {@link REDACTED}. Recurses into nested objects and arrays; other values are copied as is.
34
+ */
35
+ declare function redactFields<T>(value: T, extraKeys?: readonly string[]): T;
36
+ /** A known secret: a plain string or a {@link Secret}. */
37
+ type KnownSecret = string | Secret | null | undefined;
38
+ /**
39
+ * Replaces every occurrence of each known secret value (length >= 4) in `text` with
40
+ * {@link REDACTED}. Longer secrets are replaced first so overlapping values never leak a suffix.
41
+ */
42
+ declare function redactText(text: string, knownSecrets?: Iterable<KnownSecret>): string;
43
+ /**
44
+ * Wraps a credential. `toString()`, `JSON.stringify` and `util.inspect` all print
45
+ * {@link REDACTED}; {@link Secret.reveal} returns the value.
46
+ */
47
+ declare class Secret {
48
+ #private;
49
+ constructor(value: string);
50
+ /** Wraps a string (returns `undefined` for `undefined`/empty, keeps an existing Secret). */
51
+ static from(value: string | Secret | undefined | null): Secret | undefined;
52
+ /** The wrapped value. */
53
+ reveal(): string;
54
+ /** Constant-time-ish comparison with another value. */
55
+ equals(other: string | Secret): boolean;
56
+ toString(): string;
57
+ toJSON(): string;
58
+ [INSPECT$1](): string;
59
+ }
60
+ /** Redacts the message of an arbitrary error value, keeping its name and `code`. */
61
+ declare function redactError(err: unknown, knownSecrets?: Iterable<KnownSecret>): Error;
62
+
63
+ /** An environment map (defaults to `process.env`); injectable so tests never touch the real one. */
64
+ type EnvMap = Readonly<Record<string, string | undefined>>;
65
+ /**
66
+ * Parses a duration into milliseconds: integer milliseconds (`"1500"`) or Go-style units
67
+ * (`"500ms"`, `"10s"`, `"2m"`, `"1h"`, `"1m30s"`). Returns `undefined` when invalid.
68
+ */
69
+ declare function parseDuration(raw: string): number | undefined;
70
+ /** Parses `true/false/1/0/yes/no/on/off` (case-insensitive). Returns `undefined` when invalid. */
71
+ declare function parseBool(raw: string): boolean | undefined;
72
+ /** Parses a base-10 integer (optional sign). Returns `undefined` when invalid. */
73
+ declare function parseInteger(raw: string): number | undefined;
74
+ /** A variable found by {@link EnvReader.lookup}. */
75
+ interface EnvHit {
76
+ /** Name of the variable that supplied the value. */
77
+ name: string;
78
+ /** Raw (non-empty) value. */
79
+ value: string;
80
+ }
81
+ /**
82
+ * Reads configuration from the environment with the SPEC §2.2 precedence
83
+ * `GROW_<KEY_UPPER>_<NAME>` > vendor variables (in order). Empty values count as unset.
84
+ * Every reader returns `undefined` when no variable is present; an invalid value throws
85
+ * {@link ConfigError} naming the variable but never its value.
86
+ */
87
+ declare class EnvReader {
88
+ #private;
89
+ readonly prefix: string;
90
+ /**
91
+ * @param prefix e.g. `"GROW_GRAFANA_LOKI_"`.
92
+ * @param env environment map, defaults to `process.env`.
93
+ */
94
+ constructor(prefix: string, env?: EnvMap);
95
+ /** Finds the first present variable: `<prefix><name>`, then each vendor name. */
96
+ lookup(name: string, vendorNames?: readonly string[]): EnvHit | undefined;
97
+ /** String value. */
98
+ string(name: string, vendorNames?: readonly string[]): string | undefined;
99
+ /** Credential value wrapped in a {@link Secret}. */
100
+ secret(name: string, vendorNames?: readonly string[]): Secret | undefined;
101
+ /** Duration in milliseconds (see {@link parseDuration}). */
102
+ duration(name: string, vendorNames?: readonly string[]): number | undefined;
103
+ /** Boolean (see {@link parseBool}). */
104
+ bool(name: string, vendorNames?: readonly string[]): boolean | undefined;
105
+ /** Integer. */
106
+ int(name: string, vendorNames?: readonly string[]): number | undefined;
107
+ }
108
+
109
+ /** Structured fields attached to a log line. */
110
+ type LogFields = Record<string, unknown>;
111
+ /**
112
+ * Minimal logger the client writes diagnostics to (SPEC §2.5). Compatible with `console`,
113
+ * pino and winston loggers. The default is silent.
114
+ */
115
+ interface ClientLogger {
116
+ debug(message: string, fields?: LogFields): void;
117
+ info(message: string, fields?: LogFields): void;
118
+ warn(message: string, fields?: LogFields): void;
119
+ error(message: string, fields?: LogFields): void;
120
+ }
121
+ /** A logger that discards everything (the default). */
122
+ declare const silentLogger: ClientLogger;
123
+ /** Data passed to {@link Hooks.onRequest}. URL query values and headers are redacted. */
124
+ interface RequestInfo {
125
+ method: string;
126
+ url: string;
127
+ headers: Record<string, string>;
128
+ /** Attempt number, starting at 1. */
129
+ attempt: number;
130
+ }
131
+ /** Data passed to {@link Hooks.onResponse}. */
132
+ interface ResponseInfo {
133
+ method: string;
134
+ url: string;
135
+ status: number;
136
+ durationMs: number;
137
+ attempt: number;
138
+ requestId?: string;
139
+ }
140
+ /** Data passed to {@link Hooks.onError}. */
141
+ interface ErrorInfo {
142
+ method: string;
143
+ url: string;
144
+ error: Error;
145
+ attempt: number;
146
+ /** Whether the transport will retry after this error. */
147
+ willRetry: boolean;
148
+ }
149
+ /** Observability hooks called on every HTTP attempt. Exceptions thrown by hooks are ignored. */
150
+ interface Hooks {
151
+ onRequest?: (info: RequestInfo) => void;
152
+ onResponse?: (info: ResponseInfo) => void;
153
+ onError?: (info: ErrorInfo) => void;
154
+ }
155
+ /** Calls `fn` and swallows anything it throws (hooks and loggers must never break a call). */
156
+ declare function safeCall<A extends unknown[]>(fn: ((...args: A) => unknown) | undefined, ...args: A): void;
157
+ /** Wraps a logger so that no method ever throws. */
158
+ declare function safeLogger(logger: ClientLogger | undefined): ClientLogger;
159
+
160
+ /** Options of {@link RetryPolicy} (SPEC §2.3). */
161
+ interface RetryPolicyOptions {
162
+ /** Retries after the first attempt (default 3, so up to 4 attempts). */
163
+ maxRetries?: number;
164
+ /** Backoff cap for the first retry, in ms (default 100). */
165
+ initialBackoffMs?: number;
166
+ /** Upper bound of any backoff, in ms (default 10 000). */
167
+ maxBackoffMs?: number;
168
+ /** Exponential growth factor (default 2). */
169
+ multiplier?: number;
170
+ /** Longest `Retry-After` the client is willing to wait, in ms (default 60 000). */
171
+ maxRetryAfterMs?: number;
172
+ /** Random source in [0, 1) used for full jitter; injectable for tests. */
173
+ random?: () => number;
174
+ }
175
+ /** Retry policy with full-jitter exponential backoff. Immutable. */
176
+ declare class RetryPolicy {
177
+ static readonly DEFAULTS: Readonly<{
178
+ maxRetries: 3;
179
+ initialBackoffMs: 100;
180
+ maxBackoffMs: 10000;
181
+ multiplier: 2;
182
+ maxRetryAfterMs: 60000;
183
+ }>;
184
+ readonly maxRetries: number;
185
+ readonly initialBackoffMs: number;
186
+ readonly maxBackoffMs: number;
187
+ readonly multiplier: number;
188
+ readonly maxRetryAfterMs: number;
189
+ readonly random: () => number;
190
+ constructor(options?: RetryPolicyOptions);
191
+ /** Returns a policy from options, keeping an existing instance as is. */
192
+ static from(value: RetryPolicy | RetryPolicyOptions | undefined): RetryPolicy;
193
+ /** Upper bound of the backoff before retry `n` (0-based): `min(max, initial * multiplier^n)`. */
194
+ backoffCapMs(retry: number): number;
195
+ /** Full-jitter backoff before retry `n` (0-based): `random(0, backoffCapMs(n))`. */
196
+ backoffMs(retry: number): number;
197
+ /** Validation problems (empty when valid). */
198
+ problems(): string[];
199
+ toJSON(): Record<string, number>;
200
+ }
201
+ /**
202
+ * Parses a `Retry-After` header (delta seconds or HTTP-date) into milliseconds from `now`.
203
+ * Returns `undefined` when absent or invalid; past dates give 0.
204
+ */
205
+ declare function parseRetryAfter(value: string | null | undefined, now?: number): number | undefined;
206
+ /** `GET HEAD OPTIONS PUT DELETE` are idempotent. */
207
+ declare function isIdempotentMethod(method: string): boolean;
208
+ /**
209
+ * Whether a response with this status should be retried (SPEC §2.3): 429 always; 408, 502, 503,
210
+ * 504 for idempotent requests; 500 only for idempotent requests. Non-idempotent requests are
211
+ * retried only on 429.
212
+ */
213
+ declare function isRetryableStatus(status: number, idempotent: boolean): boolean;
214
+
215
+ /** TLS settings (SPEC §2.2). */
216
+ interface TlsOptions {
217
+ /** Path to a PEM CA bundle. */
218
+ caCertPath?: string;
219
+ /** PEM CA bundle contents. */
220
+ caCertPem?: string;
221
+ /** Path to a PEM client certificate (requires {@link clientKeyPath}). */
222
+ clientCertPath?: string;
223
+ /** Path to the PEM client key (requires {@link clientCertPath}). */
224
+ clientKeyPath?: string;
225
+ /** Disables certificate verification. Tests only; logs a warning once. */
226
+ insecureSkipVerify?: boolean;
227
+ }
228
+ /** Common configuration input shared by every client config (all optional). */
229
+ interface CommonConfigOptions {
230
+ /** Endpoint base URL. */
231
+ url?: string;
232
+ /** Connection setup timeout in ms (default 10 000). */
233
+ connectTimeoutMs?: number;
234
+ /** Per-attempt timeout in ms, headers + body (default 30 000). */
235
+ requestTimeoutMs?: number;
236
+ /** Whole-call timeout in ms including retries and backoff (default 120 000). */
237
+ totalTimeoutMs?: number;
238
+ /** Retry policy or its options. */
239
+ retry?: RetryPolicy | RetryPolicyOptions;
240
+ /** TLS settings. */
241
+ tls?: TlsOptions;
242
+ /** Proxy URL. Environment proxies (`HTTPS_PROXY`, …) are ignored unless set here. */
243
+ proxy?: string;
244
+ /** Extra request headers. */
245
+ headers?: Record<string, string>;
246
+ /** Appended after the standard User-Agent. */
247
+ userAgentSuffix?: string;
248
+ /** Request/response hooks. */
249
+ hooks?: Hooks;
250
+ /** Diagnostic logger (silent by default). */
251
+ logger?: ClientLogger;
252
+ }
253
+ /** Resolved common configuration (defaults applied). */
254
+ interface CommonConfig {
255
+ readonly url: string;
256
+ readonly connectTimeoutMs: number;
257
+ readonly requestTimeoutMs: number;
258
+ readonly totalTimeoutMs: number;
259
+ readonly retry: RetryPolicy;
260
+ readonly tls: Readonly<TlsOptions>;
261
+ readonly proxy?: string;
262
+ readonly headers: Readonly<Record<string, string>>;
263
+ readonly userAgentSuffix?: string;
264
+ readonly hooks?: Hooks;
265
+ readonly logger?: ClientLogger;
266
+ }
267
+ /** Default timeouts (SPEC §2.2). */
268
+ declare const DEFAULT_TIMEOUTS: Readonly<{
269
+ connectTimeoutMs: 10000;
270
+ requestTimeoutMs: 30000;
271
+ totalTimeoutMs: 120000;
272
+ }>;
273
+ /** Applies defaults to common options. Does not validate (see {@link validateCommonConfig}). */
274
+ declare function resolveCommonConfig(options: CommonConfigOptions, defaultUrl: string): CommonConfig;
275
+ /** Throws {@link ConfigError} when the common settings are invalid (SPEC §2.2). */
276
+ declare function validateCommonConfig(config: CommonConfig): void;
277
+ /** Vendor variable names consulted after `GROW_<KEY_UPPER>_<NAME>` for the common settings. */
278
+ interface CommonVendorEnv {
279
+ url?: readonly string[];
280
+ caCert?: readonly string[];
281
+ clientCert?: readonly string[];
282
+ clientKey?: readonly string[];
283
+ insecureSkipVerify?: readonly string[];
284
+ proxy?: readonly string[];
285
+ }
286
+ /** Reads the common settings from the environment (only values that are present). */
287
+ declare function readCommonEnv(reader: EnvReader, vendor?: CommonVendorEnv): CommonConfigOptions;
288
+ /** Drops keys whose value is `undefined` so they do not shadow lower-precedence values. */
289
+ declare function definedOnly<T extends object>(value: T): Partial<T>;
290
+ /**
291
+ * Merges option layers, later layers winning; `retry`, `tls` and `headers` are merged
292
+ * key by key. `undefined` values never override.
293
+ */
294
+ declare function mergeOptions<T extends CommonConfigOptions>(...layers: (Partial<T> | undefined)[]): T;
295
+ /** Debug description of the common settings with credentials redacted. */
296
+ declare function describeCommonConfig(config: CommonConfig): Record<string, unknown>;
297
+ /** Collects the revealed values of every {@link Secret} found in `values`. */
298
+ declare function secretValues(...values: unknown[]): string[];
299
+
300
+ /** Options of {@link pollUntil}. */
301
+ interface PollOptions {
302
+ /** Give up after this many ms (default 30 000). */
303
+ timeoutMs?: number;
304
+ /** Wait between attempts in ms (default 1 000). */
305
+ intervalMs?: number;
306
+ /** Caller cancellation. */
307
+ signal?: AbortSignal;
308
+ /** Name used in the timeout message (default `"poll"`). */
309
+ operation?: string;
310
+ /** Errors for which polling continues instead of failing (default: none). */
311
+ ignoreError?: (error: unknown) => boolean;
312
+ /** Test seam. */
313
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
314
+ /** Test seam: clock in ms. */
315
+ now?: () => number;
316
+ }
317
+ /**
318
+ * Calls `fn` until `predicate(value)` is true and returns that value. Throws
319
+ * {@link TimeoutError} when the time budget runs out (the message includes the last value's
320
+ * failure reason when the predicate never matched) and `CancelledError` on abort.
321
+ */
322
+ declare function pollUntil<T>(fn: (attempt: number) => Promise<T>, predicate: (value: T) => boolean, options?: PollOptions): Promise<T>;
323
+
324
+ /** Response headers that carry a vendor request id, checked in order. */
325
+ declare const DEFAULT_REQUEST_ID_HEADERS: readonly string[];
326
+ /** Longest vendor error text kept in an error message (SPEC §2.1). */
327
+ declare const MAX_VENDOR_TEXT = 300;
328
+ /** Query parameter values accepted by {@link RequestOptions.query}. */
329
+ type QueryValue = string | number | boolean | null | undefined | readonly (string | number | boolean)[];
330
+ /** How the response body is decoded. */
331
+ type ResponseType = "json" | "text" | "bytes" | "none";
332
+ /** One HTTP call made through {@link HttpTransport.request}. */
333
+ interface RequestOptions {
334
+ /** HTTP method (default `GET`). */
335
+ method?: string;
336
+ /** Path joined to the base URL (`/v1/x`), or an absolute URL. */
337
+ path: string;
338
+ /** Query parameters (`undefined`/`null` are skipped, arrays repeat the key). */
339
+ query?: Readonly<Record<string, QueryValue>>;
340
+ /** Extra headers for this call. */
341
+ headers?: Readonly<Record<string, string>>;
342
+ /** JSON body (sets `content-type: application/json`). */
343
+ json?: unknown;
344
+ /** Raw body. */
345
+ body?: string | Uint8Array;
346
+ /** Marks a non-idempotent method (e.g. `POST`) as safe to retry. */
347
+ idempotent?: boolean;
348
+ /** Caller cancellation. */
349
+ signal?: AbortSignal;
350
+ /** Operation name used in error messages (default `"<METHOD> <path>"`). */
351
+ operation?: string;
352
+ /** Per-attempt timeout override in ms. */
353
+ requestTimeoutMs?: number;
354
+ /** Whole-call timeout override in ms. */
355
+ totalTimeoutMs?: number;
356
+ /** Body decoding (default `json`; empty bodies decode to `undefined`). */
357
+ responseType?: ResponseType;
358
+ /**
359
+ * Error statuses returned to the caller instead of thrown (e.g. `[404]`). Their body is decoded
360
+ * like a success body (`data`; JSON that does not parse decodes to `undefined` instead of
361
+ * throwing) and the raw text is in {@link TransportResponse.text}.
362
+ */
363
+ allowStatus?: readonly number[];
364
+ /**
365
+ * Maps an HTTP error response of this call to an SDK error; runs before
366
+ * {@link TransportOptions.classifyError}. Return `undefined` to keep the next mapping.
367
+ */
368
+ classifyError?: ErrorClassifier;
369
+ }
370
+ /**
371
+ * An HTTP error response (status >= 400, not in `allowStatus`), passed to an
372
+ * {@link ErrorClassifier} before the transport decides about retries and calls `onError`.
373
+ */
374
+ interface ErrorResponse {
375
+ /** Operation name used in error messages (e.g. `"GET /v1/x"`). */
376
+ readonly operation: string;
377
+ readonly method: string;
378
+ readonly status: number;
379
+ readonly headers: Headers;
380
+ /**
381
+ * Raw response body text. It is NOT redacted: parse it (vendor error codes, request ids), but do
382
+ * not copy it into an error message unfiltered — use {@link reason} or
383
+ * {@link HttpTransport.redact} instead.
384
+ */
385
+ readonly body: string;
386
+ /** Vendor message extracted from the body: whitespace collapsed, redacted, truncated. */
387
+ readonly reason?: string;
388
+ readonly requestId?: string;
389
+ readonly retryAfterMs?: number;
390
+ /** 1-based attempt number. */
391
+ readonly attempt: number;
392
+ /** The error the transport throws when no classifier returns one (SPEC §2.1 mapping). */
393
+ readonly defaultError: LokiError;
394
+ }
395
+ /**
396
+ * Service-specific error mapping: returns the error to raise for an HTTP error response, or
397
+ * `undefined` to keep the default. Retries still follow the HTTP status (SPEC §2.3); a returned
398
+ * error with `retryable: false` stops them. A classifier that throws an SDK error is treated as
399
+ * if it had returned it; any other exception is ignored.
400
+ */
401
+ type ErrorClassifier = (response: ErrorResponse) => LokiError | undefined;
402
+ /** Result of {@link HttpTransport.request}. */
403
+ interface TransportResponse<T = unknown> {
404
+ status: number;
405
+ headers: Headers;
406
+ data: T;
407
+ requestId?: string;
408
+ durationMs: number;
409
+ /** Attempts made, starting at 1. */
410
+ attempts: number;
411
+ /** Raw body text of an allowed error response (status >= 400 listed in `allowStatus`). */
412
+ text?: string;
413
+ }
414
+ /** Options of {@link HttpTransport}. */
415
+ interface TransportOptions {
416
+ /** Resolved common configuration (URL, timeouts, retry, TLS, proxy, headers, hooks, logger). */
417
+ config: CommonConfig;
418
+ /** Default headers added to every request (e.g. authorization), after `config.headers`. */
419
+ defaultHeaders?: () => Readonly<Record<string, string>>;
420
+ /** Known secret values redacted from every error message, hook payload and log line. */
421
+ knownSecrets?: () => Iterable<KnownSecret>;
422
+ /** Header names that carry a vendor request id. */
423
+ requestIdHeaders?: readonly string[];
424
+ /**
425
+ * Service-specific mapping of HTTP error responses to SDK errors (e.g. a vendor error code in
426
+ * the body that means `CONFLICT`). Runs after {@link RequestOptions.classifyError} and before
427
+ * retries and the `onError` hook, so hooks see the mapped error.
428
+ */
429
+ classifyError?: ErrorClassifier;
430
+ /** Test seam: replaces the dispatcher built from TLS/proxy settings (e.g. undici `MockAgent`). */
431
+ dispatcher?: Dispatcher;
432
+ /** Test seam: replaces the backoff sleep. */
433
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
434
+ /** Test seam: clock in ms. */
435
+ now?: () => number;
436
+ }
437
+ /** Builds the undici dispatcher for the TLS, proxy and connect-timeout settings. */
438
+ declare function createDispatcher(config: CommonConfig, logger?: ClientLogger): Dispatcher;
439
+ /**
440
+ * The HTTP transport shared by every client: base URL join, query and JSON encoding, default
441
+ * headers and User-Agent, retries with full-jitter backoff and `Retry-After`, per-attempt and
442
+ * total timeouts, cancellation, hooks, logging and status → error mapping (SPEC §2.3).
443
+ */
444
+ declare class HttpTransport {
445
+ #private;
446
+ /** `grow-codes-<key>/<version> (typescript)[ <suffix>]`. */
447
+ readonly userAgent: string;
448
+ readonly retry: RetryPolicy;
449
+ constructor(options: TransportOptions);
450
+ /** Whether {@link close} was called. */
451
+ get closed(): boolean;
452
+ /**
453
+ * Throws `CancelledError` (`"<operation>: client is closed"`, not retryable) once {@link close}
454
+ * was called (SPEC §2.4). Requests check this themselves; service methods that send no request
455
+ * (cached reads, local helpers) call it first.
456
+ */
457
+ ensureOpen(operation: string): void;
458
+ /** Builds the absolute URL for a path and query. */
459
+ buildUrl(path: string, query?: Readonly<Record<string, QueryValue>>): URL;
460
+ /** Redacts known secrets from a text (error messages, vendor text). */
461
+ redact(text: string): string;
462
+ /** `GET` shortcut. */
463
+ get<T = unknown>(path: string, options?: Omit<RequestOptions, "path" | "method">): Promise<TransportResponse<T>>;
464
+ /** `POST` shortcut. */
465
+ post<T = unknown>(path: string, options?: Omit<RequestOptions, "path" | "method">): Promise<TransportResponse<T>>;
466
+ /** `PUT` shortcut. */
467
+ put<T = unknown>(path: string, options?: Omit<RequestOptions, "path" | "method">): Promise<TransportResponse<T>>;
468
+ /** `DELETE` shortcut. */
469
+ delete<T = unknown>(path: string, options?: Omit<RequestOptions, "path" | "method">): Promise<TransportResponse<T>>;
470
+ /**
471
+ * Sends a request with retries; throws an SDK error on failure. Every error message passes
472
+ * through {@link redact} with the known secrets.
473
+ */
474
+ request<T = unknown>(options: RequestOptions): Promise<TransportResponse<T>>;
475
+ /**
476
+ * Extracts the vendor error message from a response body (JSON `message`, `error`, … or plain
477
+ * text; HTML is ignored), collapses whitespace, trims, redacts secrets and truncates it to
478
+ * {@link MAX_VENDOR_TEXT} characters. Returns `undefined` when there is nothing useful.
479
+ */
480
+ vendorText(text: string): string | undefined;
481
+ /** Releases connections. Idempotent. */
482
+ close(): Promise<void>;
483
+ }
484
+ /** Redacts `key=value`/`"key": "value"` pairs with sensitive keys and bearer tokens. */
485
+ declare function redactSecretsInText(text: string): string;
486
+
487
+ /** Package version (kept in sync by release-please). */
488
+ declare const SDK_VERSION = "0.1.1";
489
+ /** Catalog key of the service (`grafana-loki`). */
490
+ declare const PACKAGE_KEY = "grafana-loki";
491
+ /** Language tag used in the User-Agent. */
492
+ declare const LANGUAGE = "typescript";
493
+ /** sdk-kit version this package was generated from. */
494
+ declare const SDK_KIT_VERSION = "0.3.0";
495
+
496
+ declare const INSPECT: unique symbol;
497
+ /** Longest tenant id Loki accepts (bytes). */
498
+ declare const MAX_TENANT_ID_LENGTH = 150;
499
+ /**
500
+ * Returns the problem with a tenant id (`X-Scope-OrgID`), or `undefined` when it is valid.
501
+ * Loki rules: non-empty, at most 150 bytes, not `.`/`..`, only `[A-Za-z0-9!-_.*'()]`. A `|`
502
+ * joins tenants for a multi-tenant query; it is accepted only when `multiTenantQueries` is set
503
+ * (the server must enable `multi_tenant_queries_enabled`), and each part must then be valid.
504
+ */
505
+ declare function tenantIdProblem(id: string, multiTenantQueries?: boolean): string | undefined;
506
+ /** Options accepted by {@link LokiConfig} (all optional). */
507
+ interface LokiConfigOptions extends CommonConfigOptions {
508
+ /** Tenant sent as `X-Scope-OrgID` (env `GROW_GRAFANA_LOKI_TENANT_ID`, `LOKI_TENANT_ID`). */
509
+ tenantId?: string;
510
+ /** Basic-auth user for gateways / Grafana Cloud (env `GROW_GRAFANA_LOKI_USERNAME`, `LOKI_USERNAME`). */
511
+ username?: string;
512
+ /** Basic-auth password or access token (env `GROW_GRAFANA_LOKI_PASSWORD`, `LOKI_PASSWORD`). */
513
+ password?: string | Secret;
514
+ /** Bearer token for gateways (env `GROW_GRAFANA_LOKI_BEARER_TOKEN`, `LOKI_BEARER_TOKEN`). */
515
+ bearerToken?: string | Secret;
516
+ /**
517
+ * Allows tenant ids joined with `|` (Loki multi-tenant queries; the server must enable
518
+ * `multi_tenant_queries_enabled`). Default `false`.
519
+ */
520
+ multiTenantQueries?: boolean;
521
+ /**
522
+ * Cardinality guard allowlist used by `push` and the log exporter: only these label names
523
+ * become index labels, everything else goes to structured metadata. Default
524
+ * `DEFAULT_ALLOWED_LABELS`.
525
+ */
526
+ allowedLabels?: readonly string[];
527
+ /** Sends every stream label of `push` as an index label (turns the guard off). Default `false`. */
528
+ disableLabelGuard?: boolean;
529
+ }
530
+ /** Vendor environment variables read after `GROW_GRAFANA_LOKI_*`, in order. */
531
+ declare const VENDOR_ENV: CommonVendorEnv & {
532
+ tenantId: readonly string[];
533
+ username: readonly string[];
534
+ password: readonly string[];
535
+ bearerToken: readonly string[];
536
+ };
537
+ /** Immutable configuration of {@link LokiClient}. */
538
+ declare class LokiConfig implements CommonConfig {
539
+ /** Default endpoint. */
540
+ static readonly DEFAULT_URL: string;
541
+ /** Prefix of every environment variable. */
542
+ static readonly ENV_PREFIX = "GROW_GRAFANA_LOKI_";
543
+ readonly url: string;
544
+ readonly connectTimeoutMs: number;
545
+ readonly requestTimeoutMs: number;
546
+ readonly totalTimeoutMs: number;
547
+ readonly retry: RetryPolicy;
548
+ readonly tls: Readonly<TlsOptions>;
549
+ readonly proxy?: string;
550
+ readonly headers: Readonly<Record<string, string>>;
551
+ readonly userAgentSuffix?: string;
552
+ readonly hooks?: Hooks;
553
+ readonly logger?: ClientLogger;
554
+ /** Tenant (`X-Scope-OrgID`); not sent when unset. */
555
+ readonly tenantId?: string;
556
+ /** Basic-auth user. */
557
+ readonly username?: string;
558
+ /** Basic-auth password. */
559
+ readonly password?: Secret;
560
+ /** Bearer token. */
561
+ readonly bearerToken?: Secret;
562
+ /** Whether tenant ids joined with `|` are allowed. */
563
+ readonly multiTenantQueries: boolean;
564
+ /** Configured cardinality guard allowlist (`undefined` = `DEFAULT_ALLOWED_LABELS`). */
565
+ readonly allowedLabels?: readonly string[];
566
+ /** Whether `push` skips the cardinality guard. */
567
+ readonly disableLabelGuard: boolean;
568
+ /** Applies defaults, validates (throws {@link ConfigError}) and freezes. */
569
+ constructor(options?: LokiConfigOptions);
570
+ /** Returns `options` when it already is a config, otherwise builds one. */
571
+ static from(options?: LokiConfigOptions): LokiConfig;
572
+ /**
573
+ * Builds a config from the environment. Precedence: explicit `overrides` >
574
+ * `GROW_GRAFANA_LOKI_<NAME>` > vendor variables ({@link VENDOR_ENV}) > defaults.
575
+ */
576
+ static fromEnv(overrides?: LokiConfigOptions, env?: EnvMap): LokiConfig;
577
+ /** A copy of this config with some fields replaced (validated again). */
578
+ with(overrides: LokiConfigOptions): LokiConfig;
579
+ /** Throws {@link ConfigError} when a setting is invalid. */
580
+ validate(): void;
581
+ /** The `Authorization` header value, when credentials are configured. */
582
+ authorizationHeader(): string | undefined;
583
+ /** Credential values to redact from error messages and logs. */
584
+ knownSecrets(): string[];
585
+ /** Debug form with every credential redacted. */
586
+ toJSON(): Record<string, unknown>;
587
+ toString(): string;
588
+ [INSPECT](): string;
589
+ }
590
+
591
+ /** Normalized wire form of a {@link LogRecord} (`spec/schemas/log-record.schema.json`). */
592
+ interface LogRecordJson {
593
+ /** RFC 3339 UTC (JavaScript dates carry millisecond precision). */
594
+ timestamp: string;
595
+ observedTimestamp?: string;
596
+ /** Named OTel severity number (1, 5, 9, 13, 17, 21). */
597
+ severity: number;
598
+ severityText: string;
599
+ body: string;
600
+ attributes: Attributes;
601
+ resource: Attributes;
602
+ traceId?: string;
603
+ spanId?: string;
604
+ traceFlags?: number;
605
+ }
606
+ /**
607
+ * Converts an arbitrary value into an {@link AttrValue}. `null`, `undefined`, functions and symbols
608
+ * become `undefined` (the caller omits the key); dates become ISO strings; bigints become strings;
609
+ * errors become `{ name, message }`; cycles and very deep values become `"[Circular]"`/`"[Truncated]"`.
610
+ */
611
+ declare function toAttrValue(value: unknown, depth?: number, seen?: WeakSet<object>): AttrValue | undefined;
612
+ /** Converts every entry of `input` with {@link toAttrValue}, omitting entries without a value. */
613
+ declare function toAttributes(input: Record<string, unknown>, depth?: number, seen?: WeakSet<object>): Attributes;
614
+ /**
615
+ * Converts a record to its normalized wire form. Severity numbers between the named values are
616
+ * written as the named value of their range; the vendor text stays in `severityText`.
617
+ */
618
+ declare function logRecordToJson(record: LogRecord): LogRecordJson;
619
+ /**
620
+ * Parses the normalized JSON form (object) back into a {@link LogRecord}. Non-string bodies are
621
+ * JSON-encoded. Throws `ValidationError` when required fields are missing or malformed.
622
+ */
623
+ declare function logRecordFromJson(input: unknown): LogRecord;
624
+ /** Serialises a record to a JSON string in the normalized wire form. */
625
+ declare function serializeLogRecord(record: LogRecord): string;
626
+ /** Parses a JSON string in the normalized wire form. Throws `ValidationError` on invalid input. */
627
+ declare function parseLogRecord(text: string): LogRecord;
628
+ /** UTF-8 size in bytes of the record's normalized JSON form. */
629
+ declare function logRecordByteSize(record: LogRecord): number;
630
+
631
+ /** Options of {@link createPinoTransport}. */
632
+ interface PinoTransportOptions {
633
+ /** Key of the message in pino output. Default `"msg"`. */
634
+ messageKey?: string;
635
+ /** Extra attributes added to every record. */
636
+ attributes?: Attributes;
637
+ /** Call `client.flush()` when the stream ends. Default true. */
638
+ flushOnEnd?: boolean;
639
+ }
640
+ /** Maps a pino level (number or label) to a {@link Severity}. */
641
+ declare function pinoLevelToSeverity(level: unknown): Severity;
642
+ /** Converts one parsed pino log line into a {@link LogRecord}. */
643
+ declare function pinoLineToRecord(line: Record<string, unknown>, opts?: PinoTransportOptions): LogRecord;
644
+ /**
645
+ * Creates a writable stream for `pino(stream)`: every NDJSON line pino writes becomes a record sent
646
+ * through `client`. Lines that are not JSON are sent as the body of an INFO record.
647
+ *
648
+ * ```ts
649
+ * const log = pino(createPinoTransport(client));
650
+ * ```
651
+ */
652
+ declare function createPinoTransport(client: LogClient, opts?: PinoTransportOptions): Writable;
653
+
654
+ /** Options of {@link WinstonTransport}. */
655
+ interface WinstonTransportOptions {
656
+ /** Most verbose winston level this transport accepts (uses the logger's level table). */
657
+ level?: string;
658
+ /** Extra attributes added to every record. */
659
+ attributes?: Attributes;
660
+ }
661
+ /** Maps a winston level name (npm, syslog or cli levels) to a {@link Severity}. */
662
+ declare function winstonLevelToSeverity(level: string): Severity;
663
+ /** Winston `info` object (structural; no hard winston dependency). */
664
+ interface WinstonInfo {
665
+ level: string;
666
+ message?: unknown;
667
+ [key: string | symbol]: unknown;
668
+ }
669
+ /**
670
+ * Winston transport that sends every log entry through a {@link LogClient}. It is an object-mode
671
+ * writable stream, which is what `winston.createLogger({ transports: [...] })` expects.
672
+ *
673
+ * ```ts
674
+ * const logger = winston.createLogger({ transports: [new WinstonTransport(client)] });
675
+ * ```
676
+ */
677
+ declare class WinstonTransport extends Writable {
678
+ #private;
679
+ /** Level filter (same meaning as winston-transport's `level`). */
680
+ level: string | undefined;
681
+ /** Level table, set by winston when the logger pipes into this transport. */
682
+ levels: Record<string, number> | undefined;
683
+ constructor(client: LogClient, opts?: WinstonTransportOptions);
684
+ /** Converts a winston info object into a {@link LogRecord}. */
685
+ toRecord(info: WinstonInfo): LogRecord;
686
+ /** Winston-compatible entry point. */
687
+ log(info: WinstonInfo, callback?: () => void): void;
688
+ _write(info: WinstonInfo, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void;
689
+ _final(callback: (error?: Error | null) => void): void;
690
+ /** Called by winston when the transport is removed or the logger closes. */
691
+ close(): void;
692
+ }
693
+
694
+ /** Label names allowed by Loki (Prometheus rules). */
695
+ declare const LABEL_NAME_PATTERN: RegExp;
696
+ /**
697
+ * Keys the cardinality guard lets become index labels by default (coordinator decision 3).
698
+ * Every other attribute or resource key goes to structured metadata.
699
+ */
700
+ declare const DEFAULT_ALLOWED_LABELS: readonly string[];
701
+ /** Metadata keys the SDK writes itself (and reads back into `LogRecord` fields). */
702
+ declare const RESERVED_METADATA_KEYS: readonly string[];
703
+ /** True when `name` is a valid, non-reserved Loki label name. */
704
+ declare function isValidLabelName(name: string): boolean;
705
+ /** Throws `ValidationError` unless `name` is a valid, non-reserved label name. */
706
+ declare function validateLabelName(name: string, what?: string): void;
707
+ /** Validates a label set: valid names and non-empty values. */
708
+ declare function validateLabels(labels: Readonly<Record<string, string>>): void;
709
+ /**
710
+ * Normalizes an attribute key to a label/metadata name the way Loki does for OTLP attributes:
711
+ * every character outside `[a-zA-Z0-9_]` becomes `_` (`service.name` → `service_name`), and a
712
+ * leading digit gets a `_` prefix.
713
+ */
714
+ declare function normalizeLabelName(key: string): string;
715
+ /**
716
+ * Renders a label set in Prometheus syntax, `{a="b", c="d"}`, with sorted names and
717
+ * Go-compatible quoting (the form protobuf push and `listStreams()` use).
718
+ */
719
+ declare function formatLabelSet(labels: Readonly<Record<string, string>>): string;
720
+ /** Stringifies an attribute value for structured metadata (objects and arrays as JSON). */
721
+ declare function attrToString(value: AttrValue): string;
722
+ /** One log line pushed to Loki. */
723
+ interface LokiEntry {
724
+ /** Entry time: `Date`, bigint nanoseconds or a decimal nanosecond string (unset = now). */
725
+ timestamp?: Date | bigint | string;
726
+ /** The log line. */
727
+ line: string;
728
+ /** Structured metadata (string → string), stored next to the line but not indexed. */
729
+ structuredMetadata?: Readonly<Record<string, string>>;
730
+ }
731
+ /** A stream: one label set and its entries (`push` input). */
732
+ interface LokiStream {
733
+ /** Index labels. Keep them few and low-cardinality. */
734
+ labels: Readonly<Record<string, string>>;
735
+ /** Entries of the stream (any order inside the ingest window). */
736
+ entries: readonly LokiEntry[];
737
+ }
738
+ /**
739
+ * Keeps Loki's index small: only allowlisted label names become index labels, every other
740
+ * stream label is moved to the structured metadata of each entry (an entry's own metadata wins).
741
+ * `push` applies it unless `LokiConfig.disableLabelGuard` is set.
742
+ */
743
+ declare class CardinalityGuard {
744
+ #private;
745
+ /** A guard for `allowed` (default {@link DEFAULT_ALLOWED_LABELS}). */
746
+ constructor(allowed?: readonly string[]);
747
+ /** The allowlist, sorted. */
748
+ get allowed(): string[];
749
+ /** Whether `name` may be an index label. */
750
+ isAllowed(name: string): boolean;
751
+ /** A copy of `stream` whose labels outside the allowlist are moved to every entry's metadata. */
752
+ apply(stream: LokiStream): LokiStream;
753
+ }
754
+ /** Options of the cardinality guard ({@link recordsToStreams}). */
755
+ interface CardinalityGuardOptions {
756
+ /** Normalized keys allowed as index labels. Default {@link DEFAULT_ALLOWED_LABELS}. */
757
+ allowedLabels?: readonly string[];
758
+ }
759
+ /**
760
+ * Maps log records to Loki streams with the cardinality guard: resource and attribute keys are
761
+ * normalized (`service.name` → `service_name`); keys in `allowedLabels` with scalar, non-empty
762
+ * values become index labels, everything else becomes structured metadata. `level` (the
763
+ * lower-case severity text) is added as a label when allowed. Severity, trace id, span id and
764
+ * trace flags travel as metadata (`severity_text`, `severity_number`, `trace_id`, `span_id`,
765
+ * `trace_flags`) and are never labels. Records with the same final label set share a stream.
766
+ */
767
+ declare function recordsToStreams(records: readonly LogRecord[], options?: CardinalityGuardOptions): LokiStream[];
768
+
769
+ /** Wire format of `push`. */
770
+ type PushFormat = "json" | "protobuf";
771
+ /**
772
+ * Internal push option: the streams were already built by the cardinality guard (the log
773
+ * exporter), so `push` must not apply the config's guard a second time. @internal
774
+ */
775
+ declare const SKIP_LABEL_GUARD: unique symbol;
776
+ /** Options of a push call. */
777
+ interface PushOptions {
778
+ /** `json` (default) or `protobuf` (Snappy-compressed `PushRequest`). */
779
+ format?: PushFormat;
780
+ /** Gzip the JSON body (ignored for protobuf, which is Snappy-compressed). Default false. */
781
+ gzip?: boolean;
782
+ signal?: AbortSignal;
783
+ /** @internal */
784
+ [SKIP_LABEL_GUARD]?: boolean;
785
+ }
786
+ /** Options of an OTLP push call. */
787
+ interface OtlpPushOptions {
788
+ /** Gzip the body. Default false. */
789
+ gzip?: boolean;
790
+ signal?: AbortSignal;
791
+ }
792
+ /** What the exporters need from the client. @internal */
793
+ interface LokiPusher {
794
+ push(streams: readonly LokiStream[], options?: PushOptions): Promise<void>;
795
+ pushOtlp(records: readonly LogRecord[], options?: OtlpPushOptions): Promise<void>;
796
+ }
797
+ /** Options of {@link LokiLogExporter}. */
798
+ interface LokiLogExporterOptions extends CardinalityGuardOptions {
799
+ /** Wire format. Default `json`. */
800
+ format?: PushFormat;
801
+ }
802
+ /**
803
+ * {@link LogExporter} that writes records with `POST /loki/api/v1/push`. Records are grouped into
804
+ * streams by the cardinality guard ({@link recordsToStreams}). Loki accepts or rejects a whole
805
+ * push, so a result is either all accepted or all rejected (with the error).
806
+ */
807
+ declare class LokiLogExporter implements LogExporter {
808
+ #private;
809
+ constructor(pusher: LokiPusher, options?: LokiLogExporterOptions);
810
+ export(records: LogRecord[], opts: ExportOptions): Promise<ExportResult>;
811
+ shutdown(): Promise<void>;
812
+ }
813
+ /**
814
+ * {@link LogExporter} that writes OTLP/JSON to `POST /otlp/v1/logs`. Loki then decides which
815
+ * resource attributes become labels (its OTLP defaults) and stores the rest as structured
816
+ * metadata.
817
+ */
818
+ declare class LokiOtlpExporter implements LogExporter {
819
+ #private;
820
+ constructor(pusher: LokiPusher);
821
+ export(records: LogRecord[], opts: ExportOptions): Promise<ExportResult>;
822
+ shutdown(): Promise<void>;
823
+ }
824
+ /** Instrumentation scope name used in OTLP payloads. */
825
+ declare const OTLP_SCOPE_NAME = "grow-codes-grafana-loki";
826
+ /** OTLP/JSON `AnyValue`. */
827
+ type OtlpAnyValue = {
828
+ stringValue: string;
829
+ } | {
830
+ boolValue: boolean;
831
+ } | {
832
+ intValue: string;
833
+ } | {
834
+ doubleValue: number;
835
+ } | {
836
+ arrayValue: {
837
+ values: OtlpAnyValue[];
838
+ };
839
+ } | {
840
+ kvlistValue: {
841
+ values: OtlpKeyValue[];
842
+ };
843
+ };
844
+ /** OTLP/JSON `KeyValue`. */
845
+ interface OtlpKeyValue {
846
+ key: string;
847
+ value: OtlpAnyValue;
848
+ }
849
+ /** Converts an attribute value to an OTLP/JSON `AnyValue`. */
850
+ declare function toOtlpValue(value: AttrValue): OtlpAnyValue;
851
+ /**
852
+ * Encodes records as an OTLP/JSON `ExportLogsServiceRequest` (one `resourceLogs` entry per
853
+ * distinct resource).
854
+ */
855
+ declare function recordsToOtlpJson(records: readonly LogRecord[]): Record<string, unknown>;
856
+
857
+ /** One log entry returned by a query or the tail stream. */
858
+ interface LokiEntryResult {
859
+ /** Unix nanoseconds as a decimal string (lossless). */
860
+ timestampNs: string;
861
+ /** The same time as a `Date` (millisecond precision). */
862
+ timestamp: Date;
863
+ /** The log line. */
864
+ line: string;
865
+ /** Structured metadata of the entry (includes Loki's `detected_level`). */
866
+ structuredMetadata: Record<string, string>;
867
+ /** Labels extracted by parser stages (`| json`, `| logfmt`, …). */
868
+ parsed: Record<string, string>;
869
+ }
870
+ /** One stream of a `streams` result. */
871
+ interface LokiStreamResult {
872
+ /** Index labels of the stream. */
873
+ labels: Record<string, string>;
874
+ /** Entries in the requested direction. */
875
+ entries: LokiEntryResult[];
876
+ }
877
+ /** One metric sample. */
878
+ interface LokiSample {
879
+ timestamp: Date;
880
+ /** Sample value (`NaN`/`±Infinity` kept). */
881
+ value: number;
882
+ }
883
+ /** One series of a `vector` result. */
884
+ interface LokiVectorSample extends LokiSample {
885
+ metric: Record<string, string>;
886
+ }
887
+ /** One series of a `matrix` result. */
888
+ interface LokiMatrixSeries {
889
+ metric: Record<string, string>;
890
+ samples: LokiSample[];
891
+ }
892
+ /** Result type reported by Loki. */
893
+ type LokiResultType = "streams" | "vector" | "matrix" | "scalar";
894
+ /** Result of `query`, `queryRange`, `volume` and `volumeRange`. */
895
+ interface LokiQueryResult {
896
+ resultType: LokiResultType;
897
+ /** Filled for `streams` results. */
898
+ streams: LokiStreamResult[];
899
+ /** Filled for `vector` results. */
900
+ vector: LokiVectorSample[];
901
+ /** Filled for `matrix` results. */
902
+ matrix: LokiMatrixSeries[];
903
+ /** Filled for `scalar` results. */
904
+ scalar?: LokiSample;
905
+ /** Raw query statistics (`data.stats`), `{}` when absent. */
906
+ stats: Record<string, unknown>;
907
+ }
908
+ /** Result of `indexStats` (approximate, from the TSDB index only). */
909
+ interface LokiIndexStats {
910
+ streams: number;
911
+ chunks: number;
912
+ bytes: number;
913
+ entries: number;
914
+ }
915
+ /** Build information of the server (`/loki/api/v1/status/buildinfo`). */
916
+ interface LokiBuildInfo {
917
+ version: string;
918
+ revision: string;
919
+ branch: string;
920
+ buildUser: string;
921
+ buildDate: string;
922
+ goVersion: string;
923
+ }
924
+ /** Labels of one dropped entry reported by the tail stream. */
925
+ interface LokiDroppedEntry {
926
+ labels: Record<string, string>;
927
+ timestampNs: string;
928
+ }
929
+ /** One frame of the tail WebSocket. */
930
+ interface LokiTailFrame {
931
+ streams: LokiStreamResult[];
932
+ droppedEntries: LokiDroppedEntry[];
933
+ }
934
+ /** Converts a JSON object of string values to a string map (other values are stringified). */
935
+ declare function stringMap(v: unknown): Record<string, string>;
936
+ /** Decodes one `[ns, line, {structuredMetadata, parsed}?]` value. */
937
+ declare function decodeEntry(v: unknown): LokiEntryResult;
938
+ /** Decodes a list of `{stream, values}` objects. */
939
+ declare function decodeStreams(v: unknown): LokiStreamResult[];
940
+ /** Decodes the `{status, data: {resultType, result, stats}}` envelope. */
941
+ declare function decodeQueryResult(body: unknown): LokiQueryResult;
942
+ /** Decodes `{status, data: [...]}`; a missing `data` (empty result) is `[]`. */
943
+ declare function decodeStringList(body: unknown): string[];
944
+ /** Decodes the series response (list of label maps). */
945
+ declare function decodeSeries(body: unknown): Record<string, string>[];
946
+ /** Decodes the index stats response (no envelope). */
947
+ declare function decodeIndexStats(body: unknown): LokiIndexStats;
948
+ /** Decodes the build info response. */
949
+ declare function decodeBuildInfo(body: unknown): LokiBuildInfo;
950
+ /** Decodes one tail WebSocket frame. */
951
+ declare function decodeTailFrame(body: unknown): LokiTailFrame;
952
+
953
+ /** Handle of an open tail stream. */
954
+ interface LokiTail {
955
+ /** Closes the WebSocket (close frame 1000). Idempotent. */
956
+ stop(): void;
957
+ /** Resolves once the socket is closed (after {@link stop} or when the server closes it). */
958
+ readonly closed: Promise<void>;
959
+ }
960
+ /** Callbacks of a tail stream besides the frame handler. */
961
+ interface TailCallbacks {
962
+ /** Entries the server dropped because the client fell behind. */
963
+ onDropped?: (entries: LokiDroppedEntry[]) => void;
964
+ /** Errors after the connection was established (bad frame, abnormal close). */
965
+ onError?: (error: LokiError) => void;
966
+ }
967
+
968
+ /**
969
+ * A point in time accepted by the Loki API:
970
+ *
971
+ * - `Date` (millisecond precision),
972
+ * - `bigint` Unix nanoseconds (lossless),
973
+ * - `string`: a decimal Unix-nanosecond string (`"1795034767066713072"`) or an RFC 3339 date.
974
+ */
975
+ type LokiTime = Date | bigint | string;
976
+ /** Converts a `Date` to a decimal Unix-nanosecond string. */
977
+ declare function dateToNanos(date: Date): string;
978
+ /** Converts a decimal Unix-nanosecond string (or bigint) to a `Date` (millisecond precision). */
979
+ declare function nanosToDate(ns: string | bigint): Date;
980
+ /**
981
+ * Converts a {@link LokiTime} to the decimal Unix-nanosecond string Loki expects in push bodies
982
+ * and query parameters. Throws `ValidationError` for an unparsable value.
983
+ */
984
+ declare function toNanos(value: LokiTime, field?: string): string;
985
+ /** `toNanos` for optional values. */
986
+ declare function optionalNanos(value: LokiTime | undefined, field: string): string | undefined;
987
+ /** Converts float Unix seconds (metric samples) to a `Date`. */
988
+ declare function secondsToDate(seconds: number): Date;
989
+ /** Renders a duration in milliseconds as a Loki/Prometheus duration (`"1500ms"`). */
990
+ declare function msToDuration(ms: number, field: string): string;
991
+
992
+ /** Largest `limit` Loki accepts per query by default (`max_entries_limit_per_query`). */
993
+ declare const MAX_QUERY_LIMIT = 5000;
994
+ /** Selector used for free-text searches and `listStreams()`. */
995
+ declare const ALL_STREAMS_SELECTOR = "{service_name=~\".+\"}";
996
+ /** What the query client needs from {@link LokiClient}. @internal */
997
+ interface LokiQuerySource {
998
+ queryRange(logql: string, options?: {
999
+ start?: LokiTime;
1000
+ end?: LokiTime;
1001
+ limit?: number;
1002
+ direction?: "forward" | "backward";
1003
+ signal?: AbortSignal;
1004
+ }): Promise<LokiQueryResult>;
1005
+ labels(options?: {
1006
+ signal?: AbortSignal;
1007
+ }): Promise<string[]>;
1008
+ series(matchers: string | readonly string[]): Promise<Record<string, string>[]>;
1009
+ tail(logql: string, onEntries: (streams: LokiStreamResult[], frame: LokiTailFrame) => void, options?: TailCallbacks & {
1010
+ start?: LokiTime;
1011
+ }): Promise<LokiTail>;
1012
+ }
1013
+ /**
1014
+ * Turns a search text into LogQL: text starting with `{` is used as LogQL as is; anything else
1015
+ * is a case-sensitive substring search over every stream (`{service_name=~".+"} |= "<text>"`).
1016
+ */
1017
+ declare function toSearchLogQL(query: string): string;
1018
+ /** Encodes a search cursor (`<ns>:<entries at ns already returned>`, base64). */
1019
+ declare function encodeCursor(ns: string, skip: number): string;
1020
+ /** Decodes a search cursor; throws `ValidationError` when it is malformed. */
1021
+ declare function decodeCursor(cursor: string): {
1022
+ ns: string;
1023
+ skip: number;
1024
+ };
1025
+ /**
1026
+ * Converts one Loki entry to a normalized {@link LogRecord}: the line becomes `body`; structured
1027
+ * metadata and parsed labels become `attributes` (the SDK's own keys are mapped back to
1028
+ * `severity`, `traceId`, `spanId`, `traceFlags`, `observedTimestamp`); stream labels become
1029
+ * `resource` (`service_name` → `service.name`, `deployment_environment` →
1030
+ * `deployment.environment`, …).
1031
+ */
1032
+ declare function entryToLogRecord(labels: Record<string, string>, entry: LokiEntryResult): LogRecord;
1033
+ /** One entry of the merged, sorted search result. */
1034
+ interface MergedEntry {
1035
+ labels: Record<string, string>;
1036
+ labelKey: string;
1037
+ entry: LokiEntryResult;
1038
+ }
1039
+ /** Merge-sorts the entries of all streams by time (then labels, then line for stable ties). */
1040
+ declare function mergeStreams(streams: readonly LokiStreamResult[], order: "asc" | "desc"): MergedEntry[];
1041
+ /**
1042
+ * {@link LogQueryClient} for Loki: `search` (query_range, merge-sorted, cursor pagination),
1043
+ * `tail` (WebSocket), `listStreams` (series), `listLabels` (labels) and `waitForLog`.
1044
+ */
1045
+ declare class LokiLogQueryClient extends BaseLogQueryClient {
1046
+ #private;
1047
+ constructor(source: LokiQuerySource);
1048
+ /**
1049
+ * Searches with `query_range`. `query` is LogQL (starting with `{`) or free text. `order`
1050
+ * `desc` (default) is newest first. Pass `nextCursor` back as `cursor` for the next page
1051
+ * (the cursor is `<timestamp>:<entries at that timestamp already returned>`, so pages never
1052
+ * skip or repeat entries sharing a nanosecond). `total` is not available from Loki.
1053
+ */
1054
+ search(query: string, opts?: LogSearchOptions): Promise<LogSearchResult>;
1055
+ /**
1056
+ * Live tail over the WebSocket API (`start` defaults to now, so only new records arrive).
1057
+ * Connection errors and abnormal closes go to `opts.onError`.
1058
+ */
1059
+ tail(query: string, onRecord: (record: LogRecord) => void, opts?: TailOptions): TailHandle;
1060
+ /** Every stream of the default window as a label-set string (`{a="b", c="d"}`), sorted. */
1061
+ listStreams(): Promise<string[]>;
1062
+ /** Label names of the default window. */
1063
+ listLabels(): Promise<string[]>;
1064
+ }
1065
+
1066
+ /** Per-call options. */
1067
+ interface CallOptions {
1068
+ /** Cancels the call (`CancelledError`). */
1069
+ signal?: AbortSignal;
1070
+ }
1071
+ /** Test seams (undici `MockAgent`, fake sleep). Not part of the stable API. */
1072
+ type ClientInternals = Pick<TransportOptions, "dispatcher" | "sleep" | "now">;
1073
+ /** Sort order of log results. */
1074
+ type Direction = "forward" | "backward";
1075
+ /** Options of {@link LokiClient.query}. */
1076
+ interface QueryOptions extends CallOptions {
1077
+ /** Evaluation time. Default: now. */
1078
+ time?: LokiTime;
1079
+ /** Kept for API parity; instant queries only return metrics. */
1080
+ limit?: number;
1081
+ /** Kept for API parity. */
1082
+ direction?: Direction;
1083
+ }
1084
+ /** Options of {@link LokiClient.queryRange}. */
1085
+ interface QueryRangeOptions extends CallOptions {
1086
+ /** Inclusive start. Default: one hour before `end`. */
1087
+ start?: LokiTime;
1088
+ /** Exclusive end. Default: now. */
1089
+ end?: LokiTime;
1090
+ /** Relative start (milliseconds before `end`) used when `start` is unset. */
1091
+ sinceMs?: number;
1092
+ /** Metric query resolution in milliseconds. */
1093
+ stepMs?: number;
1094
+ /** Stream sampling interval in milliseconds (log queries). */
1095
+ intervalMs?: number;
1096
+ /** Maximum entries across all streams (default 100, server max 5000). */
1097
+ limit?: number;
1098
+ /** `backward` (default, newest first) or `forward`. */
1099
+ direction?: Direction;
1100
+ }
1101
+ /** Time window options. */
1102
+ interface TimeRangeOptions extends CallOptions {
1103
+ start?: LokiTime;
1104
+ end?: LokiTime;
1105
+ }
1106
+ /** Options of {@link LokiClient.indexStats} (same name as in the other languages). */
1107
+ type IndexOptions = TimeRangeOptions;
1108
+ /** Options of {@link LokiClient.series}. */
1109
+ interface SeriesOptions extends TimeRangeOptions {
1110
+ /** Relative start (milliseconds before `end`) used when `start` is unset. */
1111
+ sinceMs?: number;
1112
+ }
1113
+ /** Options of {@link LokiClient.labels} and {@link LokiClient.labelValues}. */
1114
+ interface LabelsOptions extends TimeRangeOptions {
1115
+ /** Relative start (milliseconds before `end`) used when `start` is unset. */
1116
+ sinceMs?: number;
1117
+ /** Stream selector that scopes the result. */
1118
+ query?: string;
1119
+ }
1120
+ /** Options of {@link LokiClient.volume} and {@link LokiClient.volumeRange}. */
1121
+ interface VolumeOptions extends TimeRangeOptions {
1122
+ /** Maximum series. */
1123
+ limit?: number;
1124
+ /** Labels to aggregate on. */
1125
+ targetLabels?: readonly string[];
1126
+ /** `series` (default) or `labels`. */
1127
+ aggregateBy?: "series" | "labels";
1128
+ }
1129
+ /** Options of {@link LokiClient.volumeRange}. */
1130
+ interface VolumeRangeOptions extends VolumeOptions {
1131
+ /** Resolution in milliseconds. */
1132
+ stepMs?: number;
1133
+ }
1134
+ /** Options of {@link LokiClient.tail}. */
1135
+ interface LiveTailOptions extends TailCallbacks, CallOptions {
1136
+ /**
1137
+ * Replay entries from this time before streaming live ones. Default: now ("live only");
1138
+ * without a start Loki would replay the last hour.
1139
+ */
1140
+ start?: LokiTime;
1141
+ /** Maximum replayed entries (Loki default 100). */
1142
+ limit?: number;
1143
+ /** Server-side delay in milliseconds, 0–5000 (sent as whole seconds). */
1144
+ delayForMs?: number;
1145
+ }
1146
+ /** Options of {@link LokiClient.logClient}. */
1147
+ interface LokiLogClientOptions extends BatchingLogClientOptions, CardinalityGuardOptions {
1148
+ /** `json` (default) or `protobuf` push, or `otlp` (`/otlp/v1/logs`). */
1149
+ protocol?: "json" | "protobuf" | "otlp";
1150
+ }
1151
+ /** Header that switches query responses to categorized labels. */
1152
+ declare const ENCODING_FLAGS_HEADER = "x-loki-response-encoding-flags";
1153
+ /** Tenant header. */
1154
+ declare const TENANT_HEADER = "x-scope-orgid";
1155
+ /** Shared state between a client and its {@link LokiClient.withTenant} children. @internal */
1156
+ interface LokiClientShared {
1157
+ transport: HttpTransport;
1158
+ }
1159
+ /**
1160
+ * Client for Grafana Loki: push (JSON, protobuf + Snappy, OTLP), LogQL queries, labels,
1161
+ * series, index stats and volume, WebSocket tail, status, multi-tenancy and the logging
1162
+ * category (`logClient()`, `logQueryClient()`).
1163
+ */
1164
+ declare class LokiClient implements LokiPusher {
1165
+ #private;
1166
+ /** The immutable configuration. */
1167
+ readonly config: LokiConfig;
1168
+ /** Accepts a {@link LokiConfig} or plain options. */
1169
+ constructor(config?: LokiConfigOptions, internals?: ClientInternals, shared?: LokiClientShared);
1170
+ /** Builds a client from `GROW_GRAFANA_LOKI_*` (and `LOKI_*`) environment variables. */
1171
+ static fromEnv(overrides?: LokiConfigOptions): LokiClient;
1172
+ /** The shared HTTP transport (for service modules). @internal */
1173
+ get transport(): HttpTransport;
1174
+ /** The tenant this client sends as `X-Scope-OrgID`, if any. */
1175
+ get tenantId(): string | undefined;
1176
+ /**
1177
+ * A client for another tenant: shares this client's connections, sends `X-Scope-OrgID: id`
1178
+ * on every request and on the tail handshake. This client is unchanged. Closing the child
1179
+ * does not close the shared connections. Throws `ValidationError` for an invalid id.
1180
+ */
1181
+ withTenant(id: string): LokiClient;
1182
+ /**
1183
+ * Readiness: `GET /ready`. `200 ready` → healthy `ok`; `503` → unhealthy with Loki's text
1184
+ * (e.g. `Ingester not ready: waiting for 15s after being ready`); network errors →
1185
+ * `unreachable`. Never throws except for `CANCELLED` and `CONFIG`.
1186
+ */
1187
+ health(options?: CallOptions): Promise<HealthStatus>;
1188
+ /** `true` when `GET /ready` answers 200 (same probe as {@link health}). */
1189
+ ready(options?: CallOptions): Promise<boolean>;
1190
+ /**
1191
+ * Authenticated round trip: `GET /loki/api/v1/labels?since=5m` with auth and tenant headers.
1192
+ * Returns the latency in milliseconds; `AuthenticationError` without a tenant (multi-tenant
1193
+ * Loki) or with wrong gateway credentials.
1194
+ */
1195
+ ping(options?: CallOptions): Promise<number>;
1196
+ /** Build information: `GET /loki/api/v1/status/buildinfo`. */
1197
+ buildInfo(options?: CallOptions): Promise<LokiBuildInfo>;
1198
+ /** Server version (`buildInfo().version`, e.g. `"3.7.10"`). */
1199
+ serverVersion(options?: CallOptions): Promise<string>;
1200
+ /**
1201
+ * Pushes streams with `POST /loki/api/v1/push`. JSON by default (optionally gzip);
1202
+ * `format: "protobuf"` sends a Snappy-compressed `PushRequest`. The cardinality guard moves
1203
+ * labels outside `config.allowedLabels` to every entry's structured metadata (unless
1204
+ * `config.disableLabelGuard`), then labels are validated client side. Entries without a
1205
+ * timestamp get "now". Retrying is safe: Loki drops entries identical to stored ones (same labels,
1206
+ * timestamp and line), so the push is marked idempotent and retried on 5xx and network
1207
+ * errors. Status 260 (ingestion blocked by the operator) throws a non-retryable error.
1208
+ */
1209
+ push(streams: readonly LokiStream[], options?: PushOptions): Promise<void>;
1210
+ /**
1211
+ * Pushes records as OTLP/JSON to `POST /otlp/v1/logs` (Loki's OTLP endpoint). Loki promotes
1212
+ * its default resource attributes (`service.name`, `deployment.environment`, …) to labels and
1213
+ * stores everything else as structured metadata.
1214
+ */
1215
+ pushOtlp(records: readonly LogRecord[], options?: OtlpPushOptions): Promise<void>;
1216
+ /**
1217
+ * Instant metric query: `GET /loki/api/v1/query`. A plain log selector (`{...}` with or
1218
+ * without a pipeline) is rejected with `ValidationError`, as Loki does not run log queries
1219
+ * as instant queries; use {@link queryRange} instead.
1220
+ */
1221
+ query(logql: string, options?: QueryOptions): Promise<LokiQueryResult>;
1222
+ /** Range query (logs or metrics): `GET /loki/api/v1/query_range`. */
1223
+ queryRange(logql: string, options?: QueryRangeOptions): Promise<LokiQueryResult>;
1224
+ /** Label names: `GET /loki/api/v1/labels` (an empty result is `[]`). */
1225
+ labels(options?: LabelsOptions): Promise<string[]>;
1226
+ /**
1227
+ * Values of one label: `GET /loki/api/v1/label/{name}/values`. The name is validated client
1228
+ * side (Loki answers unknown and invalid names with an empty result).
1229
+ */
1230
+ labelValues(name: string, options?: LabelsOptions): Promise<string[]>;
1231
+ /** Series matching any of the selectors: `GET /loki/api/v1/series` (at least one matcher). */
1232
+ series(matchers: string | readonly string[], options?: SeriesOptions): Promise<Record<string, string>[]>;
1233
+ /**
1234
+ * Approximate index statistics: `GET /loki/api/v1/index/stats`. Reads the TSDB index only,
1235
+ * so data still in the ingester counts after the next chunk flush.
1236
+ */
1237
+ indexStats(query: string, options?: IndexOptions): Promise<LokiIndexStats>;
1238
+ /**
1239
+ * Ingested bytes per series or label: `GET /loki/api/v1/index/volume` (vector result).
1240
+ * Needs `limits_config.volume_enabled: true`; otherwise Loki returns an empty vector.
1241
+ */
1242
+ volume(query: string, options?: VolumeOptions): Promise<LokiQueryResult>;
1243
+ /**
1244
+ * Volume over time: `GET /loki/api/v1/index/volume_range`. Always a matrix: Loki answers
1245
+ * with a `vector` when every series has a single point, which is converted to one-sample
1246
+ * matrix series.
1247
+ */
1248
+ volumeRange(query: string, options?: VolumeRangeOptions): Promise<LokiQueryResult>;
1249
+ /** Normalizes a LogQL query on the server (`GET /loki/api/v1/format_query`). */
1250
+ formatQuery(logql: string, options?: CallOptions): Promise<string>;
1251
+ /**
1252
+ * Live tail over WebSocket (`/loki/api/v1/tail`). Resolves once connected; handshake errors
1253
+ * reject (`AuthenticationError`, `ValidationError`, …). `onEntries` receives the streams of
1254
+ * every frame; dropped entries go to `onDropped`, later errors to `onError`. Only log queries
1255
+ * (starting with `{`) are allowed. Stop with `handle.stop()` or `close()`.
1256
+ * Proxies are not used for the WebSocket.
1257
+ */
1258
+ tail(logql: string, onEntries: (streams: LokiStreamResult[], frame: LokiTailFrame) => void, options?: LiveTailOptions): Promise<LokiTail>;
1259
+ /**
1260
+ * A batching {@link LogClient} that writes to this Loki (and tenant). Records go through
1261
+ * redaction and the cardinality guard; `protocol: "otlp"` uses `/otlp/v1/logs` instead.
1262
+ * {@link close} flushes and closes every log client created here.
1263
+ */
1264
+ logClient(options?: LokiLogClientOptions): BatchingLogClient;
1265
+ /** A {@link LogQueryClient} (search, tail, listStreams, listLabels, waitForLog) on this Loki. */
1266
+ logQueryClient(): LokiLogQueryClient;
1267
+ /**
1268
+ * Flushes and closes log clients created by {@link logClient}, stops open tails and releases
1269
+ * connections (children from {@link withTenant} leave the shared connections open).
1270
+ * Idempotent.
1271
+ */
1272
+ close(): Promise<void>;
1273
+ }
1274
+
1275
+ /** Selector / label-filter operators for string values. */
1276
+ type MatchOperator = "=" | "!=" | "=~" | "!~";
1277
+ /** Numeric label-filter operators. */
1278
+ type NumericOperator = "==" | "!=" | ">" | ">=" | "<" | "<=";
1279
+ /**
1280
+ * Quotes a LogQL string literal with Go/JSON escaping (`"`, `\`, newlines, tabs; Unicode stays
1281
+ * as is). Verified against Loki 3.7 (`format_query` and round trips).
1282
+ */
1283
+ declare function quoteLogQL(value: string): string;
1284
+ /**
1285
+ * Immutable LogQL builder. Every method returns a new builder.
1286
+ *
1287
+ * ```ts
1288
+ * LogQL.selector({ app: "x" }).lineContains("err").json().where("status", ">=", 500).toString()
1289
+ * // {app="x"} |= "err" | json | status >= 500
1290
+ * ```
1291
+ */
1292
+ declare class LogQL {
1293
+ #private;
1294
+ private constructor();
1295
+ /** Starts a query from equality matchers (`{app="x", env="prod"}`). */
1296
+ static selector(labels?: Readonly<Record<string, string>>): LogQL;
1297
+ /** Quotes a string literal (see {@link quoteLogQL}). */
1298
+ static quote(value: string): string;
1299
+ /** Adds a stream-selector matcher (`=`, `!=`, `=~`, `!~`). */
1300
+ label(name: string, op: MatchOperator, value: string): LogQL;
1301
+ /** Line filter `|= "text"` (case-sensitive substring). */
1302
+ lineContains(text: string): LogQL;
1303
+ /** Line filter `!= "text"`. */
1304
+ lineNotContains(text: string): LogQL;
1305
+ /** Line filter `|~ "regex"` (RE2; prefix `(?i)` for case-insensitive). */
1306
+ lineMatches(regex: string): LogQL;
1307
+ /** Line filter `!~ "regex"`. */
1308
+ lineNotMatches(regex: string): LogQL;
1309
+ /** Parser stage `| json`. */
1310
+ json(): LogQL;
1311
+ /** Parser stage `| logfmt`. */
1312
+ logfmt(): LogQL;
1313
+ /** Parser stage `| unpack` (lines packed by Promtail's `pack` stage). */
1314
+ unpack(): LogQL;
1315
+ /** Parser stage `| regexp "<re>"` with named capture groups. */
1316
+ regexp(pattern: string): LogQL;
1317
+ /** Parser stage `| pattern "<pattern>"`. */
1318
+ pattern(pattern: string): LogQL;
1319
+ /** Formatting stage `| line_format "<template>"`. */
1320
+ lineFormat(template: string): LogQL;
1321
+ /**
1322
+ * Label filter on an extracted label or structured-metadata key. Numbers use the numeric
1323
+ * operators (`==`, `!=`, `>`, `>=`, `<`, `<=`); strings use `=`, `!=`, `=~`, `!~`.
1324
+ */
1325
+ where(field: string, op: MatchOperator | NumericOperator, value: string | number): LogQL;
1326
+ /** Appends a raw pipeline stage (`| <stage>`, e.g. `drop level`); the text is not escaped. */
1327
+ pipe(stage: string): LogQL;
1328
+ /**
1329
+ * Renders the query. Throws `ValidationError` when the selector is empty or every matcher
1330
+ * also matches the empty string (Loki rejects such selectors).
1331
+ */
1332
+ toString(): string;
1333
+ /** Same as {@link toString}. */
1334
+ build(): string;
1335
+ }
1336
+
1337
+ /** Encodes streams as an (uncompressed) Loki `PushRequest` protobuf message. */
1338
+ declare function encodePushRequest(streams: readonly LokiStream[]): Uint8Array;
1339
+ /** Snappy block compression (not the framed format), as `/loki/api/v1/push` expects. */
1340
+ declare function snappyCompress(data: Uint8Array): Uint8Array;
1341
+ /**
1342
+ * Extracts the message (field 2) of a protobuf `google.rpc.Status` body, which Loki returns
1343
+ * for OTLP errors. Returns `undefined` when the bytes do not look like one.
1344
+ */
1345
+ declare function decodeRpcStatusMessage(bytes: Uint8Array): string | undefined;
1346
+
1347
+ export { ALL_STREAMS_SELECTOR, AttrValue, Attributes, BaseLogQueryClient, BatchingLogClient, BatchingLogClientOptions, CardinalityGuard, DEFAULT_ALLOWED_LABELS, DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, ENCODING_FLAGS_HEADER, EnvReader, ExportOptions, ExportResult, HealthStatus, HttpTransport, LABEL_NAME_PATTERN, LANGUAGE, LogClient, LogExporter, LogQL, LogRecord, LogSearchOptions, LogSearchResult, LokiClient, LokiConfig, LokiError, LokiLogExporter, LokiLogQueryClient, LokiOtlpExporter, MAX_QUERY_LIMIT, MAX_TENANT_ID_LENGTH, MAX_VENDOR_TEXT, MIN_SECRET_LENGTH, OTLP_SCOPE_NAME, PACKAGE_KEY, REDACTED, RESERVED_METADATA_KEYS, RetryPolicy, SDK_KIT_VERSION, SDK_VERSION, SENSITIVE_FIELD_PARTS, Secret, Severity, TENANT_HEADER, TailHandle, TailOptions, VENDOR_ENV, WinstonTransport, attrToString, createDispatcher, createPinoTransport, dateToNanos, decodeBuildInfo, decodeCursor, decodeEntry, decodeIndexStats, decodeQueryResult, decodeRpcStatusMessage, decodeSeries, decodeStreams, decodeStringList, decodeTailFrame, definedOnly, describeCommonConfig, encodeCursor, encodePushRequest, entryToLogRecord, formatLabelSet, isIdempotentMethod, isRetryableStatus, isSensitiveField, isSensitiveHeader, isValidLabelName, logRecordByteSize, logRecordFromJson, logRecordToJson, mergeOptions, mergeStreams, msToDuration, nanosToDate, normalizeLabelName, optionalNanos, parseBool, parseDuration, parseInteger, parseLogRecord, parseRetryAfter, pinoLevelToSeverity, pinoLineToRecord, pollUntil, quoteLogQL, readCommonEnv, recordsToOtlpJson, recordsToStreams, redactError, redactFields, redactHeaders, redactSecretsInText, redactText, redactUrl, resolveCommonConfig, safeCall, safeLogger, secondsToDate, secretValues, serializeLogRecord, silentLogger, sleep, snappyCompress, stringMap, tenantIdProblem, throwIfAborted, toAttrValue, toAttributes, toNanos, toOtlpValue, toSearchLogQL, validateCommonConfig, validateLabelName, validateLabels, winstonLevelToSeverity };
1348
+ export type { CallOptions, CardinalityGuardOptions, ClientInternals, ClientLogger, CommonConfig, CommonConfigOptions, CommonVendorEnv, Direction, EnvHit, EnvMap, ErrorClassifier, ErrorInfo, ErrorResponse, HeadersInput, Hooks, IndexOptions, KnownSecret, LabelsOptions, LiveTailOptions, LogFields, LogRecordJson, LokiBuildInfo, LokiClientShared, LokiConfigOptions, LokiDroppedEntry, LokiEntry, LokiEntryResult, LokiIndexStats, LokiLogClientOptions, LokiLogExporterOptions, LokiMatrixSeries, LokiPusher, LokiQueryResult, LokiQuerySource, LokiResultType, LokiSample, LokiStream, LokiStreamResult, LokiTail, LokiTailFrame, LokiTime, LokiVectorSample, MatchOperator, MergedEntry, NumericOperator, OtlpAnyValue, OtlpKeyValue, OtlpPushOptions, PinoTransportOptions, PollOptions, PushFormat, PushOptions, QueryOptions, QueryRangeOptions, QueryValue, RequestInfo, RequestOptions, ResponseInfo, ResponseType, RetryPolicyOptions, SeriesOptions, TailCallbacks, TimeRangeOptions, TlsOptions, TransportOptions, TransportResponse, VolumeOptions, VolumeRangeOptions, WinstonInfo, WinstonTransportOptions };