zlient 3.1.0 → 3.2.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/README.md CHANGED
@@ -16,6 +16,7 @@ Build robust, type-safe API clients with runtime validation, retry logic, and ze
16
16
  - **Runtime Validation**: Validate requests, responses, query params, and path params.
17
17
  - **Resilience**: Built-in exponential backoff retries and timeouts.
18
18
  - **Auth**: Logic-safe authentication providers (Bearer, API Key, Custom).
19
+ - **Real-Time**: Type-safe WebSockets and Server-Sent Events (SSE).
19
20
  - **Observability**: Hooks for structured logging and metrics.
20
21
 
21
22
  ---
@@ -233,6 +234,34 @@ const client = new HttpClient({
233
234
  });
234
235
  ```
235
236
 
237
+ ### Real-Time (WebSockets & SSE)
238
+
239
+ Zlient makes real-time communication as simple as HTTP requests.
240
+
241
+ #### **WebSockets**
242
+ ```typescript
243
+ const chatWs = client.createWebSocket({
244
+ path: '/chat',
245
+ send: z.object({ text: z.string() }),
246
+ receive: z.object({ user: z.string(), text: z.string() }),
247
+ });
248
+
249
+ const socket = chatWs();
250
+ socket.on('message', (data) => console.log(data.text));
251
+ socket.send({ text: 'Hello!' });
252
+ ```
253
+
254
+ #### **SSE**
255
+ ```typescript
256
+ const stream = client.createSSE({
257
+ path: '/events',
258
+ response: z.object({ type: z.string(), value: z.number() }),
259
+ });
260
+
261
+ const sse = stream();
262
+ sse.on('message', (data) => console.log(data.value));
263
+ ```
264
+
236
265
  ---
237
266
 
238
267
  ## Migration from v2
@@ -251,7 +280,7 @@ v3 introduces Standard Schema support. Key changes:
251
280
 
252
281
  ## Documentation
253
282
 
254
- 📖 [Full Documentation](https://zlient.dev)
283
+ 📖 [Full Documentation](https://emirhangumus.github.io/zlient/)
255
284
 
256
285
  ---
257
286
 
@@ -1,6 +1,6 @@
1
1
  import type { AuthProvider } from '../auth';
2
- import { EndpointCall, EndpointConfig } from '../endpoint/base-endpoint';
3
- import { ClientOptions, HTTPMethod, HTTPStatusCodeNumber, RequestOptions, ResponseSchema, StandardSchemaV1 } from '../types';
2
+ import { ClientOptions, HTTPMethod, HTTPStatusCodeNumber, RequestOptions, ResponseSchema, SSEEndpointCall, SSEEndpointConfig, StandardSchemaV1, WSEndpointCall, WSEndpointConfig } from '../types';
3
+ import { EndpointCall, EndpointConfig } from './http-endpoint';
4
4
  /**
5
5
  * HTTP client with built-in authentication, and interceptors.
6
6
  * Supports multiple base URLs, type-safe requests, and comprehensive error handling.
@@ -179,5 +179,19 @@ export declare class HttpClient {
179
179
  * ```
180
180
  */
181
181
  createEndpoint<ResSchema extends ResponseSchema, ReqSchema extends StandardSchemaV1 | undefined = undefined, QuerySchema extends StandardSchemaV1 | undefined = undefined, PathSchema extends StandardSchemaV1 | undefined = undefined, MustHeaderKeys extends readonly string[] = readonly []>(config: EndpointConfig<ResSchema, ReqSchema, QuerySchema, PathSchema, MustHeaderKeys>): EndpointCall<ResSchema, ReqSchema, QuerySchema, PathSchema, MustHeaderKeys>;
182
+ /**
183
+ * Create a strongly-typed WebSocket endpoint builder.
184
+ *
185
+ * @param config - WebSocket endpoint configuration
186
+ * @returns WebSocket endpoint call function
187
+ */
188
+ createWebSocket<SendSchema extends StandardSchemaV1 | undefined = undefined, ReceiveSchema extends StandardSchemaV1 | undefined = undefined, QuerySchema extends StandardSchemaV1 | undefined = undefined, PathSchema extends StandardSchemaV1 | undefined = undefined>(config: WSEndpointConfig<SendSchema, ReceiveSchema, QuerySchema, PathSchema>): WSEndpointCall<SendSchema, ReceiveSchema, QuerySchema, PathSchema>;
189
+ /**
190
+ * Create a strongly-typed Server-Sent Events (SSE) endpoint builder.
191
+ *
192
+ * @param config - SSE endpoint configuration
193
+ * @returns SSE endpoint call function
194
+ */
195
+ createSSE<ResSchema extends StandardSchemaV1 | undefined = undefined, QuerySchema extends StandardSchemaV1 | undefined = undefined, PathSchema extends StandardSchemaV1 | undefined = undefined>(config: SSEEndpointConfig<ResSchema, QuerySchema, PathSchema>): SSEEndpointCall<ResSchema, QuerySchema, PathSchema>;
182
196
  }
183
197
  //# sourceMappingURL=http-client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"http-client.d.ts","sourceRoot":"","sources":["../../lib/http/http-client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAAE,YAAY,EAAE,cAAc,EAAgB,MAAM,2BAA2B,CAAC;AAGvF,OAAO,EAEL,aAAa,EAEb,UAAU,EACV,oBAAoB,EAEpB,cAAc,EACd,cAAc,EAEd,gBAAgB,EAEjB,MAAM,UAAU,CAAC;AAElB;;;;;;;;;;;;;;GAcG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,SAAS,CAAY;IAC7B,OAAO,CAAC,QAAQ,CAA4B;IAC5C,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,YAAY,CAAe;IACnC,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,SAAS,CAAC,CAAS;IAC3B,OAAO,CAAC,IAAI,CAAe;IAC3B,OAAO,CAAC,MAAM,CAAa;IAC3B,OAAO,CAAC,OAAO,CAAmB;IAClC,OAAO,CAAC,iBAAiB,CAAC,CAAqD;IAE/E;;;;;OAKG;gBACS,IAAI,EAAE,aAAa;IAsC/B;;;;;;;;OAQG;IACH,OAAO,CAAC,IAAI,EAAE,YAAY;IAI1B,OAAO,CAAC,cAAc;IAUtB;;;OAGG;YACW,cAAc;IAM5B;;;OAGG;YACW,aAAa;IAM3B;;;;OAIG;IACI,WAAW;IAIlB;;;;;OAKG;IACI,UAAU,CAAC,GAAG,EAAE,MAAM;IAI7B;;;;;;;;;;;;;;;;;OAiBG;IACG,OAAO,CAAC,CAAC,GAAG,OAAO,EACvB,MAAM,EAAE,MAAM,OAAO,UAAU,EAC/B,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,OAAO,EACd,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO,CAAC;QAAE,IAAI,EAAE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,SAAS,gBAAgB,GAAG,SAAS,GAAG,SAAS,EAC5D,UAAU,SAAS,gBAAgB,GAAG,SAAS,GAAG,SAAS,EAE3D,MAAM,EAAE,iBAAiB,CAAC,SAAS,EAAE,WAAW,EAAE,UAAU,CAAC,GAC5D,eAAe,CAAC,SAAS,EAAE,WAAW,EAAE,UAAU,CAAC;CAIvD"}
@@ -1,5 +1,5 @@
1
- import { HttpClient } from '../http/http-client';
2
1
  import { HTTPMethod, ResponseSchema, SchemaMap, StandardSchemaV1 } from '../types';
2
+ import { HttpClient } from './http-client';
3
3
  export type EndpointConfig<ResSchema extends ResponseSchema, ReqSchema extends StandardSchemaV1 | undefined = undefined, QuerySchema extends StandardSchemaV1 | undefined = undefined, PathSchema extends StandardSchemaV1 | undefined = undefined, MustHeaderKeys extends readonly string[] = readonly []> = {
4
4
  method: keyof typeof HTTPMethod;
5
5
  path: string | ((params: StandardSchemaV1.InferOutput<Exclude<PathSchema, undefined>>) => string);
@@ -41,4 +41,4 @@ export declare class EndpointImpl<ResSchema extends ResponseSchema, ReqSchema ex
41
41
  call(params: EndpointCallParams<ReqSchema, QuerySchema, PathSchema, MustHeaderKeys>): Promise<InferResponse<ResSchema>>;
42
42
  }
43
43
  export {};
44
- //# sourceMappingURL=base-endpoint.d.ts.map
44
+ //# sourceMappingURL=http-endpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-endpoint.d.ts","sourceRoot":"","sources":["../../lib/http/http-endpoint.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,cAAc,EAEd,SAAS,EACT,gBAAgB,EACjB,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,MAAM,MAAM,cAAc,CACxB,SAAS,SAAS,cAAc,EAChC,SAAS,SAAS,gBAAgB,GAAG,SAAS,GAAG,SAAS,EAC1D,WAAW,SAAS,gBAAgB,GAAG,SAAS,GAAG,SAAS,EAC5D,UAAU,SAAS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CACvB,SAAS,SAAS,cAAc,EAChC,SAAS,SAAS,gBAAgB,GAAG,SAAS,EAC9C,WAAW,SAAS,gBAAgB,GAAG,SAAS,EAChD,UAAU,SAAS,gBAAgB,GAAG,SAAS,EAC/C,cAAc,SAAS,SAAS,MAAM,EAAE,GAAG,SAAS,EAAE;IAGpD,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,MAAM;gBADN,MAAM,EAAE,UAAU,EAClB,MAAM,EAAE,cAAc,CAAC,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,cAAc,CAAC;IAGzF,IAAI,CACR,MAAM,EAAE,kBAAkB,CAAC,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,cAAc,CAAC,GAC7E,OAAO,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;CAsFrC"}
package/dist/index.cjs CHANGED
@@ -73,6 +73,179 @@ var BearerTokenAuth = class {
73
73
  }
74
74
  };
75
75
  //#endregion
76
+ //#region lib/logger.ts
77
+ /**
78
+ * Log levels for structured logging.
79
+ */
80
+ let LogLevel = /* @__PURE__ */ function(LogLevel) {
81
+ LogLevel["DEBUG"] = "debug";
82
+ LogLevel["INFO"] = "info";
83
+ LogLevel["WARN"] = "warn";
84
+ LogLevel["ERROR"] = "error";
85
+ return LogLevel;
86
+ }({});
87
+ /**
88
+ * Default console logger implementation.
89
+ * Formats log entries as JSON for easy parsing.
90
+ */
91
+ var ConsoleLogger = class {
92
+ constructor(minLevel = LogLevel.INFO) {
93
+ this.minLevel = minLevel;
94
+ }
95
+ log(entry) {
96
+ const levels = [
97
+ LogLevel.DEBUG,
98
+ LogLevel.INFO,
99
+ LogLevel.WARN,
100
+ LogLevel.ERROR
101
+ ];
102
+ if (levels.indexOf(entry.level) < levels.indexOf(this.minLevel)) return;
103
+ const output = {
104
+ ...entry,
105
+ error: entry.error ? {
106
+ message: entry.error.message,
107
+ stack: entry.error.stack,
108
+ name: entry.error.name
109
+ } : void 0
110
+ };
111
+ switch (entry.level) {
112
+ case LogLevel.DEBUG:
113
+ console.debug(JSON.stringify(output));
114
+ break;
115
+ case LogLevel.INFO:
116
+ console.info(JSON.stringify(output));
117
+ break;
118
+ case LogLevel.WARN:
119
+ console.warn(JSON.stringify(output));
120
+ break;
121
+ case LogLevel.ERROR:
122
+ console.error(JSON.stringify(output));
123
+ break;
124
+ }
125
+ }
126
+ };
127
+ /**
128
+ * No-op logger that discards all log entries.
129
+ * Use this in production if you don't want any logging.
130
+ */
131
+ var NoOpLogger = class {
132
+ log(_entry) {}
133
+ };
134
+ /**
135
+ * Utility class for creating structured log entries.
136
+ */
137
+ var LoggerUtil = class {
138
+ constructor(logger) {
139
+ this.logger = logger;
140
+ }
141
+ debug(message, context) {
142
+ this.logger.log({
143
+ level: LogLevel.DEBUG,
144
+ message,
145
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
146
+ context
147
+ });
148
+ }
149
+ info(message, context) {
150
+ this.logger.log({
151
+ level: LogLevel.INFO,
152
+ message,
153
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
154
+ context
155
+ });
156
+ }
157
+ warn(message, context) {
158
+ this.logger.log({
159
+ level: LogLevel.WARN,
160
+ message,
161
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
162
+ context
163
+ });
164
+ }
165
+ error(message, error, context) {
166
+ this.logger.log({
167
+ level: LogLevel.ERROR,
168
+ message,
169
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
170
+ context,
171
+ error
172
+ });
173
+ }
174
+ };
175
+ //#endregion
176
+ //#region lib/metrics.ts
177
+ /**
178
+ * No-op metrics collector that discards all metrics.
179
+ */
180
+ var NoOpMetricsCollector = class {
181
+ collect(_metrics) {}
182
+ };
183
+ /**
184
+ * In-memory metrics collector for testing and development.
185
+ * Stores metrics in memory with configurable retention.
186
+ */
187
+ var InMemoryMetricsCollector = class {
188
+ constructor(maxEntries = 1e3) {
189
+ this.metrics = [];
190
+ this.maxEntries = maxEntries;
191
+ }
192
+ collect(metrics) {
193
+ this.metrics.push(metrics);
194
+ if (this.metrics.length > this.maxEntries) this.metrics.shift();
195
+ }
196
+ /**
197
+ * Get all collected metrics.
198
+ */
199
+ getMetrics() {
200
+ return [...this.metrics];
201
+ }
202
+ /**
203
+ * Get metrics summary statistics.
204
+ */
205
+ getSummary() {
206
+ if (this.metrics.length === 0) return {
207
+ total: 0,
208
+ successful: 0,
209
+ failed: 0,
210
+ avgDurationMs: 0,
211
+ minDurationMs: 0,
212
+ maxDurationMs: 0
213
+ };
214
+ const successful = this.metrics.filter((m) => m.success).length;
215
+ let sum = 0;
216
+ let min = Infinity;
217
+ let max = -Infinity;
218
+ for (const m of this.metrics) {
219
+ const d = m.durationMs;
220
+ sum += d;
221
+ if (d < min) min = d;
222
+ if (d > max) max = d;
223
+ }
224
+ return {
225
+ total: this.metrics.length,
226
+ successful,
227
+ failed: this.metrics.length - successful,
228
+ avgDurationMs: sum / this.metrics.length,
229
+ minDurationMs: min === Infinity ? 0 : min,
230
+ maxDurationMs: max === -Infinity ? 0 : max
231
+ };
232
+ }
233
+ /**
234
+ * Clear all collected metrics.
235
+ */
236
+ clear() {
237
+ this.metrics = [];
238
+ }
239
+ };
240
+ /**
241
+ * Console-based metrics collector for debugging.
242
+ */
243
+ var ConsoleMetricsCollector = class {
244
+ collect(metrics) {
245
+ console.log("[METRICS]", JSON.stringify(metrics));
246
+ }
247
+ };
248
+ //#endregion
76
249
  //#region lib/types.ts
77
250
  const HTTPMethod = {
78
251
  GET: "GET",
@@ -322,7 +495,153 @@ function isStandardSchema(value) {
322
495
  return "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && schema["~standard"].version === 1 && typeof schema["~standard"].validate === "function";
323
496
  }
324
497
  //#endregion
325
- //#region lib/endpoint/base-endpoint.ts
498
+ //#region lib/sse/sse-client.ts
499
+ var SSEConnectionImpl = class {
500
+ constructor(url, responseSchema, skipResponseValidation = false, withCredentials = false) {
501
+ this.responseSchema = responseSchema;
502
+ this.skipResponseValidation = skipResponseValidation;
503
+ this.handlers = /* @__PURE__ */ new Map();
504
+ if (typeof EventSource === "undefined") throw new Error("EventSource is not defined. Ensure you are in a supported environment.");
505
+ this.es = new EventSource(url, { withCredentials });
506
+ this.es.onopen = (event) => this.emit("open", event);
507
+ this.es.onerror = (event) => this.emit("error", event);
508
+ this.es.onmessage = async (event) => {
509
+ let data = event.data;
510
+ try {
511
+ if (typeof data === "string") try {
512
+ data = JSON.parse(data);
513
+ } catch {}
514
+ if (!this.skipResponseValidation && this.responseSchema) data = await parseOrThrow(this.responseSchema, data);
515
+ this.emit("message", data);
516
+ } catch (error) {
517
+ this.emit("error", error);
518
+ }
519
+ };
520
+ }
521
+ on(event, handler) {
522
+ if (!this.handlers.has(event)) {
523
+ this.handlers.set(event, /* @__PURE__ */ new Set());
524
+ if (event !== "message" && event !== "open" && event !== "error") this.es.addEventListener(event, async (ev) => {
525
+ let data = ev.data;
526
+ try {
527
+ if (typeof data === "string") try {
528
+ data = JSON.parse(data);
529
+ } catch {}
530
+ if (!this.skipResponseValidation && this.responseSchema) data = await parseOrThrow(this.responseSchema, data);
531
+ this.emit(event, data);
532
+ } catch (error) {
533
+ this.emit("error", error);
534
+ }
535
+ });
536
+ }
537
+ this.handlers.get(event).add(handler);
538
+ }
539
+ off(event, handler) {
540
+ const handlers = this.handlers.get(event);
541
+ if (handlers) handlers.delete(handler);
542
+ }
543
+ emit(event, ...args) {
544
+ const handlers = this.handlers.get(event);
545
+ if (handlers) handlers.forEach((handler) => handler(...args));
546
+ }
547
+ close() {
548
+ this.es.close();
549
+ }
550
+ get readyState() {
551
+ return this.es.readyState;
552
+ }
553
+ };
554
+ //#endregion
555
+ //#region lib/sse/sse-endpoint.ts
556
+ var SSEEndpointImpl = class {
557
+ constructor(client, config) {
558
+ this.client = client;
559
+ this.config = config;
560
+ }
561
+ createCall() {
562
+ return (params) => {
563
+ const { query, pathParams } = params || {};
564
+ let pathStr;
565
+ if (typeof this.config.path === "function") {
566
+ if (!pathParams) throw new Error("Path function requires pathParams");
567
+ pathStr = this.config.path(pathParams);
568
+ } else pathStr = this.config.path;
569
+ return new SSEConnectionImpl(`${this.client.getBaseUrl(this.config.advanced?.baseUrlKey || "default")}${pathStr}${toQueryString(query)}`, this.config.response, this.config.advanced?.skipResponseValidation, this.config.advanced?.withCredentials);
570
+ };
571
+ }
572
+ };
573
+ //#endregion
574
+ //#region lib/ws/ws-client.ts
575
+ var WSConnectionImpl = class {
576
+ constructor(url, sendSchema, receiveSchema, skipRequestValidation = false, skipResponseValidation = false, protocols) {
577
+ this.sendSchema = sendSchema;
578
+ this.receiveSchema = receiveSchema;
579
+ this.skipRequestValidation = skipRequestValidation;
580
+ this.skipResponseValidation = skipResponseValidation;
581
+ this.handlers = /* @__PURE__ */ new Map();
582
+ if (typeof WebSocket === "undefined") throw new Error("WebSocket is not defined. Ensure you are in a supported environment.");
583
+ this.ws = new WebSocket(url, protocols);
584
+ this.ws.onopen = () => this.emit("open");
585
+ this.ws.onclose = (event) => this.emit("close", event);
586
+ this.ws.onerror = (event) => this.emit("error", event);
587
+ this.ws.onmessage = async (event) => {
588
+ let data = event.data;
589
+ try {
590
+ if (typeof data === "string") try {
591
+ data = JSON.parse(data);
592
+ } catch {}
593
+ if (!this.skipResponseValidation && this.receiveSchema) data = await parseOrThrow(this.receiveSchema, data);
594
+ this.emit("message", data);
595
+ } catch (error) {
596
+ this.emit("error", error);
597
+ }
598
+ };
599
+ }
600
+ async send(data) {
601
+ if (!this.skipRequestValidation && this.sendSchema) await parseOrThrow(this.sendSchema, data);
602
+ const message = data != null && typeof data === "object" ? JSON.stringify(data) : data;
603
+ this.ws.send(message);
604
+ }
605
+ on(event, handler) {
606
+ if (!this.handlers.has(event)) this.handlers.set(event, /* @__PURE__ */ new Set());
607
+ this.handlers.get(event).add(handler);
608
+ }
609
+ off(event, handler) {
610
+ const handlers = this.handlers.get(event);
611
+ if (handlers) handlers.delete(handler);
612
+ }
613
+ emit(event, ...args) {
614
+ const handlers = this.handlers.get(event);
615
+ if (handlers) handlers.forEach((handler) => handler(...args));
616
+ }
617
+ close(code, reason) {
618
+ this.ws.close(code, reason);
619
+ }
620
+ get readyState() {
621
+ return this.ws.readyState;
622
+ }
623
+ };
624
+ //#endregion
625
+ //#region lib/ws/ws-endpoint.ts
626
+ var WSEndpointImpl = class {
627
+ constructor(client, config) {
628
+ this.client = client;
629
+ this.config = config;
630
+ }
631
+ createCall() {
632
+ return (params) => {
633
+ const { query, pathParams, protocols } = params || {};
634
+ let pathStr;
635
+ if (typeof this.config.path === "function") {
636
+ if (!pathParams) throw new Error("Path function requires pathParams");
637
+ pathStr = this.config.path(pathParams);
638
+ } else pathStr = this.config.path;
639
+ return new WSConnectionImpl(`${this.client.getBaseUrl(this.config.advanced?.baseUrlKey || "default").replace(/^http/, "ws")}${pathStr}${toQueryString(query)}`, this.config.send, this.config.receive, this.config.advanced?.skipRequestValidation, this.config.advanced?.skipResponseValidation, protocols);
640
+ };
641
+ }
642
+ };
643
+ //#endregion
644
+ //#region lib/http/http-endpoint.ts
326
645
  var EndpointImpl = class {
327
646
  constructor(client, config) {
328
647
  this.client = client;
@@ -364,179 +683,6 @@ var EndpointImpl = class {
364
683
  }
365
684
  };
366
685
  //#endregion
367
- //#region lib/logger.ts
368
- /**
369
- * Log levels for structured logging.
370
- */
371
- let LogLevel = /* @__PURE__ */ function(LogLevel) {
372
- LogLevel["DEBUG"] = "debug";
373
- LogLevel["INFO"] = "info";
374
- LogLevel["WARN"] = "warn";
375
- LogLevel["ERROR"] = "error";
376
- return LogLevel;
377
- }({});
378
- /**
379
- * Default console logger implementation.
380
- * Formats log entries as JSON for easy parsing.
381
- */
382
- var ConsoleLogger = class {
383
- constructor(minLevel = LogLevel.INFO) {
384
- this.minLevel = minLevel;
385
- }
386
- log(entry) {
387
- const levels = [
388
- LogLevel.DEBUG,
389
- LogLevel.INFO,
390
- LogLevel.WARN,
391
- LogLevel.ERROR
392
- ];
393
- if (levels.indexOf(entry.level) < levels.indexOf(this.minLevel)) return;
394
- const output = {
395
- ...entry,
396
- error: entry.error ? {
397
- message: entry.error.message,
398
- stack: entry.error.stack,
399
- name: entry.error.name
400
- } : void 0
401
- };
402
- switch (entry.level) {
403
- case LogLevel.DEBUG:
404
- console.debug(JSON.stringify(output));
405
- break;
406
- case LogLevel.INFO:
407
- console.info(JSON.stringify(output));
408
- break;
409
- case LogLevel.WARN:
410
- console.warn(JSON.stringify(output));
411
- break;
412
- case LogLevel.ERROR:
413
- console.error(JSON.stringify(output));
414
- break;
415
- }
416
- }
417
- };
418
- /**
419
- * No-op logger that discards all log entries.
420
- * Use this in production if you don't want any logging.
421
- */
422
- var NoOpLogger = class {
423
- log(_entry) {}
424
- };
425
- /**
426
- * Utility class for creating structured log entries.
427
- */
428
- var LoggerUtil = class {
429
- constructor(logger) {
430
- this.logger = logger;
431
- }
432
- debug(message, context) {
433
- this.logger.log({
434
- level: LogLevel.DEBUG,
435
- message,
436
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
437
- context
438
- });
439
- }
440
- info(message, context) {
441
- this.logger.log({
442
- level: LogLevel.INFO,
443
- message,
444
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
445
- context
446
- });
447
- }
448
- warn(message, context) {
449
- this.logger.log({
450
- level: LogLevel.WARN,
451
- message,
452
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
453
- context
454
- });
455
- }
456
- error(message, error, context) {
457
- this.logger.log({
458
- level: LogLevel.ERROR,
459
- message,
460
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
461
- context,
462
- error
463
- });
464
- }
465
- };
466
- //#endregion
467
- //#region lib/metrics.ts
468
- /**
469
- * No-op metrics collector that discards all metrics.
470
- */
471
- var NoOpMetricsCollector = class {
472
- collect(_metrics) {}
473
- };
474
- /**
475
- * In-memory metrics collector for testing and development.
476
- * Stores metrics in memory with configurable retention.
477
- */
478
- var InMemoryMetricsCollector = class {
479
- constructor(maxEntries = 1e3) {
480
- this.metrics = [];
481
- this.maxEntries = maxEntries;
482
- }
483
- collect(metrics) {
484
- this.metrics.push(metrics);
485
- if (this.metrics.length > this.maxEntries) this.metrics.shift();
486
- }
487
- /**
488
- * Get all collected metrics.
489
- */
490
- getMetrics() {
491
- return [...this.metrics];
492
- }
493
- /**
494
- * Get metrics summary statistics.
495
- */
496
- getSummary() {
497
- if (this.metrics.length === 0) return {
498
- total: 0,
499
- successful: 0,
500
- failed: 0,
501
- avgDurationMs: 0,
502
- minDurationMs: 0,
503
- maxDurationMs: 0
504
- };
505
- const successful = this.metrics.filter((m) => m.success).length;
506
- let sum = 0;
507
- let min = Infinity;
508
- let max = -Infinity;
509
- for (const m of this.metrics) {
510
- const d = m.durationMs;
511
- sum += d;
512
- if (d < min) min = d;
513
- if (d > max) max = d;
514
- }
515
- return {
516
- total: this.metrics.length,
517
- successful,
518
- failed: this.metrics.length - successful,
519
- avgDurationMs: sum / this.metrics.length,
520
- minDurationMs: min === Infinity ? 0 : min,
521
- maxDurationMs: max === -Infinity ? 0 : max
522
- };
523
- }
524
- /**
525
- * Clear all collected metrics.
526
- */
527
- clear() {
528
- this.metrics = [];
529
- }
530
- };
531
- /**
532
- * Console-based metrics collector for debugging.
533
- */
534
- var ConsoleMetricsCollector = class {
535
- collect(metrics) {
536
- console.log("[METRICS]", JSON.stringify(metrics));
537
- }
538
- };
539
- //#endregion
540
686
  //#region lib/http/http-client.ts
541
687
  /**
542
688
  * HTTP client with built-in authentication, and interceptors.
@@ -897,6 +1043,24 @@ var HttpClient = class {
897
1043
  const endpoint = new EndpointImpl(this, config);
898
1044
  return (params) => endpoint.call(params);
899
1045
  }
1046
+ /**
1047
+ * Create a strongly-typed WebSocket endpoint builder.
1048
+ *
1049
+ * @param config - WebSocket endpoint configuration
1050
+ * @returns WebSocket endpoint call function
1051
+ */
1052
+ createWebSocket(config) {
1053
+ return new WSEndpointImpl(this, config).createCall();
1054
+ }
1055
+ /**
1056
+ * Create a strongly-typed Server-Sent Events (SSE) endpoint builder.
1057
+ *
1058
+ * @param config - SSE endpoint configuration
1059
+ * @returns SSE endpoint call function
1060
+ */
1061
+ createSSE(config) {
1062
+ return new SSEEndpointImpl(this, config).createCall();
1063
+ }
900
1064
  };
901
1065
  //#endregion
902
1066
  exports.ApiError = ApiError;
@@ -914,7 +1078,11 @@ exports.LoggerUtil = LoggerUtil;
914
1078
  exports.NoAuth = NoAuth;
915
1079
  exports.NoOpLogger = NoOpLogger;
916
1080
  exports.NoOpMetricsCollector = NoOpMetricsCollector;
1081
+ exports.SSEConnectionImpl = SSEConnectionImpl;
1082
+ exports.SSEEndpointImpl = SSEEndpointImpl;
917
1083
  exports.SchemaDefinitionError = SchemaDefinitionError;
1084
+ exports.WSConnectionImpl = WSConnectionImpl;
1085
+ exports.WSEndpointImpl = WSEndpointImpl;
918
1086
  exports.isStandardSchema = isStandardSchema;
919
1087
  exports.parseOrThrow = parseOrThrow;
920
1088
  exports.safeParse = safeParse;