@aj-2000-test/goodlogs-sdk 0.1.20 → 0.3.0

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/dist/index.d.cts CHANGED
@@ -1,102 +1,290 @@
1
- type Severity = "debug" | "info" | "warn" | "error" | "fatal";
2
- interface GoodLogsOptions {
3
- /** API key (gl_sk_... for logs, gl_pk_... for events only) */
1
+ import { G as GoodLogs } from './client-w3t1Yzjd.cjs';
2
+ export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-w3t1Yzjd.cjs';
3
+
4
+ interface LogRecord {
5
+ id: number;
6
+ severity: string;
7
+ message: string;
8
+ properties: Record<string, unknown>;
9
+ timestamp: string;
10
+ }
11
+ interface GqlResult {
12
+ query: string;
13
+ data: unknown[];
14
+ columns?: string[];
15
+ source?: string;
16
+ error?: string;
17
+ }
18
+ interface GqlBatchResult {
19
+ status: "ok" | "error";
20
+ query?: unknown;
21
+ data?: unknown;
22
+ error?: string;
23
+ }
24
+ interface GqlAutocompleteResult {
25
+ suggestions: string[];
26
+ valid: boolean;
27
+ error?: string;
28
+ parsed?: Record<string, unknown>;
29
+ }
30
+ interface Nl2GqlResult {
31
+ gql: string;
32
+ valid: boolean;
33
+ error?: string;
34
+ parsed?: Record<string, unknown>;
35
+ }
36
+ interface SchemaField {
37
+ name: string;
38
+ type: string;
39
+ count?: number;
40
+ }
41
+ interface SchemaResponse {
42
+ events: SchemaField[];
43
+ properties: SchemaField[];
44
+ log_properties: SchemaField[];
45
+ [key: string]: unknown;
46
+ }
47
+ interface AlertRule {
48
+ id: string;
49
+ project_id: string;
50
+ name: string;
51
+ metric: string;
52
+ alert_type: string;
53
+ status: string;
54
+ severity: string;
55
+ threshold: number;
56
+ window_minutes: number;
57
+ cooldown_minutes: number;
58
+ notify_email: boolean;
59
+ webhook_url?: string;
60
+ enabled: boolean;
61
+ pattern?: string;
62
+ change_percent?: number;
63
+ muted_until?: string;
64
+ message_template?: string;
65
+ notify_channels: NotifyChannel[];
66
+ last_triggered_at?: string;
67
+ last_value?: number;
68
+ anomaly_sigma?: number;
69
+ composite_rules: string[];
70
+ composite_operator?: string;
71
+ created_at: string;
72
+ updated_at: string;
73
+ }
74
+ interface NotifyChannel {
75
+ type: string;
76
+ url?: string;
77
+ to?: string;
78
+ secret?: string;
79
+ }
80
+ interface CreateAlertRule {
81
+ name: string;
82
+ metric: string;
83
+ threshold: number;
84
+ window_minutes?: number;
85
+ notify_email?: boolean;
86
+ webhook_url?: string;
87
+ alert_type?: string;
88
+ pattern?: string;
89
+ change_percent?: number;
90
+ message_template?: string;
91
+ notify_channels?: NotifyChannel[];
92
+ severity?: string;
93
+ cooldown_minutes?: number;
94
+ anomaly_sigma?: number;
95
+ composite_rules?: string[];
96
+ composite_operator?: string;
97
+ }
98
+ interface UpdateAlertRule {
99
+ name?: string;
100
+ metric?: string;
101
+ threshold?: number;
102
+ window_minutes?: number;
103
+ notify_email?: boolean;
104
+ webhook_url?: string;
105
+ enabled?: boolean;
106
+ pattern?: string;
107
+ change_percent?: number;
108
+ message_template?: string;
109
+ notify_channels?: NotifyChannel[];
110
+ severity?: string;
111
+ cooldown_minutes?: number;
112
+ anomaly_sigma?: number;
113
+ }
114
+ interface MuteAlertRequest {
115
+ minutes: number;
116
+ }
117
+ interface SloDefinition {
118
+ id: string;
119
+ project_id: string;
120
+ name: string;
121
+ description?: string;
122
+ metric: string;
123
+ status: string;
124
+ target_percent: number;
125
+ threshold?: number;
126
+ window_days: number;
127
+ current_percent?: number;
128
+ budget_remaining?: number;
129
+ budget_burn_rate?: number;
130
+ enabled: boolean;
131
+ created_at: string;
132
+ updated_at: string;
133
+ }
134
+ interface CreateSlo {
135
+ name: string;
136
+ description?: string;
137
+ metric?: string;
138
+ target_percent?: number;
139
+ threshold?: number;
140
+ window_days?: number;
141
+ }
142
+ interface UpdateSlo {
143
+ name?: string;
144
+ description?: string;
145
+ target_percent?: number;
146
+ threshold?: number;
147
+ window_days?: number;
148
+ enabled?: boolean;
149
+ }
150
+ interface AiChatRequest {
151
+ message: string;
152
+ session_id?: string;
153
+ }
154
+ interface AiChatResponse {
155
+ reply: string;
156
+ session_id: string;
157
+ tool_calls?: AiToolCall[];
158
+ }
159
+ interface AiToolCall {
160
+ tool: string;
161
+ input: Record<string, unknown>;
162
+ result: unknown;
163
+ }
164
+ interface ProjectInfo {
165
+ project: {
166
+ id: string;
167
+ name: string;
168
+ slug: string;
169
+ region: string;
170
+ };
171
+ org: {
172
+ id: string;
173
+ name: string;
174
+ plan: string;
175
+ };
176
+ usage?: Record<string, unknown>;
177
+ keys?: {
178
+ count: number;
179
+ };
180
+ }
181
+ interface GoodLogsClientOptions {
182
+ /** Secret API key (gl_sk_...) — required for all read/write operations */
4
183
  apiKey: string;
5
184
  /** API endpoint (default: auto-resolved from API key region) */
6
185
  endpoint?: string;
7
- /** Flush interval in ms (default: 5000) */
8
- flushInterval?: number;
9
- /** Max batch size before auto-flush (default: 50) */
10
- batchSize?: number;
11
- /** Default context merged into every log/event */
12
- defaultContext?: Record<string, unknown>;
13
- /** Called on flush errors */
14
- onError?: (error: Error) => void;
15
- /** Disable SDK (useful for tests) */
16
- disabled?: boolean;
17
- /** Send SDK diagnostics to platform logs (default: true) */
18
- telemetry?: boolean;
19
- /** Auto-capture click events on elements with data-gl-event attribute (default: true in browser) */
20
- autocapture?: boolean;
21
- }
22
- interface LogEntry {
23
- severity: Severity;
24
- message: string;
25
- properties?: Record<string, unknown>;
26
- timestamp?: string;
27
- }
28
- interface EventEntry {
29
- event: string;
30
- distinctId?: string;
31
- properties?: Record<string, unknown>;
32
- timestamp?: string;
186
+ /** Request timeout in ms (default: 30000) */
187
+ timeout?: number;
33
188
  }
34
189
 
35
- declare class GoodLogs {
36
- private apiKey;
37
- private endpoint;
38
- private flushInterval;
39
- private batchSize;
40
- private defaultContext;
41
- private onError;
42
- private disabled;
43
- private telemetry;
44
- private logBuffer;
45
- private eventBuffer;
46
- private timer;
47
- private visibilityHandler;
48
- private clickHandler;
49
- private lastPath;
50
- private anonymousId;
51
- private sessionId;
52
- constructor(options: GoodLogsOptions);
53
- log(severity: Severity, message: string, properties?: Record<string, unknown>): void;
54
- debug(message: string, properties?: Record<string, unknown>): void;
55
- info(message: string, properties?: Record<string, unknown>): void;
56
- warn(message: string, properties?: Record<string, unknown>): void;
57
- error(message: string, properties?: Record<string, unknown>): void;
58
- fatal(message: string, properties?: Record<string, unknown>): void;
59
- /** Set the user ID for all subsequent events. Replaces the anonymous ID. */
60
- identify(userId: string): void;
61
- /** Get the current anonymous/user ID. */
62
- getDistinctId(): string;
63
- /** Reset identity generates a new anonymous ID (e.g., on logout). */
64
- reset(): void;
65
- /** Get the current session ID. */
66
- getSessionId(): string;
67
- /** Start a new session (e.g., on navigation reset). */
68
- newSession(): void;
69
- /** Set a specific session ID. */
70
- setSessionId(id: string): void;
71
- track(event: string, properties?: Record<string, unknown> & {
72
- distinctId?: string;
73
- }): void;
74
- flush(): Promise<void>;
75
- /** Flush remaining data and stop the timer */
76
- shutdown(): Promise<void>;
77
- private sendLogs;
78
- private sendEvents;
79
- private postWithRetry;
80
- private startTimer;
81
- private stopTimer;
190
+ /**
191
+ * GoodLogs programmatic API client.
192
+ *
193
+ * Provides typed access to all /v1 read & write endpoints:
194
+ * analytics, logs, GQL queries, alerts, SLOs, AI chat, and schema.
195
+ *
196
+ * Requires a **secret** API key (`gl_sk_...`) with appropriate scopes.
197
+ *
198
+ * ```ts
199
+ * import { GoodLogsClient } from "@aj-2000-test/goodlogs-sdk";
200
+ *
201
+ * const client = new GoodLogsClient({ apiKey: "gl_sk_us_..." });
202
+ *
203
+ * // Query logs
204
+ * const { logs, total } = await client.logs.list({ severity: "error", limit: 10 });
205
+ *
206
+ * // Run GQL query
207
+ * const result = await client.gql("count | where severity = 'error' | last 1h");
208
+ *
209
+ * // Manage alerts
210
+ * const alerts = await client.alerts.list();
211
+ * await client.alerts.create({ name: "High Errors", metric: "error_count", threshold: 100 });
212
+ * ```
213
+ */
214
+ declare class GoodLogsClient {
215
+ private readonly endpoint;
216
+ private readonly apiKey;
217
+ private readonly timeout;
218
+ /** Alert CRUD methods */
219
+ readonly alerts: AlertsApi;
220
+ /** SLO CRUD methods */
221
+ readonly slos: SlosApi;
222
+ /** AI chat methods */
223
+ readonly ai: AiApi;
224
+ constructor(options: GoodLogsClientOptions);
225
+ /** @internal */
226
+ _request<T>(method: string, path: string, body?: unknown): Promise<T>;
227
+ /** @internal */
228
+ _get<T>(path: string): Promise<T>;
229
+ /** @internal */
230
+ _post<T>(path: string, body?: unknown): Promise<T>;
231
+ /** @internal */
232
+ _put<T>(path: string, body?: unknown): Promise<T>;
233
+ /** @internal */
234
+ _delete<T>(path: string): Promise<T>;
235
+ /** Get project info, org, usage, and key count */
236
+ info(): Promise<ProjectInfo>;
237
+ /** Get full schema (event names, property fields, log properties) */
238
+ schema(): Promise<SchemaResponse>;
239
+ /** Run a single GQL query */
240
+ gql(query: string): Promise<GqlResult>;
82
241
  /**
83
- * In browsers: flush via fetch+keepalive when page goes hidden or closes.
84
- * keepalive lets the request complete even after the page unloads,
85
- * while still supporting custom headers (unlike sendBeacon).
242
+ * Run multiple GQL queries in a single request.
243
+ * Returns an array of results (same index as input).
244
+ * Each result has `status: "ok"` with `data`, or `status: "error"` with `error`.
86
245
  */
87
- private attachPageLifecycle;
88
- /** Auto-capture Core Web Vitals using PerformanceObserver */
89
- private captureWebVitals;
90
- /** Auto-capture page views on route changes (SPA-aware via History API) */
91
- private attachPageviewCapture;
92
- /** Auto-capture clicks on elements with text content or data-gl-event */
93
- private attachClickCapture;
94
- private detachClickCapture;
95
- private detachPageLifecycle;
96
- /** Fire-and-forget flush using fetch with keepalive — survives page unload */
97
- private keepaliveFlush;
98
- /** Fire-and-forget telemetry to platform logs. Never throws, never recurses. */
99
- private sendTelemetry;
246
+ gqlBatch(queries: string[]): Promise<GqlBatchResult[]>;
247
+ /** Get GQL autocomplete suggestions */
248
+ gqlAutocomplete(query: string, cursor?: number): Promise<GqlAutocompleteResult>;
249
+ /** Convert natural language to GQL */
250
+ nl2gql(prompt: string, mode?: string): Promise<Nl2GqlResult>;
251
+ }
252
+ declare class AlertsApi {
253
+ private client;
254
+ constructor(client: GoodLogsClient);
255
+ /** List all alert rules */
256
+ list(): Promise<AlertRule[]>;
257
+ /** Create a new alert rule */
258
+ create(rule: CreateAlertRule): Promise<AlertRule>;
259
+ /** Update an alert rule */
260
+ update(alertId: string, rule: UpdateAlertRule): Promise<AlertRule>;
261
+ /** Delete an alert rule */
262
+ delete(alertId: string): Promise<void>;
263
+ /** Mute an alert for N minutes */
264
+ mute(alertId: string, minutes: number): Promise<void>;
265
+ }
266
+ declare class SlosApi {
267
+ private client;
268
+ constructor(client: GoodLogsClient);
269
+ /** List all SLO definitions */
270
+ list(): Promise<SloDefinition[]>;
271
+ /** Create a new SLO */
272
+ create(slo: CreateSlo): Promise<SloDefinition>;
273
+ /** Update an SLO */
274
+ update(sloId: string, slo: UpdateSlo): Promise<SloDefinition>;
275
+ /** Delete an SLO */
276
+ delete(sloId: string): Promise<void>;
277
+ }
278
+ declare class AiApi {
279
+ private client;
280
+ constructor(client: GoodLogsClient);
281
+ /** Send a message to AI chat */
282
+ chat(message: string, sessionId?: string): Promise<AiChatResponse>;
283
+ }
284
+ declare class GoodLogsApiError extends Error {
285
+ readonly status: number;
286
+ readonly code?: string | undefined;
287
+ constructor(status: number, message: string, code?: string | undefined);
100
288
  }
101
289
 
102
290
  interface TelemetryEvent {
@@ -137,4 +325,154 @@ declare function resolveRegion(apiKey: string): string;
137
325
  /** Resolve API endpoint from key. User-provided endpoint always wins. */
138
326
  declare function resolveEndpoint(apiKey: string, userEndpoint?: string): string;
139
327
 
140
- export { type EventEntry, GoodLogs, type GoodLogsOptions, type LogEntry, REGION_URLS, type Severity, type TelemetryEvent, type TelemetryOptions, resolveEndpoint, resolveRegion, sendTelemetry };
328
+ /**
329
+ * Node.js framework adapters for GoodLogs tracing.
330
+ *
331
+ * Each adapter accepts a GoodLogs client instance and returns a middleware /
332
+ * plugin / interceptor that starts a span per incoming request and finishes
333
+ * it when the response is sent. Adapters are structurally typed — we don't
334
+ * depend on express / fastify / @nestjs/common at runtime.
335
+ *
336
+ * All adapters honour W3C traceparent in incoming headers so multi-service
337
+ * traces stitch together.
338
+ */
339
+
340
+ /** A subset of Express's req/res shape we actually touch. */
341
+ interface ExpressReq {
342
+ method?: string;
343
+ url?: string;
344
+ originalUrl?: string;
345
+ route?: {
346
+ path?: string;
347
+ };
348
+ headers?: Record<string, string | string[] | undefined>;
349
+ }
350
+ interface ExpressRes {
351
+ statusCode?: number;
352
+ on(event: "finish" | "close", cb: () => void): void;
353
+ }
354
+ type ExpressNext = (err?: unknown) => void;
355
+ /** A subset of Fastify's request/reply shape. */
356
+ interface FastifyRequest {
357
+ method?: string;
358
+ url?: string;
359
+ routerPath?: string;
360
+ routeOptions?: {
361
+ url?: string;
362
+ };
363
+ headers?: Record<string, string | string[] | undefined>;
364
+ }
365
+ interface FastifyReply {
366
+ statusCode?: number;
367
+ raw?: {
368
+ statusCode?: number;
369
+ };
370
+ }
371
+ interface FastifyInstance {
372
+ addHook(name: "onRequest", fn: (req: FastifyRequest, reply: FastifyReply, done: () => void) => void): void;
373
+ addHook(name: "onResponse", fn: (req: FastifyRequest, reply: FastifyReply, done: () => void) => void): void;
374
+ }
375
+ /** Parse a W3C traceparent header: 00-<trace 32>-<parent 16>-<flags 2>. */
376
+ declare function parseTraceparent(h: string | undefined | null): {
377
+ trace_id: string;
378
+ parent_span_id: string;
379
+ } | null;
380
+ /**
381
+ * Express / Connect / Restify-compatible middleware.
382
+ *
383
+ * Usage:
384
+ * import express from "express";
385
+ * import { goodlogsExpress, GoodLogs } from "@goodlogs/sdk";
386
+ * const gl = new GoodLogs({ apiKey: "...", useEnvelope: true });
387
+ * const app = express();
388
+ * app.use(goodlogsExpress(gl));
389
+ */
390
+ declare function goodlogsExpress(gl: GoodLogs): (req: ExpressReq, res: ExpressRes, next: ExpressNext) => void;
391
+ /**
392
+ * Fastify plugin. Registers onRequest + onResponse hooks.
393
+ *
394
+ * Usage:
395
+ * import Fastify from "fastify";
396
+ * import { goodlogsFastify, GoodLogs } from "@goodlogs/sdk";
397
+ * const gl = new GoodLogs({ apiKey: "...", useEnvelope: true });
398
+ * const app = Fastify();
399
+ * app.register(goodlogsFastify(gl));
400
+ */
401
+ declare function goodlogsFastify(gl: GoodLogs): (fastify: FastifyInstance, _opts: unknown, done: () => void) => void;
402
+ /**
403
+ * NestJS interceptor.
404
+ *
405
+ * Usage:
406
+ * import { Module } from "@nestjs/common";
407
+ * import { goodlogsNestInterceptor, GoodLogs } from "@goodlogs/sdk";
408
+ * const gl = new GoodLogs({ apiKey: "...", useEnvelope: true });
409
+ * @Module({
410
+ * providers: [{ provide: APP_INTERCEPTOR, useValue: goodlogsNestInterceptor(gl) }],
411
+ * })
412
+ * export class AppModule {}
413
+ *
414
+ * The returned value is shaped like a NestInterceptor (`intercept(ctx, next)`).
415
+ * `next.handle()` must return a stream-like with `pipe()` — we use a small
416
+ * adapter so we don't depend on rxjs.
417
+ */
418
+ interface NestExecutionContext {
419
+ switchToHttp(): {
420
+ getRequest(): ExpressReq;
421
+ getResponse(): ExpressRes;
422
+ };
423
+ }
424
+ interface NestCallHandler {
425
+ handle(): {
426
+ subscribe?(observer: {
427
+ next?: (v: unknown) => void;
428
+ error?: (e: unknown) => void;
429
+ complete?: () => void;
430
+ }): {
431
+ unsubscribe?: () => void;
432
+ };
433
+ pipe?(...args: unknown[]): unknown;
434
+ };
435
+ }
436
+ declare function goodlogsNestInterceptor(gl: GoodLogs): {
437
+ intercept(ctx: NestExecutionContext, next: NestCallHandler): {
438
+ subscribe?(observer: {
439
+ next?: (v: unknown) => void;
440
+ error?: (e: unknown) => void;
441
+ complete?: () => void;
442
+ }): {
443
+ unsubscribe?: () => void;
444
+ };
445
+ pipe?(...args: unknown[]): unknown;
446
+ } | {
447
+ unsubscribe: () => void | undefined;
448
+ };
449
+ };
450
+ /** Hook process.on("uncaughtException") and ("unhandledRejection") so
451
+ * uncaught failures become captureException entries before the process
452
+ * exits. Idempotent via a Symbol.for marker.
453
+ *
454
+ * Important: uncaughtException is, by design, *terminal*. Node will exit
455
+ * after our handler returns unless someone else also subscribed. We flush
456
+ * synchronously on a best-effort basis (gl.flush returns a Promise — we
457
+ * schedule a microtask via setImmediate to give the envelope POST a chance
458
+ * to land before Node tears down). */
459
+ declare function instrumentNodeProcess(gl: GoodLogs): void;
460
+
461
+ /**
462
+ * Patch Node's built-in `http` and `https` modules so every outgoing request
463
+ * becomes an `op:http.client` span and injects W3C traceparent. Mirrors what
464
+ * the browser SDK does for `fetch` automatically.
465
+ *
466
+ * Usage:
467
+ * import { instrumentNodeHttp, GoodLogs } from "@goodlogs/sdk";
468
+ * const gl = new GoodLogs({ apiKey: "...", useEnvelope: true });
469
+ * instrumentNodeHttp(gl); // call once on startup
470
+ *
471
+ * Idempotent: calling twice is a no-op.
472
+ */
473
+
474
+ declare function instrumentNodeHttp(gl: GoodLogs, opts?: {
475
+ endpoint?: string;
476
+ }): void;
477
+
478
+ export { type AiChatRequest, type AiChatResponse, type AiToolCall, type AlertRule, type CreateAlertRule, type CreateSlo, GoodLogs, GoodLogsApiError, GoodLogsClient, type GoodLogsClientOptions, type GqlAutocompleteResult, type GqlBatchResult, type GqlResult, type LogRecord, type MuteAlertRequest, type Nl2GqlResult, type NotifyChannel, type ProjectInfo, REGION_URLS, type SchemaField, type SchemaResponse, type SloDefinition, type TelemetryEvent, type TelemetryOptions, type UpdateAlertRule, type UpdateSlo, goodlogsExpress, goodlogsFastify, goodlogsNestInterceptor, instrumentNodeHttp, instrumentNodeProcess, parseTraceparent, resolveEndpoint, resolveRegion, sendTelemetry };