myio-js-library 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MyIO
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,328 @@
1
+ # myio-js-library
2
+
3
+ A clean, standalone JavaScript SDK for **MYIO** projects.
4
+ Works in **Node.js (>=18)** and modern browsers.
5
+ Distributed as **ESM**, **CJS**, and **UMD** (with a pre-minified build for CDN usage).
6
+
7
+ ---
8
+
9
+ ## πŸš€ Features
10
+
11
+ - πŸ”‘ **Core codecs** β€” e.g., `decodePayloadBase64Xor`.
12
+ - 🌐 **HTTP wrapper** β€” with retries, timeout, and backoff.
13
+ - 🏷️ **Namespace utilities** β€” add prefixes/suffixes to object keys.
14
+ - πŸ“± **Device detection** β€” context-aware device type identification.
15
+ - 🧩 **String utilities** β€” normalization helpers.
16
+ - πŸ”’ **Number utilities** β€” safe fixed formatting, percentages.
17
+ - ⚑ **Dual module support** β€” ESM and CJS.
18
+ - 🌍 **Browser-ready** β€” UMD global + CDN link.
19
+
20
+ ---
21
+
22
+ ## πŸ“¦ Installation
23
+
24
+ ```bash
25
+ npm install myio-js-library
26
+ # or
27
+ yarn add myio-js-library
28
+ # or
29
+ pnpm add myio-js-library
30
+ ```
31
+
32
+ ## πŸ›  Usage
33
+
34
+ ### Node.js (ESM)
35
+ ```javascript
36
+ import {
37
+ decodePayload,
38
+ fetchWithRetry,
39
+ addNamespace,
40
+ detectDeviceType,
41
+ strings,
42
+ numbers
43
+ } from 'myio-js-library';
44
+
45
+ // Decode with string key
46
+ const text = decodePayload('AwAVBwo=', 'key'); // "hello"
47
+ console.log(text);
48
+
49
+ // HTTP request with retries
50
+ const response = await fetchWithRetry('https://api.example.com/data', {
51
+ retries: 3,
52
+ timeout: 5000
53
+ });
54
+
55
+ // Add namespace to object keys
56
+ const data = { temperature: 25, humidity: 60 };
57
+ const namespaced = addNamespace(data, 'sensor1');
58
+ // { "temperature (sensor1)": 25, "humidity (sensor1)": 60 }
59
+
60
+ // Detect device type from context
61
+ const deviceType = detectDeviceType('building', 'floor2-room101');
62
+ console.log(deviceType); // "room" or "unknown"
63
+ ```
64
+
65
+ ### Node.js (CJS)
66
+ ```javascript
67
+ const {
68
+ decodePayload,
69
+ fetchWithRetry,
70
+ addNamespace,
71
+ detectDeviceType,
72
+ strings,
73
+ numbers
74
+ } = require('myio-js-library');
75
+ ```
76
+
77
+ ### Browser (CDN/UMD)
78
+ ```html
79
+ <script src="https://unpkg.com/myio-js-library@0.1.0/dist/myio-js-library.umd.min.js"></script>
80
+ <script>
81
+ // Decode payload
82
+ const text = MyIOJSLibrary.decodePayload('AwAVBwo=', 'key');
83
+ console.log(text); // "hello"
84
+
85
+ // Add namespace to data
86
+ const data = { temperature: 25, humidity: 60 };
87
+ const namespaced = MyIOJSLibrary.addNamespace(data, 'sensor1');
88
+ console.log(namespaced); // { "temperature (sensor1)": 25, "humidity (sensor1)": 60 }
89
+
90
+ // Detect device type
91
+ const deviceType = MyIOJSLibrary.detectDeviceType('building', 'floor2-room101');
92
+ console.log(deviceType); // "room"
93
+ </script>
94
+ ```
95
+
96
+ ## πŸ“š API
97
+
98
+ ### Codec Functions
99
+
100
+ #### `decodePayload(encoded: string, key: string | number | null | undefined): string`
101
+
102
+ Advanced base64 XOR decoder with flexible key support:
103
+ - **String key**: Repeats the key over the bytes (e.g., "abc" -> "abcabcabc...")
104
+ - **Number key**: Applies single byte (0-255) to all bytes
105
+ - **Empty/null/undefined key**: No XOR applied (plain base64 decode)
106
+
107
+ ```javascript
108
+ import { decodePayload } from 'myio-js-library';
109
+
110
+ // String key (repeating)
111
+ const result1 = decodePayload('AwAVBwo=', 'key'); // "hello"
112
+
113
+ // Number key (single byte)
114
+ const result2 = decodePayload('SGVsbG8=', 73); // XOR with 73
115
+
116
+ // No key (plain decode)
117
+ const result3 = decodePayload('aGVsbG8=', ''); // "hello"
118
+ ```
119
+
120
+ #### `decodePayloadBase64Xor(encoded: string, xorKey?: number): string`
121
+
122
+ Legacy compatibility function for single-byte XOR (defaults to 73).
123
+
124
+ ```javascript
125
+ import { decodePayloadBase64Xor } from 'myio-js-library';
126
+
127
+ const result = decodePayloadBase64Xor('SGVsbG8=', 73);
128
+ ```
129
+
130
+ ### HTTP Functions
131
+
132
+ #### `fetchWithRetry(url: string, options?: object): Promise<Response>`
133
+
134
+ Enhanced fetch wrapper with retry logic, timeout, and exponential backoff.
135
+
136
+ **Options:**
137
+ - `retries?: number` - Number of retry attempts (default: 0)
138
+ - `retryDelay?: number` - Base delay between retries in ms (default: 100)
139
+ - `timeout?: number` - Request timeout in ms (default: 10000)
140
+ - `retryCondition?: (error, response) => boolean` - Custom retry logic
141
+ - All standard `fetch` options (method, headers, body, signal, etc.)
142
+
143
+ ```javascript
144
+ import { fetchWithRetry } from 'myio-js-library';
145
+
146
+ const response = await fetchWithRetry('https://api.example.com/data', {
147
+ retries: 3,
148
+ retryDelay: 200,
149
+ timeout: 5000,
150
+ method: 'POST',
151
+ headers: { 'Content-Type': 'application/json' },
152
+ body: JSON.stringify({ data: 'example' })
153
+ });
154
+ ```
155
+
156
+ #### `http(url: string, options?: object): Promise<Response>`
157
+
158
+ Alias for `fetchWithRetry`.
159
+
160
+ ### Namespace Utilities
161
+
162
+ #### `addNamespace(payload: object, namespace?: string): object`
163
+
164
+ Adds a namespace suffix to all keys in an object. Useful for prefixing data from different sources or sensors.
165
+
166
+ **Parameters:**
167
+ - `payload: object` - The object whose keys will be namespaced (must be a plain object, not array)
168
+ - `namespace?: string` - The namespace to append (optional, defaults to empty string)
169
+
170
+ **Returns:** New object with namespaced keys in format `"originalKey (namespace)"`
171
+
172
+ **Throws:** Error if payload is not a plain object
173
+
174
+ ```javascript
175
+ import { addNamespace } from 'myio-js-library';
176
+
177
+ // Basic usage
178
+ const data = { temperature: 25, humidity: 60 };
179
+ const result = addNamespace(data, 'sensor1');
180
+ // { "temperature (sensor1)": 25, "humidity (sensor1)": 60 }
181
+
182
+ // Empty namespace (no suffix added)
183
+ const result2 = addNamespace(data, '');
184
+ // { "temperature": 25, "humidity": 60 }
185
+
186
+ // Whitespace handling
187
+ const result3 = addNamespace(data, ' room-101 ');
188
+ // { "temperature (room-101)": 25, "humidity (room-101)": 60 }
189
+ ```
190
+
191
+ ### Device Detection Utilities
192
+
193
+ #### `detectDeviceType(context: string, deviceId: string): string`
194
+
195
+ Detects device type based on context and device ID patterns. Uses built-in detection contexts for common environments.
196
+
197
+ **Parameters:**
198
+ - `context: string` - The context environment ('building', 'mall', etc.)
199
+ - `deviceId: string` - The device identifier to analyze
200
+
201
+ **Returns:** Detected device type or 'unknown' if no pattern matches
202
+
203
+ **Built-in contexts:**
204
+ - **building**: Detects rooms, floors, elevators, stairs, parking, entrance, exit
205
+ - **mall**: Detects stores, corridors, escalators, elevators, parking, entrance, exit, food court, restrooms
206
+
207
+ ```javascript
208
+ import { detectDeviceType } from 'myio-js-library';
209
+
210
+ // Building context
211
+ detectDeviceType('building', 'floor2-room101'); // "room"
212
+ detectDeviceType('building', 'elevator-A'); // "elevator"
213
+ detectDeviceType('building', 'parking-level1'); // "parking"
214
+
215
+ // Mall context
216
+ detectDeviceType('mall', 'store-nike-001'); // "store"
217
+ detectDeviceType('mall', 'corridor-main'); // "corridor"
218
+ detectDeviceType('mall', 'food-court-area'); // "food_court"
219
+
220
+ // Unknown patterns
221
+ detectDeviceType('building', 'unknown-device'); // "unknown"
222
+ ```
223
+
224
+ #### `getAvailableContexts(): string[]`
225
+
226
+ Returns list of all available detection contexts.
227
+
228
+ ```javascript
229
+ import { getAvailableContexts } from 'myio-js-library';
230
+
231
+ const contexts = getAvailableContexts();
232
+ // ['building', 'mall']
233
+ ```
234
+
235
+ #### `addDetectionContext(contextName: string, patterns: object): void`
236
+
237
+ Adds a new detection context with custom patterns.
238
+
239
+ **Parameters:**
240
+ - `contextName: string` - Name of the new context
241
+ - `patterns: object` - Object mapping device types to regex patterns
242
+
243
+ ```javascript
244
+ import { addDetectionContext, detectDeviceType } from 'myio-js-library';
245
+
246
+ // Add custom hospital context
247
+ addDetectionContext('hospital', {
248
+ room: /^(room|ward|chamber)-/i,
249
+ operating_room: /^(or|surgery|operating)-/i,
250
+ emergency: /^(er|emergency|trauma)-/i
251
+ });
252
+
253
+ // Use the new context
254
+ detectDeviceType('hospital', 'room-icu-101'); // "room"
255
+ detectDeviceType('hospital', 'or-surgery-3'); // "operating_room"
256
+ ```
257
+
258
+ ### String Utilities
259
+
260
+ #### `strings.normalizeRecipients(val: unknown): string`
261
+
262
+ Normalizes various list formats into a comma-separated string.
263
+
264
+ **Supported inputs:**
265
+ - Arrays: `['a', 'b', 'c']` β†’ `"a,b,c"`
266
+ - JSON strings: `'["a", "b", "c"]'` β†’ `"a,b,c"`
267
+ - Delimited strings: `"a; b, c"` β†’ `"a,b,c"`
268
+
269
+ ```javascript
270
+ import { strings } from 'myio-js-library';
271
+
272
+ strings.normalizeRecipients(['user1', 'user2']); // "user1,user2"
273
+ strings.normalizeRecipients('["a", "b"]'); // "a,b"
274
+ strings.normalizeRecipients('a; b, c'); // "a,b,c"
275
+ ```
276
+
277
+ ### Number Utilities
278
+
279
+ #### `numbers.fmtPerc(x: number, digits?: number): string`
280
+
281
+ Formats a ratio (0-1) as a percentage string.
282
+
283
+ ```javascript
284
+ import { numbers } from 'myio-js-library';
285
+
286
+ numbers.fmtPerc(0.1234); // "12.34%"
287
+ numbers.fmtPerc(0.1234, 1); // "12.3%"
288
+ numbers.fmtPerc(NaN); // "β€”"
289
+ ```
290
+
291
+ #### `numbers.toFixedSafe(x: number, digits?: number): string`
292
+
293
+ Safely formats a number to fixed decimals (returns "β€”" for invalid numbers).
294
+
295
+ ```javascript
296
+ import { numbers } from 'myio-js-library';
297
+
298
+ numbers.toFixedSafe(3.14159, 2); // "3.14"
299
+ numbers.toFixedSafe(NaN); // "β€”"
300
+ numbers.toFixedSafe(Infinity); // "β€”"
301
+ ```
302
+
303
+ ## πŸ§ͺ Development
304
+
305
+ ```bash
306
+ # install dependencies
307
+ npm install
308
+
309
+ # run tests
310
+ npm test
311
+
312
+ # build (esm+cjs+umd+min)
313
+ npm run build
314
+ ```
315
+
316
+ ## πŸ”„ Versioning
317
+
318
+ Uses [SemVer](https://semver.org/).
319
+
320
+ Managed via [Changesets](https://github.com/changesets/changesets) for changelogs & automated npm publishing.
321
+
322
+ ## 🀝 Contributing
323
+
324
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
325
+
326
+ ## πŸ“œ License
327
+
328
+ MIT Β© 2025 MYIO
package/dist/index.cjs ADDED
@@ -0,0 +1,266 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/index.js
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
+ addDetectionContext: () => addDetectionContext,
23
+ addNamespace: () => addNamespace,
24
+ decodePayload: () => decodePayload,
25
+ decodePayloadBase64Xor: () => decodePayloadBase64Xor,
26
+ detectDeviceType: () => detectDeviceType,
27
+ fetchWithRetry: () => fetchWithRetry,
28
+ getAvailableContexts: () => getAvailableContexts,
29
+ http: () => http,
30
+ numbers: () => numbers_exports,
31
+ strings: () => strings_exports
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+
35
+ // src/codec/decodePayload.js
36
+ function decodePayload(encoded, key) {
37
+ const bytes = base64ToBytesStrict(encoded);
38
+ if (bytes.length === 0) return "";
39
+ if (key === "" || key === void 0 || key === null) {
40
+ return new TextDecoder().decode(bytes);
41
+ }
42
+ if (typeof key === "number" && Number.isFinite(key)) {
43
+ const k = key & 255;
44
+ for (let i = 0; i < bytes.length; i++) bytes[i] ^= k;
45
+ return new TextDecoder().decode(bytes);
46
+ }
47
+ const keyStr = String(key);
48
+ const keyBytes = new TextEncoder().encode(keyStr);
49
+ if (keyBytes.length === 0) {
50
+ return new TextDecoder().decode(bytes);
51
+ }
52
+ for (let i = 0; i < bytes.length; i++) {
53
+ bytes[i] ^= keyBytes[i % keyBytes.length];
54
+ }
55
+ return new TextDecoder().decode(bytes);
56
+ }
57
+ function decodePayloadBase64Xor(encoded, xorKey = 73) {
58
+ const bytes = base64ToBytesStrict(encoded);
59
+ for (let i = 0; i < bytes.length; i++) bytes[i] ^= xorKey & 255;
60
+ return new TextDecoder().decode(bytes);
61
+ }
62
+ function base64ToBytesStrict(b64) {
63
+ if (b64 === "" || b64 === void 0 || b64 === null) return new Uint8Array();
64
+ const s = String(b64).replace(/\s+/g, "");
65
+ const re = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
66
+ if (!re.test(s)) throw new Error("Invalid base64");
67
+ if (typeof Buffer !== "undefined" && Buffer.from) {
68
+ return Uint8Array.from(Buffer.from(s, "base64"));
69
+ }
70
+ const bin = atob(s);
71
+ const out = new Uint8Array(bin.length);
72
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
73
+ return out;
74
+ }
75
+
76
+ // src/net/http.js
77
+ async function fetchWithRetry(url, options = {}) {
78
+ const {
79
+ retries = 0,
80
+ retryDelay = 100,
81
+ timeout = 1e4,
82
+ retryCondition,
83
+ ...passThrough
84
+ } = options;
85
+ const baseInit = { ...passThrough, timeout };
86
+ let attempt = 0;
87
+ while (true) {
88
+ try {
89
+ const res = await withTimeout(fetch(url, baseInit), timeout);
90
+ if (!res.ok) {
91
+ const doRetry = typeof retryCondition === "function" && retryCondition(null, res) || res.status >= 500;
92
+ if (doRetry && attempt < retries) {
93
+ await delay(expBackoff(retryDelay, attempt));
94
+ attempt++;
95
+ continue;
96
+ }
97
+ const msg = `HTTP ${res.status}: ${res.statusText || ""}`.trim();
98
+ throw new Error(msg);
99
+ }
100
+ return res;
101
+ } catch (err) {
102
+ if (err && err.message === "Request timeout") {
103
+ if (attempt < retries) {
104
+ await delay(expBackoff(retryDelay, attempt));
105
+ attempt++;
106
+ continue;
107
+ }
108
+ throw err;
109
+ }
110
+ const doRetry = typeof retryCondition === "function" && retryCondition(err, void 0) || isRetryableNetworkError(err);
111
+ if (doRetry && attempt < retries) {
112
+ await delay(expBackoff(retryDelay, attempt));
113
+ attempt++;
114
+ continue;
115
+ }
116
+ throw err;
117
+ }
118
+ }
119
+ }
120
+ var http = fetchWithRetry;
121
+ function withTimeout(promise, ms) {
122
+ return new Promise((resolve, reject) => {
123
+ const t = setTimeout(() => reject(new Error("Request timeout")), ms);
124
+ promise.then(
125
+ (v) => {
126
+ clearTimeout(t);
127
+ resolve(v);
128
+ },
129
+ (e) => {
130
+ clearTimeout(t);
131
+ reject(e);
132
+ }
133
+ );
134
+ });
135
+ }
136
+ function delay(ms) {
137
+ return new Promise((r) => setTimeout(r, ms));
138
+ }
139
+ function expBackoff(base, attempt) {
140
+ return base * Math.pow(2, attempt);
141
+ }
142
+ function isRetryableNetworkError(err) {
143
+ if (!err) return false;
144
+ const msg = String(err.message || "").toLowerCase();
145
+ return msg.includes("network") || err.name === "AbortError";
146
+ }
147
+
148
+ // src/utils/namespace.js
149
+ function addNamespace(payload, namespace = "") {
150
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
151
+ throw new Error("Payload must be an object.");
152
+ }
153
+ const keys = Object.keys(payload);
154
+ const suffix = namespace.trim() ? ` (${namespace.trim()})` : "";
155
+ return keys.reduce((acc, key) => {
156
+ acc[`${key}${suffix}`] = payload[key];
157
+ return acc;
158
+ }, {});
159
+ }
160
+
161
+ // src/utils/deviceType.js
162
+ var contexts = {
163
+ building: (name) => {
164
+ const upper = name.toUpperCase();
165
+ if (upper.includes("COMPRESSOR")) return "COMPRESSOR";
166
+ if (upper.includes("VENT")) return "VENTILADOR";
167
+ if (upper.includes("AUTOMATICO") || upper.includes("AUTOM\xC1TICO")) return "SELETOR_AUTO_MANUAL";
168
+ if (upper.includes("TERMOSTATO")) return "TERMOSTATO";
169
+ if (upper.includes("3F")) return "3F_MEDIDOR";
170
+ if (upper.includes("TERMO") || upper.includes("TEMP")) return "TERMOSTATO";
171
+ if (upper.includes("HIDR")) return "HIDROMETRO";
172
+ if (upper.includes("ABRE")) return "SOLENOIDE";
173
+ if (upper.includes("RECALQUE")) return "MOTOR";
174
+ if (upper.includes("AUTOMACAO") || upper.includes("AUTOMA\xC7\xC3O")) return "GLOBAL_AUTOMACAO";
175
+ if (upper.includes("AC")) return "CONTROLE REMOTO";
176
+ if (upper.includes("SCD")) return "CAIXA_D_AGUA";
177
+ return "default";
178
+ },
179
+ mall: (name) => {
180
+ const upper = name.toUpperCase();
181
+ if (upper.includes("CHILLER")) return "CHILLER";
182
+ if (upper.includes("ESCADA")) return "ESCADA_ROLANTE";
183
+ if (upper.includes("LOJA")) return "LOJA_SENSOR";
184
+ if (upper.includes("ILUMINACAO") || upper.includes("ILUMINA\xC7\xC3O")) return "ILUMINACAO";
185
+ return "default";
186
+ }
187
+ };
188
+ function detectDeviceType(name, context = "building") {
189
+ if (typeof name !== "string") {
190
+ throw new Error("Device name must be a string.");
191
+ }
192
+ const detectFunction = contexts[context];
193
+ if (!detectFunction) {
194
+ console.warn(`[myio-js-library] Context "${context}" not found. Using default fallback.`);
195
+ return contexts.building(name);
196
+ }
197
+ return detectFunction(name);
198
+ }
199
+ function getAvailableContexts() {
200
+ return Object.keys(contexts);
201
+ }
202
+ function addDetectionContext(contextName, detectFunction) {
203
+ if (typeof contextName !== "string") {
204
+ throw new Error("Context name must be a string.");
205
+ }
206
+ if (typeof detectFunction !== "function") {
207
+ throw new Error("Detection function must be a function.");
208
+ }
209
+ contexts[contextName] = detectFunction;
210
+ }
211
+
212
+ // src/utils/strings.js
213
+ var strings_exports = {};
214
+ __export(strings_exports, {
215
+ normalizeRecipients: () => normalizeRecipients
216
+ });
217
+ function normalizeRecipients(val) {
218
+ if (val === null || val === void 0 || val === "") return "";
219
+ if (Object.prototype.toString.call(val) === "[object Array]") {
220
+ return (
221
+ /** @type {unknown[]} */
222
+ val.filter(Boolean).join(",")
223
+ );
224
+ }
225
+ let s = String(val).trim();
226
+ if (/^\s*\[/.test(s)) {
227
+ try {
228
+ const arr = JSON.parse(s);
229
+ if (Object.prototype.toString.call(arr) === "[object Array]") {
230
+ return arr.filter(Boolean).join(",");
231
+ }
232
+ } catch {
233
+ }
234
+ }
235
+ s = s.replace(/[;\s]+/g, ",");
236
+ s = s.replace(/,+/g, ",").replace(/^,|,$/g, "");
237
+ return s;
238
+ }
239
+
240
+ // src/utils/numbers.js
241
+ var numbers_exports = {};
242
+ __export(numbers_exports, {
243
+ fmtPerc: () => fmtPerc,
244
+ toFixedSafe: () => toFixedSafe
245
+ });
246
+ function fmtPerc(x, digits = 2) {
247
+ if (!Number.isFinite(x)) return "\u2014";
248
+ return (x * 100).toFixed(digits) + "%";
249
+ }
250
+ function toFixedSafe(x, digits = 2) {
251
+ if (!Number.isFinite(x)) return "\u2014";
252
+ return x.toFixed(digits);
253
+ }
254
+ // Annotate the CommonJS export names for ESM import in node:
255
+ 0 && (module.exports = {
256
+ addDetectionContext,
257
+ addNamespace,
258
+ decodePayload,
259
+ decodePayloadBase64Xor,
260
+ detectDeviceType,
261
+ fetchWithRetry,
262
+ getAvailableContexts,
263
+ http,
264
+ numbers,
265
+ strings
266
+ });
@@ -0,0 +1,28 @@
1
+ export function decodePayload(encoded: string, key: string | number): string;
2
+ export function decodePayloadBase64Xor(encoded: string, xorKey?: number): string;
3
+
4
+ export function fetchWithRetry(
5
+ url: string | URL,
6
+ options?: RequestInit & {
7
+ retries?: number;
8
+ retryDelay?: number;
9
+ timeout?: number;
10
+ retryCondition?: (error?: unknown, response?: Response) => boolean;
11
+ }
12
+ ): Promise<Response>;
13
+
14
+ export const http: typeof fetchWithRetry;
15
+
16
+ export namespace strings {
17
+ function normalizeRecipients(val: unknown): string;
18
+ }
19
+ export namespace numbers {
20
+ function fmtPerc(x: number, digits?: number): string;
21
+ function toFixedSafe(x: number, digits?: number): string;
22
+ }
23
+
24
+ export function addNamespace(payload: object, namespace?: string): object;
25
+
26
+ export function detectDeviceType(name: string, context?: string): string;
27
+ export function getAvailableContexts(): string[];
28
+ export function addDetectionContext(contextName: string, detectFunction: (name: string) => string): void;
package/dist/index.js ADDED
@@ -0,0 +1,237 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/codec/decodePayload.js
8
+ function decodePayload(encoded, key) {
9
+ const bytes = base64ToBytesStrict(encoded);
10
+ if (bytes.length === 0) return "";
11
+ if (key === "" || key === void 0 || key === null) {
12
+ return new TextDecoder().decode(bytes);
13
+ }
14
+ if (typeof key === "number" && Number.isFinite(key)) {
15
+ const k = key & 255;
16
+ for (let i = 0; i < bytes.length; i++) bytes[i] ^= k;
17
+ return new TextDecoder().decode(bytes);
18
+ }
19
+ const keyStr = String(key);
20
+ const keyBytes = new TextEncoder().encode(keyStr);
21
+ if (keyBytes.length === 0) {
22
+ return new TextDecoder().decode(bytes);
23
+ }
24
+ for (let i = 0; i < bytes.length; i++) {
25
+ bytes[i] ^= keyBytes[i % keyBytes.length];
26
+ }
27
+ return new TextDecoder().decode(bytes);
28
+ }
29
+ function decodePayloadBase64Xor(encoded, xorKey = 73) {
30
+ const bytes = base64ToBytesStrict(encoded);
31
+ for (let i = 0; i < bytes.length; i++) bytes[i] ^= xorKey & 255;
32
+ return new TextDecoder().decode(bytes);
33
+ }
34
+ function base64ToBytesStrict(b64) {
35
+ if (b64 === "" || b64 === void 0 || b64 === null) return new Uint8Array();
36
+ const s = String(b64).replace(/\s+/g, "");
37
+ const re = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
38
+ if (!re.test(s)) throw new Error("Invalid base64");
39
+ if (typeof Buffer !== "undefined" && Buffer.from) {
40
+ return Uint8Array.from(Buffer.from(s, "base64"));
41
+ }
42
+ const bin = atob(s);
43
+ const out = new Uint8Array(bin.length);
44
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
45
+ return out;
46
+ }
47
+
48
+ // src/net/http.js
49
+ async function fetchWithRetry(url, options = {}) {
50
+ const {
51
+ retries = 0,
52
+ retryDelay = 100,
53
+ timeout = 1e4,
54
+ retryCondition,
55
+ ...passThrough
56
+ } = options;
57
+ const baseInit = { ...passThrough, timeout };
58
+ let attempt = 0;
59
+ while (true) {
60
+ try {
61
+ const res = await withTimeout(fetch(url, baseInit), timeout);
62
+ if (!res.ok) {
63
+ const doRetry = typeof retryCondition === "function" && retryCondition(null, res) || res.status >= 500;
64
+ if (doRetry && attempt < retries) {
65
+ await delay(expBackoff(retryDelay, attempt));
66
+ attempt++;
67
+ continue;
68
+ }
69
+ const msg = `HTTP ${res.status}: ${res.statusText || ""}`.trim();
70
+ throw new Error(msg);
71
+ }
72
+ return res;
73
+ } catch (err) {
74
+ if (err && err.message === "Request timeout") {
75
+ if (attempt < retries) {
76
+ await delay(expBackoff(retryDelay, attempt));
77
+ attempt++;
78
+ continue;
79
+ }
80
+ throw err;
81
+ }
82
+ const doRetry = typeof retryCondition === "function" && retryCondition(err, void 0) || isRetryableNetworkError(err);
83
+ if (doRetry && attempt < retries) {
84
+ await delay(expBackoff(retryDelay, attempt));
85
+ attempt++;
86
+ continue;
87
+ }
88
+ throw err;
89
+ }
90
+ }
91
+ }
92
+ var http = fetchWithRetry;
93
+ function withTimeout(promise, ms) {
94
+ return new Promise((resolve, reject) => {
95
+ const t = setTimeout(() => reject(new Error("Request timeout")), ms);
96
+ promise.then(
97
+ (v) => {
98
+ clearTimeout(t);
99
+ resolve(v);
100
+ },
101
+ (e) => {
102
+ clearTimeout(t);
103
+ reject(e);
104
+ }
105
+ );
106
+ });
107
+ }
108
+ function delay(ms) {
109
+ return new Promise((r) => setTimeout(r, ms));
110
+ }
111
+ function expBackoff(base, attempt) {
112
+ return base * Math.pow(2, attempt);
113
+ }
114
+ function isRetryableNetworkError(err) {
115
+ if (!err) return false;
116
+ const msg = String(err.message || "").toLowerCase();
117
+ return msg.includes("network") || err.name === "AbortError";
118
+ }
119
+
120
+ // src/utils/namespace.js
121
+ function addNamespace(payload, namespace = "") {
122
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
123
+ throw new Error("Payload must be an object.");
124
+ }
125
+ const keys = Object.keys(payload);
126
+ const suffix = namespace.trim() ? ` (${namespace.trim()})` : "";
127
+ return keys.reduce((acc, key) => {
128
+ acc[`${key}${suffix}`] = payload[key];
129
+ return acc;
130
+ }, {});
131
+ }
132
+
133
+ // src/utils/deviceType.js
134
+ var contexts = {
135
+ building: (name) => {
136
+ const upper = name.toUpperCase();
137
+ if (upper.includes("COMPRESSOR")) return "COMPRESSOR";
138
+ if (upper.includes("VENT")) return "VENTILADOR";
139
+ if (upper.includes("AUTOMATICO") || upper.includes("AUTOM\xC1TICO")) return "SELETOR_AUTO_MANUAL";
140
+ if (upper.includes("TERMOSTATO")) return "TERMOSTATO";
141
+ if (upper.includes("3F")) return "3F_MEDIDOR";
142
+ if (upper.includes("TERMO") || upper.includes("TEMP")) return "TERMOSTATO";
143
+ if (upper.includes("HIDR")) return "HIDROMETRO";
144
+ if (upper.includes("ABRE")) return "SOLENOIDE";
145
+ if (upper.includes("RECALQUE")) return "MOTOR";
146
+ if (upper.includes("AUTOMACAO") || upper.includes("AUTOMA\xC7\xC3O")) return "GLOBAL_AUTOMACAO";
147
+ if (upper.includes("AC")) return "CONTROLE REMOTO";
148
+ if (upper.includes("SCD")) return "CAIXA_D_AGUA";
149
+ return "default";
150
+ },
151
+ mall: (name) => {
152
+ const upper = name.toUpperCase();
153
+ if (upper.includes("CHILLER")) return "CHILLER";
154
+ if (upper.includes("ESCADA")) return "ESCADA_ROLANTE";
155
+ if (upper.includes("LOJA")) return "LOJA_SENSOR";
156
+ if (upper.includes("ILUMINACAO") || upper.includes("ILUMINA\xC7\xC3O")) return "ILUMINACAO";
157
+ return "default";
158
+ }
159
+ };
160
+ function detectDeviceType(name, context = "building") {
161
+ if (typeof name !== "string") {
162
+ throw new Error("Device name must be a string.");
163
+ }
164
+ const detectFunction = contexts[context];
165
+ if (!detectFunction) {
166
+ console.warn(`[myio-js-library] Context "${context}" not found. Using default fallback.`);
167
+ return contexts.building(name);
168
+ }
169
+ return detectFunction(name);
170
+ }
171
+ function getAvailableContexts() {
172
+ return Object.keys(contexts);
173
+ }
174
+ function addDetectionContext(contextName, detectFunction) {
175
+ if (typeof contextName !== "string") {
176
+ throw new Error("Context name must be a string.");
177
+ }
178
+ if (typeof detectFunction !== "function") {
179
+ throw new Error("Detection function must be a function.");
180
+ }
181
+ contexts[contextName] = detectFunction;
182
+ }
183
+
184
+ // src/utils/strings.js
185
+ var strings_exports = {};
186
+ __export(strings_exports, {
187
+ normalizeRecipients: () => normalizeRecipients
188
+ });
189
+ function normalizeRecipients(val) {
190
+ if (val === null || val === void 0 || val === "") return "";
191
+ if (Object.prototype.toString.call(val) === "[object Array]") {
192
+ return (
193
+ /** @type {unknown[]} */
194
+ val.filter(Boolean).join(",")
195
+ );
196
+ }
197
+ let s = String(val).trim();
198
+ if (/^\s*\[/.test(s)) {
199
+ try {
200
+ const arr = JSON.parse(s);
201
+ if (Object.prototype.toString.call(arr) === "[object Array]") {
202
+ return arr.filter(Boolean).join(",");
203
+ }
204
+ } catch {
205
+ }
206
+ }
207
+ s = s.replace(/[;\s]+/g, ",");
208
+ s = s.replace(/,+/g, ",").replace(/^,|,$/g, "");
209
+ return s;
210
+ }
211
+
212
+ // src/utils/numbers.js
213
+ var numbers_exports = {};
214
+ __export(numbers_exports, {
215
+ fmtPerc: () => fmtPerc,
216
+ toFixedSafe: () => toFixedSafe
217
+ });
218
+ function fmtPerc(x, digits = 2) {
219
+ if (!Number.isFinite(x)) return "\u2014";
220
+ return (x * 100).toFixed(digits) + "%";
221
+ }
222
+ function toFixedSafe(x, digits = 2) {
223
+ if (!Number.isFinite(x)) return "\u2014";
224
+ return x.toFixed(digits);
225
+ }
226
+ export {
227
+ addDetectionContext,
228
+ addNamespace,
229
+ decodePayload,
230
+ decodePayloadBase64Xor,
231
+ detectDeviceType,
232
+ fetchWithRetry,
233
+ getAvailableContexts,
234
+ http,
235
+ numbers_exports as numbers,
236
+ strings_exports as strings
237
+ };
@@ -0,0 +1,314 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.MyIOJSLibrary = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ // XOR sobre bytes decodificados de base64.
8
+ // - key string: repete a chave sobre os bytes
9
+ // - key number: aplica 1 byte (0..255) em todos os bytes
10
+ // - key vazia/undefined: sem XOR
11
+ function decodePayload(encoded, key) {
12
+ const bytes = base64ToBytesStrict(encoded);
13
+ if (bytes.length === 0) return '';
14
+
15
+ if (key === '' || key === undefined || key === null) {
16
+ return new TextDecoder().decode(bytes);
17
+ }
18
+
19
+ if (typeof key === 'number' && Number.isFinite(key)) {
20
+ const k = key & 0xff;
21
+ for (let i = 0; i < bytes.length; i++) bytes[i] ^= k;
22
+ return new TextDecoder().decode(bytes);
23
+ }
24
+
25
+ const keyStr = String(key);
26
+ const keyBytes = new TextEncoder().encode(keyStr);
27
+ if (keyBytes.length === 0) {
28
+ return new TextDecoder().decode(bytes);
29
+ }
30
+ for (let i = 0; i < bytes.length; i++) {
31
+ bytes[i] ^= keyBytes[i % keyBytes.length];
32
+ }
33
+ return new TextDecoder().decode(bytes);
34
+ }
35
+
36
+ // Compat jΓ‘ existente (1 byte XOR)
37
+ function decodePayloadBase64Xor(encoded, xorKey = 73) {
38
+ const bytes = base64ToBytesStrict(encoded);
39
+ for (let i = 0; i < bytes.length; i++) bytes[i] ^= (xorKey & 0xff);
40
+ return new TextDecoder().decode(bytes);
41
+ }
42
+
43
+ function base64ToBytesStrict(b64) {
44
+ if (b64 === '' || b64 === undefined || b64 === null) return new Uint8Array();
45
+ const s = String(b64).replace(/\s+/g, '');
46
+ // valida base64 (com padding)
47
+ const re = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
48
+ if (!re.test(s)) throw new Error('Invalid base64');
49
+
50
+ if (typeof Buffer !== 'undefined' && Buffer.from) {
51
+ return Uint8Array.from(Buffer.from(s, 'base64'));
52
+ }
53
+ const bin = atob(s); // lanΓ§a se invΓ‘lido
54
+ const out = new Uint8Array(bin.length);
55
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
56
+ return out;
57
+ }
58
+
59
+ /**
60
+ * fetchWithRetry(url, {
61
+ * retries?: number = 0,
62
+ * retryDelay?: number = 100,
63
+ * timeout?: number = 10000,
64
+ * retryCondition?: (error, response) => boolean,
65
+ * ...RequestInit (method, headers, body, signal, etc.)
66
+ * })
67
+ *
68
+ * ObservaΓ§Γ£o: os testes verificam que o objeto de options passado ao fetch
69
+ * contΓ©m a prop `timeout`, entΓ£o mantemos `{ timeout }` no init.
70
+ */
71
+ async function fetchWithRetry(url, options = {}) {
72
+ const {
73
+ retries = 0,
74
+ retryDelay = 100,
75
+ timeout = 10000,
76
+ retryCondition,
77
+ ...passThrough
78
+ } = options;
79
+
80
+ const baseInit = { ...passThrough, timeout }; // manter timeout no objeto
81
+
82
+ let attempt = 0;
83
+ while (true) {
84
+ try {
85
+ const res = await withTimeout(fetch(url, baseInit), timeout);
86
+ if (!res.ok) {
87
+ const doRetry =
88
+ (typeof retryCondition === 'function' && retryCondition(null, res)) ||
89
+ res.status >= 500; // padrΓ£o: 5xx
90
+ if (doRetry && attempt < retries) {
91
+ await delay(expBackoff(retryDelay, attempt));
92
+ attempt++;
93
+ continue;
94
+ }
95
+ const msg = `HTTP ${res.status}: ${res.statusText || ''}`.trim();
96
+ throw new Error(msg);
97
+ }
98
+ return res;
99
+ } catch (err) {
100
+ if (err && err.message === 'Request timeout') {
101
+ if (attempt < retries) {
102
+ await delay(expBackoff(retryDelay, attempt));
103
+ attempt++;
104
+ continue;
105
+ }
106
+ throw err;
107
+ }
108
+ const doRetry =
109
+ (typeof retryCondition === 'function' && retryCondition(err, undefined)) ||
110
+ isRetryableNetworkError(err);
111
+ if (doRetry && attempt < retries) {
112
+ await delay(expBackoff(retryDelay, attempt));
113
+ attempt++;
114
+ continue;
115
+ }
116
+ throw err;
117
+ }
118
+ }
119
+ }
120
+
121
+ const http = fetchWithRetry; // alias para manter compat
122
+
123
+ function withTimeout(promise, ms) {
124
+ return new Promise((resolve, reject) => {
125
+ const t = setTimeout(() => reject(new Error('Request timeout')), ms);
126
+ promise.then(
127
+ (v) => { clearTimeout(t); resolve(v); },
128
+ (e) => { clearTimeout(t); reject(e); }
129
+ );
130
+ });
131
+ }
132
+
133
+ function delay(ms) { return new Promise((r) => setTimeout(r, ms)); }
134
+ function expBackoff(base, attempt) { return base * Math.pow(2, attempt); } // 0->base,1->2x,...
135
+ function isRetryableNetworkError(err) {
136
+ if (!err) return false;
137
+ const msg = String(err.message || '').toLowerCase();
138
+ return msg.includes('network') || err.name === 'AbortError';
139
+ }
140
+
141
+ /**
142
+ * Adds a namespace (e.g., building name or location) to the keys of a payload object.
143
+ *
144
+ * @param {object} payload - Original object with simple keys (e.g., { temperature: 22 }).
145
+ * @param {string} namespace - Text to be appended as a suffix to the keys (e.g., "BB Campos dos Goytacazes").
146
+ * @returns {object} - New object with renamed keys.
147
+ * @throws {Error} - If payload is not an object.
148
+ */
149
+ function addNamespace(payload, namespace = '') {
150
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
151
+ throw new Error('Payload must be an object.');
152
+ }
153
+
154
+ const keys = Object.keys(payload);
155
+ const suffix = namespace.trim() ? ` (${namespace.trim()})` : '';
156
+
157
+ return keys.reduce((acc, key) => {
158
+ acc[`${key}${suffix}`] = payload[key];
159
+ return acc;
160
+ }, {});
161
+ }
162
+
163
+ /**
164
+ * Device detection contexts for different environments
165
+ */
166
+ const contexts = {
167
+ building: (name) => {
168
+ const upper = name.toUpperCase();
169
+
170
+ if (upper.includes('COMPRESSOR')) return 'COMPRESSOR';
171
+ if (upper.includes('VENT')) return 'VENTILADOR';
172
+ if (upper.includes('AUTOMATICO') || upper.includes('AUTOMÁTICO')) return 'SELETOR_AUTO_MANUAL';
173
+ if (upper.includes('TERMOSTATO')) return 'TERMOSTATO';
174
+ if (upper.includes('3F')) return '3F_MEDIDOR';
175
+ if (upper.includes('TERMO') || upper.includes('TEMP')) return 'TERMOSTATO';
176
+ if (upper.includes('HIDR')) return 'HIDROMETRO';
177
+ if (upper.includes('ABRE')) return 'SOLENOIDE';
178
+ if (upper.includes('RECALQUE')) return 'MOTOR';
179
+ if (upper.includes('AUTOMACAO') || upper.includes('AUTOMAÇÃO')) return 'GLOBAL_AUTOMACAO';
180
+ if (upper.includes('AC')) return 'CONTROLE REMOTO';
181
+ if (upper.includes('SCD')) return 'CAIXA_D_AGUA';
182
+
183
+ return 'default';
184
+ },
185
+
186
+ mall: (name) => {
187
+ const upper = name.toUpperCase();
188
+
189
+ if (upper.includes('CHILLER')) return 'CHILLER';
190
+ if (upper.includes('ESCADA')) return 'ESCADA_ROLANTE';
191
+ if (upper.includes('LOJA')) return 'LOJA_SENSOR';
192
+ if (upper.includes('ILUMINACAO') || upper.includes('ILUMINAÇÃO')) return 'ILUMINACAO';
193
+
194
+ return 'default';
195
+ }
196
+ };
197
+
198
+ /**
199
+ * Detects the device type based on the given name and context.
200
+ * Uses the specified detection context to identify device types.
201
+ * If the specified context does not exist, falls back to 'building' context.
202
+ *
203
+ * @param {string} name - The name of the device (e.g., "Compressor 7 Andar").
204
+ * @param {string} [context='building'] - The detection context (e.g., "mall", "building").
205
+ * @returns {string} - The detected device type (e.g., "COMPRESSOR", "VENTILADOR", or "default").
206
+ */
207
+ function detectDeviceType(name, context = 'building') {
208
+ if (typeof name !== 'string') {
209
+ throw new Error('Device name must be a string.');
210
+ }
211
+
212
+ const detectFunction = contexts[context];
213
+
214
+ if (!detectFunction) {
215
+ console.warn(`[myio-js-library] Context "${context}" not found. Using default fallback.`);
216
+ return contexts.building(name);
217
+ }
218
+
219
+ return detectFunction(name);
220
+ }
221
+
222
+ /**
223
+ * Get available detection contexts
224
+ * @returns {string[]} Array of available context names
225
+ */
226
+ function getAvailableContexts() {
227
+ return Object.keys(contexts);
228
+ }
229
+
230
+ /**
231
+ * Add a custom detection context
232
+ * @param {string} contextName - Name of the new context
233
+ * @param {function} detectFunction - Function that takes a device name and returns a device type
234
+ */
235
+ function addDetectionContext(contextName, detectFunction) {
236
+ if (typeof contextName !== 'string') {
237
+ throw new Error('Context name must be a string.');
238
+ }
239
+
240
+ if (typeof detectFunction !== 'function') {
241
+ throw new Error('Detection function must be a function.');
242
+ }
243
+
244
+ contexts[contextName] = detectFunction;
245
+ }
246
+
247
+ /**
248
+ * Normalize list-like inputs into a comma-separated string.
249
+ * Accepts array, JSON-stringified array, or delimited strings (; , space).
250
+ * @param {unknown} val
251
+ * @returns {string}
252
+ */
253
+ function normalizeRecipients(val) {
254
+ if (val === null || val === undefined || val === '') return '';
255
+ if (Object.prototype.toString.call(val) === '[object Array]') {
256
+ return /** @type {unknown[]} */(val).filter(Boolean).join(',');
257
+ }
258
+ let s = String(val).trim();
259
+ if (/^\s*\[/.test(s)) {
260
+ try {
261
+ const arr = JSON.parse(s);
262
+ if (Object.prototype.toString.call(arr) === '[object Array]') {
263
+ return arr.filter(Boolean).join(',');
264
+ }
265
+ } catch { /* fall through */ }
266
+ }
267
+ s = s.replace(/[;\s]+/g, ',');
268
+ s = s.replace(/,+/g, ',').replace(/^,|,$/g, '');
269
+ return s;
270
+ }
271
+
272
+ var strings = /*#__PURE__*/Object.freeze({
273
+ __proto__: null,
274
+ normalizeRecipients: normalizeRecipients
275
+ });
276
+
277
+ /**
278
+ * Format ratio 0..1 as percentage string (e.g., 0.1234 -> "12.34%").
279
+ * @param {number} x
280
+ * @param {number} [digits=2]
281
+ */
282
+ function fmtPerc(x, digits = 2) {
283
+ if (!Number.isFinite(x)) return 'β€”';
284
+ return (x * 100).toFixed(digits) + '%';
285
+ }
286
+
287
+ /**
288
+ * Safe fixed decimal formatting (returns string, or 'β€”' if NaN/Inf).
289
+ * @param {number} x
290
+ * @param {number} [digits=2]
291
+ */
292
+ function toFixedSafe(x, digits = 2) {
293
+ if (!Number.isFinite(x)) return 'β€”';
294
+ return x.toFixed(digits);
295
+ }
296
+
297
+ var numbers = /*#__PURE__*/Object.freeze({
298
+ __proto__: null,
299
+ fmtPerc: fmtPerc,
300
+ toFixedSafe: toFixedSafe
301
+ });
302
+
303
+ exports.addDetectionContext = addDetectionContext;
304
+ exports.addNamespace = addNamespace;
305
+ exports.decodePayload = decodePayload;
306
+ exports.decodePayloadBase64Xor = decodePayloadBase64Xor;
307
+ exports.detectDeviceType = detectDeviceType;
308
+ exports.fetchWithRetry = fetchWithRetry;
309
+ exports.getAvailableContexts = getAvailableContexts;
310
+ exports.http = http;
311
+ exports.numbers = numbers;
312
+ exports.strings = strings;
313
+
314
+ }));
@@ -0,0 +1 @@
1
+ (function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):(global=typeof globalThis!=="undefined"?globalThis:global||self,factory(global.MyIOJSLibrary={}))})(this,function(exports){"use strict";function decodePayload(encoded,key){const bytes=base64ToBytesStrict(encoded);if(bytes.length===0)return"";if(key===""||key===undefined||key===null){return(new TextDecoder).decode(bytes)}if(typeof key==="number"&&Number.isFinite(key)){const k=key&255;for(let i=0;i<bytes.length;i++)bytes[i]^=k;return(new TextDecoder).decode(bytes)}const keyStr=String(key);const keyBytes=(new TextEncoder).encode(keyStr);if(keyBytes.length===0){return(new TextDecoder).decode(bytes)}for(let i=0;i<bytes.length;i++){bytes[i]^=keyBytes[i%keyBytes.length]}return(new TextDecoder).decode(bytes)}function decodePayloadBase64Xor(encoded,xorKey=73){const bytes=base64ToBytesStrict(encoded);for(let i=0;i<bytes.length;i++)bytes[i]^=xorKey&255;return(new TextDecoder).decode(bytes)}function base64ToBytesStrict(b64){if(b64===""||b64===undefined||b64===null)return new Uint8Array;const s=String(b64).replace(/\s+/g,"");const re=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;if(!re.test(s))throw new Error("Invalid base64");if(typeof Buffer!=="undefined"&&Buffer.from){return Uint8Array.from(Buffer.from(s,"base64"))}const bin=atob(s);const out=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)out[i]=bin.charCodeAt(i);return out}async function fetchWithRetry(url,options={}){const{retries:retries=0,retryDelay:retryDelay=100,timeout:timeout=1e4,retryCondition:retryCondition,...passThrough}=options;const baseInit={...passThrough,timeout:timeout};let attempt=0;while(true){try{const res=await withTimeout(fetch(url,baseInit),timeout);if(!res.ok){const doRetry=typeof retryCondition==="function"&&retryCondition(null,res)||res.status>=500;if(doRetry&&attempt<retries){await delay(expBackoff(retryDelay,attempt));attempt++;continue}const msg=`HTTP ${res.status}: ${res.statusText||""}`.trim();throw new Error(msg)}return res}catch(err){if(err&&err.message==="Request timeout"){if(attempt<retries){await delay(expBackoff(retryDelay,attempt));attempt++;continue}throw err}const doRetry=typeof retryCondition==="function"&&retryCondition(err,undefined)||isRetryableNetworkError(err);if(doRetry&&attempt<retries){await delay(expBackoff(retryDelay,attempt));attempt++;continue}throw err}}}const http=fetchWithRetry;function withTimeout(promise,ms){return new Promise((resolve,reject)=>{const t=setTimeout(()=>reject(new Error("Request timeout")),ms);promise.then(v=>{clearTimeout(t);resolve(v)},e=>{clearTimeout(t);reject(e)})})}function delay(ms){return new Promise(r=>setTimeout(r,ms))}function expBackoff(base,attempt){return base*Math.pow(2,attempt)}function isRetryableNetworkError(err){if(!err)return false;const msg=String(err.message||"").toLowerCase();return msg.includes("network")||err.name==="AbortError"}function addNamespace(payload,namespace=""){if(!payload||typeof payload!=="object"||Array.isArray(payload)){throw new Error("Payload must be an object.")}const keys=Object.keys(payload);const suffix=namespace.trim()?` (${namespace.trim()})`:"";return keys.reduce((acc,key)=>{acc[`${key}${suffix}`]=payload[key];return acc},{})}const contexts={building:name=>{const upper=name.toUpperCase();if(upper.includes("COMPRESSOR"))return"COMPRESSOR";if(upper.includes("VENT"))return"VENTILADOR";if(upper.includes("AUTOMATICO")||upper.includes("AUTOMÁTICO"))return"SELETOR_AUTO_MANUAL";if(upper.includes("TERMOSTATO"))return"TERMOSTATO";if(upper.includes("3F"))return"3F_MEDIDOR";if(upper.includes("TERMO")||upper.includes("TEMP"))return"TERMOSTATO";if(upper.includes("HIDR"))return"HIDROMETRO";if(upper.includes("ABRE"))return"SOLENOIDE";if(upper.includes("RECALQUE"))return"MOTOR";if(upper.includes("AUTOMACAO")||upper.includes("AUTOMAÇÃO"))return"GLOBAL_AUTOMACAO";if(upper.includes("AC"))return"CONTROLE REMOTO";if(upper.includes("SCD"))return"CAIXA_D_AGUA";return"default"},mall:name=>{const upper=name.toUpperCase();if(upper.includes("CHILLER"))return"CHILLER";if(upper.includes("ESCADA"))return"ESCADA_ROLANTE";if(upper.includes("LOJA"))return"LOJA_SENSOR";if(upper.includes("ILUMINACAO")||upper.includes("ILUMINAÇÃO"))return"ILUMINACAO";return"default"}};function detectDeviceType(name,context="building"){if(typeof name!=="string"){throw new Error("Device name must be a string.")}const detectFunction=contexts[context];if(!detectFunction){console.warn(`[myio-js-library] Context "${context}" not found. Using default fallback.`);return contexts.building(name)}return detectFunction(name)}function getAvailableContexts(){return Object.keys(contexts)}function addDetectionContext(contextName,detectFunction){if(typeof contextName!=="string"){throw new Error("Context name must be a string.")}if(typeof detectFunction!=="function"){throw new Error("Detection function must be a function.")}contexts[contextName]=detectFunction}function normalizeRecipients(val){if(val===null||val===undefined||val==="")return"";if(Object.prototype.toString.call(val)==="[object Array]"){return val.filter(Boolean).join(",")}let s=String(val).trim();if(/^\s*\[/.test(s)){try{const arr=JSON.parse(s);if(Object.prototype.toString.call(arr)==="[object Array]"){return arr.filter(Boolean).join(",")}}catch{}}s=s.replace(/[;\s]+/g,",");s=s.replace(/,+/g,",").replace(/^,|,$/g,"");return s}var strings=Object.freeze({__proto__:null,normalizeRecipients:normalizeRecipients});function fmtPerc(x,digits=2){if(!Number.isFinite(x))return"β€”";return(x*100).toFixed(digits)+"%"}function toFixedSafe(x,digits=2){if(!Number.isFinite(x))return"β€”";return x.toFixed(digits)}var numbers=Object.freeze({__proto__:null,fmtPerc:fmtPerc,toFixedSafe:toFixedSafe});exports.addDetectionContext=addDetectionContext;exports.addNamespace=addNamespace;exports.decodePayload=decodePayload;exports.decodePayloadBase64Xor=decodePayloadBase64Xor;exports.detectDeviceType=detectDeviceType;exports.fetchWithRetry=fetchWithRetry;exports.getAvailableContexts=getAvailableContexts;exports.http=http;exports.numbers=numbers;exports.strings=strings});
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "myio-js-library",
3
+ "version": "0.1.0",
4
+ "description": "A clean, standalone JS SDK for MYIO projects",
5
+ "license": "MIT",
6
+ "repository": "github:gh-myio/myio-js-library",
7
+ "type": "module",
8
+ "main": "./dist/index.cjs",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "require": "./dist/index.cjs",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "sideEffects": false,
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "scripts": {
29
+ "clean": "rimraf dist",
30
+ "build:tsup": "tsup src/index.js --format esm,cjs --clean --outDir dist",
31
+ "build:umd": "rollup -c",
32
+ "minify:umd": "terser dist/myio-js-library.umd.js -o dist/myio-js-library.umd.min.js --comments=false",
33
+ "postbuild": "node scripts/copy-dts.js",
34
+ "build": "npm run clean && npm run build:tsup && npm run build:umd && npm run minify:umd",
35
+ "lint": "eslint .",
36
+ "test": "vitest run",
37
+ "dev:test": "vitest",
38
+ "release": "npm run build && npm publish --access public"
39
+ },
40
+ "devDependencies": {
41
+ "@eslint/js": "^9.34.0",
42
+ "@rollup/plugin-commonjs": "^25.0.7",
43
+ "@rollup/plugin-node-resolve": "^15.2.3",
44
+ "eslint": "^9.11.1",
45
+ "globals": "^16.3.0",
46
+ "rimraf": "^6.0.1",
47
+ "rollup": "^4.21.0",
48
+ "terser": "^5.31.6",
49
+ "tsup": "^8.3.0",
50
+ "typescript": "^5.6.2",
51
+ "vitest": "^2.1.1"
52
+ }
53
+ }