hs2-mock 0.2.0 → 0.3.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/README.md CHANGED
@@ -23,31 +23,59 @@ Reading a member the mock lacks throws `hs2-mock: hs.x.y is not mocked`. Tests c
23
23
 
24
24
  ## Mocked
25
25
 
26
- | Module | Members |
27
- | ---------------- | -------------------------------------------- |
28
- | `hs.application` | `frontmost`, `matchingBundleID`, `on`, `off` |
29
- | `hs.ax` | `applicationElement`, `windowElement` |
30
- | `hs.hotkey` | `bind`, `create` |
31
- | `hs.permissions` | `checkAccessibility` |
32
- | `hs.timer` | `doAfter`, `doEvery`, `secondsSinceEpoch` |
33
- | `hs.ui` | `alert` (`show`) |
34
- | `hs.urlevent` | `openURL` |
26
+ | Module | Members |
27
+ |---|---|
28
+ | `hs.appinfo` | `pid` |
29
+ | `hs.application` | `frontmost`, `fromPID`, `launchOrFocus`, `matchingBundleID`, `on`, `off` |
30
+ | `hs.audiodevice` | `allInputDevices`, `allOutputDevices`, `defaultInputDevice`, `defaultOutputDevice`, `on`, `off` |
31
+ | `hs.ax` | `applicationElement`, `windowElement` |
32
+ | `hs.distributednotifications` | `on`, `off` |
33
+ | `hs.fs` (in memory) | `exists`, `homeDirectory`, `mkdir`, `read`, `urlFromPath`, `write` |
34
+ | `hs.hotkey` | `bind`, `create` |
35
+ | `hs.menubar` | `create` (`title`, `setIcon`, `setMenu`, `destroy`) |
36
+ | `hs.notify` | `show`, `create` (`send`) |
37
+ | `hs.permissions` | `checkAccessibility`, `checkLocation`, `requestLocation`, `requestNotifications` |
38
+ | `hs.power` | `on`, `off` |
39
+ | `hs.screen` | `main` |
40
+ | `hs.task` | `create`, `runAsync` |
41
+ | `hs.timer` | `absoluteTime`, `doAfter`, `doEvery`, `secondsSinceEpoch` |
42
+ | `hs.ui` | `alert`, `dialog`, `webview`, `window` |
43
+ | `hs.urlevent` | `openURL` |
44
+ | `hs.wifi` | `currentNetwork`, `on`, `off` |
45
+ | `HSImage`, `HSSize` globals | `fromName`, `fromSymbol` |
35
46
 
36
47
  ## Controls (`ctl`)
37
48
 
38
- | Control | Does |
39
- | ----------------------------------------- | -------------------------------------------------------------------------------------- |
40
- | `advance(seconds)` | Moves the clock, firing timers and settling promises between them |
41
- | `flush()` | Settles pending promises |
42
- | `addApp({ bundleID, name, allWindows })` | Adds a running app and returns it |
43
- | `activate(bundleID)` | Brings an app to the front and emits `didActivate`; `null` for one without a bundle ID |
44
- | `hotkeys` | Created hotkeys that have not been destroyed |
45
- | `element({ role, children, attributes })` | An accessibility element |
46
- | `window(element)` | A window whose element it is, for `addApp`'s `focusedWindow` or `mainWindow` |
47
- | `url(text)` | A URL attribute value, as `hs.ax` returns it |
48
- | `alerts`, `openedURLs` | What was shown and opened |
49
- | `killed` | Bundle IDs of killed apps |
50
- | `accessibility` | Whether Accessibility permission is granted |
49
+ | Control | Does |
50
+ |---|---|
51
+ | `advance(seconds)` | Moves the clock, firing timers and settling promises between them |
52
+ | `flush()` | Settles pending promises |
53
+ | `addApp({ bundleID, name, allWindows, focusedWindow, mainWindow })` | Adds a running app and returns it |
54
+ | `activate(bundleID)` | Brings an app to the front and emits `didActivate`; `null` for one without a bundle ID |
55
+ | `killed`, `launched`, `activations`, `raised` | Apps killed, launched and activated, and windows raised |
56
+ | `frontmostRequests` | Times Hammerspoon asked to be frontmost |
57
+ | `element({ role, children, attributes })` | An accessibility element |
58
+ | `window(element)` | A window whose element it is |
59
+ | `url(text)` | A URL attribute value, as `hs.ax` returns it |
60
+ | `hotkeys` | Created hotkeys that have not been destroyed |
61
+ | `tasks` | Started tasks: `launchPath`, `args`, `environment`, `running`, `terminated`, `inputClosed`, `finish({ stdout, exitCode, reason, error })` |
62
+ | `respondToTasks(handler)` | Answers each task as it starts with what `finish()` takes, or `undefined` to leave it running |
63
+ | `menubarItems` | Menu bar items: `item`, `icon`, `menu`, `destroyed` |
64
+ | `notifications` | `title`, `body`; `click()` for `show()` ones, `options` for `create()` ones |
65
+ | `dialogs` | `message`, `informativeText`, `buttons`, `open`, `press(label)` |
66
+ | `windows` | `rect`, `title`, `view.html`, `view.post(name, body)`, `shown`, `userClose()` |
67
+ | `alerts`, `openedURLs` | What was shown and opened |
68
+ | `files`, `dirs`, `home`, `writeFails` | The in-memory file system |
69
+ | `power(event)`, `notify(name)` | Emits an `hs.power` event or a distributed notification |
70
+ | `ssid`, `wifi(event)` | The current Wi-Fi network, and its events |
71
+ | `addAudioDevice({ name, uid, input })` | Adds an audio device (emits `dev+`) and returns it |
72
+ | `removeAudioDevice(device)` | Removes it (emits `dev-`) |
73
+ | `setDefaultAudioDevice(direction, device)` | Sets the default and emits `dOut` or `dIn` |
74
+ | `updateAudioDevice(device, changes)` | Sets `volume` or `muted` and emits the device event |
75
+ | `audioListeners()` | Number of audio listeners registered |
76
+ | `images` | Add the names `HSImage.fromName` can load |
77
+ | `accessibility`, `location`, `notificationPermission` | Whether each permission is granted |
78
+ | `locationRequests` | How often location permission was requested |
51
79
 
52
80
  ## Types
53
81
 
package/index.js CHANGED
@@ -1,39 +1,112 @@
1
1
  const { createApplication } = require("./lib/application.js");
2
+ const { createAudiodevice } = require("./lib/audiodevice.js");
2
3
  const { createAx } = require("./lib/ax.js");
4
+ const { createDialog } = require("./lib/dialog.js");
5
+ const {
6
+ createDistributedNotifications,
7
+ } = require("./lib/distributednotifications.js");
8
+ const { createFs } = require("./lib/fs.js");
3
9
  const { createHotkey } = require("./lib/hotkey.js");
10
+ const { createImage } = require("./lib/image.js");
4
11
  const { loadSpoon } = require("./lib/load.js");
12
+ const { createMenubar } = require("./lib/menubar.js");
13
+ const { createNotify } = require("./lib/notify.js");
14
+ const { createPower } = require("./lib/power.js");
15
+ const { createScreen } = require("./lib/screen.js");
5
16
  const { strict } = require("./lib/strict.js");
17
+ const { createTask } = require("./lib/task.js");
6
18
  const { createTimer } = require("./lib/timer.js");
7
19
  const { createUi } = require("./lib/ui.js");
20
+ const { createWifi } = require("./lib/wifi.js");
21
+ const { createWindow } = require("./lib/window.js");
22
+
23
+ /** Copies controls, keeping getters and setters live. */
24
+ function merge(target, ...sources) {
25
+ for (const source of sources) {
26
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
27
+ }
28
+ return target;
29
+ }
8
30
 
9
31
  /**
10
32
  * A fresh strict mock of the Hammerspoon 2 `hs` global, and the test controls.
33
+ * Also sets the HSImage and HSSize globals.
11
34
  */
12
35
  function createHs() {
13
- const timer = createTimer();
14
36
  const application = createApplication();
15
- const hotkey = createHotkey();
37
+ const audiodevice = createAudiodevice();
16
38
  const ax = createAx();
39
+ const dialog = createDialog();
40
+ const distributed = createDistributedNotifications();
41
+ const fs = createFs();
42
+ const hotkey = createHotkey();
43
+ const image = createImage();
44
+ const menubar = createMenubar();
45
+ const notify = createNotify();
46
+ const power = createPower();
47
+ const task = createTask();
48
+ const timer = createTimer();
17
49
  const ui = createUi();
18
- const ctl = {
19
- ...timer.ctl,
20
- ...application.ctl,
21
- ...hotkey.ctl,
22
- ...ax.ctl,
23
- ...ui.ctl,
24
- accessibility: true,
25
- };
50
+ const wifi = createWifi(() => ctl.ssid);
51
+ const window = createWindow();
52
+ Object.assign(globalThis, image.globals);
53
+
54
+ const ctl = merge(
55
+ {
56
+ accessibility: true,
57
+ location: true,
58
+ locationRequests: 0,
59
+ notificationPermission: true,
60
+ ssid: null,
61
+ },
62
+ ...[
63
+ application,
64
+ audiodevice,
65
+ ax,
66
+ dialog,
67
+ distributed,
68
+ fs,
69
+ hotkey,
70
+ image,
71
+ ].map((m) => m.ctl),
72
+ );
73
+ merge(
74
+ ctl,
75
+ ...[menubar, notify, power, task, timer, ui, wifi, window].map(
76
+ (m) => m.ctl,
77
+ ),
78
+ );
79
+
26
80
  const modules = {
81
+ appinfo: application.appinfo,
27
82
  application: application.module,
83
+ audiodevice: audiodevice.module,
28
84
  ax: ax.module,
85
+ distributednotifications: distributed.module,
86
+ fs: fs.module,
29
87
  hotkey: hotkey.module,
30
- permissions: { checkAccessibility: () => ctl.accessibility },
88
+ menubar: menubar.module,
89
+ notify: notify.module,
90
+ permissions: {
91
+ checkAccessibility: () => ctl.accessibility,
92
+ checkLocation: () => ctl.location,
93
+ requestLocation: async () => {
94
+ ctl.locationRequests++;
95
+ return ctl.location;
96
+ },
97
+ requestNotifications: async () => ctl.notificationPermission,
98
+ },
99
+ power: power.module,
100
+ screen: createScreen().module,
101
+ task: task.module,
31
102
  timer: timer.module,
32
- ui: ui.ui,
103
+ ui: { ...ui.ui, ...dialog.module, ...window.module },
33
104
  urlevent: ui.urlevent,
105
+ wifi: wifi.module,
34
106
  };
35
- for (const [name, module] of Object.entries(modules))
107
+ for (const [name, module] of Object.entries(modules)) {
36
108
  modules[name] = strict(`hs.${name}`, module);
109
+ }
37
110
  return { hs: strict("hs", modules), ctl };
38
111
  }
39
112
 
@@ -5,10 +5,26 @@ const { strict } = require("./strict.js");
5
5
  function createApplication() {
6
6
  const apps = new Map();
7
7
  const killed = [];
8
+ const launched = [];
9
+ const activations = [];
10
+ const ownPID = 4242;
11
+ let frontmostRequests = 0;
8
12
  const events = createEmitter();
9
13
  let frontmost = null;
10
14
 
15
+ const self = strict("HSApplication", {
16
+ setFrontmost() {
17
+ frontmostRequests++;
18
+ return true;
19
+ },
20
+ });
21
+
11
22
  const module = {
23
+ fromPID: (pid) => (pid === ownPID ? self : null),
24
+ async launchOrFocus(bundleID) {
25
+ launched.push(bundleID);
26
+ return true;
27
+ },
12
28
  matchingBundleID: (bundleID) => apps.get(bundleID) ?? null,
13
29
  frontmost: () => frontmost,
14
30
  on: events.on,
@@ -33,6 +49,10 @@ function createApplication() {
33
49
  get isActive() {
34
50
  return frontmost === app;
35
51
  },
52
+ activate(allWindows = false) {
53
+ activations.push({ bundleID, allWindows });
54
+ return true;
55
+ },
36
56
  kill() {
37
57
  killed.push(bundleID);
38
58
  apps.delete(bundleID);
@@ -49,7 +69,17 @@ function createApplication() {
49
69
  events.emit("didActivate", frontmost);
50
70
  }
51
71
 
52
- return { module, ctl: { addApp, activate, killed } };
72
+ const ctl = {
73
+ addApp,
74
+ activate,
75
+ activations,
76
+ killed,
77
+ launched,
78
+ get frontmostRequests() {
79
+ return frontmostRequests;
80
+ },
81
+ };
82
+ return { module, appinfo: { pid: ownPID }, ctl };
53
83
  }
54
84
 
55
85
  module.exports = { createApplication };
@@ -0,0 +1,118 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ const SYSTEM_EVENTS = ["dOut", "dIn", "dSErr", "dev+", "dev-"];
4
+ const DEVICE_EVENTS = ["vmout", "vmin", "mout", "min"];
5
+ const CHANGE_EVENTS = { volume: "vmout", muted: "mout" };
6
+
7
+ /** Listeners by event, as HS2's watcher emitters keep them. */
8
+ function createListeners(label, known) {
9
+ const listeners = new Set();
10
+ return {
11
+ on(event, listener) {
12
+ if (!known.includes(event))
13
+ throw new Error(`${label}.on(): unknown event '${event}'`);
14
+ listeners.add({ event, listener });
15
+ },
16
+ off(event, listener) {
17
+ for (const entry of listeners)
18
+ if (entry.event === event && entry.listener === listener)
19
+ listeners.delete(entry);
20
+ },
21
+ emit(event, value) {
22
+ for (const entry of [...listeners])
23
+ if (entry.event === event) entry.listener(value);
24
+ },
25
+ count: () => listeners.size,
26
+ };
27
+ }
28
+
29
+ function createAudiodevice() {
30
+ const devices = [];
31
+ const emitters = new Map();
32
+ const system = createListeners("hs.audiodevice", SYSTEM_EVENTS);
33
+ const defaults = { output: null, input: null };
34
+ let nextID = 1;
35
+
36
+ const module = {
37
+ allOutputDevices: () => devices.filter((d) => d.isOutput),
38
+ allInputDevices: () => devices.filter((d) => d.isInput),
39
+ defaultOutputDevice: () => defaults.output,
40
+ defaultInputDevice: () => defaults.input,
41
+ on: system.on,
42
+ off: system.off,
43
+ };
44
+
45
+ function addAudioDevice({
46
+ name,
47
+ uid = name,
48
+ input = false,
49
+ output = !input,
50
+ volume = 0.5,
51
+ muted = false,
52
+ }) {
53
+ const events = createListeners("HSAudioDevice", DEVICE_EVENTS);
54
+ const device = strict("HSAudioDevice", {
55
+ id: nextID++,
56
+ name,
57
+ uid,
58
+ isInput: input,
59
+ isOutput: output,
60
+ volume,
61
+ muted,
62
+ setDefaultOutputDevice() {
63
+ defaults.output = device;
64
+ return true;
65
+ },
66
+ setDefaultInputDevice() {
67
+ defaults.input = device;
68
+ return true;
69
+ },
70
+ on: events.on,
71
+ off: events.off,
72
+ });
73
+ emitters.set(device, events);
74
+ devices.push(device);
75
+ system.emit("dev+", device);
76
+ return device;
77
+ }
78
+
79
+ function removeAudioDevice(device) {
80
+ devices.splice(devices.indexOf(device), 1);
81
+ for (const direction of ["output", "input"])
82
+ if (defaults[direction] === device) defaults[direction] = null;
83
+ system.emit("dev-", {
84
+ id: device.id,
85
+ uid: device.uid,
86
+ name: device.name,
87
+ });
88
+ }
89
+
90
+ function setDefaultAudioDevice(direction, device) {
91
+ defaults[direction] = device;
92
+ system.emit(direction === "output" ? "dOut" : "dIn", device);
93
+ }
94
+
95
+ function updateAudioDevice(device, changes) {
96
+ for (const [key, value] of Object.entries(changes)) {
97
+ device[key] = value;
98
+ if (CHANGE_EVENTS[key])
99
+ emitters.get(device).emit(CHANGE_EVENTS[key], value);
100
+ }
101
+ }
102
+
103
+ const audioListeners = () =>
104
+ [system, ...emitters.values()].reduce((n, e) => n + e.count(), 0);
105
+
106
+ return {
107
+ module,
108
+ ctl: {
109
+ addAudioDevice,
110
+ removeAudioDevice,
111
+ setDefaultAudioDevice,
112
+ updateAudioDevice,
113
+ audioListeners,
114
+ },
115
+ };
116
+ }
117
+
118
+ module.exports = { createAudiodevice };
package/lib/ax.js CHANGED
@@ -14,9 +14,6 @@ function element({ role, children = [], attributes = {} }) {
14
14
  });
15
15
  }
16
16
 
17
- const window = (axElement) =>
18
- strict("HSWindow", { axElement: () => axElement });
19
-
20
17
  /** hs.ax returns URL attributes as an NSURL that only util.inspect() reads. */
21
18
  const url = (text) => ({
22
19
  toString: () => "[object NSURL]",
@@ -24,11 +21,22 @@ const url = (text) => ({
24
21
  });
25
22
 
26
23
  function createAx() {
24
+ const raised = [];
25
+ const window = (axElement) => {
26
+ const self = strict("HSWindow", {
27
+ axElement: () => axElement,
28
+ raise() {
29
+ raised.push(self);
30
+ return true;
31
+ },
32
+ });
33
+ return self;
34
+ };
27
35
  const module = {
28
36
  applicationElement: (app) => app.axElement(),
29
37
  windowElement: (w) => w.axElement(),
30
38
  };
31
- return { module, ctl: { element, window, url } };
39
+ return { module, ctl: { element, raised, window, url } };
32
40
  }
33
41
 
34
42
  module.exports = { createAx, element };
package/lib/dialog.js ADDED
@@ -0,0 +1,49 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ function createDialog() {
4
+ const dialogs = [];
5
+ const module = {
6
+ dialog(message) {
7
+ let onButton;
8
+ const record = {
9
+ message,
10
+ informativeText: null,
11
+ buttons: ["OK"],
12
+ style: "informational",
13
+ open: false,
14
+ press(label) {
15
+ const index = record.buttons.indexOf(label);
16
+ if (!record.open || index < 0)
17
+ throw new Error(`hs2-mock: '${label}' is not open to be pressed`);
18
+ onButton?.(index);
19
+ record.open = false;
20
+ },
21
+ };
22
+ const set = (key) => (value) => {
23
+ record[key] = value;
24
+ return dialog;
25
+ };
26
+ const dialog = strict("HSUIDialog", {
27
+ informativeText: set("informativeText"),
28
+ buttons: set("buttons"),
29
+ style: set("style"),
30
+ onButton(callback) {
31
+ onButton = callback;
32
+ return dialog;
33
+ },
34
+ show() {
35
+ record.open = true;
36
+ return dialog;
37
+ },
38
+ close() {
39
+ record.open = false;
40
+ },
41
+ });
42
+ dialogs.push(record);
43
+ return dialog;
44
+ },
45
+ };
46
+ return { module, ctl: { dialogs } };
47
+ }
48
+
49
+ module.exports = { createDialog };
@@ -0,0 +1,11 @@
1
+ const { createEmitter } = require("./emitter.js");
2
+
3
+ function createDistributedNotifications() {
4
+ const events = createEmitter();
5
+ const module = { on: events.on, off: events.off };
6
+ const notify = (name, object = null, userInfo = {}) =>
7
+ events.emit(name, object, userInfo);
8
+ return { module, ctl: { notify } };
9
+ }
10
+
11
+ module.exports = { createDistributedNotifications };
package/lib/fs.js ADDED
@@ -0,0 +1,44 @@
1
+ const { pathToFileURL } = require("node:url");
2
+
3
+ /** An in-memory hs.fs, so tests never touch real files. Paths are kept as given. */
4
+ function createFs() {
5
+ const files = new Map();
6
+ const dirs = [];
7
+ let home = "/Users/mock";
8
+ let writeFails = false;
9
+ // Accessors, so createHs() can merge these controls and writes still arrive.
10
+ const ctl = {
11
+ files,
12
+ dirs,
13
+ get home() {
14
+ return home;
15
+ },
16
+ set home(value) {
17
+ home = value;
18
+ },
19
+ get writeFails() {
20
+ return writeFails;
21
+ },
22
+ set writeFails(value) {
23
+ writeFails = value;
24
+ },
25
+ };
26
+ const module = {
27
+ homeDirectory: () => home,
28
+ exists: (path) => files.has(path) || dirs.includes(path),
29
+ read: (path) => files.get(path) ?? null,
30
+ write(path, content) {
31
+ if (writeFails) return false;
32
+ files.set(path, content);
33
+ return true;
34
+ },
35
+ mkdir(path) {
36
+ dirs.push(path);
37
+ return true;
38
+ },
39
+ urlFromPath: (path) => pathToFileURL(path).href,
40
+ };
41
+ return { module, ctl };
42
+ }
43
+
44
+ module.exports = { createFs };
package/lib/hotkey.js CHANGED
@@ -10,6 +10,7 @@ function createHotkey() {
10
10
  mods,
11
11
  key,
12
12
  onPressed,
13
+ message: null,
13
14
  enable() {
14
15
  enabled = true;
15
16
  return true;
package/lib/image.js ADDED
@@ -0,0 +1,21 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ /** The HSImage and HSSize globals. fromName() only loads names in `images`. */
4
+ function createImage() {
5
+ const images = new Set();
6
+ class HSSize {
7
+ constructor(w, h) {
8
+ this.w = w;
9
+ this.h = h;
10
+ }
11
+ }
12
+ const image = (name) =>
13
+ strict("HSImage", { name, size: null, template: false });
14
+ const HSImage = strict("HSImage", {
15
+ fromName: (name) => (images.has(name) ? image(name) : null),
16
+ fromSymbol: image,
17
+ });
18
+ return { globals: { HSImage, HSSize }, ctl: { images } };
19
+ }
20
+
21
+ module.exports = { createImage };
package/lib/menubar.js ADDED
@@ -0,0 +1,27 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ function createMenubar() {
4
+ const menubarItems = [];
5
+ const module = {
6
+ create() {
7
+ const record = { icon: null, menu: null, destroyed: false };
8
+ record.item = strict("HSMenuBarItem", {
9
+ title: null,
10
+ setIcon(icon) {
11
+ record.icon = icon;
12
+ },
13
+ setMenu(menu) {
14
+ record.menu = menu;
15
+ },
16
+ destroy() {
17
+ record.destroyed = true;
18
+ },
19
+ });
20
+ menubarItems.push(record);
21
+ return record.item;
22
+ },
23
+ };
24
+ return { module, ctl: { menubarItems } };
25
+ }
26
+
27
+ module.exports = { createMenubar };
package/lib/notify.js ADDED
@@ -0,0 +1,39 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ /**
4
+ * show() notifications can be clicked. create() ones cannot: in HS2
5
+ * 1.0.0-beta.4 their callbacks never fire:
6
+ * https://github.com/Hammerspoon/Hammerspoon2/issues/515
7
+ */
8
+ function createNotify() {
9
+ const notifications = [];
10
+ const module = {
11
+ show(title, body, callback) {
12
+ const notificationId = `mock-${notifications.length + 1}`;
13
+ notifications.push({
14
+ title,
15
+ body,
16
+ click() {
17
+ callback({
18
+ actionIdentifier: "DEFAULT",
19
+ notificationId,
20
+ userInfo: {},
21
+ });
22
+ },
23
+ });
24
+ },
25
+ create(options) {
26
+ const notification = strict("HSNotification", {
27
+ send() {
28
+ const { title, body } = options;
29
+ notifications.push({ title, body, options });
30
+ return notification;
31
+ },
32
+ });
33
+ return notification;
34
+ },
35
+ };
36
+ return { module, ctl: { notifications } };
37
+ }
38
+
39
+ module.exports = { createNotify };
package/lib/power.js ADDED
@@ -0,0 +1,33 @@
1
+ const { createEmitter } = require("./emitter.js");
2
+
3
+ const EVENTS = new Set([
4
+ "screensDidSleep",
5
+ "screensDidWake",
6
+ "screensDidLock",
7
+ "screensDidUnlock",
8
+ "screensaverDidStart",
9
+ "screensaverDidStop",
10
+ "screensaverWillStop",
11
+ "systemWillSleep",
12
+ "systemDidWake",
13
+ "systemWillPowerOff",
14
+ "sessionDidBecomeActive",
15
+ "sessionDidResignActive",
16
+ "change",
17
+ ]);
18
+
19
+ function createPower() {
20
+ const events = createEmitter();
21
+ const known = (event) => {
22
+ if (!EVENTS.has(event))
23
+ throw new Error(`hs2-mock: unknown hs.power event '${event}'`);
24
+ return event;
25
+ };
26
+ const module = {
27
+ on: (event, listener) => events.on(known(event), listener),
28
+ off: events.off,
29
+ };
30
+ return { module, ctl: { power: (event) => events.emit(known(event)) } };
31
+ }
32
+
33
+ module.exports = { createPower };
package/lib/screen.js ADDED
@@ -0,0 +1,10 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ function createScreen() {
4
+ const main = strict("HSScreen", {
5
+ frame: { x: 0, y: 25, w: 1440, h: 875 },
6
+ });
7
+ return { module: { main: () => main } };
8
+ }
9
+
10
+ module.exports = { createScreen };
package/lib/task.js ADDED
@@ -0,0 +1,91 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ /**
4
+ * Nothing runs: a started task is recorded in `ctl.tasks`, and the test ends it
5
+ * with `finish()`, or answers each one with `ctl.respondToTasks()`.
6
+ */
7
+ function createTask() {
8
+ const tasks = [];
9
+ let respond = () => undefined;
10
+
11
+ function record(launchPath, args, environment, onFinish) {
12
+ let running = true;
13
+ const entry = {
14
+ launchPath,
15
+ args,
16
+ environment,
17
+ inputClosed: false,
18
+ terminated: false,
19
+ get running() {
20
+ return running;
21
+ },
22
+ finish({ stdout = [], exitCode = 0, reason = "exit", error } = {}) {
23
+ if (!running) return;
24
+ running = false;
25
+ onFinish([stdout].flat().filter(Boolean), exitCode, reason, error);
26
+ },
27
+ };
28
+ return entry;
29
+ }
30
+
31
+ function launch(entry) {
32
+ tasks.push(entry);
33
+ const result = respond(entry);
34
+ if (result) queueMicrotask(() => entry.finish(result));
35
+ }
36
+
37
+ const module = {
38
+ create(launchPath, args, onTermination, environment, onOutput) {
39
+ let entry = null;
40
+ const task = strict("HSTask", {
41
+ get isRunning() {
42
+ return entry?.running ?? false;
43
+ },
44
+ start() {
45
+ if (entry) return task;
46
+ entry = record(
47
+ launchPath,
48
+ args,
49
+ environment,
50
+ (chunks, code, reason, error) => {
51
+ for (const chunk of chunks) onOutput?.("stdout", chunk);
52
+ const failure = error === undefined ? [] : [error];
53
+ onTermination?.(code, reason, ...failure);
54
+ },
55
+ );
56
+ entry.task = task;
57
+ launch(entry);
58
+ return task;
59
+ },
60
+ terminate() {
61
+ if (entry) entry.terminated = true;
62
+ },
63
+ closeInput() {
64
+ if (entry) entry.inputClosed = true;
65
+ },
66
+ });
67
+ return task;
68
+ },
69
+ runAsync(launchPath, args) {
70
+ return new Promise((resolve, reject) => {
71
+ launch(
72
+ record(launchPath, args, null, (chunks, exitCode) => {
73
+ const stdout = chunks.join("");
74
+ if (exitCode === 0) resolve({ exitCode, stdout, stderr: "" });
75
+ else {
76
+ const error = new Error(`${launchPath} exited with ${exitCode}`);
77
+ reject(Object.assign(error, { exitCode }));
78
+ }
79
+ }),
80
+ );
81
+ });
82
+ },
83
+ };
84
+
85
+ const respondToTasks = (handler) => {
86
+ respond = handler;
87
+ };
88
+ return { module, ctl: { tasks, respondToTasks } };
89
+ }
90
+
91
+ module.exports = { createTask };
package/lib/timer.js CHANGED
@@ -33,6 +33,7 @@ function createTimer() {
33
33
 
34
34
  const module = {
35
35
  secondsSinceEpoch: () => now,
36
+ absoluteTime: () => Math.round((now - EPOCH) * 1e9),
36
37
  doAfter: (seconds, callback) => schedule(seconds, callback, false),
37
38
  doEvery: (interval, callback) => schedule(interval, callback, true),
38
39
  };
package/lib/wifi.js ADDED
@@ -0,0 +1,31 @@
1
+ const { createEmitter } = require("./emitter.js");
2
+
3
+ const EVENTS = new Set([
4
+ "powerChange",
5
+ "ssidChange",
6
+ "bssidChange",
7
+ "countryCodeChange",
8
+ "linkChange",
9
+ "linkQualityChange",
10
+ "modeChange",
11
+ "scanCacheUpdated",
12
+ ]);
13
+
14
+ /** @param {() => string | null} ssid the current network */
15
+ function createWifi(ssid) {
16
+ const events = createEmitter();
17
+ const known = (event) => {
18
+ if (!EVENTS.has(event))
19
+ throw new Error(`hs2-mock: unknown hs.wifi event '${event}'`);
20
+ return event;
21
+ };
22
+ const module = {
23
+ currentNetwork: () => ssid(),
24
+ on: (event, listener) => events.on(known(event), listener),
25
+ off: events.off,
26
+ };
27
+ const wifi = (event) => events.emit(known(event), { interface: "en0" });
28
+ return { module, ctl: { wifi } };
29
+ }
30
+
31
+ module.exports = { createWifi };
package/lib/window.js ADDED
@@ -0,0 +1,74 @@
1
+ const { strict } = require("./strict.js");
2
+
3
+ /** hs.ui.window() and hs.ui.webview(), without rendering anything. */
4
+ function createWindow() {
5
+ const windows = [];
6
+ const views = new Map();
7
+
8
+ function webview() {
9
+ const handlers = new Map();
10
+ const state = {
11
+ html: null,
12
+ post: (name, body) => handlers.get(name)(body),
13
+ };
14
+ const view = strict("UIWebView", {
15
+ loadHTML(html) {
16
+ state.html = html;
17
+ return view;
18
+ },
19
+ onMessage(name, callback) {
20
+ handlers.set(name, callback);
21
+ return view;
22
+ },
23
+ });
24
+ views.set(view, state);
25
+ return view;
26
+ }
27
+
28
+ function window(rect) {
29
+ let onHide = null;
30
+ const state = {
31
+ rect,
32
+ title: "",
33
+ view: null,
34
+ shown: false,
35
+ shows: 0,
36
+ destroyed: false,
37
+ userClose() {
38
+ state.shown = false;
39
+ onHide?.();
40
+ },
41
+ };
42
+ const chain = (apply) => (value) => {
43
+ apply(value);
44
+ return object;
45
+ };
46
+ const object = strict("HSUIWindow", {
47
+ windowTitle: chain((title) => {
48
+ state.title = title;
49
+ }),
50
+ allowResize: chain(() => {}),
51
+ miniaturizable: chain(() => {}),
52
+ webview: chain((view) => {
53
+ state.view = views.get(view);
54
+ }),
55
+ onHide: chain((callback) => {
56
+ onHide = callback;
57
+ }),
58
+ show: chain(() => {
59
+ state.shown = true;
60
+ state.shows++;
61
+ }),
62
+ destroy() {
63
+ state.shown = false;
64
+ state.destroyed = true;
65
+ },
66
+ });
67
+ windows.push(state);
68
+ return object;
69
+ }
70
+
71
+ return { module: { window, webview }, ctl: { windows } };
72
+ }
73
+
74
+ module.exports = { createWindow };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hs2-mock",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Strict mock of the Hammerspoon 2 hs global for testing Spoons under node:test",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -18,5 +18,14 @@
18
18
  },
19
19
  "engines": {
20
20
  "node": ">=22"
21
- }
21
+ },
22
+ "keywords": [
23
+ "hammerspoon",
24
+ "hammerspoon2",
25
+ "spoon",
26
+ "macos",
27
+ "mock",
28
+ "testing",
29
+ "node-test"
30
+ ]
22
31
  }