@uns-kit/core 2.0.36 → 2.0.38

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
@@ -56,6 +56,47 @@ const api = await proc.createApiProxy("my-service", { jwtSecret: "CHANGEME" });
56
56
  const cron = await proc.createCrontabProxy("*/5 * * * *", { event: "tick" });
57
57
  ```
58
58
 
59
+ ## Datahub client (last value)
60
+
61
+ `UnsClient` provides a minimal REST client for the UNS Datahub API, including the batch last-value endpoint. Prefer a long-lived service token if available; you can pass it directly and skip username/password auth.
62
+
63
+ ```ts
64
+ import { UnsClient } from "@uns-kit/core";
65
+
66
+ const client = new UnsClient("https://datahub.example.com", {
67
+ token: process.env.UNS_SERVICE_TOKEN,
68
+ });
69
+
70
+ const values = await client.lastValue([
71
+ "raw/data/line-1/motor/main/temperature",
72
+ "raw/data/line-1/motor/main/status",
73
+ ]);
74
+ console.log(values);
75
+ ```
76
+
77
+ ## Validity / Liveliness
78
+
79
+ UNS attributes can declare how the controller decides whether they are live or stale. These fields are optional and default to `"interval"` with the controller default (~120s) if omitted.
80
+
81
+ - `validityMode`: `"interval" | "lifecycle" | "static"`
82
+ - `expectedIntervalMs`: required for `"interval"` mode (controller marks stale after ~2x this interval)
83
+ - `lifecycleEndValue`: required for `"lifecycle"` mode (end-state marker, e.g. `"EXITED"`)
84
+
85
+ ```ts
86
+ await proxy.publishMqttMessage({
87
+ topic: "raw/data/",
88
+ asset: "line-1",
89
+ objectType: "motor",
90
+ objectId: "main",
91
+ attributes: {
92
+ attribute: "status",
93
+ data: { time: new Date().toISOString(), value: "RUNNING" },
94
+ validityMode: "lifecycle",
95
+ lifecycleEndValue: "STOPPED",
96
+ },
97
+ });
98
+ ```
99
+
59
100
  ## Sync UNS schema from the controller
60
101
 
61
102
  `sync-uns-schema` fetches the canonical UNS dictionary and measurements from the controller REST API and refreshes local JSON files and generated TypeScript artifacts.
package/dist/index.d.ts CHANGED
@@ -5,4 +5,5 @@ export { ConfigFile } from "./config-file.js";
5
5
  export { default as logger } from "./logger.js";
6
6
  export { getLogger } from "./logger.js";
7
7
  export { resolveInfisicalConfig } from "./uns-config/secret-resolver.js";
8
+ export { UnsClient, LastValueResult, LastValueClientError } from "./tools/datahub/datahub-client.js";
8
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,4BAA4B,CAAC;AACxE,YAAY,EACV,qBAAqB,EACrB,wBAAwB,EACxB,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,4BAA4B,CAAC;AACxE,YAAY,EACV,qBAAqB,EACrB,wBAAwB,EACxB,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC"}
package/dist/index.js CHANGED
@@ -4,4 +4,5 @@ export { ConfigFile } from "./config-file.js";
4
4
  export { default as logger } from "./logger.js";
5
5
  export { getLogger } from "./logger.js";
6
6
  export { resolveInfisicalConfig } from "./uns-config/secret-resolver.js";
7
+ export { UnsClient, LastValueResult, LastValueClientError } from "./tools/datahub/datahub-client.js";
7
8
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAOxE,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC","sourcesContent":["export { default as UnsProxyProcess } from \"./uns/uns-proxy-process.js\";\nexport type {\n UnsProxyProcessPlugin,\n UnsProxyProcessPluginApi,\n UnsProxyProcessPluginMethod,\n UnsProxyProcessPluginMethods,\n} from \"./uns/uns-proxy-process.js\";\nexport * from \"./uns/uns-interfaces.js\";\nexport { ConfigFile } from \"./config-file.js\";\nexport { default as logger } from \"./logger.js\";\nexport { getLogger } from \"./logger.js\";\nexport { resolveInfisicalConfig } from \"./uns-config/secret-resolver.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAOxE,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC","sourcesContent":["export { default as UnsProxyProcess } from \"./uns/uns-proxy-process.js\";\nexport type {\n UnsProxyProcessPlugin,\n UnsProxyProcessPluginApi,\n UnsProxyProcessPluginMethod,\n UnsProxyProcessPluginMethods,\n} from \"./uns/uns-proxy-process.js\";\nexport * from \"./uns/uns-interfaces.js\";\nexport { ConfigFile } from \"./config-file.js\";\nexport { default as logger } from \"./logger.js\";\nexport { getLogger } from \"./logger.js\";\nexport { resolveInfisicalConfig } from \"./uns-config/secret-resolver.js\";\nexport { UnsClient, LastValueResult, LastValueClientError } from \"./tools/datahub/datahub-client.js\";\n"]}
@@ -0,0 +1,62 @@
1
+ import { AuthClient } from "../auth/auth-client.js";
2
+ export type LastValuePayload = {
3
+ topic: string;
4
+ value: unknown;
5
+ values?: Record<string, unknown> | null;
6
+ uom?: string | null;
7
+ timestamp?: string | null;
8
+ dataGroup?: string | null;
9
+ ageMs?: number | null;
10
+ source: string;
11
+ };
12
+ export declare class LastValueResult {
13
+ readonly topic: string;
14
+ readonly value: unknown;
15
+ readonly values?: Record<string, unknown> | null;
16
+ readonly uom?: string | null;
17
+ readonly timestamp?: string | null;
18
+ readonly dataGroup?: string | null;
19
+ readonly ageMs?: number | null;
20
+ readonly source: string;
21
+ constructor(payload: LastValuePayload);
22
+ static fromMapping(value: Record<string, unknown>): LastValueResult;
23
+ get hit(): boolean;
24
+ toObject(): LastValuePayload;
25
+ }
26
+ export declare class LastValueClientError extends Error {
27
+ readonly statusCode?: number;
28
+ constructor(message: string, statusCode?: number);
29
+ }
30
+ export type UnsClientOptions = {
31
+ apiBasePath?: string;
32
+ token?: string;
33
+ timeoutMs?: number;
34
+ authClient?: AuthClient;
35
+ };
36
+ export declare class UnsClient {
37
+ private readonly apiBasePath;
38
+ private readonly baseUrl;
39
+ private readonly apiUrl;
40
+ private readonly timeoutMs;
41
+ private readonly authClient?;
42
+ private accessToken?;
43
+ constructor(baseUrl: string, options?: UnsClientOptions);
44
+ setToken(token?: string): void;
45
+ ensureToken(): Promise<string | undefined>;
46
+ get(endpoint: string, params?: Record<string, string | number | boolean>, options?: {
47
+ baseUrl?: string;
48
+ authorize?: boolean;
49
+ }): Promise<Record<string, unknown>>;
50
+ post(endpoint: string, body?: Record<string, unknown>, options?: {
51
+ baseUrl?: string;
52
+ authorize?: boolean;
53
+ }): Promise<Record<string, unknown>>;
54
+ lastValue(topics: string | string[], options?: {
55
+ token?: string;
56
+ }): Promise<Record<string, LastValuePayload> | null>;
57
+ private requestJson;
58
+ private buildUrl;
59
+ private stringifyQueryParams;
60
+ private static normalizeBasePath;
61
+ }
62
+ //# sourceMappingURL=datahub-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"datahub-client.d.ts","sourceRoot":"","sources":["../../../src/tools/datahub/datahub-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEpD,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACxC,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,qBAAa,eAAe;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB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AqB;IAgB3D,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAIxB,WAAW,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IAQ1C,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,EAAE,OAAO,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAOpK,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAMjJ,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,OAAO,GAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAAG,IAAI,CAAC;YA2BhH,WAAW;IA6CzB,OAAO,CAAC,QAAQ;IAYhB,OAAO,CAAC,oBAAoB;IAI5B,OAAO,CAAC,MAAM,CAAC,iBAAiB;CAKjC"}
@@ -0,0 +1,189 @@
1
+ export class LastValueResult {
2
+ topic;
3
+ value;
4
+ values;
5
+ uom;
6
+ timestamp;
7
+ dataGroup;
8
+ ageMs;
9
+ source;
10
+ constructor(payload) {
11
+ this.topic = payload.topic;
12
+ this.value = payload.value;
13
+ this.values = payload.values ?? null;
14
+ this.uom = payload.uom ?? null;
15
+ this.timestamp = payload.timestamp ?? null;
16
+ this.dataGroup = payload.dataGroup ?? null;
17
+ this.ageMs = payload.ageMs ?? null;
18
+ this.source = payload.source;
19
+ }
20
+ static fromMapping(value) {
21
+ const rawValues = value.values;
22
+ return new LastValueResult({
23
+ topic: typeof value.topic === "string" ? value.topic : "",
24
+ value: value.value,
25
+ values: rawValues && typeof rawValues === "object" && !Array.isArray(rawValues) ? rawValues : null,
26
+ uom: typeof value.uom === "string" ? value.uom : null,
27
+ timestamp: typeof value.timestamp === "string" ? value.timestamp : null,
28
+ dataGroup: typeof value.dataGroup === "string" ? value.dataGroup : null,
29
+ ageMs: typeof value.ageMs === "number" ? value.ageMs : null,
30
+ source: typeof value.source === "string" ? value.source : "miss",
31
+ });
32
+ }
33
+ get hit() {
34
+ return this.source === "cache";
35
+ }
36
+ toObject() {
37
+ return {
38
+ topic: this.topic,
39
+ value: this.value,
40
+ values: this.values ?? null,
41
+ uom: this.uom ?? null,
42
+ timestamp: this.timestamp ?? null,
43
+ dataGroup: this.dataGroup ?? null,
44
+ ageMs: this.ageMs ?? null,
45
+ source: this.source,
46
+ };
47
+ }
48
+ }
49
+ export class LastValueClientError extends Error {
50
+ statusCode;
51
+ constructor(message, statusCode) {
52
+ super(message);
53
+ this.statusCode = statusCode;
54
+ }
55
+ }
56
+ export class UnsClient {
57
+ apiBasePath;
58
+ baseUrl;
59
+ apiUrl;
60
+ timeoutMs;
61
+ authClient;
62
+ accessToken;
63
+ constructor(baseUrl, options = {}) {
64
+ const apiBasePath = UnsClient.normalizeBasePath(options.apiBasePath ?? "/api");
65
+ const strippedBase = baseUrl.replace(/\/$/, "");
66
+ if (apiBasePath && strippedBase.endsWith(apiBasePath)) {
67
+ this.apiUrl = strippedBase;
68
+ this.baseUrl = strippedBase.slice(0, -apiBasePath.length).replace(/\/$/, "");
69
+ }
70
+ else {
71
+ this.baseUrl = strippedBase;
72
+ this.apiUrl = `${strippedBase}${apiBasePath}`;
73
+ }
74
+ this.apiBasePath = apiBasePath;
75
+ this.timeoutMs = options.timeoutMs ?? 10_000;
76
+ this.authClient = options.authClient;
77
+ this.accessToken = options.token;
78
+ }
79
+ setToken(token) {
80
+ this.accessToken = token;
81
+ }
82
+ async ensureToken() {
83
+ if (this.accessToken)
84
+ return this.accessToken;
85
+ if (!this.authClient)
86
+ return undefined;
87
+ const token = await this.authClient.getAccessToken();
88
+ this.accessToken = token;
89
+ return token;
90
+ }
91
+ async get(endpoint, params, options = {}) {
92
+ const authorize = options.authorize ?? true;
93
+ const token = authorize ? await this.ensureToken() : undefined;
94
+ const search = params ? `?${new URLSearchParams(this.stringifyQueryParams(params))}` : "";
95
+ return this.requestJson("GET", `${this.buildUrl(endpoint, options.baseUrl)}${search}`, undefined, token);
96
+ }
97
+ async post(endpoint, body, options = {}) {
98
+ const authorize = options.authorize ?? true;
99
+ const token = authorize ? await this.ensureToken() : undefined;
100
+ return this.requestJson("POST", this.buildUrl(endpoint, options.baseUrl), body ?? {}, token);
101
+ }
102
+ async lastValue(topics, options = {}) {
103
+ const topicList = Array.isArray(topics) ? topics : [topics];
104
+ if (!topicList.length) {
105
+ throw new Error("topics must contain at least one topic.");
106
+ }
107
+ if (topicList.length > 500) {
108
+ throw new Error("Maximum 500 topics per request.");
109
+ }
110
+ const token = options.token ?? (await this.ensureToken());
111
+ try {
112
+ const payload = await this.requestJson("POST", this.buildUrl("/batch/last"), { topics: topicList }, token);
113
+ const rawResults = payload.results;
114
+ if (!Array.isArray(rawResults)) {
115
+ throw new LastValueClientError("Last-value response did not include a results array.");
116
+ }
117
+ const results = rawResults
118
+ .filter((item) => !!item && typeof item === "object" && !Array.isArray(item))
119
+ .map((item) => LastValueResult.fromMapping(item));
120
+ return Object.fromEntries(results.map((result) => [result.topic, result.toObject()]));
121
+ }
122
+ catch (error) {
123
+ if (error instanceof LastValueClientError && error.statusCode === 404) {
124
+ return null;
125
+ }
126
+ throw error;
127
+ }
128
+ }
129
+ async requestJson(method, url, body, token) {
130
+ const controller = new AbortController();
131
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
132
+ try {
133
+ const resp = await fetch(url, {
134
+ method,
135
+ headers: {
136
+ "Accept": "application/json",
137
+ ...(body ? { "Content-Type": "application/json" } : {}),
138
+ ...(token ? { "Authorization": `Bearer ${token}` } : {}),
139
+ },
140
+ ...(body ? { body: JSON.stringify(body) } : {}),
141
+ signal: controller.signal,
142
+ });
143
+ const text = await resp.text();
144
+ if (!resp.ok) {
145
+ throw new LastValueClientError(`UNS request failed with HTTP ${resp.status}: ${text || resp.statusText}`, resp.status);
146
+ }
147
+ if (!text)
148
+ return {};
149
+ const parsed = JSON.parse(text);
150
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
151
+ throw new LastValueClientError("UNS response must be a JSON object.");
152
+ }
153
+ return parsed;
154
+ }
155
+ catch (error) {
156
+ if (error instanceof LastValueClientError) {
157
+ throw error;
158
+ }
159
+ if (error?.name === "AbortError") {
160
+ throw new LastValueClientError("UNS request timed out.");
161
+ }
162
+ throw new LastValueClientError(`UNS request failed: ${error?.message ?? String(error)}`);
163
+ }
164
+ finally {
165
+ clearTimeout(timeout);
166
+ }
167
+ }
168
+ buildUrl(endpoint, baseUrl) {
169
+ if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
170
+ return endpoint;
171
+ }
172
+ const root = (baseUrl ?? this.apiUrl).replace(/\/$/, "");
173
+ let path = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
174
+ if (!baseUrl && this.apiBasePath && (path === this.apiBasePath || path.startsWith(`${this.apiBasePath}/`))) {
175
+ path = path.slice(this.apiBasePath.length) || "/";
176
+ }
177
+ return `${root}${path}`;
178
+ }
179
+ stringifyQueryParams(params) {
180
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, String(value)]));
181
+ }
182
+ static normalizeBasePath(value) {
183
+ const stripped = value.trim();
184
+ if (!stripped)
185
+ return "";
186
+ return stripped.startsWith("/") ? stripped : `/${stripped}`;
187
+ }
188
+ }
189
+ //# sourceMappingURL=datahub-client.js.map
@@ -0,0 +1 @@
1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C,IAAI,KAAK,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC,EAAE,CAAC;YAC3G,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC;QACpD,CAAC;QACD,OAAO,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC;IAC1B,CAAC;IAEO,oBAAoB,CAAC,MAAiD;QAC5E,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAChG,CAAC;IAEO,MAAM,CAAC,iBAAiB,CAAC,KAAa;QAC5C,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC,QAAQ;YAAE,OAAO,EAAE,CAAC;QACzB,OAAO,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,QAAQ,EAAE,CAAC;IAC9D,CAAC;CACF","sourcesContent":["import { AuthClient } from \"../auth/auth-client.js\";\n\nexport type LastValuePayload = {\n topic: string;\n value: unknown;\n values?: Record<string, unknown> | null;\n uom?: string | null;\n timestamp?: string | null;\n dataGroup?: string | null;\n ageMs?: number | null;\n source: string;\n};\n\nexport class LastValueResult {\n readonly topic: string;\n readonly value: unknown;\n readonly values?: Record<string, unknown> | null;\n readonly uom?: string | null;\n readonly timestamp?: string | null;\n readonly dataGroup?: string | null;\n readonly ageMs?: number | null;\n readonly source: string;\n\n constructor(payload: LastValuePayload) {\n this.topic = payload.topic;\n this.value = payload.value;\n this.values = payload.values ?? null;\n this.uom = payload.uom ?? null;\n this.timestamp = payload.timestamp ?? null;\n this.dataGroup = payload.dataGroup ?? null;\n this.ageMs = payload.ageMs ?? null;\n this.source = payload.source;\n }\n\n static fromMapping(value: Record<string, unknown>): LastValueResult {\n const rawValues = value.values;\n return new LastValueResult({\n topic: typeof value.topic === \"string\" ? value.topic : \"\",\n value: value.value,\n values: rawValues && typeof rawValues === \"object\" && !Array.isArray(rawValues) ? (rawValues as Record<string, unknown>) : null,\n uom: typeof value.uom === \"string\" ? value.uom : null,\n timestamp: typeof value.timestamp === \"string\" ? value.timestamp : null,\n dataGroup: typeof value.dataGroup === \"string\" ? value.dataGroup : null,\n ageMs: typeof value.ageMs === \"number\" ? value.ageMs : null,\n source: typeof value.source === \"string\" ? value.source : \"miss\",\n });\n }\n\n get hit(): boolean {\n return this.source === \"cache\";\n }\n\n toObject(): LastValuePayload {\n return {\n topic: this.topic,\n value: this.value,\n values: this.values ?? null,\n uom: this.uom ?? null,\n timestamp: this.timestamp ?? null,\n dataGroup: this.dataGroup ?? null,\n ageMs: this.ageMs ?? null,\n source: this.source,\n };\n }\n}\n\nexport class LastValueClientError extends Error {\n readonly statusCode?: number;\n\n constructor(message: string, statusCode?: number) {\n super(message);\n this.statusCode = statusCode;\n }\n}\n\nexport type UnsClientOptions = {\n apiBasePath?: string;\n token?: string;\n timeoutMs?: number;\n authClient?: AuthClient;\n};\n\nexport class UnsClient {\n private readonly apiBasePath: string;\n private readonly baseUrl: string;\n private readonly apiUrl: string;\n private readonly timeoutMs: number;\n private readonly authClient?: AuthClient;\n private accessToken?: string;\n\n constructor(baseUrl: string, options: UnsClientOptions = {}) {\n const apiBasePath = UnsClient.normalizeBasePath(options.apiBasePath ?? \"/api\");\n const strippedBase = baseUrl.replace(/\\/$/, \"\");\n if (apiBasePath && strippedBase.endsWith(apiBasePath)) {\n this.apiUrl = strippedBase;\n this.baseUrl = strippedBase.slice(0, -apiBasePath.length).replace(/\\/$/, \"\");\n } else {\n this.baseUrl = strippedBase;\n this.apiUrl = `${strippedBase}${apiBasePath}`;\n }\n this.apiBasePath = apiBasePath;\n this.timeoutMs = options.timeoutMs ?? 10_000;\n this.authClient = options.authClient;\n this.accessToken = options.token;\n }\n\n setToken(token?: string): void {\n this.accessToken = token;\n }\n\n async ensureToken(): Promise<string | undefined> {\n if (this.accessToken) return this.accessToken;\n if (!this.authClient) return undefined;\n const token = await this.authClient.getAccessToken();\n this.accessToken = token;\n return token;\n }\n\n async get(endpoint: string, params?: Record<string, string | number | boolean>, options: { baseUrl?: string; authorize?: boolean } = {}): Promise<Record<string, unknown>> {\n const authorize = options.authorize ?? true;\n const token = authorize ? await this.ensureToken() : undefined;\n const search = params ? `?${new URLSearchParams(this.stringifyQueryParams(params))}` : \"\";\n return this.requestJson(\"GET\", `${this.buildUrl(endpoint, options.baseUrl)}${search}`, undefined, token);\n }\n\n async post(endpoint: string, body?: Record<string, unknown>, options: { baseUrl?: string; authorize?: boolean } = {}): Promise<Record<string, unknown>> {\n const authorize = options.authorize ?? true;\n const token = authorize ? await this.ensureToken() : undefined;\n return this.requestJson(\"POST\", this.buildUrl(endpoint, options.baseUrl), body ?? {}, token);\n }\n\n async lastValue(topics: string | string[], options: { token?: string } = {}): Promise<Record<string, LastValuePayload> | null> {\n const topicList = Array.isArray(topics) ? topics : [topics];\n if (!topicList.length) {\n throw new Error(\"topics must contain at least one topic.\");\n }\n if (topicList.length > 500) {\n throw new Error(\"Maximum 500 topics per request.\");\n }\n const token = options.token ?? (await this.ensureToken());\n try {\n const payload = await this.requestJson(\"POST\", this.buildUrl(\"/batch/last\"), { topics: topicList }, token);\n const rawResults = payload.results;\n if (!Array.isArray(rawResults)) {\n throw new LastValueClientError(\"Last-value response did not include a results array.\");\n }\n const results = rawResults\n .filter((item): item is Record<string, unknown> => !!item && typeof item === \"object\" && !Array.isArray(item))\n .map((item) => LastValueResult.fromMapping(item));\n return Object.fromEntries(results.map((result) => [result.topic, result.toObject()]));\n } catch (error) {\n if (error instanceof LastValueClientError && error.statusCode === 404) {\n return null;\n }\n throw error;\n }\n }\n\n private async requestJson(\n method: \"GET\" | \"POST\",\n url: string,\n body?: Record<string, unknown>,\n token?: string,\n ): Promise<Record<string, unknown>> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n const resp = await fetch(url, {\n method,\n headers: {\n \"Accept\": \"application/json\",\n ...(body ? { \"Content-Type\": \"application/json\" } : {}),\n ...(token ? { \"Authorization\": `Bearer ${token}` } : {}),\n },\n ...(body ? { body: JSON.stringify(body) } : {}),\n signal: controller.signal,\n });\n const text = await resp.text();\n if (!resp.ok) {\n throw new LastValueClientError(\n `UNS request failed with HTTP ${resp.status}: ${text || resp.statusText}`,\n resp.status,\n );\n }\n if (!text) return {};\n const parsed = JSON.parse(text);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new LastValueClientError(\"UNS response must be a JSON object.\");\n }\n return parsed as Record<string, unknown>;\n } catch (error: any) {\n if (error instanceof LastValueClientError) {\n throw error;\n }\n if (error?.name === \"AbortError\") {\n throw new LastValueClientError(\"UNS request timed out.\");\n }\n throw new LastValueClientError(`UNS request failed: ${error?.message ?? String(error)}`);\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private buildUrl(endpoint: string, baseUrl?: string): string {\n if (endpoint.startsWith(\"http://\") || endpoint.startsWith(\"https://\")) {\n return endpoint;\n }\n const root = (baseUrl ?? this.apiUrl).replace(/\\/$/, \"\");\n let path = endpoint.startsWith(\"/\") ? endpoint : `/${endpoint}`;\n if (!baseUrl && this.apiBasePath && (path === this.apiBasePath || path.startsWith(`${this.apiBasePath}/`))) {\n path = path.slice(this.apiBasePath.length) || \"/\";\n }\n return `${root}${path}`;\n }\n\n private stringifyQueryParams(params: Record<string, string | number | boolean>): Record<string, string> {\n return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, String(value)]));\n }\n\n private static normalizeBasePath(value: string): string {\n const stripped = value.trim();\n if (!stripped) return \"\";\n return stripped.startsWith(\"/\") ? stripped : `/${stripped}`;\n }\n}\n"]}
@@ -169,8 +169,8 @@ export interface IMqttAttributeMessage {
169
169
  * // Sensor publishing every 2 seconds:
170
170
  * { validityMode: "interval", expectedIntervalMs: 2000 }
171
171
  *
172
- * // Status that changes on events (never stale by time):
173
- * { validityMode: "event" }
172
+ * // Status attribute publishing every 2 seconds (string values like "HEATING"):
173
+ * { validityMode: "interval", expectedIntervalMs: 2000 }
174
174
  *
175
175
  * // Material location with ENTERED/EXITED lifecycle:
176
176
  * { validityMode: "lifecycle", lifecycleEndValue: "EXITED" }
@@ -182,7 +182,7 @@ export interface IMqttAttributeMessage {
182
182
  /**
183
183
  * Expected publish interval in milliseconds. Only meaningful for `validityMode: "interval"`.
184
184
  * The controller marks the attribute as stale after ~2× this value without a heartbeat update.
185
- * Ignored for `"event"`, `"lifecycle"`, and `"static"` modes.
185
+ * Ignored for `"lifecycle"` and `"static"` modes.
186
186
  */
187
187
  expectedIntervalMs?: number;
188
188
  /**
@@ -243,10 +243,9 @@ export interface IUnsExtendedMessage extends IUnsMessage {
243
243
  * Controls how the controller determines whether an attribute is live or stale.
244
244
  *
245
245
  * - `"interval"` — Attribute publishes periodically. Stale if no heartbeat within ~2× the expected interval.
246
- * Use with `expectedIntervalMs`. Example: temperature sensor publishing every 2s.
247
- *
248
- * - `"event"` Attribute publishes on value change only. Never stale by time — only when the microservice stops.
249
- * Example: machine status ("HEATING" / "COOLING") that changes infrequently.
246
+ * Use with `expectedIntervalMs`. Works for both numeric sensors (temperature every 2s)
247
+ * and string status attributes (status every 2s). Example:
248
+ * `{ validityMode: "interval", expectedIntervalMs: 2000 }`
250
249
  *
251
250
  * - `"lifecycle"` — Attribute represents a lifecycle with a start and end event.
252
251
  * Use with `lifecycleEndValue` to mark the end state. Example: material location with "ENTERED" / "EXITED".
@@ -255,7 +254,7 @@ export interface IUnsExtendedMessage extends IUnsMessage {
255
254
  *
256
255
  * When omitted, defaults to `"interval"` with the controller's default interval (~120s).
257
256
  */
258
- export type ValidityMode = "interval" | "event" | "lifecycle" | "static";
257
+ export type ValidityMode = "interval" | "lifecycle" | "static";
259
258
  export interface ITopicObject {
260
259
  timestamp: string;
261
260
  attribute: string;
@@ -1 +1 @@
1
- {"version":3,"file":"uns-interfaces.d.ts","sourceRoot":"","sources":["../../src/uns/uns-interfaces.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAClE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,KAAK,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACnI,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAsB,KAAK,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAErF,MAAM,MAAM,OAAO,GAAG,GAAG,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,GAAG,CAAC;AAC/F,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,OAAO,CAG7D;AAED,MAAM,MAAM,YAAY,GAAG,qBAAqB,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAEjE,eAAO,MAAM,UAAU,+BAAgC,CAAC;AACxD,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC;AAC1D,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;AAExC,eAAO,MAAM,qBAAqB,0LAmBxB,CAAC;AAOX,MAAM,MAAM,oBAAoB,GAAG,CAA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U,aAAa,CAAC,KAAc;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,uBAAuB,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,CACL,mBAAmB,CAAC,IAAI,CAAC,KAAK,CAAC;QAC/B,mBAAmB,CAAC,IAAI,CAAC,KAAK,CAAC;QAC/B,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,CAC9B,CAAC;AACJ,CAAC","sourcesContent":["import { UnsAttributeType } from \"../graphql/schema.js\";\nimport { MeasurementUnit } from \"./uns-measurements.js\";\nimport { UnsTags } from \"./uns-tags.js\";\nimport type { UnsObjectId, UnsObjectType } from \"./uns-object.js\";\nimport type { UnsAsset } from \"./uns-asset.js\";\nimport type { IMqttConnectProperties, IMqttPublishOptions, IMqttServerConfig, MqttProtocol } from \"../uns-mqtt/mqtt-interfaces.js\";\nimport { UnsTopics } from \"./uns-topics.js\";\nimport { knownUnsAttributes, type KnownUnsAttributeName } from \"./uns-attributes.js\";\n\nexport type ISO8601 = `${number}-${string}-${string}T${string}:${string}:${string}.${string}Z`;\nexport function isIOS8601Type(value: string): value is ISO8601 {\n const iso8601Regex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/;\n return iso8601Regex.test(value);\n}\n// Known attribute names (with IntelliSense) while still allowing arbitrary strings.\nexport type UnsAttribute = KnownUnsAttributeName | (string & {});\n\nexport const valueTypes = [\"string\", \"number\"] as const;\nexport type ValueTypeString = (typeof valueTypes)[number];\nexport type ValueType = string | number;\n\nexport const questDbPrimitiveTypes = [\n \"boolean\",\n \"ipv4\",\n \"byte\",\n \"short\",\n \"char\",\n \"int\",\n \"float\",\n \"symbol\",\n \"varchar\",\n \"string\",\n \"long\",\n \"date\",\n \"timestamp\",\n \"timestamp_ns\",\n \"double\",\n \"uuid\",\n \"binary\",\n \"long256\",\n] as const;\n\nconst questDbPrimitiveTypeSet = new Set<string>(questDbPrimitiveTypes);\nconst questDbGeohashRegex = /^geohash\\(\\d+[bc]\\)$/;\nconst questDbDecimalRegex = /^decimal\\(\\d+,\\d+\\)$/;\nconst questDbArrayRegex = /^array<[^>]+>$/;\n\nexport type QuestDbPrimitiveType = (typeof questDbPrimitiveTypes)[number];\n\n// Supported QuestDB column types for UNS tables.\nexport type QuestDbType =\n | QuestDbPrimitiveType\n | `geohash(${number}${\"b\" | \"c\"})`\n | `decimal(${number},${number})`\n | `array<${string}>`;\n\nexport function isQuestDbType(value: unknown): value is QuestDbType {\n if (typeof value !== \"string\") {\n return false;\n }\n if (questDbPrimitiveTypeSet.has(value)) {\n return true;\n }\n return (\n questDbGeohashRegex.test(value) ||\n questDbDecimalRegex.test(value) ||\n questDbArrayRegex.test(value)\n );\n}\n\nexport interface IUnsParameters {\n mqttSubToTopics?: string | string[];\n username?: string;\n password?: string;\n mqttSSL?: boolean;\n publishThrottlingDelay?: number; // Delay in milliseconds; default is 1ms\n subscribeThrottlingDelay?: number; // Delay in milliseconds; default is 1ms\n rejectUnauthorized?: boolean;\n clientId?: string;\n hosts?: string[];\n servers?: IMqttServerConfig[];\n port?: number;\n protocol?: MqttProtocol;\n keepalive?: number;\n clean?: boolean;\n connectTimeout?: number;\n reconnectPeriod?: number;\n reconnectOnConnackError?: boolean;\n resubscribe?: boolean;\n queueQoSZero?: boolean;\n properties?: IMqttConnectProperties;\n ca?: string;\n cert?: string;\n key?: string;\n servername?: string;\n /**\n * Default MQTT publish options applied to all outgoing messages\n * (e.g., qos, retain, messageExpiryInterval).\n */\n defaultPublishOptions?: IMqttPublishOptions;\n}\n\nexport interface IUnsProcessParameters {\n processName: string;\n mqttSubToTopics?: string | string[];\n username?: string;\n password?: string;\n mqttSSL?: boolean;\n clientId?: string;\n hosts?: string[];\n servers?: IMqttServerConfig[];\n port?: number;\n protocol?: MqttProtocol;\n keepalive?: number;\n clean?: boolean;\n connectTimeout?: number;\n reconnectPeriod?: number;\n reconnectOnConnackError?: boolean;\n resubscribe?: boolean;\n queueQoSZero?: boolean;\n rejectUnauthorized?: boolean;\n properties?: IMqttConnectProperties;\n ca?: string;\n cert?: string;\n key?: string;\n servername?: string;\n}\n\nexport interface UnsEvents {\n // Emitters in MqttProxy, UnsMqttProxy\n input: { topic: string; message: string, packet: any };\n mqttProxyStatus: { event: string, value: number, uom: MeasurementUnit, statusTopic: string };\n \n // Emitters in MqttProxy\n error: { code: number; message: string };\n \n // Emitters in UnsMqttProxy\n mqttWorker: { command: string, instanceName: string; batchSize: number, referenceHash: string };\n\n // Emitter in UnsCronProxy\n cronEvent: { event?: string; cronExpression?: string };\n\n // Emitters in UnsApiProxy\n apiGetEvent: {req: any, res: any};\n apiPostEvent: {req: any, res: any};\n\n // Emitters in UnsProxy\n unsProxyProducedTopics: { producedTopics: ITopicObject[], statusTopic: string };\n\n // Emitters in UnsProxy\n unsProxyProducedApiEndpoints: { producedApiEndpoints: IApiObject[], statusTopic: string };\n\n // Emitters in UnsProxy\n unsProxyProducedApiCatchAll: { producedCatchall: IApiCatchallMapping[], statusTopic: string };\n}\n\nexport interface IUnsExtendedData extends IUnsData {\n valueType: ValueTypeString;\n}\n\nexport interface IUnsData {\n time: ISO8601;\n value: ValueType;\n dataGroup?: string;\n uom?: MeasurementUnit;\n foreignEventKey?: string;\n intervalStart?: ISO8601 | number;\n intervalEnd?: ISO8601 | number;\n windowStart?: ISO8601 | number;\n windowEnd?: ISO8601 | number;\n eventId?: string;\n deleted?: boolean;\n deletedAt?: ISO8601 | number;\n lastSeen?: ISO8601 | number;\n}\n\nexport interface IUnsTableColumn {\n name: string;\n type: QuestDbType;\n value: string | number | boolean | null;\n uom?: MeasurementUnit;\n}\n\nexport interface IUnsTable {\n time: ISO8601;\n dataGroup?: string;\n columns: IUnsTableColumn[];\n intervalStart?: ISO8601 | number;\n intervalEnd?: ISO8601 | number;\n windowStart?: ISO8601 | number;\n windowEnd?: ISO8601 | number;\n eventId?: string;\n deleted?: boolean;\n deletedAt?: ISO8601 | number;\n lastSeen?: ISO8601 | number;\n}\n\nexport interface IMqttAttributeMessage {\n attribute: UnsAttribute;\n description?: string;\n tags?: UnsTags[];\n attributeNeedsPersistence?: boolean | null;\n /**\n * How the controller determines if this attribute is live or stale.\n * Defaults to `\"interval\"` with the controller's default interval (~120s) when omitted.\n *\n * @example\n * // Sensor publishing every 2 seconds:\n * { validityMode: \"interval\", expectedIntervalMs: 2000 }\n *\n * // Status that changes on events (never stale by time):\n * { validityMode: \"event\" }\n *\n * // Material location with ENTERED/EXITED lifecycle:\n * { validityMode: \"lifecycle\", lifecycleEndValue: \"EXITED\" }\n *\n * // Static configuration value:\n * { validityMode: \"static\" }\n */\n validityMode?: ValidityMode;\n /**\n * Expected publish interval in milliseconds. Only meaningful for `validityMode: \"interval\"`.\n * The controller marks the attribute as stale after ~2× this value without a heartbeat update.\n * Ignored for `\"event\"`, `\"lifecycle\"`, and `\"static\"` modes.\n */\n expectedIntervalMs?: number;\n /**\n * The string value that marks a lifecycle as completed. Only meaningful for `validityMode: \"lifecycle\"`.\n * When the attribute's current value matches this, the controller considers the lifecycle done.\n * Example: `\"EXITED\"` for a location attribute with ENTERED/EXITED events.\n */\n lifecycleEndValue?: string;\n}\n\ntype AttributePayload =\n | { message: IUnsMessage; data?: never; table?: never; createdAt?: never; expiresAt?: never }\n | { message?: never; data: IUnsData; table?: never; createdAt?: ISO8601; expiresAt?: ISO8601 }\n | { message?: never; data?: never; table: IUnsTable; createdAt?: ISO8601; expiresAt?: ISO8601 };\n\nexport type IMqttAttributeEntry = IMqttAttributeMessage & AttributePayload;\n\nexport interface IMqttPublishRequest {\n topic: UnsTopics;\n asset: UnsAsset;\n assetDescription?: string;\n objectType: UnsObjectType;\n objectTypeDescription?: string;\n objectId: UnsObjectId;\n attributes: IMqttAttributeEntry | IMqttAttributeEntry[];\n}\n\n// This interface represents a packet for a UNS system\nexport interface IUnsPacket {\n // The message object of the packet\n message: IUnsExtendedMessage;\n \n // The HMAC signature of the message\n messageSignature?: string;\n\n // Automatically calculated interval between two packets in ms\n interval?: number;\n\n // Current library version\n readonly version: string;\n\n // Autogenerated sequence number\n sequenceId?: number;\n}\n\nexport interface IUnsPackatParameters {\n\n}\n\nexport interface IUnsMessage {\n data?: IUnsData;\n table?: IUnsTable;\n expiresAt?: ISO8601;\n createdAt?: ISO8601;\n}\n\nexport interface IUnsExtendedMessage extends IUnsMessage {\n data?: IUnsExtendedData;\n}\n\n/**\n * Controls how the controller determines whether an attribute is live or stale.\n *\n * - `\"interval\"` — Attribute publishes periodically. Stale if no heartbeat within ~2× the expected interval.\n * Use with `expectedIntervalMs`. Example: temperature sensor publishing every 2s.\n *\n * - `\"event\"` — Attribute publishes on value change only. Never stale by time — only when the microservice stops.\n * Example: machine status (\"HEATING\" / \"COOLING\") that changes infrequently.\n *\n * - `\"lifecycle\"` — Attribute represents a lifecycle with a start and end event.\n * Use with `lifecycleEndValue` to mark the end state. Example: material location with \"ENTERED\" / \"EXITED\".\n *\n * - `\"static\"` — Attribute is set once and never changes (configuration, metadata). Always live.\n *\n * When omitted, defaults to `\"interval\"` with the controller's default interval (~120s).\n */\nexport type ValidityMode = \"interval\" | \"event\" | \"lifecycle\" | \"static\";\n\nexport interface ITopicObject {\n timestamp: string;\n attribute:string;\n attributeType: UnsAttributeType;\n topic:string;\n description:string;\n dataGroup:string;\n tags:string[] | null;\n attributeNeedsPersistence: boolean | null;\n asset: UnsAsset;\n assetDescription?: string;\n objectType: UnsObjectType;\n objectTypeDescription?: string;\n objectId: UnsObjectId;\n /** Liveliness validity mode — how the controller determines if this attribute is live/stale. */\n validityMode?: ValidityMode;\n /** For interval mode: expected publish interval in milliseconds (stale after ~2x this value). */\n expectedIntervalMs?: number;\n /** For lifecycle mode: the string value that marks the lifecycle as completed (e.g. \"EXITED\"). */\n lifecycleEndValue?: string;\n}\n\n// API Interfaces below\nexport interface IApiObject {\n timestamp: string;\n attribute:string;\n topic:string;\n attributeType: UnsAttributeType;\n apiDescription?: string; // Optional description for the API endpoint\n apiHost: string; // Hostname of the service\n apiEndpoint: string; // API endpoint for virtual topics\n apiSwaggerEndpoint: string; // Swagger endpoint for API documentation\n apiMethod: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\"; // HTTP method for API endpoint\n apiQueryParams: QueryParamDef[]; // query parameters for the API endpoint\n asset: UnsAsset;\n objectType: UnsObjectType;\n objectId: UnsObjectId;\n controllerName?: string;\n controllerHost?: string;\n controllerPort?: string;\n controllerPublicBase?: string;\n}\n\nexport interface IApiCatchallMapping {\n topic: string;\n apiBase: string;\n apiBasePath: string;\n swaggerPath: string;\n}\n\nexport interface QueryParamDef {\n name: string;\n type: \"string\" | \"number\" | \"boolean\";\n required?: boolean;\n description?: string;\n /**\n * Optional canonical chat alias used by assistant tooling.\n * Typical values: from, to, limit, topic, timezone, summaryOnly.\n */\n chatCanonical?: string;\n /**\n * Optional default query value. Included in generated OpenAPI metadata.\n */\n defaultValue?: string | number | boolean;\n}\n\nexport interface ApiChatDefaults {\n from?: string;\n to?: string;\n limit?: number;\n topic?: string;\n timezone?: string;\n summaryOnly?: boolean;\n [key: string]: string | number | boolean | undefined;\n}\n\nexport interface IApiProxyOptions {\n jwtSecret?: string;\n jwks?: {\n wellKnownJwksUrl: string;\n activeKidUrl?: string;\n cacheTtlMs?: number;\n algorithms?: (\"RS256\" | \"RS384\" | \"RS512\")[];\n };\n /**\n * Optional base prefixes to mount the API and swagger JSON under (e.g. \"/archiver-3\").\n * Defaults to \"/api\" when not provided.\n */\n apiBasePath?: string;\n swaggerBasePath?: string;\n /**\n * Skip mounting the default \"/api\" route. Useful when rebasing entirely under a custom prefix.\n */\n disableDefaultApiMount?: boolean;\n}\n\nexport interface IGetEndpointOptions {\n apiDescription?: string;\n tags?: string[];\n queryParams?: QueryParamDef[];\n /**\n * Optional defaults consumed by chat tooling (published as OpenAPI vendor extension x-uns-chat.defaults).\n */\n chatDefaults?: ApiChatDefaults;\n}\n\nexport interface IPostEndpointOptions {\n apiDescription?: string;\n tags?: string[];\n requestBody?: {\n description?: string;\n required?: boolean;\n schema?: Record<string, unknown>;\n };\n}\n"]}
1
+ {"version":3,"file":"uns-interfaces.js","sourceRoot":"","sources":["../../src/uns/uns-interfaces.ts"],"names":[],"mappings":"AAUA,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,MAAM,YAAY,GAAG,+CAA+C,CAAC;IACrE,OAAO,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAClC,CAAC;AAID,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAU,CAAC;AAIxD,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,SAAS;IACT,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,KAAK;IACL,OAAO;IACP,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,MAAM;IACN,MAAM;IACN,WAAW;IACX,cAAc;IACd,QAAQ;IACR,MAAM;IACN,QAAQ;IACR,SAAS;CACD,CAAC;AAEX,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAAS,qBAAqB,CAAC,CAAC;AACvE,MAAM,mBAAmB,GAAG,sBAAsB,CAAC;AACnD,MAAM,mBAAmB,GAAG,sBAAsB,CAAC;AACnD,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAW3C,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,uBAAuB,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,CACL,mBAAmB,CAAC,IAAI,CAAC,KAAK,CAAC;QAC/B,mBAAmB,CAAC,IAAI,CAAC,KAAK,CAAC;QAC/B,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,CAC9B,CAAC;AACJ,CAAC","sourcesContent":["import { UnsAttributeType } from \"../graphql/schema.js\";\nimport { MeasurementUnit } from \"./uns-measurements.js\";\nimport { UnsTags } from \"./uns-tags.js\";\nimport type { UnsObjectId, UnsObjectType } from \"./uns-object.js\";\nimport type { UnsAsset } from \"./uns-asset.js\";\nimport type { IMqttConnectProperties, IMqttPublishOptions, IMqttServerConfig, MqttProtocol } from \"../uns-mqtt/mqtt-interfaces.js\";\nimport { UnsTopics } from \"./uns-topics.js\";\nimport { knownUnsAttributes, type KnownUnsAttributeName } from \"./uns-attributes.js\";\n\nexport type ISO8601 = `${number}-${string}-${string}T${string}:${string}:${string}.${string}Z`;\nexport function isIOS8601Type(value: string): value is ISO8601 {\n const iso8601Regex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/;\n return iso8601Regex.test(value);\n}\n// Known attribute names (with IntelliSense) while still allowing arbitrary strings.\nexport type UnsAttribute = KnownUnsAttributeName | (string & {});\n\nexport const valueTypes = [\"string\", \"number\"] as const;\nexport type ValueTypeString = (typeof valueTypes)[number];\nexport type ValueType = string | number;\n\nexport const questDbPrimitiveTypes = [\n \"boolean\",\n \"ipv4\",\n \"byte\",\n \"short\",\n \"char\",\n \"int\",\n \"float\",\n \"symbol\",\n \"varchar\",\n \"string\",\n \"long\",\n \"date\",\n \"timestamp\",\n \"timestamp_ns\",\n \"double\",\n \"uuid\",\n \"binary\",\n \"long256\",\n] as const;\n\nconst questDbPrimitiveTypeSet = new Set<string>(questDbPrimitiveTypes);\nconst questDbGeohashRegex = /^geohash\\(\\d+[bc]\\)$/;\nconst questDbDecimalRegex = /^decimal\\(\\d+,\\d+\\)$/;\nconst questDbArrayRegex = /^array<[^>]+>$/;\n\nexport type QuestDbPrimitiveType = (typeof questDbPrimitiveTypes)[number];\n\n// Supported QuestDB column types for UNS tables.\nexport type QuestDbType =\n | QuestDbPrimitiveType\n | `geohash(${number}${\"b\" | \"c\"})`\n | `decimal(${number},${number})`\n | `array<${string}>`;\n\nexport function isQuestDbType(value: unknown): value is QuestDbType {\n if (typeof value !== \"string\") {\n return false;\n }\n if (questDbPrimitiveTypeSet.has(value)) {\n return true;\n }\n return (\n questDbGeohashRegex.test(value) ||\n questDbDecimalRegex.test(value) ||\n questDbArrayRegex.test(value)\n );\n}\n\nexport interface IUnsParameters {\n mqttSubToTopics?: string | string[];\n username?: string;\n password?: string;\n mqttSSL?: boolean;\n publishThrottlingDelay?: number; // Delay in milliseconds; default is 1ms\n subscribeThrottlingDelay?: number; // Delay in milliseconds; default is 1ms\n rejectUnauthorized?: boolean;\n clientId?: string;\n hosts?: string[];\n servers?: IMqttServerConfig[];\n port?: number;\n protocol?: MqttProtocol;\n keepalive?: number;\n clean?: boolean;\n connectTimeout?: number;\n reconnectPeriod?: number;\n reconnectOnConnackError?: boolean;\n resubscribe?: boolean;\n queueQoSZero?: boolean;\n properties?: IMqttConnectProperties;\n ca?: string;\n cert?: string;\n key?: string;\n servername?: string;\n /**\n * Default MQTT publish options applied to all outgoing messages\n * (e.g., qos, retain, messageExpiryInterval).\n */\n defaultPublishOptions?: IMqttPublishOptions;\n}\n\nexport interface IUnsProcessParameters {\n processName: string;\n mqttSubToTopics?: string | string[];\n username?: string;\n password?: string;\n mqttSSL?: boolean;\n clientId?: string;\n hosts?: string[];\n servers?: IMqttServerConfig[];\n port?: number;\n protocol?: MqttProtocol;\n keepalive?: number;\n clean?: boolean;\n connectTimeout?: number;\n reconnectPeriod?: number;\n reconnectOnConnackError?: boolean;\n resubscribe?: boolean;\n queueQoSZero?: boolean;\n rejectUnauthorized?: boolean;\n properties?: IMqttConnectProperties;\n ca?: string;\n cert?: string;\n key?: string;\n servername?: string;\n}\n\nexport interface UnsEvents {\n // Emitters in MqttProxy, UnsMqttProxy\n input: { topic: string; message: string, packet: any };\n mqttProxyStatus: { event: string, value: number, uom: MeasurementUnit, statusTopic: string };\n \n // Emitters in MqttProxy\n error: { code: number; message: string };\n \n // Emitters in UnsMqttProxy\n mqttWorker: { command: string, instanceName: string; batchSize: number, referenceHash: string };\n\n // Emitter in UnsCronProxy\n cronEvent: { event?: string; cronExpression?: string };\n\n // Emitters in UnsApiProxy\n apiGetEvent: {req: any, res: any};\n apiPostEvent: {req: any, res: any};\n\n // Emitters in UnsProxy\n unsProxyProducedTopics: { producedTopics: ITopicObject[], statusTopic: string };\n\n // Emitters in UnsProxy\n unsProxyProducedApiEndpoints: { producedApiEndpoints: IApiObject[], statusTopic: string };\n\n // Emitters in UnsProxy\n unsProxyProducedApiCatchAll: { producedCatchall: IApiCatchallMapping[], statusTopic: string };\n}\n\nexport interface IUnsExtendedData extends IUnsData {\n valueType: ValueTypeString;\n}\n\nexport interface IUnsData {\n time: ISO8601;\n value: ValueType;\n dataGroup?: string;\n uom?: MeasurementUnit;\n foreignEventKey?: string;\n intervalStart?: ISO8601 | number;\n intervalEnd?: ISO8601 | number;\n windowStart?: ISO8601 | number;\n windowEnd?: ISO8601 | number;\n eventId?: string;\n deleted?: boolean;\n deletedAt?: ISO8601 | number;\n lastSeen?: ISO8601 | number;\n}\n\nexport interface IUnsTableColumn {\n name: string;\n type: QuestDbType;\n value: string | number | boolean | null;\n uom?: MeasurementUnit;\n}\n\nexport interface IUnsTable {\n time: ISO8601;\n dataGroup?: string;\n columns: IUnsTableColumn[];\n intervalStart?: ISO8601 | number;\n intervalEnd?: ISO8601 | number;\n windowStart?: ISO8601 | number;\n windowEnd?: ISO8601 | number;\n eventId?: string;\n deleted?: boolean;\n deletedAt?: ISO8601 | number;\n lastSeen?: ISO8601 | number;\n}\n\nexport interface IMqttAttributeMessage {\n attribute: UnsAttribute;\n description?: string;\n tags?: UnsTags[];\n attributeNeedsPersistence?: boolean | null;\n /**\n * How the controller determines if this attribute is live or stale.\n * Defaults to `\"interval\"` with the controller's default interval (~120s) when omitted.\n *\n * @example\n * // Sensor publishing every 2 seconds:\n * { validityMode: \"interval\", expectedIntervalMs: 2000 }\n *\n * // Status attribute publishing every 2 seconds (string values like \"HEATING\"):\n * { validityMode: \"interval\", expectedIntervalMs: 2000 }\n *\n * // Material location with ENTERED/EXITED lifecycle:\n * { validityMode: \"lifecycle\", lifecycleEndValue: \"EXITED\" }\n *\n * // Static configuration value:\n * { validityMode: \"static\" }\n */\n validityMode?: ValidityMode;\n /**\n * Expected publish interval in milliseconds. Only meaningful for `validityMode: \"interval\"`.\n * The controller marks the attribute as stale after ~2× this value without a heartbeat update.\n * Ignored for `\"lifecycle\"` and `\"static\"` modes.\n */\n expectedIntervalMs?: number;\n /**\n * The string value that marks a lifecycle as completed. Only meaningful for `validityMode: \"lifecycle\"`.\n * When the attribute's current value matches this, the controller considers the lifecycle done.\n * Example: `\"EXITED\"` for a location attribute with ENTERED/EXITED events.\n */\n lifecycleEndValue?: string;\n}\n\ntype AttributePayload =\n | { message: IUnsMessage; data?: never; table?: never; createdAt?: never; expiresAt?: never }\n | { message?: never; data: IUnsData; table?: never; createdAt?: ISO8601; expiresAt?: ISO8601 }\n | { message?: never; data?: never; table: IUnsTable; createdAt?: ISO8601; expiresAt?: ISO8601 };\n\nexport type IMqttAttributeEntry = IMqttAttributeMessage & AttributePayload;\n\nexport interface IMqttPublishRequest {\n topic: UnsTopics;\n asset: UnsAsset;\n assetDescription?: string;\n objectType: UnsObjectType;\n objectTypeDescription?: string;\n objectId: UnsObjectId;\n attributes: IMqttAttributeEntry | IMqttAttributeEntry[];\n}\n\n// This interface represents a packet for a UNS system\nexport interface IUnsPacket {\n // The message object of the packet\n message: IUnsExtendedMessage;\n \n // The HMAC signature of the message\n messageSignature?: string;\n\n // Automatically calculated interval between two packets in ms\n interval?: number;\n\n // Current library version\n readonly version: string;\n\n // Autogenerated sequence number\n sequenceId?: number;\n}\n\nexport interface IUnsPackatParameters {\n\n}\n\nexport interface IUnsMessage {\n data?: IUnsData;\n table?: IUnsTable;\n expiresAt?: ISO8601;\n createdAt?: ISO8601;\n}\n\nexport interface IUnsExtendedMessage extends IUnsMessage {\n data?: IUnsExtendedData;\n}\n\n/**\n * Controls how the controller determines whether an attribute is live or stale.\n *\n * - `\"interval\"` — Attribute publishes periodically. Stale if no heartbeat within ~2× the expected interval.\n * Use with `expectedIntervalMs`. Works for both numeric sensors (temperature every 2s)\n * and string status attributes (status every 2s). Example:\n * `{ validityMode: \"interval\", expectedIntervalMs: 2000 }`\n *\n * - `\"lifecycle\"` — Attribute represents a lifecycle with a start and end event.\n * Use with `lifecycleEndValue` to mark the end state. Example: material location with \"ENTERED\" / \"EXITED\".\n *\n * - `\"static\"` — Attribute is set once and never changes (configuration, metadata). Always live.\n *\n * When omitted, defaults to `\"interval\"` with the controller's default interval (~120s).\n */\nexport type ValidityMode = \"interval\" | \"lifecycle\" | \"static\";\n\nexport interface ITopicObject {\n timestamp: string;\n attribute:string;\n attributeType: UnsAttributeType;\n topic:string;\n description:string;\n dataGroup:string;\n tags:string[] | null;\n attributeNeedsPersistence: boolean | null;\n asset: UnsAsset;\n assetDescription?: string;\n objectType: UnsObjectType;\n objectTypeDescription?: string;\n objectId: UnsObjectId;\n /** Liveliness validity mode — how the controller determines if this attribute is live/stale. */\n validityMode?: ValidityMode;\n /** For interval mode: expected publish interval in milliseconds (stale after ~2x this value). */\n expectedIntervalMs?: number;\n /** For lifecycle mode: the string value that marks the lifecycle as completed (e.g. \"EXITED\"). */\n lifecycleEndValue?: string;\n}\n\n// API Interfaces below\nexport interface IApiObject {\n timestamp: string;\n attribute:string;\n topic:string;\n attributeType: UnsAttributeType;\n apiDescription?: string; // Optional description for the API endpoint\n apiHost: string; // Hostname of the service\n apiEndpoint: string; // API endpoint for virtual topics\n apiSwaggerEndpoint: string; // Swagger endpoint for API documentation\n apiMethod: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\"; // HTTP method for API endpoint\n apiQueryParams: QueryParamDef[]; // query parameters for the API endpoint\n asset: UnsAsset;\n objectType: UnsObjectType;\n objectId: UnsObjectId;\n controllerName?: string;\n controllerHost?: string;\n controllerPort?: string;\n controllerPublicBase?: string;\n}\n\nexport interface IApiCatchallMapping {\n topic: string;\n apiBase: string;\n apiBasePath: string;\n swaggerPath: string;\n}\n\nexport interface QueryParamDef {\n name: string;\n type: \"string\" | \"number\" | \"boolean\";\n required?: boolean;\n description?: string;\n /**\n * Optional canonical chat alias used by assistant tooling.\n * Typical values: from, to, limit, topic, timezone, summaryOnly.\n */\n chatCanonical?: string;\n /**\n * Optional default query value. Included in generated OpenAPI metadata.\n */\n defaultValue?: string | number | boolean;\n}\n\nexport interface ApiChatDefaults {\n from?: string;\n to?: string;\n limit?: number;\n topic?: string;\n timezone?: string;\n summaryOnly?: boolean;\n [key: string]: string | number | boolean | undefined;\n}\n\nexport interface IApiProxyOptions {\n jwtSecret?: string;\n jwks?: {\n wellKnownJwksUrl: string;\n activeKidUrl?: string;\n cacheTtlMs?: number;\n algorithms?: (\"RS256\" | \"RS384\" | \"RS512\")[];\n };\n /**\n * Optional base prefixes to mount the API and swagger JSON under (e.g. \"/archiver-3\").\n * Defaults to \"/api\" when not provided.\n */\n apiBasePath?: string;\n swaggerBasePath?: string;\n /**\n * Skip mounting the default \"/api\" route. Useful when rebasing entirely under a custom prefix.\n */\n disableDefaultApiMount?: boolean;\n}\n\nexport interface IGetEndpointOptions {\n apiDescription?: string;\n tags?: string[];\n queryParams?: QueryParamDef[];\n /**\n * Optional defaults consumed by chat tooling (published as OpenAPI vendor extension x-uns-chat.defaults).\n */\n chatDefaults?: ApiChatDefaults;\n}\n\nexport interface IPostEndpointOptions {\n apiDescription?: string;\n tags?: string[];\n requestBody?: {\n description?: string;\n required?: boolean;\n schema?: Record<string, unknown>;\n };\n}\n"]}
@@ -676,9 +676,9 @@ export declare const unsCoreSchema: z.ZodObject<{
676
676
  projectId?: string;
677
677
  };
678
678
  processName?: string;
679
+ email?: string;
679
680
  graphql?: string;
680
681
  rest?: string;
681
- email?: string;
682
682
  instanceMode?: "wait" | "force" | "handover";
683
683
  jwksWellKnownUrl?: string;
684
684
  kidWellKnownUrl?: string;
@@ -700,9 +700,9 @@ export declare const unsCoreSchema: z.ZodObject<{
700
700
  projectId?: string;
701
701
  };
702
702
  processName?: string;
703
+ email?: string;
703
704
  graphql?: string;
704
705
  rest?: string;
705
- email?: string;
706
706
  instanceMode?: "wait" | "force" | "handover";
707
707
  jwksWellKnownUrl?: string;
708
708
  kidWellKnownUrl?: string;
@@ -2649,9 +2649,9 @@ export declare const unsCoreSchema: z.ZodObject<{
2649
2649
  projectId?: string;
2650
2650
  };
2651
2651
  processName?: string;
2652
+ email?: string;
2652
2653
  graphql?: string;
2653
2654
  rest?: string;
2654
- email?: string;
2655
2655
  instanceMode?: "wait" | "force" | "handover";
2656
2656
  jwksWellKnownUrl?: string;
2657
2657
  kidWellKnownUrl?: string;
@@ -2970,9 +2970,9 @@ export declare const unsCoreSchema: z.ZodObject<{
2970
2970
  projectId?: string;
2971
2971
  };
2972
2972
  processName?: string;
2973
+ email?: string;
2973
2974
  graphql?: string;
2974
2975
  rest?: string;
2975
- email?: string;
2976
2976
  instanceMode?: "wait" | "force" | "handover";
2977
2977
  jwksWellKnownUrl?: string;
2978
2978
  kidWellKnownUrl?: string;
@@ -374,9 +374,9 @@ export default class UnsMqttProxy extends UnsProxy {
374
374
  const objectTypeDescription = msg.objectTypeDescription ?? (objectType ? getObjectTypeDescription(objectType) : undefined);
375
375
  // Runtime validation for validity fields
376
376
  if (msg.validityMode) {
377
- const validModes = new Set(["interval", "event", "lifecycle", "static"]);
377
+ const validModes = new Set(["interval", "lifecycle", "static"]);
378
378
  if (!validModes.has(msg.validityMode)) {
379
- logger.warn(`${this.instanceNameWithSuffix} - Invalid validityMode "${msg.validityMode}" for attribute "${msg.attribute}". Expected: interval | event | lifecycle | static.`);
379
+ logger.warn(`${this.instanceNameWithSuffix} - Invalid validityMode "${msg.validityMode}" for attribute "${msg.attribute}". Expected: interval | lifecycle | static.`);
380
380
  }
381
381
  if (msg.expectedIntervalMs && msg.validityMode !== "interval") {
382
382
  logger.warn(`${this.instanceNameWithSuffix} - expectedIntervalMs is set but validityMode is "${msg.validityMode}" (only used with "interval") for attribute "${msg.attribute}".`);
@@ -1 +1 @@
1
- {"version":3,"file":"uns-mqtt-proxy.js","sourceRoot":"","sources":["../../src/uns-mqtt/uns-mqtt-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAElC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,MAAM,MAAM,cAAc,CAAC;AAElC,OAAO,EAAE,wBAAwB,EAAwC,MAAM,sBAAsB,CAAC;AAGtG,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAInE,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;AAC5D,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;AAEtE,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACrE,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC9D,MAAM,gBAAgB,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,mCAAmC,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,CAAC;QACb,4CAA4C;QAC5C,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC;gBACH,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;gBAC/C,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,sBAAsB,uCAAuC,QAAQ,EAAE,CAAC,CAAC;YAC/F,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,sBAAsB,gCAAgC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9F,CAAC;QACH,CAAC;QAED,2CAA2C;QAC3C,KAAK,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACjD,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC,CAAC;YACvD,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;CAEF","sourcesContent":["import { readFileSync } from \"fs\";\nimport { IClientPublishOptions } from \"mqtt\";\nimport * as path from \"path\";\nimport { Worker } from \"worker_threads\";\nimport { fileURLToPath } from \"url\";\nimport { basePath } from \"../base-path.js\";\nimport logger from \"../logger.js\";\nimport { IMqttPublishRequest, IUnsMessage, IUnsPacket, IUnsParameters, UnsAttribute, UnsEvents, ValueType } from \"../uns/uns-interfaces.js\";\nimport { getObjectTypeDescription, type UnsObjectId, type UnsObjectType } from \"../uns/uns-object.js\";\nimport type { UnsAsset } from \"../uns/uns-asset.js\";\nimport { MeasurementUnit } from \"../uns/uns-measurements.js\";\nimport { UnsPacket } from \"../uns/uns-packet.js\";\nimport { IMqttParameters, IMqttWorkerData } from \"./mqtt-interfaces.js\";\nimport { MqttTopicBuilder } from \"./mqtt-topic-builder.js\";\nimport UnsProxy from \"../uns/uns-proxy.js\";\nimport { UnsAttributeType } from \"../graphql/schema.js\";\nimport { getAttributeDescription } from \"../uns/uns-attributes.js\";\nimport { UnsTags } from \"../uns/uns-tags.js\";\nimport { UnsTopics } from \"../uns/uns-topics.js\";\n\nconst packageJsonPath = path.join(basePath, \"package.json\");\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\nconst moduleDirectory = path.dirname(fileURLToPath(import.meta.url));\nconst packageRoot = path.resolve(moduleDirectory, \"..\", \"..\");\nconst workerScriptPath = path.join(packageRoot, \"dist/uns-mqtt/mqtt-worker-init.js\");\n\nexport enum MessageMode {\n Raw = 'raw', // Send only the original message\n Delta = 'delta', // Send only the delta message\n Both = 'both' // Send both the original and delta messages\n}\n\ntype InternalMqttMessage = {\n topic: UnsTopics;\n attribute: UnsAttribute;\n asset: UnsAsset;\n assetDescription?: string;\n objectType: UnsObjectType;\n objectTypeDescription?: string;\n objectId: UnsObjectId;\n description?: string;\n tags?: UnsTags[];\n attributeNeedsPersistence?: boolean | null;\n validityMode?: \"interval\" | \"event\" | \"lifecycle\" | \"static\";\n expectedIntervalMs?: number;\n lifecycleEndValue?: string;\n packet: IUnsPacket;\n};\n\nexport default class UnsMqttProxy extends UnsProxy {\n private lastValues: Map<string, { value: ValueType; uom: string; timestamp: Date }> = new Map();\n private worker: Worker;\n private pendingEnqueues: Map<string, { resolve: () => void; reject: (reason?: any) => void }> = new Map();\n private unsParameters: IUnsParameters;\n protected processStatusTopic: string;\n public instanceName: string;\n private currentSequenceId: Map<string, number> = new Map();\n private topicBuilder: MqttTopicBuilder;\n\n constructor(\n mqttHost: string,\n processName: string,\n instanceName: string,\n unsParameters?: IUnsParameters,\n publisherActive: boolean = false,\n subscriberActive: boolean = false\n ) {\n super();\n this.instanceName = instanceName;\n // Create the topic builder using packageJson values and the processName.\n this.topicBuilder = new MqttTopicBuilder(`uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageJson.name)}/${MqttTopicBuilder.sanitizeTopicPart(packageJson.version)}/${MqttTopicBuilder.sanitizeTopicPart(processName)}/`);\n\n // Generate the processStatusTopic using the builder.\n this.processStatusTopic = this.topicBuilder.getProcessStatusTopic();\n // Derive the instanceStatusTopic by appending the instance name.\n this.instanceStatusTopic = this.processStatusTopic + instanceName + \"/\";\n\n // Concatenate processName with instanceName for the worker identification.\n this.instanceNameWithSuffix = `${processName}-${instanceName}`;\n \n const mqttParameters: IMqttParameters = {\n mqttSubToTopics: unsParameters?.mqttSubToTopics ?? [],\n username: unsParameters?.username ?? \"\",\n password: unsParameters?.password ?? \"\",\n mqttSSL: unsParameters?.mqttSSL ?? false,\n statusTopic: this.instanceStatusTopic,\n rejectUnauthorized: unsParameters?.rejectUnauthorized ?? false,\n clientId: unsParameters?.clientId,\n hosts: unsParameters?.hosts,\n servers: unsParameters?.servers,\n port: unsParameters?.port,\n protocol: unsParameters?.protocol,\n keepalive: unsParameters?.keepalive,\n clean: unsParameters?.clean,\n connectTimeout: unsParameters?.connectTimeout,\n reconnectPeriod: unsParameters?.reconnectPeriod,\n reconnectOnConnackError: unsParameters?.reconnectOnConnackError,\n resubscribe: unsParameters?.resubscribe,\n queueQoSZero: unsParameters?.queueQoSZero,\n properties: unsParameters?.properties,\n ca: unsParameters?.ca,\n cert: unsParameters?.cert,\n key: unsParameters?.key,\n servername: unsParameters?.servername,\n };\n this.unsParameters = unsParameters ?? {};\n this.startQueueWorker(mqttHost, this.instanceNameWithSuffix, mqttParameters, publisherActive, subscriberActive);\n }\n\n /**\n * Resolve object identity from explicit fields or the tail of the topic path.\n * Falls back to parsing when not provided for backward compatibility.\n */\n private resolveObjectIdentity(msg: InternalMqttMessage): { objectType?: UnsObjectType; objectId?: UnsObjectId; asset?: UnsAsset } {\n const providedType = msg.objectType;\n const providedId = msg.objectId;\n const providedAsset = msg.asset;\n\n const topicParts = msg.topic.split(\"/\").filter((part) => part.length > 0);\n const hasObjectTail = topicParts.length >= 2;\n const parsedType = hasObjectTail ? topicParts[topicParts.length - 2] as UnsObjectType : undefined;\n const parsedId = hasObjectTail ? topicParts[topicParts.length - 1] as UnsObjectId : undefined;\n const parsedAsset = hasObjectTail\n ? (topicParts.length >= 3 ? topicParts[topicParts.length - 3] as UnsAsset : undefined)\n : (topicParts.length >= 1 ? topicParts[topicParts.length - 1] as UnsAsset : undefined);\n\n const objectType = providedType ?? parsedType;\n const objectId = providedId ?? parsedId ?? \"main\";\n const asset = providedAsset ?? parsedAsset;\n\n // If values are provided, trust them; otherwise derive from topic.\n if (!providedType || !providedId) {\n if (parsedType && parsedId) {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; derived from topic tail ${parsedType}/${parsedId}`);\n } else {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; defaulting objectId to 'main' for topic '${msg.topic}'. Expected topic to end with '<objectType>/<objectId>/'`);\n }\n }\n // Asset is optional; no warning on mismatch to avoid noisy logs when base topics don't carry it.\n\n msg.objectType = objectType;\n msg.objectId = objectId;\n msg.asset = asset;\n\n return { objectType, objectId, asset };\n }\n\n /**\n * Ensure the topic ends with a trailing slash for attribute concatenation.\n */\n private normalizeTopicWithObject(topic: string): string {\n return topic.endsWith(\"/\") ? topic : `${topic}/`;\n }\n\n /**\n * Starts a worker thread to process the throttled publish queue.\n */\n private startQueueWorker(\n mqttHost: string,\n instanceNameWithSuffix: string,\n mqttParameters: IMqttParameters,\n publisherActive: boolean,\n subscriberActive: boolean\n ): void {\n const workerData: IMqttWorkerData = {\n publishThrottlingDelay: this.unsParameters.publishThrottlingDelay ?? 1,\n subscribeThrottlingDelay: this.unsParameters.subscribeThrottlingDelay ?? 1,\n persistToDisk: false,\n mqttHost: mqttHost,\n instanceNameWithSuffix: instanceNameWithSuffix,\n mqttParameters: mqttParameters,\n publisherActive,\n subscriberActive,\n defaultPublishOptions: this.unsParameters.defaultPublishOptions,\n };\n\n this.worker = new Worker(workerScriptPath, { workerData });\n\n this.worker.on(\"message\", (msg) => {\n if (msg && msg.command === \"enqueueResult\" && msg.id) {\n const pending = this.pendingEnqueues.get(msg.id);\n if (pending) {\n if (msg.status === \"success\" && msg.topic && msg.message) {\n pending.resolve();\n } else {\n pending.reject(new Error(msg.error));\n }\n this.pendingEnqueues.delete(msg.id);\n }\n } else if (msg && msg.command === \"input\") {\n this.event.emit(\"input\", { topic: msg.topic, message: msg.message.toString(), packet: msg.packet });\n } else if (msg && (msg.command === \"handover_subscriber\" || msg.command === \"handover_publisher\")) {\n this.event.emit(\"mqttWorker\", { command: msg.command, batchSize: msg.batchSize, referenceHash: msg.referenceHash, instanceName: this.instanceName });\n } else if (msg && msg.command === \"mqttProxyStatus\") {\n this.event.emit(\"mqttProxyStatus\", { event: msg.event, value: msg.value, uom: msg.uom, statusTopic: msg.statusTopic });\n }\n });\n\n this.worker.on(\"error\", (err) => {\n logger.error(\"Error in worker:\", err);\n const reason = err instanceof Error ? err : new Error(String(err));\n for (const pending of this.pendingEnqueues.values()) {\n pending.reject(reason);\n }\n this.pendingEnqueues.clear();\n });\n\n this.worker.on(\"exit\", (code) => {\n if (code !== 0) {\n logger.error(`Worker exited with code ${code}`);\n const reason = new Error(`MQTT worker exited with code ${code}`);\n for (const pending of this.pendingEnqueues.values()) {\n pending.reject(reason);\n }\n this.pendingEnqueues.clear();\n }\n });\n }\n\n /**\n * Enqueues a message to the worker queue.\n *\n * @param topic - The topic to which the message belongs.\n * @param message - The message to be enqueued.\n * @param options - Optional publish options.\n * @returns A promise that resolves when the message is successfully enqueued.\n */\n private async enqueueMessageToWorkerQueue(topic: string, message: string, options?: IClientPublishOptions): Promise<void> {\n return new Promise((resolve, reject) => {\n // const id: string = String(this.currentSequenceId.get(topic) ?? 0);\n const id = `${Date.now()}-${Math.random()}`;\n this.pendingEnqueues.set(id, { resolve, reject });\n this.worker.postMessage({ command: \"enqueue\", id, topic, message, options });\n });\n }\n\n /**\n * Sets the publisher active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setPublisherActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setPublisherActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the publisher to passive mode.\n * @returns A promise that resolves when the publisher is set to passive.\n */\n public setPublisherPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setPublisherPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_publisher\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n /**\n * Sets the subscriber active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setSubscriberActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setSubscriberActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the subscriber to passive mode.\n * @returns A promise that resolves when the subscriber is set to passive.\n */\n public setSubscriberPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setSubscriberPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_subscriber\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n\n /**\n * Sets the subscriber to passive mode and allows the publisher to run\n * until the queue is empty (all messages are processed).\n */\n public async setSubscriberPassiveAndDrainQueue(): Promise<UnsEvents[\"mqttWorker\"]> {\n return new Promise(async (resolve) => {\n const mqttWorkerData = await this.setSubscriberPassive();\n while (this.pendingEnqueues.size > 0) {\n await new Promise((resolve) => setTimeout(resolve, 100)); // Poll every 100ms\n }\n logger.info(`${this.instanceNameWithSuffix} - Subscriber set to passive and queue drained.`);\n resolve(mqttWorkerData);\n });\n }\n\n /**\n * Processes and publishes MQTT messages based on the selected message mode.\n *\n * @param mqttMessage - The MQTT message object.\n * @param mode - The message mode (Raw, Delta, or Both).\n */\n public async publishMqttMessage(mqttMessage: IMqttPublishRequest | null, mode: MessageMode = MessageMode.Raw) {\n if (!mqttMessage) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing mqtt message: mqttMessage must be defined.`);\n return;\n }\n\n const attrs = Array.isArray(mqttMessage.attributes)\n ? mqttMessage.attributes\n : [mqttMessage.attributes];\n const { topic, asset, assetDescription, objectType, objectTypeDescription, objectId } = mqttMessage;\n for (const attrEntry of attrs) {\n const attrDescription = attrEntry.description ?? getAttributeDescription(attrEntry.attribute);\n const message: IUnsMessage =\n \"message\" in attrEntry && attrEntry.message\n ? attrEntry.message\n : \"data\" in attrEntry && attrEntry.data\n ? { data: attrEntry.data, createdAt: attrEntry.createdAt, expiresAt: attrEntry.expiresAt }\n : \"table\" in attrEntry && attrEntry.table\n ? { table: attrEntry.table, createdAt: attrEntry.createdAt, expiresAt: attrEntry.expiresAt }\n : (() => { throw new Error(\"Attribute entry must include exactly one of data/table/message\"); })();\n const packet = await UnsPacket.unsPacketFromUnsMessage(message);\n const singleMsg: InternalMqttMessage = {\n topic,\n asset,\n assetDescription,\n objectType,\n objectTypeDescription,\n objectId,\n attribute: attrEntry.attribute,\n description: attrDescription,\n tags: attrEntry.tags,\n attributeNeedsPersistence: attrEntry.attributeNeedsPersistence,\n ...(attrEntry.validityMode ? { validityMode: attrEntry.validityMode } : {}),\n ...(attrEntry.expectedIntervalMs ? { expectedIntervalMs: attrEntry.expectedIntervalMs } : {}),\n ...(attrEntry.lifecycleEndValue ? { lifecycleEndValue: attrEntry.lifecycleEndValue } : {}),\n packet,\n };\n\n // existing single-attribute flow\n const baseDescription =\n singleMsg.description ??\n getAttributeDescription(singleMsg.attribute) ??\n singleMsg.attribute;\n const mqttMessageWithDesc = { ...singleMsg, description: baseDescription };\n\n const time = UnsPacket.formatToISO8601(new Date());\n switch (mode) {\n case MessageMode.Raw: {\n await this.processAndEnqueueMessage(mqttMessageWithDesc, time, false);\n break;\n }\n case MessageMode.Delta: {\n const deltaMessage = { ...mqttMessageWithDesc };\n deltaMessage.attribute = `${mqttMessageWithDesc.attribute}-delta`;\n deltaMessage.description = `${baseDescription ?? \"\"} (delta)`;\n await this.processAndEnqueueMessage(deltaMessage, time, true);\n break;\n }\n case MessageMode.Both: {\n await this.processAndEnqueueMessage(mqttMessageWithDesc, time, false);\n const deltaMessageBoth = { ...mqttMessageWithDesc };\n deltaMessageBoth.attribute = `${mqttMessageWithDesc.attribute}-delta`;\n deltaMessageBoth.description = `${baseDescription ?? \"\"} (delta)`;\n await this.processAndEnqueueMessage(deltaMessageBoth, time, true);\n break;\n }\n }\n }\n return;\n }\n\n /**\n * Publishes a message to a specified topic.\n *\n * @param topic - The MQTT topic.\n * @param message - The message to publish.\n * @returns A promise that resolves when enqueued.\n */\n public publishMessage(topic: string, message: string, options?: IClientPublishOptions): Promise<void> {\n return this.enqueueMessageToWorkerQueue(topic, message, options);\n }\n\n /**\n * Parses an MQTT packet from a JSON string.\n *\n * @param mqttPacket - The MQTT packet string.\n * @returns A parsed IUnsPacket object or null.\n */\n public parseMqttPacket(mqttPacket: string): IUnsPacket | null {\n return UnsPacket.parseMqttPacket(mqttPacket, this.instanceNameWithSuffix);\n }\n\n /**\n * Subscribes asynchronously to one or more topics.\n *\n * @param topics - A topic or list of topics.\n */\n public subscribeAsync(topics: string | string[]): void {\n this.worker.postMessage({ command: \"subscribeAsync\", topics });\n }\n\n /**\n * Unsubscribes asynchronously from the given topics.\n *\n * @param topics - A list of topics.\n */\n public unsubscribeAsync(topics: string[]): void {\n this.worker.postMessage({ command: \"unsubscribeAsync\", topics });\n }\n\n /**\n * Processes and enqueues a message to the worker queue, including handling\n * sequencing, value differences, and tracking of unique topics.\n *\n * @param msg - The MQTT message to process.\n * @param time - The timestamp.\n * @param valueIsCumulative - Whether the value is cumulative.\n */\n private async processAndEnqueueMessage(msg: InternalMqttMessage, time: string, valueIsCumulative: boolean = false): Promise<void> {\n try {\n const attributeType =\n msg.packet.message.data ? UnsAttributeType.Data :\n msg.packet.message.table ? UnsAttributeType.Table : null;\n \n let dataGroup = \"\";\n if (attributeType == UnsAttributeType.Data)\n dataGroup = msg.packet.message.data.dataGroup ?? \"\";\n if (attributeType == UnsAttributeType.Table)\n dataGroup = msg.packet.message.table.dataGroup ?? \"\";\n\n const { objectType, objectId, asset } = this.resolveObjectIdentity(msg);\n const normalizedTopic = this.normalizeTopicWithObject(msg.topic);\n msg.topic = normalizedTopic;\n const description = msg.description ?? getAttributeDescription(msg.attribute as string) ?? \"\";\n const objectTypeDescription = msg.objectTypeDescription ?? (objectType ? getObjectTypeDescription(objectType) : undefined);\n\n // Runtime validation for validity fields\n if (msg.validityMode) {\n const validModes = new Set([\"interval\", \"event\", \"lifecycle\", \"static\"]);\n if (!validModes.has(msg.validityMode)) {\n logger.warn(`${this.instanceNameWithSuffix} - Invalid validityMode \"${msg.validityMode}\" for attribute \"${msg.attribute}\". Expected: interval | event | lifecycle | static.`);\n }\n if (msg.expectedIntervalMs && msg.validityMode !== \"interval\") {\n logger.warn(`${this.instanceNameWithSuffix} - expectedIntervalMs is set but validityMode is \"${msg.validityMode}\" (only used with \"interval\") for attribute \"${msg.attribute}\".`);\n }\n if (msg.lifecycleEndValue && msg.validityMode !== \"lifecycle\") {\n logger.warn(`${this.instanceNameWithSuffix} - lifecycleEndValue is set but validityMode is \"${msg.validityMode}\" (only used with \"lifecycle\") for attribute \"${msg.attribute}\".`);\n }\n if (msg.validityMode === \"interval\" && !msg.expectedIntervalMs) {\n logger.debug(`${this.instanceNameWithSuffix} - validityMode \"interval\" without expectedIntervalMs for attribute \"${msg.attribute}\" — controller will use its default.`);\n }\n }\n\n this.registerUniqueTopic({\n timestamp: time,\n topic: msg.topic,\n attribute: msg.attribute,\n attributeType: attributeType,\n description,\n tags: msg.tags,\n attributeNeedsPersistence: msg.attributeNeedsPersistence,\n dataGroup,\n asset,\n assetDescription: msg.assetDescription,\n objectType,\n objectTypeDescription,\n objectId,\n ...(msg.validityMode ? { validityMode: msg.validityMode } : {}),\n ...(msg.expectedIntervalMs ? { expectedIntervalMs: msg.expectedIntervalMs } : {}),\n ...(msg.lifecycleEndValue ? { lifecycleEndValue: msg.lifecycleEndValue } : {}),\n });\n\n const publishTopic = `${msg.topic}${asset ? `${asset}/` : \"\"}${objectType ? `${objectType}/` : \"\"}${objectId ? `${objectId}/` : \"\"}${msg.attribute}`;\n const sequenceId = this.currentSequenceId.get(msg.topic) ?? 0;\n this.currentSequenceId.set(msg.topic, sequenceId + 1);\n msg.packet.sequenceId = sequenceId;\n\n if (msg.packet.message.data) {\n const newValue = msg.packet.message.data.value;\n const newUom: MeasurementUnit = msg.packet.message.data.uom;\n const lastValueEntry = this.lastValues.get(publishTopic);\n const currentTime = new Date(msg.packet.message.data.time);\n\n if (lastValueEntry) {\n const intervalBetweenMessages = currentTime.getTime() - lastValueEntry.timestamp.getTime();\n const lastValue = lastValueEntry.value;\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n // Compute the delta and manage cumulative resets\n if (valueIsCumulative == true && typeof newValue === \"number\" && typeof lastValue === \"number\") {\n // Skip if newValue is 0 (likely a glitch)\n if (newValue === 0) {\n return; // Don't process or enqueue\n }\n const delta = newValue - lastValue;\n msg.packet.message.data.value = delta < 0 ? newValue : delta;\n }\n msg.packet.interval = intervalBetweenMessages;\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate interval on topic ${publishTopic}`);\n if (valueIsCumulative === false) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate difference on value in data for topic ${publishTopic}`);\n }\n }\n } else if (msg.packet.message.table) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing message to topic ${publishTopic}: packet.message must include data or table`);\n }\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing message to topic ${msg.topic}${msg.attribute}: ${error.message}`);\n }\n }\n\n /**\n * Stops the UnsProxy instance and cleans up resources.\n */\n public async stop(): Promise<void> {\n super.stop();\n // Terminate the worker thread if it exists.\n if (this.worker) {\n try {\n const exitCode = await this.worker.terminate();\n logger.info(`${this.instanceNameWithSuffix} - Worker terminated with exit code ${exitCode}`);\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error terminating worker: ${error.message}`);\n }\n }\n \n // Optionally, handle any pending enqueues.\n for (const [id, pending] of this.pendingEnqueues) {\n pending.reject(new Error(\"UnsProxy has been stopped\"));\n this.pendingEnqueues.delete(id);\n }\n }\n\n}\n"]}
1
+ {"version":3,"file":"uns-mqtt-proxy.js","sourceRoot":"","sources":["../../src/uns-mqtt/uns-mqtt-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAElC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,MAAM,MAAM,cAAc,CAAC;AAElC,OAAO,EAAE,wBAAwB,EAAwC,MAAM,sBAAsB,CAAC;AAGtG,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAInE,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ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C;gBACN,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,sBAAsB,wCAAwC,YAAY,6CAA6C,CAAC,CAAC;YAChJ,CAAC;QACH,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,sBAAsB,wCAAwC,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,SAAS,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACpI,CAAC;IACH,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,IAAI;QACf,KAAK,CAAC,IAAI,EAAE,CAAC;QACb,4CAA4C;QAC5C,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC;gBACH,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;gBAC/C,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,sBAAsB,uCAAuC,QAAQ,EAAE,CAAC,CAAC;YAC/F,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,sBAAsB,gCAAgC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9F,CAAC;QACH,CAAC;QAED,2CAA2C;QAC3C,KAAK,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACjD,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC,CAAC;YACvD,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;CAEF","sourcesContent":["import { readFileSync } from \"fs\";\nimport { IClientPublishOptions } from \"mqtt\";\nimport * as path from \"path\";\nimport { Worker } from \"worker_threads\";\nimport { fileURLToPath } from \"url\";\nimport { basePath } from \"../base-path.js\";\nimport logger from \"../logger.js\";\nimport { IMqttPublishRequest, IUnsMessage, IUnsPacket, IUnsParameters, UnsAttribute, UnsEvents, ValueType } from \"../uns/uns-interfaces.js\";\nimport { getObjectTypeDescription, type UnsObjectId, type UnsObjectType } from \"../uns/uns-object.js\";\nimport type { UnsAsset } from \"../uns/uns-asset.js\";\nimport { MeasurementUnit } from \"../uns/uns-measurements.js\";\nimport { UnsPacket } from \"../uns/uns-packet.js\";\nimport { IMqttParameters, IMqttWorkerData } from \"./mqtt-interfaces.js\";\nimport { MqttTopicBuilder } from \"./mqtt-topic-builder.js\";\nimport UnsProxy from \"../uns/uns-proxy.js\";\nimport { UnsAttributeType } from \"../graphql/schema.js\";\nimport { getAttributeDescription } from \"../uns/uns-attributes.js\";\nimport { UnsTags } from \"../uns/uns-tags.js\";\nimport { UnsTopics } from \"../uns/uns-topics.js\";\n\nconst packageJsonPath = path.join(basePath, \"package.json\");\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\nconst moduleDirectory = path.dirname(fileURLToPath(import.meta.url));\nconst packageRoot = path.resolve(moduleDirectory, \"..\", \"..\");\nconst workerScriptPath = path.join(packageRoot, \"dist/uns-mqtt/mqtt-worker-init.js\");\n\nexport enum MessageMode {\n Raw = 'raw', // Send only the original message\n Delta = 'delta', // Send only the delta message\n Both = 'both' // Send both the original and delta messages\n}\n\ntype InternalMqttMessage = {\n topic: UnsTopics;\n attribute: UnsAttribute;\n asset: UnsAsset;\n assetDescription?: string;\n objectType: UnsObjectType;\n objectTypeDescription?: string;\n objectId: UnsObjectId;\n description?: string;\n tags?: UnsTags[];\n attributeNeedsPersistence?: boolean | null;\n validityMode?: \"interval\" | \"lifecycle\" | \"static\";\n expectedIntervalMs?: number;\n lifecycleEndValue?: string;\n packet: IUnsPacket;\n};\n\nexport default class UnsMqttProxy extends UnsProxy {\n private lastValues: Map<string, { value: ValueType; uom: string; timestamp: Date }> = new Map();\n private worker: Worker;\n private pendingEnqueues: Map<string, { resolve: () => void; reject: (reason?: any) => void }> = new Map();\n private unsParameters: IUnsParameters;\n protected processStatusTopic: string;\n public instanceName: string;\n private currentSequenceId: Map<string, number> = new Map();\n private topicBuilder: MqttTopicBuilder;\n\n constructor(\n mqttHost: string,\n processName: string,\n instanceName: string,\n unsParameters?: IUnsParameters,\n publisherActive: boolean = false,\n subscriberActive: boolean = false\n ) {\n super();\n this.instanceName = instanceName;\n // Create the topic builder using packageJson values and the processName.\n this.topicBuilder = new MqttTopicBuilder(`uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageJson.name)}/${MqttTopicBuilder.sanitizeTopicPart(packageJson.version)}/${MqttTopicBuilder.sanitizeTopicPart(processName)}/`);\n\n // Generate the processStatusTopic using the builder.\n this.processStatusTopic = this.topicBuilder.getProcessStatusTopic();\n // Derive the instanceStatusTopic by appending the instance name.\n this.instanceStatusTopic = this.processStatusTopic + instanceName + \"/\";\n\n // Concatenate processName with instanceName for the worker identification.\n this.instanceNameWithSuffix = `${processName}-${instanceName}`;\n \n const mqttParameters: IMqttParameters = {\n mqttSubToTopics: unsParameters?.mqttSubToTopics ?? [],\n username: unsParameters?.username ?? \"\",\n password: unsParameters?.password ?? \"\",\n mqttSSL: unsParameters?.mqttSSL ?? false,\n statusTopic: this.instanceStatusTopic,\n rejectUnauthorized: unsParameters?.rejectUnauthorized ?? false,\n clientId: unsParameters?.clientId,\n hosts: unsParameters?.hosts,\n servers: unsParameters?.servers,\n port: unsParameters?.port,\n protocol: unsParameters?.protocol,\n keepalive: unsParameters?.keepalive,\n clean: unsParameters?.clean,\n connectTimeout: unsParameters?.connectTimeout,\n reconnectPeriod: unsParameters?.reconnectPeriod,\n reconnectOnConnackError: unsParameters?.reconnectOnConnackError,\n resubscribe: unsParameters?.resubscribe,\n queueQoSZero: unsParameters?.queueQoSZero,\n properties: unsParameters?.properties,\n ca: unsParameters?.ca,\n cert: unsParameters?.cert,\n key: unsParameters?.key,\n servername: unsParameters?.servername,\n };\n this.unsParameters = unsParameters ?? {};\n this.startQueueWorker(mqttHost, this.instanceNameWithSuffix, mqttParameters, publisherActive, subscriberActive);\n }\n\n /**\n * Resolve object identity from explicit fields or the tail of the topic path.\n * Falls back to parsing when not provided for backward compatibility.\n */\n private resolveObjectIdentity(msg: InternalMqttMessage): { objectType?: UnsObjectType; objectId?: UnsObjectId; asset?: UnsAsset } {\n const providedType = msg.objectType;\n const providedId = msg.objectId;\n const providedAsset = msg.asset;\n\n const topicParts = msg.topic.split(\"/\").filter((part) => part.length > 0);\n const hasObjectTail = topicParts.length >= 2;\n const parsedType = hasObjectTail ? topicParts[topicParts.length - 2] as UnsObjectType : undefined;\n const parsedId = hasObjectTail ? topicParts[topicParts.length - 1] as UnsObjectId : undefined;\n const parsedAsset = hasObjectTail\n ? (topicParts.length >= 3 ? topicParts[topicParts.length - 3] as UnsAsset : undefined)\n : (topicParts.length >= 1 ? topicParts[topicParts.length - 1] as UnsAsset : undefined);\n\n const objectType = providedType ?? parsedType;\n const objectId = providedId ?? parsedId ?? \"main\";\n const asset = providedAsset ?? parsedAsset;\n\n // If values are provided, trust them; otherwise derive from topic.\n if (!providedType || !providedId) {\n if (parsedType && parsedId) {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; derived from topic tail ${parsedType}/${parsedId}`);\n } else {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; defaulting objectId to 'main' for topic '${msg.topic}'. Expected topic to end with '<objectType>/<objectId>/'`);\n }\n }\n // Asset is optional; no warning on mismatch to avoid noisy logs when base topics don't carry it.\n\n msg.objectType = objectType;\n msg.objectId = objectId;\n msg.asset = asset;\n\n return { objectType, objectId, asset };\n }\n\n /**\n * Ensure the topic ends with a trailing slash for attribute concatenation.\n */\n private normalizeTopicWithObject(topic: string): string {\n return topic.endsWith(\"/\") ? topic : `${topic}/`;\n }\n\n /**\n * Starts a worker thread to process the throttled publish queue.\n */\n private startQueueWorker(\n mqttHost: string,\n instanceNameWithSuffix: string,\n mqttParameters: IMqttParameters,\n publisherActive: boolean,\n subscriberActive: boolean\n ): void {\n const workerData: IMqttWorkerData = {\n publishThrottlingDelay: this.unsParameters.publishThrottlingDelay ?? 1,\n subscribeThrottlingDelay: this.unsParameters.subscribeThrottlingDelay ?? 1,\n persistToDisk: false,\n mqttHost: mqttHost,\n instanceNameWithSuffix: instanceNameWithSuffix,\n mqttParameters: mqttParameters,\n publisherActive,\n subscriberActive,\n defaultPublishOptions: this.unsParameters.defaultPublishOptions,\n };\n\n this.worker = new Worker(workerScriptPath, { workerData });\n\n this.worker.on(\"message\", (msg) => {\n if (msg && msg.command === \"enqueueResult\" && msg.id) {\n const pending = this.pendingEnqueues.get(msg.id);\n if (pending) {\n if (msg.status === \"success\" && msg.topic && msg.message) {\n pending.resolve();\n } else {\n pending.reject(new Error(msg.error));\n }\n this.pendingEnqueues.delete(msg.id);\n }\n } else if (msg && msg.command === \"input\") {\n this.event.emit(\"input\", { topic: msg.topic, message: msg.message.toString(), packet: msg.packet });\n } else if (msg && (msg.command === \"handover_subscriber\" || msg.command === \"handover_publisher\")) {\n this.event.emit(\"mqttWorker\", { command: msg.command, batchSize: msg.batchSize, referenceHash: msg.referenceHash, instanceName: this.instanceName });\n } else if (msg && msg.command === \"mqttProxyStatus\") {\n this.event.emit(\"mqttProxyStatus\", { event: msg.event, value: msg.value, uom: msg.uom, statusTopic: msg.statusTopic });\n }\n });\n\n this.worker.on(\"error\", (err) => {\n logger.error(\"Error in worker:\", err);\n const reason = err instanceof Error ? err : new Error(String(err));\n for (const pending of this.pendingEnqueues.values()) {\n pending.reject(reason);\n }\n this.pendingEnqueues.clear();\n });\n\n this.worker.on(\"exit\", (code) => {\n if (code !== 0) {\n logger.error(`Worker exited with code ${code}`);\n const reason = new Error(`MQTT worker exited with code ${code}`);\n for (const pending of this.pendingEnqueues.values()) {\n pending.reject(reason);\n }\n this.pendingEnqueues.clear();\n }\n });\n }\n\n /**\n * Enqueues a message to the worker queue.\n *\n * @param topic - The topic to which the message belongs.\n * @param message - The message to be enqueued.\n * @param options - Optional publish options.\n * @returns A promise that resolves when the message is successfully enqueued.\n */\n private async enqueueMessageToWorkerQueue(topic: string, message: string, options?: IClientPublishOptions): Promise<void> {\n return new Promise((resolve, reject) => {\n // const id: string = String(this.currentSequenceId.get(topic) ?? 0);\n const id = `${Date.now()}-${Math.random()}`;\n this.pendingEnqueues.set(id, { resolve, reject });\n this.worker.postMessage({ command: \"enqueue\", id, topic, message, options });\n });\n }\n\n /**\n * Sets the publisher active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setPublisherActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setPublisherActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the publisher to passive mode.\n * @returns A promise that resolves when the publisher is set to passive.\n */\n public setPublisherPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setPublisherPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_publisher\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n /**\n * Sets the subscriber active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setSubscriberActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setSubscriberActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the subscriber to passive mode.\n * @returns A promise that resolves when the subscriber is set to passive.\n */\n public setSubscriberPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setSubscriberPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_subscriber\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n\n /**\n * Sets the subscriber to passive mode and allows the publisher to run\n * until the queue is empty (all messages are processed).\n */\n public async setSubscriberPassiveAndDrainQueue(): Promise<UnsEvents[\"mqttWorker\"]> {\n return new Promise(async (resolve) => {\n const mqttWorkerData = await this.setSubscriberPassive();\n while (this.pendingEnqueues.size > 0) {\n await new Promise((resolve) => setTimeout(resolve, 100)); // Poll every 100ms\n }\n logger.info(`${this.instanceNameWithSuffix} - Subscriber set to passive and queue drained.`);\n resolve(mqttWorkerData);\n });\n }\n\n /**\n * Processes and publishes MQTT messages based on the selected message mode.\n *\n * @param mqttMessage - The MQTT message object.\n * @param mode - The message mode (Raw, Delta, or Both).\n */\n public async publishMqttMessage(mqttMessage: IMqttPublishRequest | null, mode: MessageMode = MessageMode.Raw) {\n if (!mqttMessage) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing mqtt message: mqttMessage must be defined.`);\n return;\n }\n\n const attrs = Array.isArray(mqttMessage.attributes)\n ? mqttMessage.attributes\n : [mqttMessage.attributes];\n const { topic, asset, assetDescription, objectType, objectTypeDescription, objectId } = mqttMessage;\n for (const attrEntry of attrs) {\n const attrDescription = attrEntry.description ?? getAttributeDescription(attrEntry.attribute);\n const message: IUnsMessage =\n \"message\" in attrEntry && attrEntry.message\n ? attrEntry.message\n : \"data\" in attrEntry && attrEntry.data\n ? { data: attrEntry.data, createdAt: attrEntry.createdAt, expiresAt: attrEntry.expiresAt }\n : \"table\" in attrEntry && attrEntry.table\n ? { table: attrEntry.table, createdAt: attrEntry.createdAt, expiresAt: attrEntry.expiresAt }\n : (() => { throw new Error(\"Attribute entry must include exactly one of data/table/message\"); })();\n const packet = await UnsPacket.unsPacketFromUnsMessage(message);\n const singleMsg: InternalMqttMessage = {\n topic,\n asset,\n assetDescription,\n objectType,\n objectTypeDescription,\n objectId,\n attribute: attrEntry.attribute,\n description: attrDescription,\n tags: attrEntry.tags,\n attributeNeedsPersistence: attrEntry.attributeNeedsPersistence,\n ...(attrEntry.validityMode ? { validityMode: attrEntry.validityMode } : {}),\n ...(attrEntry.expectedIntervalMs ? { expectedIntervalMs: attrEntry.expectedIntervalMs } : {}),\n ...(attrEntry.lifecycleEndValue ? { lifecycleEndValue: attrEntry.lifecycleEndValue } : {}),\n packet,\n };\n\n // existing single-attribute flow\n const baseDescription =\n singleMsg.description ??\n getAttributeDescription(singleMsg.attribute) ??\n singleMsg.attribute;\n const mqttMessageWithDesc = { ...singleMsg, description: baseDescription };\n\n const time = UnsPacket.formatToISO8601(new Date());\n switch (mode) {\n case MessageMode.Raw: {\n await this.processAndEnqueueMessage(mqttMessageWithDesc, time, false);\n break;\n }\n case MessageMode.Delta: {\n const deltaMessage = { ...mqttMessageWithDesc };\n deltaMessage.attribute = `${mqttMessageWithDesc.attribute}-delta`;\n deltaMessage.description = `${baseDescription ?? \"\"} (delta)`;\n await this.processAndEnqueueMessage(deltaMessage, time, true);\n break;\n }\n case MessageMode.Both: {\n await this.processAndEnqueueMessage(mqttMessageWithDesc, time, false);\n const deltaMessageBoth = { ...mqttMessageWithDesc };\n deltaMessageBoth.attribute = `${mqttMessageWithDesc.attribute}-delta`;\n deltaMessageBoth.description = `${baseDescription ?? \"\"} (delta)`;\n await this.processAndEnqueueMessage(deltaMessageBoth, time, true);\n break;\n }\n }\n }\n return;\n }\n\n /**\n * Publishes a message to a specified topic.\n *\n * @param topic - The MQTT topic.\n * @param message - The message to publish.\n * @returns A promise that resolves when enqueued.\n */\n public publishMessage(topic: string, message: string, options?: IClientPublishOptions): Promise<void> {\n return this.enqueueMessageToWorkerQueue(topic, message, options);\n }\n\n /**\n * Parses an MQTT packet from a JSON string.\n *\n * @param mqttPacket - The MQTT packet string.\n * @returns A parsed IUnsPacket object or null.\n */\n public parseMqttPacket(mqttPacket: string): IUnsPacket | null {\n return UnsPacket.parseMqttPacket(mqttPacket, this.instanceNameWithSuffix);\n }\n\n /**\n * Subscribes asynchronously to one or more topics.\n *\n * @param topics - A topic or list of topics.\n */\n public subscribeAsync(topics: string | string[]): void {\n this.worker.postMessage({ command: \"subscribeAsync\", topics });\n }\n\n /**\n * Unsubscribes asynchronously from the given topics.\n *\n * @param topics - A list of topics.\n */\n public unsubscribeAsync(topics: string[]): void {\n this.worker.postMessage({ command: \"unsubscribeAsync\", topics });\n }\n\n /**\n * Processes and enqueues a message to the worker queue, including handling\n * sequencing, value differences, and tracking of unique topics.\n *\n * @param msg - The MQTT message to process.\n * @param time - The timestamp.\n * @param valueIsCumulative - Whether the value is cumulative.\n */\n private async processAndEnqueueMessage(msg: InternalMqttMessage, time: string, valueIsCumulative: boolean = false): Promise<void> {\n try {\n const attributeType =\n msg.packet.message.data ? UnsAttributeType.Data :\n msg.packet.message.table ? UnsAttributeType.Table : null;\n \n let dataGroup = \"\";\n if (attributeType == UnsAttributeType.Data)\n dataGroup = msg.packet.message.data.dataGroup ?? \"\";\n if (attributeType == UnsAttributeType.Table)\n dataGroup = msg.packet.message.table.dataGroup ?? \"\";\n\n const { objectType, objectId, asset } = this.resolveObjectIdentity(msg);\n const normalizedTopic = this.normalizeTopicWithObject(msg.topic);\n msg.topic = normalizedTopic;\n const description = msg.description ?? getAttributeDescription(msg.attribute as string) ?? \"\";\n const objectTypeDescription = msg.objectTypeDescription ?? (objectType ? getObjectTypeDescription(objectType) : undefined);\n\n // Runtime validation for validity fields\n if (msg.validityMode) {\n const validModes = new Set([\"interval\", \"lifecycle\", \"static\"]);\n if (!validModes.has(msg.validityMode)) {\n logger.warn(`${this.instanceNameWithSuffix} - Invalid validityMode \"${msg.validityMode}\" for attribute \"${msg.attribute}\". Expected: interval | lifecycle | static.`);\n }\n if (msg.expectedIntervalMs && msg.validityMode !== \"interval\") {\n logger.warn(`${this.instanceNameWithSuffix} - expectedIntervalMs is set but validityMode is \"${msg.validityMode}\" (only used with \"interval\") for attribute \"${msg.attribute}\".`);\n }\n if (msg.lifecycleEndValue && msg.validityMode !== \"lifecycle\") {\n logger.warn(`${this.instanceNameWithSuffix} - lifecycleEndValue is set but validityMode is \"${msg.validityMode}\" (only used with \"lifecycle\") for attribute \"${msg.attribute}\".`);\n }\n if (msg.validityMode === \"interval\" && !msg.expectedIntervalMs) {\n logger.debug(`${this.instanceNameWithSuffix} - validityMode \"interval\" without expectedIntervalMs for attribute \"${msg.attribute}\" — controller will use its default.`);\n }\n }\n\n this.registerUniqueTopic({\n timestamp: time,\n topic: msg.topic,\n attribute: msg.attribute,\n attributeType: attributeType,\n description,\n tags: msg.tags,\n attributeNeedsPersistence: msg.attributeNeedsPersistence,\n dataGroup,\n asset,\n assetDescription: msg.assetDescription,\n objectType,\n objectTypeDescription,\n objectId,\n ...(msg.validityMode ? { validityMode: msg.validityMode } : {}),\n ...(msg.expectedIntervalMs ? { expectedIntervalMs: msg.expectedIntervalMs } : {}),\n ...(msg.lifecycleEndValue ? { lifecycleEndValue: msg.lifecycleEndValue } : {}),\n });\n\n const publishTopic = `${msg.topic}${asset ? `${asset}/` : \"\"}${objectType ? `${objectType}/` : \"\"}${objectId ? `${objectId}/` : \"\"}${msg.attribute}`;\n const sequenceId = this.currentSequenceId.get(msg.topic) ?? 0;\n this.currentSequenceId.set(msg.topic, sequenceId + 1);\n msg.packet.sequenceId = sequenceId;\n\n if (msg.packet.message.data) {\n const newValue = msg.packet.message.data.value;\n const newUom: MeasurementUnit = msg.packet.message.data.uom;\n const lastValueEntry = this.lastValues.get(publishTopic);\n const currentTime = new Date(msg.packet.message.data.time);\n\n if (lastValueEntry) {\n const intervalBetweenMessages = currentTime.getTime() - lastValueEntry.timestamp.getTime();\n const lastValue = lastValueEntry.value;\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n // Compute the delta and manage cumulative resets\n if (valueIsCumulative == true && typeof newValue === \"number\" && typeof lastValue === \"number\") {\n // Skip if newValue is 0 (likely a glitch)\n if (newValue === 0) {\n return; // Don't process or enqueue\n }\n const delta = newValue - lastValue;\n msg.packet.message.data.value = delta < 0 ? newValue : delta;\n }\n msg.packet.interval = intervalBetweenMessages;\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate interval on topic ${publishTopic}`);\n if (valueIsCumulative === false) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate difference on value in data for topic ${publishTopic}`);\n }\n }\n } else if (msg.packet.message.table) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing message to topic ${publishTopic}: packet.message must include data or table`);\n }\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing message to topic ${msg.topic}${msg.attribute}: ${error.message}`);\n }\n }\n\n /**\n * Stops the UnsProxy instance and cleans up resources.\n */\n public async stop(): Promise<void> {\n super.stop();\n // Terminate the worker thread if it exists.\n if (this.worker) {\n try {\n const exitCode = await this.worker.terminate();\n logger.info(`${this.instanceNameWithSuffix} - Worker terminated with exit code ${exitCode}`);\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error terminating worker: ${error.message}`);\n }\n }\n \n // Optionally, handle any pending enqueues.\n for (const [id, pending] of this.pendingEnqueues) {\n pending.reject(new Error(\"UnsProxy has been stopped\"));\n this.pendingEnqueues.delete(id);\n }\n }\n\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uns-kit/core",
3
- "version": "2.0.36",
3
+ "version": "2.0.38",
4
4
  "description": "Core utilities and runtime building blocks for UNS-based realtime transformers.",
5
5
  "type": "module",
6
6
  "license": "MIT",