@machhub-dev/sdk-ts 0.0.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.
Files changed (112) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/classes/auth.d.ts +18 -0
  3. package/dist/cjs/classes/auth.js +90 -0
  4. package/dist/cjs/classes/collection.d.ts +18 -0
  5. package/dist/cjs/classes/collection.js +43 -0
  6. package/dist/cjs/classes/flow.d.ts +6 -0
  7. package/dist/cjs/classes/flow.js +12 -0
  8. package/dist/cjs/classes/function.d.ts +10 -0
  9. package/dist/cjs/classes/function.js +29 -0
  10. package/dist/cjs/classes/historian.d.ts +12 -0
  11. package/dist/cjs/classes/historian.js +40 -0
  12. package/dist/cjs/classes/tag.d.ts +10 -0
  13. package/dist/cjs/classes/tag.js +25 -0
  14. package/dist/cjs/client.d.ts +13 -0
  15. package/dist/cjs/client.js +35 -0
  16. package/dist/cjs/config.d.ts +21 -0
  17. package/dist/cjs/config.js +37 -0
  18. package/dist/cjs/example/functions-file-config.d.ts +0 -0
  19. package/dist/cjs/example/functions-file-config.js +1 -0
  20. package/dist/cjs/example/functions.d.ts +1 -0
  21. package/dist/cjs/example/functions.js +18 -0
  22. package/dist/cjs/http-client.d.ts +10 -0
  23. package/dist/cjs/http-client.js +62 -0
  24. package/dist/cjs/index.d.ts +6 -0
  25. package/dist/cjs/index.js +7 -0
  26. package/dist/cjs/sdk-ts-clean.d.ts +108 -0
  27. package/dist/cjs/sdk-ts-clean.js +294 -0
  28. package/dist/cjs/sdk-ts.d.ts +71 -0
  29. package/dist/cjs/sdk-ts.js +227 -0
  30. package/dist/cjs/services/http.service.d.ts +41 -0
  31. package/dist/cjs/services/http.service.js +178 -0
  32. package/dist/cjs/services/mqtt.service.d.ts +15 -0
  33. package/dist/cjs/services/mqtt.service.js +103 -0
  34. package/dist/cjs/services/nats.service.d.ts +78 -0
  35. package/dist/cjs/services/nats.service.js +237 -0
  36. package/dist/cjs/types/auth.models.d.ts +52 -0
  37. package/dist/cjs/types/auth.models.js +100 -0
  38. package/dist/cjs/types/recordID.models.d.ts +7 -0
  39. package/dist/cjs/types/recordID.models.js +32 -0
  40. package/dist/cjs/types/response.models.d.ts +4 -0
  41. package/dist/cjs/types/response.models.js +2 -0
  42. package/dist/cjs/types/tag.models.d.ts +4 -0
  43. package/dist/cjs/types/tag.models.js +2 -0
  44. package/dist/cjs/utils/appConfig.d.ts +5 -0
  45. package/dist/cjs/utils/appConfig.js +62 -0
  46. package/dist/cjs/websocket-client.d.ts +15 -0
  47. package/dist/cjs/websocket-client.js +96 -0
  48. package/dist/classes/auth.d.ts +18 -0
  49. package/dist/classes/auth.js +86 -0
  50. package/dist/classes/collection.d.ts +18 -0
  51. package/dist/classes/collection.js +39 -0
  52. package/dist/classes/flow.d.ts +6 -0
  53. package/dist/classes/flow.js +8 -0
  54. package/dist/classes/function.d.ts +10 -0
  55. package/dist/classes/function.js +25 -0
  56. package/dist/classes/historian.d.ts +12 -0
  57. package/dist/classes/historian.js +36 -0
  58. package/dist/classes/tag.d.ts +10 -0
  59. package/dist/classes/tag.js +21 -0
  60. package/dist/client.d.ts +13 -0
  61. package/dist/client.js +31 -0
  62. package/dist/config.d.ts +21 -0
  63. package/dist/config.js +33 -0
  64. package/dist/example/functions-file-config.d.ts +0 -0
  65. package/dist/example/functions-file-config.js +1 -0
  66. package/dist/example/functions.d.ts +1 -0
  67. package/dist/example/functions.js +16 -0
  68. package/dist/http-client.d.ts +10 -0
  69. package/dist/http-client.js +58 -0
  70. package/dist/index.d.ts +6 -0
  71. package/dist/index.js +2 -0
  72. package/dist/sdk-ts-clean.d.ts +108 -0
  73. package/dist/sdk-ts-clean.js +290 -0
  74. package/dist/sdk-ts.d.ts +71 -0
  75. package/dist/sdk-ts.js +223 -0
  76. package/dist/services/http.service.d.ts +41 -0
  77. package/dist/services/http.service.js +173 -0
  78. package/dist/services/mqtt.service.d.ts +15 -0
  79. package/dist/services/mqtt.service.js +96 -0
  80. package/dist/services/nats.service.d.ts +78 -0
  81. package/dist/services/nats.service.js +233 -0
  82. package/dist/types/auth.models.d.ts +52 -0
  83. package/dist/types/auth.models.js +97 -0
  84. package/dist/types/recordID.models.d.ts +7 -0
  85. package/dist/types/recordID.models.js +27 -0
  86. package/dist/types/response.models.d.ts +4 -0
  87. package/dist/types/response.models.js +1 -0
  88. package/dist/types/tag.models.d.ts +4 -0
  89. package/dist/types/tag.models.js +1 -0
  90. package/dist/utils/appConfig.d.ts +5 -0
  91. package/dist/utils/appConfig.js +26 -0
  92. package/dist/websocket-client.d.ts +15 -0
  93. package/dist/websocket-client.js +92 -0
  94. package/package.json +33 -0
  95. package/src/classes/auth.ts +103 -0
  96. package/src/classes/collection.ts +55 -0
  97. package/src/classes/flow.ts +13 -0
  98. package/src/classes/function.ts +34 -0
  99. package/src/classes/historian.ts +49 -0
  100. package/src/classes/tag.ts +30 -0
  101. package/src/example/functions.ts +21 -0
  102. package/src/index.ts +8 -0
  103. package/src/sdk-ts.ts +255 -0
  104. package/src/services/http.service.ts +239 -0
  105. package/src/services/mqtt.service.ts +114 -0
  106. package/src/services/nats.service.ts +262 -0
  107. package/src/types/auth.models.ts +157 -0
  108. package/src/types/recordID.models.ts +33 -0
  109. package/src/types/response.models.ts +4 -0
  110. package/src/types/tag.models.ts +4 -0
  111. package/src/utils/appConfig.ts +30 -0
  112. package/tsconfig.json +14 -0
@@ -0,0 +1,10 @@
1
+ import { HTTPService } from "../services/http.service";
2
+ import { MQTTService } from "../services/mqtt.service";
3
+ export declare class Tag {
4
+ private httpService;
5
+ private mqttService;
6
+ constructor(httpService: HTTPService, mqttService: MQTTService | null);
7
+ getAllTags(): Promise<string[]>;
8
+ publish(topic: string, data: any): Promise<void>;
9
+ subscribe(topic: string, callback: (data: any) => void): Promise<void>;
10
+ }
@@ -0,0 +1,21 @@
1
+ export class Tag {
2
+ constructor(httpService, mqttService) {
3
+ this.httpService = httpService;
4
+ this.mqttService = mqttService;
5
+ }
6
+ async getAllTags() {
7
+ return this.httpService.request.get("tag/list");
8
+ }
9
+ async publish(topic, data) {
10
+ if (!this.mqttService) {
11
+ throw new Error("MQTT service not connected");
12
+ }
13
+ this.mqttService.publish(topic, data);
14
+ }
15
+ async subscribe(topic, callback) {
16
+ if (!this.mqttService) {
17
+ throw new Error("MQTT service not connected");
18
+ }
19
+ this.mqttService.addTopicHandler(topic, callback);
20
+ }
21
+ }
@@ -0,0 +1,13 @@
1
+ import { SDKConfig } from './config';
2
+ export declare class MachHubSDK {
3
+ private configManager;
4
+ private httpClient;
5
+ private wsClient;
6
+ constructor(config: SDKConfig);
7
+ configure(httpUrl: string, wsUrl: string, runtimeId?: string): void;
8
+ getConfig(): import("./config").RuntimeConfig;
9
+ get(endpoint: string, params?: Record<string, any>): Promise<any>;
10
+ post(endpoint: string, data?: any): Promise<any>;
11
+ connect(): Promise<void>;
12
+ disconnect(): void;
13
+ }
package/dist/client.js ADDED
@@ -0,0 +1,31 @@
1
+ import { ConfigManager } from './config';
2
+ import { HttpClient } from './http-client';
3
+ import { WebSocketClient } from './websocket-client';
4
+ export class MachHubSDK {
5
+ constructor(config) {
6
+ this.configManager = new ConfigManager(config);
7
+ this.httpClient = new HttpClient(this.configManager);
8
+ this.wsClient = new WebSocketClient(this.configManager);
9
+ }
10
+ configure(httpUrl, wsUrl, runtimeId) {
11
+ this.configManager.updateUrls(httpUrl, wsUrl, runtimeId);
12
+ this.httpClient.updateConfig();
13
+ this.wsClient.updateConfig();
14
+ }
15
+ getConfig() {
16
+ return this.configManager.getConfig();
17
+ }
18
+ // Existing methods...
19
+ async get(endpoint, params) {
20
+ return this.httpClient.get(endpoint, params);
21
+ }
22
+ async post(endpoint, data) {
23
+ return this.httpClient.post(endpoint, data);
24
+ }
25
+ connect() {
26
+ return this.wsClient.connect();
27
+ }
28
+ disconnect() {
29
+ return this.wsClient.disconnect();
30
+ }
31
+ }
@@ -0,0 +1,21 @@
1
+ export interface SDKConfig {
2
+ apiKey: string;
3
+ httpUrl?: string;
4
+ wsUrl?: string;
5
+ timeout?: number;
6
+ retryAttempts?: number;
7
+ environment?: 'development' | 'staging' | 'production';
8
+ }
9
+ export interface RuntimeConfig extends SDKConfig {
10
+ runtimeId?: string;
11
+ proxyEnabled?: boolean;
12
+ originalHttpUrl?: string;
13
+ originalWsUrl?: string;
14
+ }
15
+ export declare class ConfigManager {
16
+ private config;
17
+ constructor(initialConfig: SDKConfig);
18
+ getConfig(): RuntimeConfig;
19
+ updateUrls(httpUrl: string, wsUrl: string, runtimeId?: string): void;
20
+ resetUrls(): void;
21
+ }
package/dist/config.js ADDED
@@ -0,0 +1,33 @@
1
+ export class ConfigManager {
2
+ constructor(initialConfig) {
3
+ this.config = {
4
+ ...initialConfig,
5
+ httpUrl: initialConfig.httpUrl || 'https://api.machhub.com',
6
+ wsUrl: initialConfig.wsUrl || 'wss://ws.machhub.com',
7
+ timeout: initialConfig.timeout || 30000,
8
+ retryAttempts: initialConfig.retryAttempts || 3,
9
+ environment: initialConfig.environment || 'production'
10
+ };
11
+ }
12
+ getConfig() {
13
+ return { ...this.config };
14
+ }
15
+ updateUrls(httpUrl, wsUrl, runtimeId) {
16
+ if (!this.config.originalHttpUrl) {
17
+ this.config.originalHttpUrl = this.config.httpUrl;
18
+ this.config.originalWsUrl = this.config.wsUrl;
19
+ }
20
+ this.config.httpUrl = httpUrl;
21
+ this.config.wsUrl = wsUrl;
22
+ this.config.runtimeId = runtimeId;
23
+ this.config.proxyEnabled = true;
24
+ }
25
+ resetUrls() {
26
+ if (this.config.originalHttpUrl) {
27
+ this.config.httpUrl = this.config.originalHttpUrl;
28
+ this.config.wsUrl = this.config.originalWsUrl;
29
+ this.config.proxyEnabled = false;
30
+ delete this.config.runtimeId;
31
+ }
32
+ }
33
+ }
File without changes
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
1
+ import { SDK } from "../index";
2
+ let sdk = new SDK();
3
+ let config = {
4
+ application_id: "machhub_admin",
5
+ natsUrl: "nats://localhost:4222",
6
+ };
7
+ (async () => {
8
+ await sdk.Initialize(config);
9
+ function add10(data) {
10
+ data.result = data.a + 10;
11
+ console.log("Function add executed with data:", data);
12
+ return data;
13
+ }
14
+ sdk.function.addFunction("add", add10);
15
+ await sdk.function.initializeFunctions();
16
+ })();
@@ -0,0 +1,10 @@
1
+ import { ConfigManager } from './config';
2
+ export declare class HttpClient {
3
+ private configManager;
4
+ constructor(configManager: ConfigManager);
5
+ updateConfig(): void;
6
+ get(endpoint: string, params?: Record<string, any>): Promise<any>;
7
+ post(endpoint: string, data?: any): Promise<any>;
8
+ private getHeaders;
9
+ private makeRequest;
10
+ }
@@ -0,0 +1,58 @@
1
+ export class HttpClient {
2
+ constructor(configManager) {
3
+ this.configManager = configManager;
4
+ }
5
+ updateConfig() {
6
+ // Trigger any necessary updates when config changes
7
+ }
8
+ async get(endpoint, params) {
9
+ const config = this.configManager.getConfig();
10
+ const url = new URL(endpoint, config.httpUrl);
11
+ if (params) {
12
+ Object.entries(params).forEach(([key, value]) => {
13
+ url.searchParams.append(key, String(value));
14
+ });
15
+ }
16
+ return this.makeRequest(url.toString(), {
17
+ method: 'GET',
18
+ headers: this.getHeaders(),
19
+ });
20
+ }
21
+ async post(endpoint, data) {
22
+ const config = this.configManager.getConfig();
23
+ const url = new URL(endpoint, config.httpUrl).toString();
24
+ return this.makeRequest(url, {
25
+ method: 'POST',
26
+ headers: this.getHeaders(),
27
+ body: data ? JSON.stringify(data) : undefined,
28
+ });
29
+ }
30
+ getHeaders() {
31
+ const config = this.configManager.getConfig();
32
+ const headers = {
33
+ 'Authorization': `Bearer ${config.apiKey}`,
34
+ 'Content-Type': 'application/json',
35
+ };
36
+ if (config.runtimeId) {
37
+ headers['X-Runtime-ID'] = config.runtimeId;
38
+ }
39
+ return headers;
40
+ }
41
+ async makeRequest(url, options) {
42
+ const config = this.configManager.getConfig();
43
+ try {
44
+ const response = await fetch(url, {
45
+ ...options,
46
+ signal: AbortSignal.timeout(config.timeout || 30000),
47
+ });
48
+ if (!response.ok) {
49
+ throw new Error(`HTTP error! status: ${response.status}`);
50
+ }
51
+ return await response.json();
52
+ }
53
+ catch (error) {
54
+ console.error('Request failed:', error);
55
+ throw error;
56
+ }
57
+ }
58
+ }
@@ -0,0 +1,6 @@
1
+ export { SDK, type SDKConfig } from './sdk-ts';
2
+ export { getAppConfig } from './utils/appConfig';
3
+ export type { LoginResponse, PermissionResponse, User, Group, Feature, Permission, ActionResponse, Action, Scope } from './types/auth.models';
4
+ export type { BaseResponse } from './types/response.models';
5
+ export type { RecordID } from './types/recordID.models';
6
+ export type { HistorizedData } from './types/tag.models';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { SDK } from './sdk-ts';
2
+ export { getAppConfig } from './utils/appConfig';
@@ -0,0 +1,108 @@
1
+ import { Collection } from "./classes/collection";
2
+ import { Historian } from "./classes/historian";
3
+ import { Tag } from "./classes/tag";
4
+ import { Function } from "./classes/function";
5
+ import { Flow } from "./classes/flow";
6
+ import { Auth } from "./classes/auth";
7
+ export interface SDKConfig {
8
+ application_id: string;
9
+ httpUrl?: string;
10
+ mqttUrl?: string;
11
+ natsUrl?: string;
12
+ }
13
+ export declare class SDK {
14
+ private http;
15
+ private mqtt;
16
+ private nats;
17
+ private _historian;
18
+ private _tag;
19
+ private _function;
20
+ private _flow;
21
+ private _auth;
22
+ /**
23
+ * Initializes the SDK with the required clients.
24
+ *
25
+ * You can initialize the SDK in the following ways:
26
+ *
27
+ * **1. Environment Variables (Recommended - works in both Node.js and Browser):**
28
+ * ```bash
29
+ * # For Vite/SPA projects (prefix with VITE_):
30
+ * VITE_MACHHUB_APPLICATION_ID=your-app-id
31
+ * VITE_MACHHUB_HTTP_URL=http://localhost:80
32
+ * VITE_MACHHUB_MQTT_URL=ws://localhost:180
33
+ * VITE_MACHHUB_NATS_URL=ws://localhost:7500
34
+ *
35
+ * # For Node.js projects:
36
+ * MACHHUB_APPLICATION_ID=your-app-id
37
+ * MACHHUB_HTTP_URL=http://localhost:80
38
+ * MACHHUB_MQTT_URL=ws://localhost:180
39
+ * MACHHUB_NATS_URL=ws://localhost:7500
40
+ * ```
41
+ *
42
+ * ```typescript
43
+ * import { SDK } from '@machhub-dev/sdk-ts';
44
+ *
45
+ * const sdk = new SDK();
46
+ * await sdk.Initialize(); // Automatically reads from environment variables
47
+ * ```
48
+ *
49
+ * **2. Programmatic Configuration:**
50
+ * ```typescript
51
+ * import { SDK, type SDKConfig } from '@machhub-dev/sdk-ts';
52
+ *
53
+ * const config: SDKConfig = {
54
+ * application_id: 'your-app-id',
55
+ * httpUrl: 'http://localhost:80', // optional
56
+ * mqttUrl: 'ws://localhost:180', // optional
57
+ * natsUrl: 'ws://localhost:7500', // optional
58
+ * };
59
+ *
60
+ * const sdk = new SDK();
61
+ * await sdk.Initialize(config);
62
+ * ```
63
+ *
64
+ * **3. machhub.sdk.env File (Node.js only):**
65
+ * ```typescript
66
+ * // Create machhub.sdk.env in your project root:
67
+ * // MACHHUB_APPLICATION_ID=your-app-id
68
+ * // MACHHUB_HTTP_URL=http://localhost:80
69
+ * // MACHHUB_MQTT_URL=ws://localhost:180
70
+ * // MACHHUB_NATS_URL=ws://localhost:7500
71
+ *
72
+ * const sdk = new SDK();
73
+ * await sdk.Initialize(); // Reads from machhub.sdk.env if no env vars
74
+ * ```
75
+ *
76
+ * @param config {SDKConfig} Optional configuration object. If not provided, will try environment variables first, then machhub.sdk.env file.
77
+ * @param envFilePath {string} Optional path to env file. Only works in Node.js environments. Defaults to 'machhub.sdk.env' in project root.
78
+ * @returns {Promise<boolean>} Resolves to true if initialization is successful.
79
+ */
80
+ Initialize(config?: SDKConfig | null, envFilePath?: string): Promise<boolean>;
81
+ /**
82
+ * Getter for `auth`. Ensures `auth` is accessed only after initialization.
83
+ */
84
+ get auth(): Auth;
85
+ /**
86
+ * Getter for `historian`. Ensures `historian` is accessed only after initialization.
87
+ */
88
+ get historian(): Historian;
89
+ /**
90
+ * Getter for `tag`. Ensures `tag` is accessed only after initialization.
91
+ */
92
+ get tag(): Tag;
93
+ /**
94
+ * Getter for `function`. Ensures `function` is accessed only after initialization.
95
+ */
96
+ get function(): Function;
97
+ /**
98
+ * Getter for `flow`. Ensures `flow` is accessed only after initialization.
99
+ */
100
+ get flow(): Flow;
101
+ /**
102
+ * Creates a collection instance to interact with the specified table/collection.
103
+ * Throws an error if the SDK is not initialized.
104
+ * @param collectionName {string} The collection/table name.
105
+ * @returns {Collection} An instance of Collection.
106
+ */
107
+ collection(collectionName: string): Collection;
108
+ }
@@ -0,0 +1,290 @@
1
+ import { HTTPService } from "./services/http.service";
2
+ import { MQTTService } from "./services/mqtt.service";
3
+ import { NATSService } from "./services/nats.service";
4
+ import { loadSDKConfig } from "./utils/appConfig";
5
+ import { Collection } from "./classes/collection";
6
+ import { Historian } from "./classes/historian";
7
+ import { Tag } from "./classes/tag";
8
+ import { Function } from "./classes/function";
9
+ import { Flow } from "./classes/flow";
10
+ import { Auth } from "./classes/auth";
11
+ const MACHHUB_SDK_PATH = "machhub";
12
+ // Core HTTP client class
13
+ class HTTPClient {
14
+ /**
15
+ * Creates a new HTTPClient instance
16
+ * @param applicationID The ID for your application (required)
17
+ * @param httpUrl The base URL for HTTP connection (default = http://localhost:80)
18
+ */
19
+ constructor(applicationID, httpUrl = "http://localhost:80") {
20
+ if (!applicationID) {
21
+ throw new Error("Application ID is required.");
22
+ }
23
+ this.httpService = new HTTPService(httpUrl, MACHHUB_SDK_PATH, applicationID);
24
+ }
25
+ /**
26
+ * Gets server info
27
+ */
28
+ async getInfo() {
29
+ return this.httpService.request.get("info");
30
+ }
31
+ }
32
+ // Core MQTT client class
33
+ class MQTTClient {
34
+ constructor(mqttService) {
35
+ this.mqttService = mqttService;
36
+ }
37
+ /**
38
+ * Creates a new MQTTClient instance
39
+ * @param applicationID The ID for your application
40
+ * @param mqttUrl The base URL for MQTT connection (default = ws://localhost:180)
41
+ */
42
+ static async getInstance(applicationID, mqttUrl = "ws://localhost:180") {
43
+ if (!this.instance) {
44
+ const mqttService = await MQTTService.getInstance(mqttUrl);
45
+ this.instance = new MQTTClient(mqttService);
46
+ }
47
+ return this.instance;
48
+ }
49
+ /**
50
+ * Subscribes to live tag data updates
51
+ * @param topic The tag topic
52
+ * @param callback The callback function for data updates
53
+ */
54
+ async subscribeLiveData(topic, callback) {
55
+ return this.mqttService.addTopicHandler(topic, callback);
56
+ }
57
+ /**
58
+ * Publishes a message to a specific topic
59
+ * @param topic The topic to publish to
60
+ * @param data The data to publish
61
+ */
62
+ async publish(topic, data) {
63
+ return this.mqttService.publish(topic, data);
64
+ }
65
+ }
66
+ // Core NATS client class
67
+ class NATSClient {
68
+ constructor(natsService) {
69
+ this.natsService = natsService;
70
+ }
71
+ /**
72
+ * Creates a new NATSClient instance
73
+ * @param applicationID The ID for your application
74
+ * @param natsUrl The base URL for NATS connection (default = ws://localhost:7500)
75
+ */
76
+ static async getInstance(applicationID, natsUrl = "ws://localhost:7500") {
77
+ if (!this.instance) {
78
+ const natsService = await NATSService.getInstance(natsUrl);
79
+ this.instance = new NATSClient(natsService);
80
+ }
81
+ return this.instance;
82
+ }
83
+ /**
84
+ * Subscribes to subject updates
85
+ * @param subject The subject to subscribe to
86
+ * @param callback The callback function for data updates
87
+ */
88
+ async subscribe(subject, callback) {
89
+ return this.natsService.addSubjectHandler(subject, callback);
90
+ }
91
+ /**
92
+ * Publishes a message to a specific subject
93
+ * @param subject The subject to publish to
94
+ * @param data The data to publish
95
+ */
96
+ async publish(subject, data) {
97
+ return this.natsService.publish(subject, data);
98
+ }
99
+ }
100
+ // SDK Class
101
+ export class SDK {
102
+ constructor() {
103
+ this.http = null;
104
+ this.mqtt = null;
105
+ this.nats = null;
106
+ this._historian = null;
107
+ this._tag = null;
108
+ this._function = null;
109
+ this._flow = null;
110
+ this._auth = null;
111
+ }
112
+ /**
113
+ * Initializes the SDK with the required clients.
114
+ *
115
+ * You can initialize the SDK in the following ways:
116
+ *
117
+ * **1. Environment Variables (Recommended - works in both Node.js and Browser):**
118
+ * ```bash
119
+ * # For Vite/SPA projects (prefix with VITE_):
120
+ * VITE_MACHHUB_APPLICATION_ID=your-app-id
121
+ * VITE_MACHHUB_HTTP_URL=http://localhost:80
122
+ * VITE_MACHHUB_MQTT_URL=ws://localhost:180
123
+ * VITE_MACHHUB_NATS_URL=ws://localhost:7500
124
+ *
125
+ * # For Node.js projects:
126
+ * MACHHUB_APPLICATION_ID=your-app-id
127
+ * MACHHUB_HTTP_URL=http://localhost:80
128
+ * MACHHUB_MQTT_URL=ws://localhost:180
129
+ * MACHHUB_NATS_URL=ws://localhost:7500
130
+ * ```
131
+ *
132
+ * ```typescript
133
+ * import { SDK } from '@machhub-dev/sdk-ts';
134
+ *
135
+ * const sdk = new SDK();
136
+ * await sdk.Initialize(); // Automatically reads from environment variables
137
+ * ```
138
+ *
139
+ * **2. Programmatic Configuration:**
140
+ * ```typescript
141
+ * import { SDK, type SDKConfig } from '@machhub-dev/sdk-ts';
142
+ *
143
+ * const config: SDKConfig = {
144
+ * application_id: 'your-app-id',
145
+ * httpUrl: 'http://localhost:80', // optional
146
+ * mqttUrl: 'ws://localhost:180', // optional
147
+ * natsUrl: 'ws://localhost:7500', // optional
148
+ * };
149
+ *
150
+ * const sdk = new SDK();
151
+ * await sdk.Initialize(config);
152
+ * ```
153
+ *
154
+ * **3. machhub.sdk.env File (Node.js only):**
155
+ * ```typescript
156
+ * // Create machhub.sdk.env in your project root:
157
+ * // MACHHUB_APPLICATION_ID=your-app-id
158
+ * // MACHHUB_HTTP_URL=http://localhost:80
159
+ * // MACHHUB_MQTT_URL=ws://localhost:180
160
+ * // MACHHUB_NATS_URL=ws://localhost:7500
161
+ *
162
+ * const sdk = new SDK();
163
+ * await sdk.Initialize(); // Reads from machhub.sdk.env if no env vars
164
+ * ```
165
+ *
166
+ * @param config {SDKConfig} Optional configuration object. If not provided, will try environment variables first, then machhub.sdk.env file.
167
+ * @param envFilePath {string} Optional path to env file. Only works in Node.js environments. Defaults to 'machhub.sdk.env' in project root.
168
+ * @returns {Promise<boolean>} Resolves to true if initialization is successful.
169
+ */
170
+ async Initialize(config, envFilePath) {
171
+ try {
172
+ let finalConfig;
173
+ if (config) {
174
+ // Use provided config
175
+ finalConfig = config;
176
+ console.log("Using programmatic configuration");
177
+ }
178
+ else {
179
+ // Try to load configuration automatically
180
+ const autoConfig = loadSDKConfig(envFilePath);
181
+ if (!autoConfig) {
182
+ const isBrowser = typeof window !== 'undefined';
183
+ if (isBrowser) {
184
+ throw new Error(`No configuration found. For browser environments, either:
185
+
186
+ 1. Set environment variables (recommended):
187
+ VITE_MACHHUB_APPLICATION_ID=your-app-id
188
+ VITE_MACHHUB_HTTP_URL=http://localhost:80
189
+ VITE_MACHHUB_MQTT_URL=ws://localhost:180
190
+ VITE_MACHHUB_NATS_URL=ws://localhost:7500
191
+
192
+ 2. Pass a config object:
193
+ await sdk.Initialize({application_id: 'your-id', ...})`);
194
+ }
195
+ else {
196
+ const defaultPath = envFilePath || 'machhub.sdk.env (in project root)';
197
+ throw new Error(`No configuration found. Either:
198
+
199
+ 1. Set environment variables:
200
+ MACHHUB_APPLICATION_ID=your-app-id
201
+ MACHHUB_HTTP_URL=http://localhost:80
202
+ MACHHUB_MQTT_URL=ws://localhost:180
203
+ MACHHUB_NATS_URL=ws://localhost:7500
204
+
205
+ 2. Create a '${defaultPath}' file with your configuration
206
+
207
+ 3. Pass a config object:
208
+ await sdk.Initialize({application_id: 'your-id', ...})`);
209
+ }
210
+ }
211
+ finalConfig = autoConfig;
212
+ }
213
+ const { application_id, httpUrl, mqttUrl, natsUrl } = finalConfig;
214
+ if (!application_id) {
215
+ throw new Error("application_id is required in the configuration.");
216
+ }
217
+ this.http = new HTTPClient(application_id, httpUrl);
218
+ this.mqtt = await MQTTClient.getInstance(application_id, mqttUrl);
219
+ this.nats = await NATSClient.getInstance(application_id, natsUrl);
220
+ this._historian = new Historian(this.http["httpService"], this.mqtt["mqttService"]);
221
+ this._tag = new Tag(this.http["httpService"], this.mqtt["mqttService"]);
222
+ this._function = new Function(this.http["httpService"], this.nats["natsService"]);
223
+ this._flow = new Flow(this.http["httpService"]);
224
+ this._auth = new Auth(this.http["httpService"]);
225
+ console.log("SDK initialized successfully!");
226
+ }
227
+ catch (error) {
228
+ console.error("Failed to initialize SDK:", error.message || error);
229
+ return false;
230
+ }
231
+ return true;
232
+ }
233
+ /**
234
+ * Getter for `auth`. Ensures `auth` is accessed only after initialization.
235
+ */
236
+ get auth() {
237
+ if (!this._auth) {
238
+ throw new Error("SDK is not initialized. Call `Initialize` before accessing `auth`.");
239
+ }
240
+ return this._auth;
241
+ }
242
+ /**
243
+ * Getter for `historian`. Ensures `historian` is accessed only after initialization.
244
+ */
245
+ get historian() {
246
+ if (!this._historian) {
247
+ throw new Error("SDK is not initialized. Call `Initialize` before accessing `historian`.");
248
+ }
249
+ return this._historian;
250
+ }
251
+ /**
252
+ * Getter for `tag`. Ensures `tag` is accessed only after initialization.
253
+ */
254
+ get tag() {
255
+ if (!this._tag) {
256
+ throw new Error("SDK is not initialized. Call `Initialize` before accessing `tag`.");
257
+ }
258
+ return this._tag;
259
+ }
260
+ /**
261
+ * Getter for `function`. Ensures `function` is accessed only after initialization.
262
+ */
263
+ get function() {
264
+ if (!this._function) {
265
+ throw new Error("SDK is not initialized. Call `Initialize` before accessing `function`.");
266
+ }
267
+ return this._function;
268
+ }
269
+ /**
270
+ * Getter for `flow`. Ensures `flow` is accessed only after initialization.
271
+ */
272
+ get flow() {
273
+ if (!this._flow) {
274
+ throw new Error("SDK is not initialized. Call `Initialize` before accessing `flow`.");
275
+ }
276
+ return this._flow;
277
+ }
278
+ /**
279
+ * Creates a collection instance to interact with the specified table/collection.
280
+ * Throws an error if the SDK is not initialized.
281
+ * @param collectionName {string} The collection/table name.
282
+ * @returns {Collection} An instance of Collection.
283
+ */
284
+ collection(collectionName) {
285
+ if (!this.http) {
286
+ throw new Error("SDK is not initialized. Call `Initialize` before accessing collection.");
287
+ }
288
+ return new Collection(this.http["httpService"], this.mqtt ? this.mqtt["mqttService"] : null, collectionName);
289
+ }
290
+ }