@cutos/core 4.0.6 → 4.0.8

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
@@ -49,9 +49,11 @@ Hardware Device/Driver APIs remain available as the compatibility layer, but new
49
49
  5. [Notification API](#notification-api)
50
50
  6. [Logger API](#logger-api)
51
51
  7. [Error Model](#error-model)
52
- 8. [Capability Contract](#capability-contract)
53
- 9. [Mock Dev](#mock-dev)
54
- 10. [Documentation](#documentation)
52
+ 8. [Device Capability Base](#device-capability-base)
53
+ 9. [Device Provider Base](#device-provider-base)
54
+ 10. [Capability Contract](#capability-contract)
55
+ 11. [Core Simulator](#core-simulator)
56
+ 12. [Documentation](#documentation)
55
57
 
56
58
  # Quick Start
57
59
 
@@ -93,15 +95,47 @@ import { CoreAPI, CutosMock } from "@cutos/core"
93
95
 
94
96
  CutosMock.install({
95
97
  capabilities: {
96
- "hello-device": {
98
+ demo: {
97
99
  methods: {
98
- echo: params => params
100
+ echo: params => ({ message: params.message })
99
101
  }
100
102
  }
101
103
  }
102
104
  })
103
105
 
104
106
  await CoreAPI.init("mock")
107
+
108
+ const demo = new CoreClass.Capability("demo")
109
+ const result = await demo.call("echo", { message: "hello" })
110
+ ```
111
+
112
+ `CutosMock.install()` connects the existing `Capability`, `Provider`, `DeviceCapabilityBase`, and `DeviceProviderBase` classes to an in-memory transport. Capability names must match exactly. Device Base classes derive `capability.device.<deviceType>` automatically.
113
+
114
+ ```ts
115
+ CutosMock.install()
116
+ await CoreAPI.init("mock")
117
+
118
+ class HelloProvider extends DeviceProviderBase {
119
+ connect() {
120
+ this.setStatus("online")
121
+ return { connected: true }
122
+ }
123
+
124
+ disconnect() {
125
+ this.setStatus("offline")
126
+ return { connected: false }
127
+ }
128
+
129
+ readDeviceInfo() {
130
+ return { deviceType: this.deviceType }
131
+ }
132
+ }
133
+
134
+ const provider = new HelloProvider("hello")
135
+ const device = new DeviceCapabilityBase("hello")
136
+
137
+ await device.init()
138
+ await device.connect()
105
139
  ```
106
140
 
107
141
  For simple UI development, set the CUTOS host to `mock` and keep application code unchanged:
@@ -186,15 +220,6 @@ Get registered CUTOS device identity information.
186
220
  const deviceInfo = await CoreAPI.getDeviceInfo<Record<string, unknown>>()
187
221
  ```
188
222
 
189
- ## CoreAPI.getSignInfo / CoreAPI.getSignGroupInfo
190
-
191
- Get sign and sign group metadata.
192
-
193
- ```ts
194
- const signInfo = await CoreAPI.getSignInfo<Record<string, unknown>>()
195
- const groupInfo = await CoreAPI.getSignGroupInfo<Record<string, unknown>>()
196
- ```
197
-
198
223
  ## CoreAPI.getVolume / CoreAPI.setVolume
199
224
 
200
225
  ```ts
@@ -423,6 +448,47 @@ The third argument is optional and defaults to `LWA`.
423
448
  logger.info("hello-provider", "started", "Provider")
424
449
  ```
425
450
 
451
+ # Device Capability Base
452
+
453
+ `DeviceCapabilityBase` is the consumer-side base used by a Device Capability SDK. It derives the Capability identity from the raw `deviceType` and supplies the standard Device API:
454
+
455
+ - `init()`
456
+ - `connect()`
457
+ - `disconnect()`
458
+ - `readDeviceInfo()`
459
+ - `onData()`
460
+ - `onStatus()`
461
+ - `onError()`
462
+
463
+ Concrete SDK classes add only device-specific extension methods:
464
+
465
+ ```ts
466
+ class PrinterCapability extends DeviceCapabilityBase {
467
+ constructor(options = {}) {
468
+ super("printer", options)
469
+ }
470
+
471
+ printText(params) {
472
+ return this.call("printText", params)
473
+ }
474
+ }
475
+
476
+ const printer = new PrinterCapability()
477
+ await printer.init()
478
+ await printer.connect()
479
+
480
+ const info = await printer.readDeviceInfo()
481
+ const offData = printer.onData(data => console.log(data))
482
+ const offStatus = printer.onStatus(status => console.log(status))
483
+ const offError = printer.onError(error => console.error(error))
484
+
485
+ offData()
486
+ offStatus()
487
+ offError()
488
+ ```
489
+
490
+ `onStatus()` receives both Provider status events and Runtime heartbeat status. Consumers should inspect the received payload rather than assuming every heartbeat message is a Device state transition.
491
+
426
492
  # Device Provider Base
427
493
 
428
494
  `DeviceProviderBase` automatically registers the standard `connect`, `disconnect`, and `readDeviceInfo` Capability methods. A concrete device Provider overrides those methods and registers only its device-specific extensions:
@@ -459,6 +525,22 @@ class PrinterProvider extends DeviceProviderBase {
459
525
 
460
526
  The Base implementations throw `DEVICE_CONNECT_NOT_IMPLEMENTED`, `DEVICE_DISCONNECT_NOT_IMPLEMENTED`, and `DEVICE_INFO_NOT_IMPLEMENTED`. This makes an incomplete Provider fail explicitly instead of leaving a standard method unregistered.
461
527
 
528
+ Provider helpers map directly to Device Capability events and Runtime health reporting:
529
+
530
+ ```ts
531
+ this.emitData({ paper: "ready" })
532
+ this.setStatus("online", { port: "COM3" })
533
+ this.emitError(new CutosError("PRINTER_ERROR", "Printer failed"))
534
+
535
+ this.setBeatInterval(3000)
536
+ this.startBeat()
537
+ ```
538
+
539
+ - `emitData(data)` emits the standard `data` event.
540
+ - `setStatus(status, info)` emits the standard `status` event and updates heartbeat state.
541
+ - `emitError(error)` normalizes the error, emits `error`, and marks heartbeat state as failed.
542
+ - `startBeat()` registers and starts the Provider heartbeat. Calling it more than once is safe.
543
+
462
544
  # Error Model
463
545
 
464
546
  CUTOS 4.0 normalizes SDK errors to `CutosError`.
@@ -493,8 +575,8 @@ Capabilities should be described by `capability.contract.json`.
493
575
  ```json
494
576
  {
495
577
  "schemaVersion": "0.1",
496
- "name": "hello-device",
497
- "version": "1.0.0",
578
+ "name": "capability.device.hello",
579
+ "version": "4.0.0",
498
580
  "type": "device",
499
581
  "methods": {},
500
582
  "events": {},
@@ -505,6 +587,20 @@ Capabilities should be described by `capability.contract.json`.
505
587
 
506
588
  Contracts are the source of truth for future SDK generation, Provider stubs, documentation, tests, permissions, and AI tool schemas.
507
589
 
590
+ # Core Simulator
591
+
592
+ `CoreSimulator` is a lightweight compatibility helper for testing legacy Driver initialization against an MQTT broker. It connects to `ws://localhost:<port>` and handles the default Device `init` command:
593
+
594
+ ```ts
595
+ CoreSimulator.start({
596
+ init(args) {
597
+ console.log("Driver init", args)
598
+ }
599
+ }, 1883)
600
+ ```
601
+
602
+ Use `CutosMock` for normal LWA and Capability UI development. `CoreSimulator` requires a compatible MQTT broker and is not a replacement for full CUTOS Runtime verification.
603
+
508
604
  # Documentation
509
605
 
510
606
  Full CUTOS 4.0 SDK API guide:
package/dist/cutos.cjs.js CHANGED
@@ -398,14 +398,14 @@ const cutosAPI$2 = {
398
398
  var cutosApi = cutosAPI$2;
399
399
 
400
400
  var name = "@cutos/core";
401
- var version = "4.0.6";
401
+ var version = "4.0.8";
402
402
  var description = "The CUTOS (CUT Operating System) Core API is a JavaScript library that provides essential functionalities for LWA (Local Web Application) edge computing and communication in the CUTOS ecosystem. ";
403
403
  var main = "dist/cutos.cjs.js";
404
404
  var module$1 = "dist/cutos.esm.js";
405
405
  var types = "types/index.d.ts";
406
406
  var scripts = {
407
407
  "build:rollup": "rollup -c rollup.config.cjs",
408
- test: "node test/device-provider-base.mjs"
408
+ test: "node test/device-provider-base.mjs && node test/mock-capability.mjs"
409
409
  };
410
410
  var keywords = [
411
411
  "CUTOS",
@@ -470,6 +470,13 @@ let callbackTimer = null;
470
470
  let coreApiInitialized = false;
471
471
  let _logger = null;
472
472
  let _notification = null;
473
+ let mockDeviceFactory = null;
474
+ let mockDriverFactory = null;
475
+
476
+ function configureMockTransports$1(deviceFactory = null, driverFactory = null) {
477
+ mockDeviceFactory = deviceFactory;
478
+ mockDriverFactory = driverFactory;
479
+ }
473
480
 
474
481
  let CutosError$2 = class CutosError extends Error {
475
482
  constructor(code = 'CUTOS_ERROR', message = 'CUTOS error', detail = undefined) {
@@ -1171,6 +1178,9 @@ class Device {
1171
1178
  * @param type
1172
1179
  */
1173
1180
  constructor(name = 'default-device-name', type = cutosAPI$1.DEVICE.DEFAULT) {
1181
+ if (mockDeviceFactory) {
1182
+ return mockDeviceFactory(name, type);
1183
+ }
1174
1184
  this.name = name;
1175
1185
  this.type = type;
1176
1186
  this.topicData = cutosAPI$1.DEVICE.CHANNEL + '-' + type + '-data';
@@ -1244,6 +1254,9 @@ class Driver {
1244
1254
  * @param counter
1245
1255
  */
1246
1256
  constructor(name = 'default-driver-name', type = cutosAPI$1.DEVICE.DEFAULT, counter = 10) {
1257
+ if (mockDriverFactory) {
1258
+ return mockDriverFactory(name, type, counter);
1259
+ }
1247
1260
  this.name = name;
1248
1261
  this.type = type;
1249
1262
  this.heartbeat = new Heartbeat(type, counter);
@@ -1354,11 +1367,15 @@ class Capability {
1354
1367
  this.eventListeners.get(event).add(listener);
1355
1368
 
1356
1369
  if (!this.dataListenerRegistered) {
1357
- if (!listenerMap.has(this.device.topicData)) {
1358
- client.subscribe(this.device.topicData);
1370
+ if (typeof this.device.onData === "function") {
1371
+ this.unsubscribeData = this.device.onData(message => this._dispatchEvent(message));
1372
+ } else {
1373
+ if (!listenerMap.has(this.device.topicData)) {
1374
+ client.subscribe(this.device.topicData);
1375
+ }
1376
+ listenerMap.set(this.device.topicData, message => this._dispatchEvent(message));
1377
+ this.unsubscribeData = () => listenerMap.delete(this.device.topicData);
1359
1378
  }
1360
- listenerMap.set(this.device.topicData, message => this._dispatchEvent(message));
1361
- this.unsubscribeData = () => listenerMap.delete(this.device.topicData);
1362
1379
  this.dataListenerRegistered = true;
1363
1380
  }
1364
1381
 
@@ -1723,14 +1740,6 @@ const CoreAPI$3 = {
1723
1740
  return maybePromise(callback, cb => publishRequest(cutosAPI$1.CORE.BOX_INFO, cb));
1724
1741
  },
1725
1742
 
1726
- /**
1727
- * Get sign information
1728
- * @param {Function} callback - callback(result)
1729
- */
1730
- getSignInfo(callback) {
1731
- return maybePromise(callback, cb => publishRequest(cutosAPI$1.CORE.SIGN_INFO, cb));
1732
- },
1733
-
1734
1743
  /**
1735
1744
  * Get device information
1736
1745
  * @param {Function} callback - callback(result)
@@ -1739,10 +1748,6 @@ const CoreAPI$3 = {
1739
1748
  return maybePromise(callback, cb => publishRequest(cutosAPI$1.CORE.DEVICE_INFO, cb));
1740
1749
  },
1741
1750
 
1742
- getSignGroupInfo(callback) {
1743
- return maybePromise(callback, cb => publishRequest(cutosAPI$1.CORE.SIGN_GROUP_INFO, cb));
1744
- },
1745
-
1746
1751
  /**
1747
1752
  * Get IPC instance object
1748
1753
  * @param {String} destAddress - optional parameter, target IP address, used for inter-device process communication
@@ -1821,6 +1826,7 @@ cutos.cutosAPI = cutosAPI$1;
1821
1826
  cutos.CutosError = CutosError$2;
1822
1827
  cutos.DeviceCapabilityBase = DeviceCapabilityBase$1;
1823
1828
  cutos.DeviceProviderBase = DeviceProviderBase$1;
1829
+ cutos.configureMockTransports = configureMockTransports$1;
1824
1830
 
1825
1831
  // simulate cutos core for development
1826
1832
  const {CoreAPI: CoreAPI$2, CoreClass: CoreClass$1} = cutos;
@@ -1855,7 +1861,7 @@ const CoreSimulator$1 = {
1855
1861
 
1856
1862
  var coreSimulator = {CoreSimulator: CoreSimulator$1};
1857
1863
 
1858
- const {CoreAPI: CoreAPI$1, CutosError: CutosError$1} = cutos;
1864
+ const {CoreAPI: CoreAPI$1, CutosError: CutosError$1, configureMockTransports} = cutos;
1859
1865
 
1860
1866
  const original = {
1861
1867
  init: CoreAPI$1.init,
@@ -1863,9 +1869,7 @@ const original = {
1863
1869
  getPlatform: CoreAPI$1.getPlatform,
1864
1870
  getConfig: CoreAPI$1.getConfig,
1865
1871
  getBoxInfo: CoreAPI$1.getBoxInfo,
1866
- getSignInfo: CoreAPI$1.getSignInfo,
1867
1872
  getDeviceInfo: CoreAPI$1.getDeviceInfo,
1868
- getSignGroupInfo: CoreAPI$1.getSignGroupInfo,
1869
1873
  shell: CoreAPI$1.shell,
1870
1874
  getVolume: CoreAPI$1.getVolume,
1871
1875
  setVolume: CoreAPI$1.setVolume,
@@ -1876,8 +1880,7 @@ const mockState = {
1876
1880
  installed: false,
1877
1881
  connected: false,
1878
1882
  options: {},
1879
- capabilities: new Map(),
1880
- providers: new Map()
1883
+ capabilities: new Map()
1881
1884
  };
1882
1885
 
1883
1886
  function resolveCallback(callback, value, error) {
@@ -1885,25 +1888,20 @@ function resolveCallback(callback, value, error) {
1885
1888
  setTimeout(() => callback(error ? null : value, error), 0);
1886
1889
  return true;
1887
1890
  }
1888
-
1889
- if (error) {
1890
- return Promise.reject(error);
1891
- }
1892
- return Promise.resolve(value);
1891
+ return error ? Promise.reject(error) : Promise.resolve(value);
1893
1892
  }
1894
1893
 
1895
1894
  function normalizeMethod(method) {
1896
- if (typeof method === 'function') {
1897
- return method;
1898
- }
1899
- return () => method;
1895
+ return typeof method === 'function' ? method : () => method;
1900
1896
  }
1901
1897
 
1902
1898
  function ensureCapabilityRecord(name) {
1903
1899
  if (!mockState.capabilities.has(name)) {
1904
1900
  mockState.capabilities.set(name, {
1905
1901
  methods: new Map(),
1906
- listeners: new Map()
1902
+ dataListeners: new Set(),
1903
+ commandListener: null,
1904
+ heartbeat: null
1907
1905
  });
1908
1906
  }
1909
1907
  return mockState.capabilities.get(name);
@@ -1912,38 +1910,117 @@ function ensureCapabilityRecord(name) {
1912
1910
  function registerCapability(name, definition = {}) {
1913
1911
  const record = ensureCapabilityRecord(name);
1914
1912
  const methods = definition.methods || {};
1915
-
1916
1913
  Object.keys(methods).forEach(methodName => {
1917
1914
  record.methods.set(methodName, normalizeMethod(methods[methodName]));
1918
1915
  });
1919
-
1920
1916
  return record;
1921
1917
  }
1922
1918
 
1919
+ function invokeMockMethod(record, command, callback) {
1920
+ if (record.commandListener) {
1921
+ record.commandListener(command, callback);
1922
+ return true;
1923
+ }
1924
+
1925
+ const handler = record.methods.get(command.cmd);
1926
+ if (!handler) {
1927
+ callback({
1928
+ status: false,
1929
+ msg: new CutosError$1('METHOD_NOT_FOUND', `Mock capability method ${command.cmd} is not registered.`)
1930
+ });
1931
+ return true;
1932
+ }
1933
+
1934
+ Promise.resolve()
1935
+ .then(() => handler(command.args, {command}))
1936
+ .then(result => callback({status: true, msg: result}))
1937
+ .catch(error => callback({status: false, msg: error}));
1938
+ return true;
1939
+ }
1940
+
1941
+ function invokeMockTransport(record, command, callback) {
1942
+ if (typeof callback === 'function') {
1943
+ return invokeMockMethod(record, command, callback);
1944
+ }
1945
+ return new Promise((resolve, reject) => {
1946
+ invokeMockMethod(record, command, result => {
1947
+ if (result && result.status === false) {
1948
+ reject(result.msg);
1949
+ } else {
1950
+ resolve(result && result.status === true ? result.msg : result);
1951
+ }
1952
+ });
1953
+ });
1954
+ }
1955
+
1956
+ function createMockDevice(name, type) {
1957
+ const record = ensureCapabilityRecord(type);
1958
+ return {
1959
+ name,
1960
+ type,
1961
+ topicData: `mock-${type}-data`,
1962
+ init(opts, callback) {
1963
+ if (typeof opts === 'function') callback = opts;
1964
+ return resolveCallback(callback, mockState.options.initResult ?? `Mock device ${type} initialized`);
1965
+ },
1966
+ sendCommand(command, callback) {
1967
+ return invokeMockTransport(record, command, callback);
1968
+ },
1969
+ sendCommandWithOptions(command, opts, callback) {
1970
+ if (typeof opts === 'function') callback = opts;
1971
+ return invokeMockTransport(record, command, callback);
1972
+ },
1973
+ onData(listener) {
1974
+ record.dataListeners.add(listener);
1975
+ return () => record.dataListeners.delete(listener);
1976
+ }
1977
+ };
1978
+ }
1979
+
1980
+ function createMockDriver(name, type) {
1981
+ const record = ensureCapabilityRecord(type);
1982
+ return {
1983
+ name,
1984
+ type,
1985
+ beatInterval: 3000,
1986
+ onCommand(listener) {
1987
+ record.commandListener = listener;
1988
+ return () => {
1989
+ if (record.commandListener === listener) record.commandListener = null;
1990
+ };
1991
+ },
1992
+ offCommand() {
1993
+ record.commandListener = null;
1994
+ },
1995
+ sendData(data) {
1996
+ record.dataListeners.forEach(listener => listener(data));
1997
+ },
1998
+ startBeat() {},
1999
+ updateStatusInfo(status, info) {
2000
+ record.heartbeat = {status, info};
2001
+ }
2002
+ };
2003
+ }
2004
+
1923
2005
  function installCutosMock$1(options = {}) {
1924
2006
  mockState.options = options;
1925
2007
  mockState.connected = false;
1926
2008
  mockState.capabilities.clear();
1927
- mockState.providers.clear();
1928
2009
 
1929
2010
  const capabilities = options.capabilities || {};
1930
2011
  Object.keys(capabilities).forEach(name => registerCapability(name, capabilities[name]));
2012
+ configureMockTransports(createMockDevice, createMockDriver);
1931
2013
 
1932
2014
  CoreAPI$1.init = function (host = 'localhost', callback) {
1933
- if (typeof host === 'function') {
1934
- callback = host;
1935
- host = 'localhost';
1936
- }
2015
+ if (typeof host === 'function') callback = host;
1937
2016
  mockState.connected = true;
1938
- return resolveCallback(callback, options.initResult || 'CoreAPI mock init success');
2017
+ return resolveCallback(callback, options.initResult ?? 'CoreAPI mock init success');
1939
2018
  };
1940
2019
  CoreAPI$1.connected = () => mockState.connected;
1941
- CoreAPI$1.getPlatform = callback => resolveCallback(callback, options.platform || {name: 'CUTOS Mock'});
1942
- CoreAPI$1.getConfig = callback => resolveCallback(callback, options.config || {});
1943
- CoreAPI$1.getBoxInfo = callback => resolveCallback(callback, options.boxInfo || {name: 'CUTOS Mock Node'});
1944
- CoreAPI$1.getSignInfo = callback => resolveCallback(callback, options.signInfo || {});
1945
- CoreAPI$1.getDeviceInfo = callback => resolveCallback(callback, options.deviceInfo || []);
1946
- CoreAPI$1.getSignGroupInfo = callback => resolveCallback(callback, options.signGroupInfo || {});
2020
+ CoreAPI$1.getPlatform = callback => resolveCallback(callback, options.platform ?? {name: 'CUTOS Mock'});
2021
+ CoreAPI$1.getConfig = callback => resolveCallback(callback, options.config ?? {});
2022
+ CoreAPI$1.getBoxInfo = callback => resolveCallback(callback, options.boxInfo ?? {name: 'CUTOS Mock Node'});
2023
+ CoreAPI$1.getDeviceInfo = callback => resolveCallback(callback, options.deviceInfo ?? {name: 'CUTOS Mock Device'});
1947
2024
  CoreAPI$1.shell = (command, callback) => resolveCallback(callback, {command, stdout: '', stderr: '', code: 0});
1948
2025
  CoreAPI$1.getVolume = callback => resolveCallback(callback, options.volume ?? 50);
1949
2026
  CoreAPI$1.setVolume = (vol, callback) => {
@@ -1957,14 +2034,13 @@ function installCutosMock$1(options = {}) {
1957
2034
  }
1958
2035
 
1959
2036
  function uninstallCutosMock$1() {
2037
+ configureMockTransports();
1960
2038
  CoreAPI$1.init = original.init;
1961
2039
  CoreAPI$1.connected = original.connected;
1962
2040
  CoreAPI$1.getPlatform = original.getPlatform;
1963
2041
  CoreAPI$1.getConfig = original.getConfig;
1964
2042
  CoreAPI$1.getBoxInfo = original.getBoxInfo;
1965
- CoreAPI$1.getSignInfo = original.getSignInfo;
1966
2043
  CoreAPI$1.getDeviceInfo = original.getDeviceInfo;
1967
- CoreAPI$1.getSignGroupInfo = original.getSignGroupInfo;
1968
2044
  CoreAPI$1.shell = original.shell;
1969
2045
  CoreAPI$1.getVolume = original.getVolume;
1970
2046
  CoreAPI$1.setVolume = original.setVolume;
@@ -1973,7 +2049,6 @@ function uninstallCutosMock$1() {
1973
2049
  mockState.connected = false;
1974
2050
  mockState.installed = false;
1975
2051
  mockState.capabilities.clear();
1976
- mockState.providers.clear();
1977
2052
  }
1978
2053
 
1979
2054
  const CutosMock$1 = {
package/dist/cutos.esm.js CHANGED
@@ -690,14 +690,14 @@ const cutosAPI$2 = {
690
690
  var cutosApi = cutosAPI$2;
691
691
 
692
692
  var name = "@cutos/core";
693
- var version = "4.0.6";
693
+ var version = "4.0.8";
694
694
  var description = "The CUTOS (CUT Operating System) Core API is a JavaScript library that provides essential functionalities for LWA (Local Web Application) edge computing and communication in the CUTOS ecosystem. ";
695
695
  var main = "dist/cutos.cjs.js";
696
696
  var module = "dist/cutos.esm.js";
697
697
  var types = "types/index.d.ts";
698
698
  var scripts = {
699
699
  "build:rollup": "rollup -c rollup.config.cjs",
700
- test: "node test/device-provider-base.mjs"
700
+ test: "node test/device-provider-base.mjs && node test/mock-capability.mjs"
701
701
  };
702
702
  var keywords = [
703
703
  "CUTOS",
@@ -762,6 +762,13 @@ let callbackTimer = null;
762
762
  let coreApiInitialized = false;
763
763
  let _logger = null;
764
764
  let _notification = null;
765
+ let mockDeviceFactory = null;
766
+ let mockDriverFactory = null;
767
+
768
+ function configureMockTransports$1(deviceFactory = null, driverFactory = null) {
769
+ mockDeviceFactory = deviceFactory;
770
+ mockDriverFactory = driverFactory;
771
+ }
765
772
 
766
773
  let CutosError$2 = class CutosError extends Error {
767
774
  constructor(code = 'CUTOS_ERROR', message = 'CUTOS error', detail = undefined) {
@@ -1463,6 +1470,9 @@ class Device {
1463
1470
  * @param type
1464
1471
  */
1465
1472
  constructor(name = 'default-device-name', type = cutosAPI$1.DEVICE.DEFAULT) {
1473
+ if (mockDeviceFactory) {
1474
+ return mockDeviceFactory(name, type);
1475
+ }
1466
1476
  this.name = name;
1467
1477
  this.type = type;
1468
1478
  this.topicData = cutosAPI$1.DEVICE.CHANNEL + '-' + type + '-data';
@@ -1536,6 +1546,9 @@ class Driver {
1536
1546
  * @param counter
1537
1547
  */
1538
1548
  constructor(name = 'default-driver-name', type = cutosAPI$1.DEVICE.DEFAULT, counter = 10) {
1549
+ if (mockDriverFactory) {
1550
+ return mockDriverFactory(name, type, counter);
1551
+ }
1539
1552
  this.name = name;
1540
1553
  this.type = type;
1541
1554
  this.heartbeat = new Heartbeat(type, counter);
@@ -1646,11 +1659,15 @@ class Capability {
1646
1659
  this.eventListeners.get(event).add(listener);
1647
1660
 
1648
1661
  if (!this.dataListenerRegistered) {
1649
- if (!listenerMap.has(this.device.topicData)) {
1650
- client.subscribe(this.device.topicData);
1662
+ if (typeof this.device.onData === "function") {
1663
+ this.unsubscribeData = this.device.onData(message => this._dispatchEvent(message));
1664
+ } else {
1665
+ if (!listenerMap.has(this.device.topicData)) {
1666
+ client.subscribe(this.device.topicData);
1667
+ }
1668
+ listenerMap.set(this.device.topicData, message => this._dispatchEvent(message));
1669
+ this.unsubscribeData = () => listenerMap.delete(this.device.topicData);
1651
1670
  }
1652
- listenerMap.set(this.device.topicData, message => this._dispatchEvent(message));
1653
- this.unsubscribeData = () => listenerMap.delete(this.device.topicData);
1654
1671
  this.dataListenerRegistered = true;
1655
1672
  }
1656
1673
 
@@ -2015,14 +2032,6 @@ const CoreAPI$3 = {
2015
2032
  return maybePromise(callback, cb => publishRequest(cutosAPI$1.CORE.BOX_INFO, cb));
2016
2033
  },
2017
2034
 
2018
- /**
2019
- * Get sign information
2020
- * @param {Function} callback - callback(result)
2021
- */
2022
- getSignInfo(callback) {
2023
- return maybePromise(callback, cb => publishRequest(cutosAPI$1.CORE.SIGN_INFO, cb));
2024
- },
2025
-
2026
2035
  /**
2027
2036
  * Get device information
2028
2037
  * @param {Function} callback - callback(result)
@@ -2031,10 +2040,6 @@ const CoreAPI$3 = {
2031
2040
  return maybePromise(callback, cb => publishRequest(cutosAPI$1.CORE.DEVICE_INFO, cb));
2032
2041
  },
2033
2042
 
2034
- getSignGroupInfo(callback) {
2035
- return maybePromise(callback, cb => publishRequest(cutosAPI$1.CORE.SIGN_GROUP_INFO, cb));
2036
- },
2037
-
2038
2043
  /**
2039
2044
  * Get IPC instance object
2040
2045
  * @param {String} destAddress - optional parameter, target IP address, used for inter-device process communication
@@ -2113,6 +2118,7 @@ cutos.cutosAPI = cutosAPI$1;
2113
2118
  cutos.CutosError = CutosError$2;
2114
2119
  cutos.DeviceCapabilityBase = DeviceCapabilityBase$1;
2115
2120
  cutos.DeviceProviderBase = DeviceProviderBase$1;
2121
+ cutos.configureMockTransports = configureMockTransports$1;
2116
2122
 
2117
2123
  // simulate cutos core for development
2118
2124
  const {CoreAPI: CoreAPI$2, CoreClass: CoreClass$1} = cutos;
@@ -2147,7 +2153,7 @@ const CoreSimulator$1 = {
2147
2153
 
2148
2154
  var coreSimulator = {CoreSimulator: CoreSimulator$1};
2149
2155
 
2150
- const {CoreAPI: CoreAPI$1, CutosError: CutosError$1} = cutos;
2156
+ const {CoreAPI: CoreAPI$1, CutosError: CutosError$1, configureMockTransports} = cutos;
2151
2157
 
2152
2158
  const original = {
2153
2159
  init: CoreAPI$1.init,
@@ -2155,9 +2161,7 @@ const original = {
2155
2161
  getPlatform: CoreAPI$1.getPlatform,
2156
2162
  getConfig: CoreAPI$1.getConfig,
2157
2163
  getBoxInfo: CoreAPI$1.getBoxInfo,
2158
- getSignInfo: CoreAPI$1.getSignInfo,
2159
2164
  getDeviceInfo: CoreAPI$1.getDeviceInfo,
2160
- getSignGroupInfo: CoreAPI$1.getSignGroupInfo,
2161
2165
  shell: CoreAPI$1.shell,
2162
2166
  getVolume: CoreAPI$1.getVolume,
2163
2167
  setVolume: CoreAPI$1.setVolume,
@@ -2168,8 +2172,7 @@ const mockState = {
2168
2172
  installed: false,
2169
2173
  connected: false,
2170
2174
  options: {},
2171
- capabilities: new Map(),
2172
- providers: new Map()
2175
+ capabilities: new Map()
2173
2176
  };
2174
2177
 
2175
2178
  function resolveCallback(callback, value, error) {
@@ -2177,25 +2180,20 @@ function resolveCallback(callback, value, error) {
2177
2180
  setTimeout(() => callback(error ? null : value, error), 0);
2178
2181
  return true;
2179
2182
  }
2180
-
2181
- if (error) {
2182
- return Promise.reject(error);
2183
- }
2184
- return Promise.resolve(value);
2183
+ return error ? Promise.reject(error) : Promise.resolve(value);
2185
2184
  }
2186
2185
 
2187
2186
  function normalizeMethod(method) {
2188
- if (typeof method === 'function') {
2189
- return method;
2190
- }
2191
- return () => method;
2187
+ return typeof method === 'function' ? method : () => method;
2192
2188
  }
2193
2189
 
2194
2190
  function ensureCapabilityRecord(name) {
2195
2191
  if (!mockState.capabilities.has(name)) {
2196
2192
  mockState.capabilities.set(name, {
2197
2193
  methods: new Map(),
2198
- listeners: new Map()
2194
+ dataListeners: new Set(),
2195
+ commandListener: null,
2196
+ heartbeat: null
2199
2197
  });
2200
2198
  }
2201
2199
  return mockState.capabilities.get(name);
@@ -2204,38 +2202,117 @@ function ensureCapabilityRecord(name) {
2204
2202
  function registerCapability(name, definition = {}) {
2205
2203
  const record = ensureCapabilityRecord(name);
2206
2204
  const methods = definition.methods || {};
2207
-
2208
2205
  Object.keys(methods).forEach(methodName => {
2209
2206
  record.methods.set(methodName, normalizeMethod(methods[methodName]));
2210
2207
  });
2211
-
2212
2208
  return record;
2213
2209
  }
2214
2210
 
2211
+ function invokeMockMethod(record, command, callback) {
2212
+ if (record.commandListener) {
2213
+ record.commandListener(command, callback);
2214
+ return true;
2215
+ }
2216
+
2217
+ const handler = record.methods.get(command.cmd);
2218
+ if (!handler) {
2219
+ callback({
2220
+ status: false,
2221
+ msg: new CutosError$1('METHOD_NOT_FOUND', `Mock capability method ${command.cmd} is not registered.`)
2222
+ });
2223
+ return true;
2224
+ }
2225
+
2226
+ Promise.resolve()
2227
+ .then(() => handler(command.args, {command}))
2228
+ .then(result => callback({status: true, msg: result}))
2229
+ .catch(error => callback({status: false, msg: error}));
2230
+ return true;
2231
+ }
2232
+
2233
+ function invokeMockTransport(record, command, callback) {
2234
+ if (typeof callback === 'function') {
2235
+ return invokeMockMethod(record, command, callback);
2236
+ }
2237
+ return new Promise((resolve, reject) => {
2238
+ invokeMockMethod(record, command, result => {
2239
+ if (result && result.status === false) {
2240
+ reject(result.msg);
2241
+ } else {
2242
+ resolve(result && result.status === true ? result.msg : result);
2243
+ }
2244
+ });
2245
+ });
2246
+ }
2247
+
2248
+ function createMockDevice(name, type) {
2249
+ const record = ensureCapabilityRecord(type);
2250
+ return {
2251
+ name,
2252
+ type,
2253
+ topicData: `mock-${type}-data`,
2254
+ init(opts, callback) {
2255
+ if (typeof opts === 'function') callback = opts;
2256
+ return resolveCallback(callback, mockState.options.initResult ?? `Mock device ${type} initialized`);
2257
+ },
2258
+ sendCommand(command, callback) {
2259
+ return invokeMockTransport(record, command, callback);
2260
+ },
2261
+ sendCommandWithOptions(command, opts, callback) {
2262
+ if (typeof opts === 'function') callback = opts;
2263
+ return invokeMockTransport(record, command, callback);
2264
+ },
2265
+ onData(listener) {
2266
+ record.dataListeners.add(listener);
2267
+ return () => record.dataListeners.delete(listener);
2268
+ }
2269
+ };
2270
+ }
2271
+
2272
+ function createMockDriver(name, type) {
2273
+ const record = ensureCapabilityRecord(type);
2274
+ return {
2275
+ name,
2276
+ type,
2277
+ beatInterval: 3000,
2278
+ onCommand(listener) {
2279
+ record.commandListener = listener;
2280
+ return () => {
2281
+ if (record.commandListener === listener) record.commandListener = null;
2282
+ };
2283
+ },
2284
+ offCommand() {
2285
+ record.commandListener = null;
2286
+ },
2287
+ sendData(data) {
2288
+ record.dataListeners.forEach(listener => listener(data));
2289
+ },
2290
+ startBeat() {},
2291
+ updateStatusInfo(status, info) {
2292
+ record.heartbeat = {status, info};
2293
+ }
2294
+ };
2295
+ }
2296
+
2215
2297
  function installCutosMock$1(options = {}) {
2216
2298
  mockState.options = options;
2217
2299
  mockState.connected = false;
2218
2300
  mockState.capabilities.clear();
2219
- mockState.providers.clear();
2220
2301
 
2221
2302
  const capabilities = options.capabilities || {};
2222
2303
  Object.keys(capabilities).forEach(name => registerCapability(name, capabilities[name]));
2304
+ configureMockTransports(createMockDevice, createMockDriver);
2223
2305
 
2224
2306
  CoreAPI$1.init = function (host = 'localhost', callback) {
2225
- if (typeof host === 'function') {
2226
- callback = host;
2227
- host = 'localhost';
2228
- }
2307
+ if (typeof host === 'function') callback = host;
2229
2308
  mockState.connected = true;
2230
- return resolveCallback(callback, options.initResult || 'CoreAPI mock init success');
2309
+ return resolveCallback(callback, options.initResult ?? 'CoreAPI mock init success');
2231
2310
  };
2232
2311
  CoreAPI$1.connected = () => mockState.connected;
2233
- CoreAPI$1.getPlatform = callback => resolveCallback(callback, options.platform || {name: 'CUTOS Mock'});
2234
- CoreAPI$1.getConfig = callback => resolveCallback(callback, options.config || {});
2235
- CoreAPI$1.getBoxInfo = callback => resolveCallback(callback, options.boxInfo || {name: 'CUTOS Mock Node'});
2236
- CoreAPI$1.getSignInfo = callback => resolveCallback(callback, options.signInfo || {});
2237
- CoreAPI$1.getDeviceInfo = callback => resolveCallback(callback, options.deviceInfo || []);
2238
- CoreAPI$1.getSignGroupInfo = callback => resolveCallback(callback, options.signGroupInfo || {});
2312
+ CoreAPI$1.getPlatform = callback => resolveCallback(callback, options.platform ?? {name: 'CUTOS Mock'});
2313
+ CoreAPI$1.getConfig = callback => resolveCallback(callback, options.config ?? {});
2314
+ CoreAPI$1.getBoxInfo = callback => resolveCallback(callback, options.boxInfo ?? {name: 'CUTOS Mock Node'});
2315
+ CoreAPI$1.getDeviceInfo = callback => resolveCallback(callback, options.deviceInfo ?? {name: 'CUTOS Mock Device'});
2239
2316
  CoreAPI$1.shell = (command, callback) => resolveCallback(callback, {command, stdout: '', stderr: '', code: 0});
2240
2317
  CoreAPI$1.getVolume = callback => resolveCallback(callback, options.volume ?? 50);
2241
2318
  CoreAPI$1.setVolume = (vol, callback) => {
@@ -2249,14 +2326,13 @@ function installCutosMock$1(options = {}) {
2249
2326
  }
2250
2327
 
2251
2328
  function uninstallCutosMock$1() {
2329
+ configureMockTransports();
2252
2330
  CoreAPI$1.init = original.init;
2253
2331
  CoreAPI$1.connected = original.connected;
2254
2332
  CoreAPI$1.getPlatform = original.getPlatform;
2255
2333
  CoreAPI$1.getConfig = original.getConfig;
2256
2334
  CoreAPI$1.getBoxInfo = original.getBoxInfo;
2257
- CoreAPI$1.getSignInfo = original.getSignInfo;
2258
2335
  CoreAPI$1.getDeviceInfo = original.getDeviceInfo;
2259
- CoreAPI$1.getSignGroupInfo = original.getSignGroupInfo;
2260
2336
  CoreAPI$1.shell = original.shell;
2261
2337
  CoreAPI$1.getVolume = original.getVolume;
2262
2338
  CoreAPI$1.setVolume = original.setVolume;
@@ -2265,7 +2341,6 @@ function uninstallCutosMock$1() {
2265
2341
  mockState.connected = false;
2266
2342
  mockState.installed = false;
2267
2343
  mockState.capabilities.clear();
2268
- mockState.providers.clear();
2269
2344
  }
2270
2345
 
2271
2346
  const CutosMock$1 = {
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@cutos/core",
3
- "version": "4.0.6",
3
+ "version": "4.0.8",
4
4
  "description": "The CUTOS (CUT Operating System) Core API is a JavaScript library that provides essential functionalities for LWA (Local Web Application) edge computing and communication in the CUTOS ecosystem. ",
5
5
  "main": "dist/cutos.cjs.js",
6
6
  "module": "dist/cutos.esm.js",
7
7
  "types": "types/index.d.ts",
8
8
  "scripts": {
9
9
  "build:rollup": "rollup -c rollup.config.cjs",
10
- "test": "node test/device-provider-base.mjs"
10
+ "test": "node test/device-provider-base.mjs && node test/mock-capability.mjs"
11
11
  },
12
12
  "keywords": [
13
13
  "CUTOS", "core", "database", "IPC", "notification", "logging", "device&driver"
package/types/index.d.ts CHANGED
@@ -344,12 +344,8 @@ export interface CoreAPI {
344
344
  getConfig<TResult = unknown>(): Promise<TResult>;
345
345
  getBoxInfo<TResult = unknown>(callback: CutosCallback<TResult>): boolean;
346
346
  getBoxInfo<TResult = unknown>(): Promise<TResult>;
347
- getSignInfo<TResult = unknown>(callback: CutosCallback<TResult>): boolean;
348
- getSignInfo<TResult = unknown>(): Promise<TResult>;
349
347
  getDeviceInfo<TResult = unknown>(callback: CutosCallback<TResult>): boolean;
350
348
  getDeviceInfo<TResult = unknown>(): Promise<TResult>;
351
- getSignGroupInfo<TResult = unknown>(callback: CutosCallback<TResult>): boolean;
352
- getSignGroupInfo<TResult = unknown>(): Promise<TResult>;
353
349
  getIPC(destAddress?: string): IPC;
354
350
  getNotification(): Notification;
355
351
  getLogger(): Logger;
@@ -392,9 +388,7 @@ export interface CutosMockOptions {
392
388
  platform?: unknown;
393
389
  config?: unknown;
394
390
  boxInfo?: unknown;
395
- signInfo?: unknown;
396
391
  deviceInfo?: unknown;
397
- signGroupInfo?: unknown;
398
392
  volume?: number;
399
393
  capabilities?: Record<string, CutosMockCapabilityDefinition>;
400
394
  }