@syswatch/core 1.0.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.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types"), exports);
18
+ __exportStar(require("./client"), exports);
package/jest.config.js ADDED
@@ -0,0 +1,6 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+ module.exports = {
3
+ preset: 'ts-jest',
4
+ testEnvironment: 'node',
5
+ testMatch: ['**/*.spec.ts'],
6
+ };
package/package.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "@syswatch/core",
3
+ "version": "1.0.0",
4
+ "main": "dist/index.js",
5
+ "types": "dist/index.d.ts",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "scripts": {
10
+ "build": "tsc"
11
+ },
12
+ "devDependencies": {
13
+ "typescript": "^5.0.0"
14
+ }
15
+ }
@@ -0,0 +1,164 @@
1
+ import { SysWatch } from "./client";
2
+ import { LogLevel } from "./types";
3
+ import { Logs } from "./logs";
4
+
5
+ // Mock global fetch
6
+ const mockFetch = jest.fn();
7
+ global.fetch = mockFetch;
8
+
9
+ describe("SysWatch", () => {
10
+ const apiKey = "test-api-key";
11
+ const defaultBaseUrl = "http://localhost:8080/v1";
12
+
13
+ beforeEach(() => {
14
+ mockFetch.mockClear();
15
+ mockFetch.mockResolvedValue({
16
+ ok: true,
17
+ json: async () => ({ success: true }),
18
+ });
19
+ });
20
+
21
+ describe("Constructor", () => {
22
+ it("should initialize with default base URL", () => {
23
+ const client = new SysWatch({ apiKey });
24
+ expect(client["baseUrl"]).toBe(defaultBaseUrl);
25
+ expect(client.log).toBeInstanceOf(Logs);
26
+ });
27
+
28
+ it("should store default meta and tags", () => {
29
+ const defaultMeta = { app: "test" };
30
+ const defaultTags = ["test-env"];
31
+ const client = new SysWatch({
32
+ apiKey,
33
+ defaultMeta,
34
+ defaultTags,
35
+ environment: "staging",
36
+ });
37
+
38
+ expect(client["defaultMeta"]).toEqual(defaultMeta);
39
+ expect(client["defaultTags"]).toEqual(defaultTags);
40
+ });
41
+ });
42
+
43
+ describe("sendLog (via log property)", () => {
44
+ let client: SysWatch;
45
+
46
+ beforeEach(() => {
47
+ client = new SysWatch({ apiKey });
48
+ });
49
+
50
+ it("should send info log", async () => {
51
+ await client.log.info("Info message", { meta: { foo: "bar" } });
52
+
53
+ expect(mockFetch).toHaveBeenCalledWith(
54
+ `${defaultBaseUrl}/logs`,
55
+ expect.objectContaining({
56
+ method: "POST",
57
+ headers: {
58
+ "Content-Type": "application/json",
59
+ "x-api-key": apiKey,
60
+ },
61
+ body: expect.stringContaining('"level":"INFO"'),
62
+ })
63
+ );
64
+
65
+ const call = mockFetch.mock.calls[0];
66
+ const body = JSON.parse(call[1].body);
67
+ expect(body.type).toBe("info");
68
+ expect(body.message).toBe("Info message");
69
+ expect(body.meta).toEqual({ foo: "bar" });
70
+ });
71
+
72
+ it("should send error log from Error object", async () => {
73
+ const error = new Error("Something went wrong");
74
+ error.stack = "Error stack trace";
75
+
76
+ await client.log.error("Failure", error);
77
+
78
+ const call = mockFetch.mock.calls[0];
79
+ const body = JSON.parse(call[1].body);
80
+ expect(body.level).toBe("ERROR");
81
+ expect(body.meta.error).toEqual({
82
+ name: "Error",
83
+ message: "Something went wrong",
84
+ stack: "Error stack trace",
85
+ });
86
+ });
87
+
88
+ it("should send error log from options object", async () => {
89
+ await client.log.error("Failure", { meta: { code: 500 } });
90
+
91
+ const call = mockFetch.mock.calls[0];
92
+ const body = JSON.parse(call[1].body);
93
+ expect(body.meta.code).toBe(500);
94
+ expect(body.level).toBe("ERROR");
95
+ });
96
+ });
97
+
98
+ describe("trackMetric", () => {
99
+ let client: SysWatch;
100
+
101
+ beforeEach(() => {
102
+ client = new SysWatch({ apiKey });
103
+ });
104
+
105
+ it("should send metric request correctly", async () => {
106
+ await client.trackMetric("cpu_usage", 80, "%");
107
+
108
+ expect(mockFetch).toHaveBeenCalledWith(`${defaultBaseUrl}/metrics`, {
109
+ method: "POST",
110
+ headers: {
111
+ "Content-Type": "application/json",
112
+ "x-api-key": apiKey,
113
+ },
114
+ body: expect.any(String),
115
+ });
116
+
117
+ const call = mockFetch.mock.calls[0];
118
+ const body = JSON.parse(call[1].body);
119
+ expect(body).toEqual({
120
+ type: "cpu_usage",
121
+ value: 80,
122
+ unit: "%",
123
+ meta: {},
124
+ tags: [],
125
+ });
126
+ });
127
+
128
+ it("should merge default meta and tags for metrics", async () => {
129
+ client = new SysWatch({
130
+ apiKey,
131
+ defaultMeta: { host: "server-1" },
132
+ defaultTags: ["prod"],
133
+ });
134
+
135
+ await client.trackMetric("memory", 1024, "MB", { tags: ["worker"] });
136
+
137
+ const call = mockFetch.mock.calls[0];
138
+ const body = JSON.parse(call[1].body);
139
+ expect(body.meta).toEqual({ host: "server-1" });
140
+ expect(body.tags).toEqual(["prod", "worker"]);
141
+ });
142
+ });
143
+
144
+ describe("Error Handling", () => {
145
+ let client: SysWatch;
146
+
147
+ beforeEach(() => {
148
+ client = new SysWatch({ apiKey });
149
+ });
150
+
151
+ it("should throw error when API returns non-200", async () => {
152
+ mockFetch.mockResolvedValue({
153
+ ok: false,
154
+ status: 401,
155
+ statusText: "Unauthorized",
156
+ text: async () => "Invalid API Key",
157
+ });
158
+
159
+ await expect(client.log.info("test")).rejects.toThrow(
160
+ "SysWatch API Error: 401 Unauthorized - Invalid API Key"
161
+ );
162
+ });
163
+ });
164
+ });
package/src/client.ts ADDED
@@ -0,0 +1,94 @@
1
+ import { Logs } from "./logs";
2
+ import { CreateLogDto, CreateMetricDto } from "./types";
3
+
4
+ export interface SysWatchConfig {
5
+ apiKey: string;
6
+ defaultMeta?: Record<string, any>;
7
+ defaultTags?: string[];
8
+ environment?: string;
9
+ }
10
+
11
+ export class SysWatch {
12
+ private apiKey: string;
13
+ private baseUrl: string;
14
+ private defaultMeta: Record<string, any>;
15
+ private defaultTags: string[];
16
+
17
+ public log: Logs;
18
+
19
+ constructor(config: SysWatchConfig) {
20
+ this.apiKey = config.apiKey;
21
+ this.baseUrl = "https://syswatchapp.discloud.app/v1";
22
+ this.defaultMeta = config.defaultMeta || {};
23
+ this.defaultTags = config.defaultTags || [];
24
+
25
+ if (this.baseUrl.endsWith("/")) {
26
+ this.baseUrl = this.baseUrl.slice(0, -1);
27
+ }
28
+
29
+ this.log = new Logs(this.sendLog.bind(this));
30
+ }
31
+
32
+ private async request(path: string, body: any) {
33
+ try {
34
+ const response = await fetch(`${this.baseUrl}${path}`, {
35
+ method: "POST",
36
+ headers: {
37
+ "Content-Type": "application/json",
38
+ "x-api-key": this.apiKey,
39
+ "user-agent": "NodeJS SysWatch SDK ",
40
+ },
41
+ body: JSON.stringify(body),
42
+ });
43
+
44
+ if (!response.ok) {
45
+ const errorText = await response.text();
46
+ throw new Error(
47
+ `SysWatch API Error: ${response.status} ${response.statusText} - ${errorText}`
48
+ );
49
+ }
50
+
51
+ return await response.json();
52
+ } catch (error) {
53
+ // Re-throw the error to let the caller handle it
54
+ throw error;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Send a log entry to SysWatch
60
+ * @param data Log data
61
+ */
62
+ async sendLog(data: CreateLogDto) {
63
+ const payload: CreateLogDto = {
64
+ ...data,
65
+ meta: { ...this.defaultMeta, ...data.meta },
66
+ tags: [...this.defaultTags, ...(data.tags || [])],
67
+ };
68
+ return this.request("/logs", payload);
69
+ }
70
+
71
+ /**
72
+ * Track a metric value
73
+ * @param type Metric type key
74
+ * @param value Metric value
75
+ * @param unit Unit of measurement (optional)
76
+ * @param options Additional options
77
+ */
78
+ async trackMetric(
79
+ type: string,
80
+ value: number,
81
+ unit?: string,
82
+ options?: Omit<CreateMetricDto, "type" | "value" | "unit">
83
+ ) {
84
+ const payload: CreateMetricDto = {
85
+ type,
86
+ value,
87
+ unit,
88
+ ...options,
89
+ meta: { ...this.defaultMeta, ...options?.meta },
90
+ tags: [...this.defaultTags, ...(options?.tags || [])],
91
+ };
92
+ return this.request("/metrics", payload);
93
+ }
94
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './types';
2
+ export * from './client';
package/src/logs.ts ADDED
@@ -0,0 +1,127 @@
1
+ import { CreateLogDto, LogLevel } from "./types";
2
+
3
+ type LogOptions = Omit<CreateLogDto, "level" | "message" | "type"> & {
4
+ type?: string;
5
+ };
6
+
7
+ export class Logs {
8
+ constructor(private sendLog: (log: CreateLogDto) => Promise<void>) {}
9
+
10
+ /**
11
+ * Send a DEBUG log
12
+ * @param message Log message
13
+ * @param options Additional options (meta, tags, etc.)
14
+ */
15
+ async debug(message: string, options?: LogOptions) {
16
+ return this.sendLog({
17
+ type: "debug",
18
+ level: LogLevel.DEBUG,
19
+ message,
20
+ ...options,
21
+ });
22
+ }
23
+
24
+ /**
25
+ * Send an INFO log
26
+ * @param message Log message
27
+ * @param options Additional options (meta, tags, etc.)
28
+ */
29
+ async info(message: string, options?: LogOptions) {
30
+ return this.sendLog({
31
+ type: "info",
32
+ level: LogLevel.INFO,
33
+ message,
34
+ ...options,
35
+ });
36
+ }
37
+
38
+ /**
39
+ * Send a SUCCESS log
40
+ * @param message Log message
41
+ * @param options Additional options (meta, tags, etc.)
42
+ */
43
+ async success(message: string, options?: LogOptions) {
44
+ return this.sendLog({
45
+ type: "success",
46
+ level: LogLevel.SUCCESS,
47
+ message,
48
+ ...options,
49
+ });
50
+ }
51
+ /**
52
+ * Send a FAILURE log
53
+ * @param message Log message
54
+ * @param options Additional options (meta, tags, etc.)
55
+ */
56
+ async failure(message: string, options?: LogOptions) {
57
+ return this.sendLog({
58
+ type: "failure",
59
+ level: LogLevel.FAILURE,
60
+ message,
61
+ ...options,
62
+ });
63
+ }
64
+
65
+ /**
66
+ * Send a WARN log
67
+ * @param message Log message
68
+ * @param options Additional options (meta, tags, etc.)
69
+ */
70
+ async warn(message: string, options?: LogOptions) {
71
+ return this.sendLog({
72
+ type: "warn",
73
+ level: LogLevel.WARN,
74
+ message,
75
+ ...options,
76
+ });
77
+ }
78
+
79
+ /**
80
+ * Send an ERROR log with smart error handling
81
+ * @param message Log message
82
+ * @param errorOrOptions Error object or options object
83
+ */
84
+ async error(
85
+ message: string,
86
+ errorOrOptions?:
87
+ | Error
88
+ | (Omit<CreateLogDto, "level" | "message" | "type"> & { type?: string })
89
+ ) {
90
+ let meta = {};
91
+ let options: Partial<CreateLogDto> = {};
92
+
93
+ if (errorOrOptions instanceof Error) {
94
+ meta = {
95
+ error: {
96
+ name: errorOrOptions.name,
97
+ message: errorOrOptions.message,
98
+ stack: errorOrOptions.stack,
99
+ },
100
+ };
101
+ } else if (errorOrOptions) {
102
+ options = errorOrOptions;
103
+ }
104
+
105
+ return this.sendLog({
106
+ type: "error",
107
+ level: LogLevel.ERROR,
108
+ message,
109
+ ...options,
110
+ meta: { ...meta, ...(options.meta || {}) },
111
+ });
112
+ }
113
+
114
+ /**
115
+ * Send a CRITICAL log
116
+ * @param message Log message
117
+ * @param options Additional options (meta, tags, etc.)
118
+ */
119
+ async critical(message: string, options?: LogOptions) {
120
+ return this.sendLog({
121
+ type: "critical",
122
+ level: LogLevel.CRITICAL,
123
+ message,
124
+ ...options,
125
+ });
126
+ }
127
+ }
package/src/types.ts ADDED
@@ -0,0 +1,31 @@
1
+ export enum LogLevel {
2
+ DEBUG = 'DEBUG',
3
+ INFO = 'INFO',
4
+ SUCCESS = 'SUCCESS',
5
+ FAILURE = 'FAILURE',
6
+ WARN = 'WARN',
7
+ ERROR = 'ERROR',
8
+ CRITICAL = 'CRITICAL',
9
+ }
10
+
11
+ export interface CreateLogDto {
12
+ type: string;
13
+ level: LogLevel;
14
+ message?: string;
15
+ meta?: Record<string, any>;
16
+ environment?: string;
17
+ userId?: string;
18
+ ip?: string;
19
+ timestamp?: Date | string;
20
+ tags?: string[];
21
+ }
22
+
23
+ export interface CreateMetricDto {
24
+ type: string;
25
+ value: number;
26
+ meta?: Record<string, any>;
27
+ environment?: string;
28
+ timestamp?: Date | string;
29
+ tags?: string[];
30
+ unit?: string;
31
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "commonjs",
5
+ "declaration": true,
6
+ "outDir": "./dist",
7
+ "strict": true,
8
+ "esModuleInterop": true,
9
+ "skipLibCheck": true
10
+ },
11
+ "include": ["src/**/*"]
12
+ }