active-window-sessions 0.0.0-stage → 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/CHANGELOG.md +10 -0
- package/LICENSE +21 -0
- package/README.md +215 -2
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.js +29 -0
- package/dist/engine.d.ts +31 -0
- package/dist/engine.js +170 -0
- package/dist/host.d.ts +11 -0
- package/dist/host.js +22 -0
- package/dist/ignore.d.ts +8 -0
- package/dist/ignore.js +43 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +7 -0
- package/dist/macos.d.ts +118 -0
- package/dist/macos.js +218 -0
- package/dist/platform.d.ts +25 -0
- package/dist/platform.js +53 -0
- package/dist/sessionize.d.ts +6 -0
- package/dist/sessionize.js +15 -0
- package/dist/tracker.d.ts +8 -0
- package/dist/tracker.js +130 -0
- package/dist/types.d.ts +132 -0
- package/dist/types.js +1 -0
- package/dist/windows.d.ts +29 -0
- package/dist/windows.js +99 -0
- package/package.json +75 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
## 0.1.0
|
|
2
|
+
|
|
3
|
+
Initial release
|
|
4
|
+
|
|
5
|
+
- `sessionize` turns timestamped samples into segments: merges short gaps, drops blips, cuts at the last input when idle starts, ends stale windows, and skips system UI.
|
|
6
|
+
- `createTracker` polls any `sample` function on an interval with the same rules, with start, stop and flush, an injectable clock and error reporting.
|
|
7
|
+
- `aggregate` totals segments per app or per website host, clipped to a `from`/`to` range.
|
|
8
|
+
- `getWindowsSampler` reads the active window through get-windows, which is an optional peer dependency loaded on first use.
|
|
9
|
+
- `active-window-sessions/macos` has injectable helpers for Accessibility, Screen Recording and per-browser Automation, with probe caching and a relaunch-needed flag.
|
|
10
|
+
- Only the host of a browser URL is stored by default; window titles are never stored.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Saimul Islam
|
|
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
CHANGED
|
@@ -1,3 +1,216 @@
|
|
|
1
|
-
#
|
|
1
|
+
# active-window-sessions
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Turn active-window polling into clean time segments per app and per website.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/active-window-sessions)
|
|
6
|
+
[](https://www.npmjs.com/package/active-window-sessions)
|
|
7
|
+
[](https://www.npmjs.com/package/active-window-sessions)
|
|
8
|
+
|
|
9
|
+
Started as the app-tracking core of the [Staffic](https://staffic.io) desktop app.
|
|
10
|
+
|
|
11
|
+
[get-windows](https://github.com/sindresorhus/get-windows) and [active-win](https://github.com/sindresorhus/active-win) tell you which window is in front at one moment. Turning a stream of those readings into reliable time segments is left to you: gaps when the window flickers, blips from a notification, time the user was away, and system UI that is not an app. `active-window-sessions` does that part. It merges short gaps, drops blips, cuts a segment at the last input when the user goes idle, ignores system UI, and adds up the totals per app and per website.
|
|
12
|
+
|
|
13
|
+
The core has no dependencies and takes any `sample` function, so it works with get-windows or anything else that can name the active window.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install active-window-sessions get-windows
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
get-windows is an optional peer dependency. The core and the macOS helpers import without it; only `getWindowsSampler()` needs it, and it loads it on first use. Node 20 or later, ESM only.
|
|
22
|
+
|
|
23
|
+
## Example
|
|
24
|
+
|
|
25
|
+
An Electron main process, using Electron's idle timer:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { app, powerMonitor } from 'electron';
|
|
29
|
+
import { aggregate, createTracker, getWindowsSampler } from 'active-window-sessions';
|
|
30
|
+
import type { Segment } from 'active-window-sessions';
|
|
31
|
+
|
|
32
|
+
const segments: Segment[] = [];
|
|
33
|
+
|
|
34
|
+
const tracker = createTracker({
|
|
35
|
+
sample: getWindowsSampler(),
|
|
36
|
+
getIdleSeconds: () => powerMonitor.getSystemIdleTime(),
|
|
37
|
+
onSegments: (batch) => segments.push(...batch),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
app.whenReady().then(() => tracker.start());
|
|
41
|
+
powerMonitor.on('suspend', () => tracker.stop());
|
|
42
|
+
powerMonitor.on('resume', () => tracker.start());
|
|
43
|
+
app.on('before-quit', () => tracker.stop());
|
|
44
|
+
|
|
45
|
+
// Later, for example for today:
|
|
46
|
+
const startOfDay = new Date().setHours(0, 0, 0, 0);
|
|
47
|
+
console.log(aggregate(segments, { by: 'app', from: startOfDay }));
|
|
48
|
+
console.log(aggregate(segments, { by: 'host', from: startOfDay }));
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Plain Node works the same way. Node has no idle-time API, so leave out `getIdleSeconds` or supply your own.
|
|
52
|
+
|
|
53
|
+
`sessionize` runs the same rules over samples you already have. This is real output from the built package:
|
|
54
|
+
|
|
55
|
+
```js
|
|
56
|
+
import { aggregate, sessionize } from 'active-window-sessions';
|
|
57
|
+
|
|
58
|
+
const t0 = Date.parse('2026-03-02T09:00:00Z');
|
|
59
|
+
const at = (seconds, window, idleSeconds) => ({ at: t0 + seconds * 1000, window, idleSeconds });
|
|
60
|
+
|
|
61
|
+
const code = { app: 'Code', appId: 'com.microsoft.VSCode' };
|
|
62
|
+
const chrome = (url) => ({ app: 'Google Chrome', appId: 'com.google.Chrome', url });
|
|
63
|
+
const alert = { app: 'UserNotificationCenter', appId: 'com.apple.UserNotificationCenter' };
|
|
64
|
+
|
|
65
|
+
const samples = [
|
|
66
|
+
at(0, code),
|
|
67
|
+
at(2, code),
|
|
68
|
+
at(4, code),
|
|
69
|
+
at(6, code),
|
|
70
|
+
at(8, chrome('https://github.com/acme/app/pulls')),
|
|
71
|
+
at(10, chrome('https://github.com/acme/app/pulls')),
|
|
72
|
+
at(12, alert), // a system alert flashes in front: ignored
|
|
73
|
+
at(14, chrome('https://github.com/acme/app/issues')),
|
|
74
|
+
at(15, code), // half a second back in the editor: a blip
|
|
75
|
+
at(15.5, chrome('https://github.com/acme/app/issues')),
|
|
76
|
+
at(19, chrome('https://github.com/acme/app/issues'), 0),
|
|
77
|
+
at(70, chrome('https://github.com/acme/app/issues'), 51), // idle for 51 s: the last input was at 19 s
|
|
78
|
+
];
|
|
79
|
+
|
|
80
|
+
const segments = sessionize(samples);
|
|
81
|
+
console.log(segments);
|
|
82
|
+
console.log(aggregate(segments, { by: 'host' }));
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
```text
|
|
86
|
+
console.log(segments)
|
|
87
|
+
[
|
|
88
|
+
{ app: 'Code', appId: 'com.microsoft.VSCode', startMs: 1772442000000, endMs: 1772442008000 },
|
|
89
|
+
{
|
|
90
|
+
app: 'Google Chrome',
|
|
91
|
+
appId: 'com.google.Chrome',
|
|
92
|
+
host: 'github.com',
|
|
93
|
+
startMs: 1772442008000,
|
|
94
|
+
endMs: 1772442019000
|
|
95
|
+
}
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
console.log(aggregate(segments, { by: 'host' }))
|
|
99
|
+
[ { key: 'github.com', name: 'github.com', durationMs: 11000, segmentCount: 1 } ]
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The alert and the half-second blip did not break the browser segment, the idle period was cut at the last input, and the two GitHub pages became one `github.com` entry. The page paths are gone.
|
|
103
|
+
|
|
104
|
+
## API
|
|
105
|
+
|
|
106
|
+
All of these are named exports of `active-window-sessions`.
|
|
107
|
+
|
|
108
|
+
- `sessionize(samples, options?)` turns `Sample[]` (`{ at, window, idleSeconds }`) into `Segment[]`. Samples are sorted by time first. `options.endAt` ends the last segment at a given time instead of at the last sample.
|
|
109
|
+
- `createTracker(options)` returns a tracker with `start()`, `stop(endMs?)`, `flush({ cut? })` and `isRunning()`. It polls `sample`, and delivers finished segments to `onSegments`, oldest first.
|
|
110
|
+
- `stop()` delivers every pending segment and ends the open one at `endMs` (default now, never later).
|
|
111
|
+
- `flush()` delivers segments held back for merging. `flush({ cut: true })` also ends the open segment now and continues it from that moment, which is useful for fixed reporting windows.
|
|
112
|
+
- Errors from `sample`, `getIdleSeconds` and `onSegments` go to `onError` and never stop polling.
|
|
113
|
+
- `aggregate(segments, { by, from?, to? })` returns `UsageTotal[]` (`{ key, name, durationMs, segmentCount }`), largest first. `by` is `'app'` (grouped by `appId`) or `'host'` (segments without a host are skipped). `from` and `to` are millisecond timestamps; only the part of a segment inside the range counts.
|
|
114
|
+
- `getWindowsSampler(options?)` returns a `sample` function backed by get-windows. Options: `urls`, `accessibilityPermission`, `screenRecordingPermission` (a boolean or a function read before each call), `loadModule`, `platform`.
|
|
115
|
+
- `toWindowInfo(result)` converts a get-windows or active-win result into a `WindowInfo`. Use it if you call get-windows yourself.
|
|
116
|
+
- `hostFromUrl(url)` returns the lower-case host of an http(s) URL, or `null`.
|
|
117
|
+
- `DEFAULT_IGNORE` is the default ignore list (macOS system UI). Extend it with `ignore: [...DEFAULT_IGNORE, 'My Overlay']`.
|
|
118
|
+
- `checkPlatformSupport(options?)` reports whether active-window reading can work: Linux needs X11 with `xprop` and `xwininfo`.
|
|
119
|
+
- `defaultIdleThresholdSeconds(options?)` and `isRemoteSession(options?)` suggest an `idleAfterSeconds` (50, or 30 on a remote session).
|
|
120
|
+
- `systemClock` is the default `Clock`. Pass your own `clock` to the tracker to control time in tests.
|
|
121
|
+
|
|
122
|
+
Types are exported for every option and result: `WindowInfo`, `Sample`, `Segment`, `SegmentationOptions`, `SessionizeOptions`, `TrackerOptions`, `Tracker`, `FlushOptions`, `AggregateOptions`, `UsageTotal`, `IgnoreRule`, `UrlMode`, `Clock`, `WindowSampler`, `IdleSource`, `WindowsSamplerOptions`, `PlatformOptions`, `PlatformSupport`.
|
|
123
|
+
|
|
124
|
+
### Options shared by `sessionize` and `createTracker`
|
|
125
|
+
|
|
126
|
+
| Option | Default | Meaning |
|
|
127
|
+
| ------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
128
|
+
| `mergeGapMs` | `2000` | Segments of the same target closer together than this become one. |
|
|
129
|
+
| `minSegmentMs` | `1000` | Shorter segments are dropped. |
|
|
130
|
+
| `staleAfterMs` | `10000` | An open segment ends at its last sighting once no window has been seen for this long. |
|
|
131
|
+
| `maxSampleGapMs` | `60000` | A longer silence between samples (sleep, a frozen process) ends the open segment. |
|
|
132
|
+
| `idleAfterSeconds` | `50` | At this much idle time the open segment is cut at the last input. |
|
|
133
|
+
| `ignore` | system UI | Rules for windows that are not apps. A string matches `appId` or `app` exactly, a `RegExp` is tested against both, a function gets the window. Replaces the default list. |
|
|
134
|
+
| `urls` | `'host'` | `'host'` keeps the host, `'full'` keeps the URL without its fragment, `'none'` keeps neither. |
|
|
135
|
+
|
|
136
|
+
Tracker only: `sample` (required), `onSegments` (required), `getIdleSeconds`, `intervalMs` (`2000`), `sampleTimeoutMs` (`4000`; a slower sample counts as no window), `onError`, `clock`. The tracker's default `maxSampleGapMs` is the larger of `60000` and three intervals.
|
|
137
|
+
|
|
138
|
+
## How segmenting works
|
|
139
|
+
|
|
140
|
+
Each sample is a window plus, optionally, how long the user has been idle. The rules run in this order.
|
|
141
|
+
|
|
142
|
+
1. **Sample gaps.** If more than `maxSampleGapMs` passed since the last sample, the open segment ends at the last sighting. Without this, a laptop that sleeps for an hour would log an hour in the app that was in front.
|
|
143
|
+
2. **Idle.** When idle time reaches `idleAfterSeconds`, the open segment ends at the last input (`now - idle`), not when idle was noticed. No segment opens while the user is idle.
|
|
144
|
+
3. **Ignored and missing windows.** System UI and missing readings do not end a segment right away. The segment stays open and ends at its last sighting once nothing has been seen for `staleAfterMs`. A notification that flashes up in front of your editor does not split it.
|
|
145
|
+
4. **Switching.** When the target changes (a different app, or a different host in the same browser), the open segment ends at the first sample of the new target.
|
|
146
|
+
5. **Merging.** A closed segment is held back for `mergeGapMs`. If the same target comes back inside that gap, the two become one segment that covers the gap.
|
|
147
|
+
6. **Blips.** A segment shorter than `minSegmentMs` is dropped. A blip between two stretches of the same target does not stop them merging, as long as the whole gap is shorter than `mergeGapMs`.
|
|
148
|
+
|
|
149
|
+
The target is the app (`appId`) plus, for browsers, the host. Pages on the same host share a target. With `urls: 'full'` each page is its own target.
|
|
150
|
+
|
|
151
|
+
## macOS permissions
|
|
152
|
+
|
|
153
|
+
`active-window-sessions/macos` has helpers for the three macOS permissions that window tracking runs into: Accessibility, Screen Recording, and Automation (Apple Events) per browser. They take Electron's `systemPreferences` and a command runner as arguments, so nothing runs until you call it and you can test with fakes.
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import { app, desktopCapturer, shell, systemPreferences } from 'electron';
|
|
157
|
+
import { getWindowsSampler } from 'active-window-sessions';
|
|
158
|
+
import { createMacPermissions } from 'active-window-sessions/macos';
|
|
159
|
+
|
|
160
|
+
// Create it once the app is ready: the Screen Recording state at that moment
|
|
161
|
+
// decides whether a later grant needs a relaunch.
|
|
162
|
+
const permissions = createMacPermissions({
|
|
163
|
+
systemPreferences,
|
|
164
|
+
openExternal: (url) => shell.openExternal(url),
|
|
165
|
+
requestScreenRecording: () =>
|
|
166
|
+
desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width: 1, height: 1 } }),
|
|
167
|
+
relaunch: () => {
|
|
168
|
+
app.relaunch();
|
|
169
|
+
app.quit();
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
// Ask get-windows only for what is granted, so it returns what it can instead of failing.
|
|
174
|
+
const sample = getWindowsSampler({
|
|
175
|
+
accessibilityPermission: () => permissions.accessibilityState() === 'granted',
|
|
176
|
+
screenRecordingPermission: () => permissions.screenState() === 'granted',
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
const view = await permissions.getView(); // for a permissions screen
|
|
180
|
+
// { supported: true, permissions: { accessibility, screen, automation: { [bundleId]: state } }, browsers, needsRelaunch }
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
- `accessibilityState()` and `screenState()` read the state without prompting.
|
|
184
|
+
- `getPermissions({ probe?, fresh? })` returns all states. Automation is probed with `osascript` through your command runner, once per browser, and the answer is cached for `automationCacheMs` (10 s) so a 2-second re-check does not repeat the macOS prompt. `fresh: true` probes again; `probe: false` reads cached answers only. A browser that is not running keeps its last real answer, because the probe never launches it.
|
|
185
|
+
- `getView()` adds the browser list and `needsRelaunch`: macOS applies a Screen Recording grant only after a restart, so it is `true` once Screen Recording was granted or requested after the app launched without it.
|
|
186
|
+
- `request(kind, bundleId?)` shows the prompt where macOS has one (`'accessibility'`, `'screen'`, or `'automation'` for one browser). A refusal can only be undone in System Settings: `openSettings(kind)` opens the right pane through your `openExternal`.
|
|
187
|
+
- `runCommand` defaults to `execFile`. Pass your own `(command, args, { timeoutMs }) => Promise<{ stdout, stderr, exitCode }>` to change that or to test.
|
|
188
|
+
- The browser list comes from `MAC_BROWSERS` filtered by installed apps. Pass `browsers` to set it yourself.
|
|
189
|
+
|
|
190
|
+
Off macOS these helpers do nothing: `getPermissions()` returns `null` and the state functions return `'granted'`.
|
|
191
|
+
|
|
192
|
+
## Privacy
|
|
193
|
+
|
|
194
|
+
This library reads which app and, for browsers, which site is in front of the user, and records when. Tell the people you track what you track.
|
|
195
|
+
|
|
196
|
+
- A segment holds the app name, an app identifier, the host of a browser URL (for example `github.com`), and start and end times. Paths, query strings and fragments are dropped before anything is stored. `urls: 'full'` keeps the path and query; `urls: 'none'` keeps no URL data at all.
|
|
197
|
+
- Window titles are read but never stored. They are only passed to your own `ignore` functions.
|
|
198
|
+
- It never captures screen contents. macOS asks for Screen Recording because get-windows needs it to read other apps' window titles.
|
|
199
|
+
- Nothing leaves the process unless your `onSegments` sends it. The library makes no network requests, writes no files and has no telemetry.
|
|
200
|
+
|
|
201
|
+
## Limits
|
|
202
|
+
|
|
203
|
+
- It is polling. Segment edges are only as accurate as `intervalMs` (2 s by default), and a window that comes and goes between two polls is not seen.
|
|
204
|
+
- Only the front window counts. Background tabs, a second monitor, and audio or meeting activity are not detected.
|
|
205
|
+
- Browser URLs come from get-windows, which reads them on macOS only, for the browsers it supports, and only with Accessibility and per-browser Automation granted. Everywhere else a browser is just an app with no host.
|
|
206
|
+
- Linux works on X11 with `xprop` and `xwininfo` installed. Wayland has no active-window API.
|
|
207
|
+
- Hosts are lower-cased but not otherwise normalised: `www.example.com` and `example.com` are different hosts.
|
|
208
|
+
- Idle time comes from the function you pass. Without `getIdleSeconds`, a user who walks away is counted as active until the window changes or goes stale.
|
|
209
|
+
- The default ignore list covers macOS system UI only. Add rules for other platforms' overlays.
|
|
210
|
+
- `aggregate` assumes segments do not overlap. Segments from one tracker never do; if you merge several sources, deduplicate first.
|
|
211
|
+
- get-windows is never called by this package's tests. The adapter and the macOS helpers are tested against fakes shaped like their real inputs, so check them on a real machine before you rely on them.
|
|
212
|
+
- get-windows is loaded with a dynamic `import()` whose name is a variable. If you bundle your app, mark `get-windows` as external.
|
|
213
|
+
|
|
214
|
+
## License
|
|
215
|
+
|
|
216
|
+
MIT © Saimul Islam
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { AggregateOptions, Segment, UsageTotal } from './types.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Adds up segment time per app or per website host, largest first. With `from` and `to`, only the
|
|
4
|
+
* part of each segment inside that range counts. Segments are expected not to overlap.
|
|
5
|
+
*/
|
|
6
|
+
export declare function aggregate(segments: readonly Segment[], options: AggregateOptions): UsageTotal[];
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adds up segment time per app or per website host, largest first. With `from` and `to`, only the
|
|
3
|
+
* part of each segment inside that range counts. Segments are expected not to overlap.
|
|
4
|
+
*/
|
|
5
|
+
export function aggregate(segments, options) {
|
|
6
|
+
if (options.by !== 'app' && options.by !== 'host')
|
|
7
|
+
throw new RangeError("by must be 'app' or 'host'");
|
|
8
|
+
const from = options.from ?? -Infinity;
|
|
9
|
+
const to = options.to ?? Infinity;
|
|
10
|
+
const totals = new Map();
|
|
11
|
+
for (const segment of segments) {
|
|
12
|
+
const key = options.by === 'app' ? segment.appId : segment.host;
|
|
13
|
+
if (!key)
|
|
14
|
+
continue;
|
|
15
|
+
const durationMs = Math.min(segment.endMs, to) - Math.max(segment.startMs, from);
|
|
16
|
+
if (!(durationMs > 0))
|
|
17
|
+
continue;
|
|
18
|
+
const total = totals.get(key) ?? {
|
|
19
|
+
key,
|
|
20
|
+
name: options.by === 'app' ? segment.app : key,
|
|
21
|
+
durationMs: 0,
|
|
22
|
+
segmentCount: 0,
|
|
23
|
+
};
|
|
24
|
+
total.durationMs += durationMs;
|
|
25
|
+
total.segmentCount += 1;
|
|
26
|
+
totals.set(key, total);
|
|
27
|
+
}
|
|
28
|
+
return [...totals.values()].sort((a, b) => b.durationMs - a.durationMs || a.key.localeCompare(b.key));
|
|
29
|
+
}
|
package/dist/engine.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Segment, SegmentationOptions, UrlMode, WindowInfo } from './types.ts';
|
|
2
|
+
/** Segmentation options with every default filled in. */
|
|
3
|
+
export interface ResolvedSegmentation {
|
|
4
|
+
mergeGapMs: number;
|
|
5
|
+
minSegmentMs: number;
|
|
6
|
+
staleAfterMs: number;
|
|
7
|
+
maxSampleGapMs: number;
|
|
8
|
+
idleAfterSeconds: number;
|
|
9
|
+
urls: UrlMode;
|
|
10
|
+
isIgnored: (window: WindowInfo) => boolean;
|
|
11
|
+
}
|
|
12
|
+
/** Applies defaults and validates segmentation options. */
|
|
13
|
+
export declare function resolveSegmentation(options?: SegmentationOptions): ResolvedSegmentation;
|
|
14
|
+
/**
|
|
15
|
+
* The state machine behind `sessionize` and `createTracker`. Feed it samples in time order with
|
|
16
|
+
* `push`, collect finished segments with `drain`, and end it with `finish`.
|
|
17
|
+
*/
|
|
18
|
+
export declare class SegmentBuilder {
|
|
19
|
+
#private;
|
|
20
|
+
constructor(options: ResolvedSegmentation);
|
|
21
|
+
/** Processes one sample taken at `at`. */
|
|
22
|
+
push(at: number, window: WindowInfo | null, idleSeconds: number | null): void;
|
|
23
|
+
/** Delivers the held segment and, with `cut`, the open one, which then continues from `now`. */
|
|
24
|
+
flush(now: number, cut: boolean): Segment[];
|
|
25
|
+
/** Ends everything at `endMs`, delivers all segments and resets the builder. */
|
|
26
|
+
finish(endMs: number): Segment[];
|
|
27
|
+
/** Returns the segments finished since the last call. */
|
|
28
|
+
drain(): Segment[];
|
|
29
|
+
/** Forgets all state without delivering anything. */
|
|
30
|
+
reset(): void;
|
|
31
|
+
}
|
package/dist/engine.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { parseHttpUrl } from "./host.js";
|
|
2
|
+
import { compileIgnore, DEFAULT_IGNORE } from "./ignore.js";
|
|
3
|
+
function nonNegative(name, value) {
|
|
4
|
+
if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {
|
|
5
|
+
throw new RangeError(`${name} must be a number of at least 0`);
|
|
6
|
+
}
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
/** Applies defaults and validates segmentation options. */
|
|
10
|
+
export function resolveSegmentation(options = {}) {
|
|
11
|
+
const urls = options.urls ?? 'host';
|
|
12
|
+
if (urls !== 'host' && urls !== 'full' && urls !== 'none') {
|
|
13
|
+
throw new RangeError("urls must be 'host', 'full' or 'none'");
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
mergeGapMs: nonNegative('mergeGapMs', options.mergeGapMs ?? 2000),
|
|
17
|
+
minSegmentMs: nonNegative('minSegmentMs', options.minSegmentMs ?? 1000),
|
|
18
|
+
staleAfterMs: nonNegative('staleAfterMs', options.staleAfterMs ?? 10_000),
|
|
19
|
+
maxSampleGapMs: nonNegative('maxSampleGapMs', options.maxSampleGapMs ?? 60_000),
|
|
20
|
+
idleAfterSeconds: nonNegative('idleAfterSeconds', options.idleAfterSeconds ?? 50),
|
|
21
|
+
urls,
|
|
22
|
+
isIgnored: compileIgnore(options.ignore ?? DEFAULT_IGNORE),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The state machine behind `sessionize` and `createTracker`. Feed it samples in time order with
|
|
27
|
+
* `push`, collect finished segments with `drain`, and end it with `finish`.
|
|
28
|
+
*/
|
|
29
|
+
export class SegmentBuilder {
|
|
30
|
+
#options;
|
|
31
|
+
#current = null;
|
|
32
|
+
/** Last closed segment, held back so a same-target gap shorter than `mergeGapMs` can merge into it. */
|
|
33
|
+
#held = null;
|
|
34
|
+
#ready = [];
|
|
35
|
+
constructor(options) {
|
|
36
|
+
this.#options = options;
|
|
37
|
+
}
|
|
38
|
+
/** Processes one sample taken at `at`. */
|
|
39
|
+
push(at, window, idleSeconds) {
|
|
40
|
+
const options = this.#options;
|
|
41
|
+
const open = this.#current;
|
|
42
|
+
if (open && at - open.seenMs > options.maxSampleGapMs)
|
|
43
|
+
this.#close(open.seenMs);
|
|
44
|
+
this.#release(at);
|
|
45
|
+
if (idleSeconds != null && Number.isFinite(idleSeconds) && idleSeconds >= options.idleAfterSeconds) {
|
|
46
|
+
// Idle: the segment ends at the last input, not at the moment idle was noticed.
|
|
47
|
+
if (this.#current)
|
|
48
|
+
this.#close(Math.max(this.#current.startMs, at - idleSeconds * 1000));
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const target = window ? this.#targetFor(window) : null;
|
|
52
|
+
if (!target) {
|
|
53
|
+
// Nothing usable (no window, or system UI): keep the segment open until it goes stale.
|
|
54
|
+
if (this.#current && at - this.#current.seenMs > options.staleAfterMs)
|
|
55
|
+
this.#close(this.#current.seenMs);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (this.#current && this.#current.key === target.key) {
|
|
59
|
+
this.#current.seenMs = at;
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
this.#close(at);
|
|
63
|
+
this.#open(target, at);
|
|
64
|
+
}
|
|
65
|
+
/** Delivers the held segment and, with `cut`, the open one, which then continues from `now`. */
|
|
66
|
+
flush(now, cut) {
|
|
67
|
+
if (this.#held) {
|
|
68
|
+
this.#deliver(this.#held);
|
|
69
|
+
this.#held = null;
|
|
70
|
+
}
|
|
71
|
+
if (cut && this.#current) {
|
|
72
|
+
this.#deliver({ ...this.#current, endMs: Math.max(this.#current.startMs, now) });
|
|
73
|
+
this.#current = { ...this.#current, startMs: now, seenMs: now };
|
|
74
|
+
}
|
|
75
|
+
return this.drain();
|
|
76
|
+
}
|
|
77
|
+
/** Ends everything at `endMs`, delivers all segments and resets the builder. */
|
|
78
|
+
finish(endMs) {
|
|
79
|
+
if (this.#held)
|
|
80
|
+
this.#deliver(this.#held);
|
|
81
|
+
if (this.#current)
|
|
82
|
+
this.#deliver({ ...this.#current, endMs: Math.max(this.#current.startMs, endMs) });
|
|
83
|
+
this.#held = null;
|
|
84
|
+
this.#current = null;
|
|
85
|
+
return this.drain();
|
|
86
|
+
}
|
|
87
|
+
/** Returns the segments finished since the last call. */
|
|
88
|
+
drain() {
|
|
89
|
+
const out = this.#ready;
|
|
90
|
+
this.#ready = [];
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
/** Forgets all state without delivering anything. */
|
|
94
|
+
reset() {
|
|
95
|
+
this.#current = null;
|
|
96
|
+
this.#held = null;
|
|
97
|
+
this.#ready = [];
|
|
98
|
+
}
|
|
99
|
+
#targetFor(window) {
|
|
100
|
+
const app = String(window.app ?? '').trim();
|
|
101
|
+
if (!app || this.#options.isIgnored(window))
|
|
102
|
+
return null;
|
|
103
|
+
const appId = String(window.appId ?? '').trim() || app;
|
|
104
|
+
const parsed = this.#options.urls === 'none' ? null : parseHttpUrl(window.url);
|
|
105
|
+
const full = this.#options.urls === 'full' && parsed ? parsed.href : undefined;
|
|
106
|
+
return {
|
|
107
|
+
key: `${appId}|${full ?? parsed?.host ?? ''}`,
|
|
108
|
+
app,
|
|
109
|
+
appId,
|
|
110
|
+
...(parsed ? { host: parsed.host } : {}),
|
|
111
|
+
...(full ? { url: full } : {}),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
#release(now) {
|
|
115
|
+
if (this.#held && now - this.#held.endMs >= this.#options.mergeGapMs) {
|
|
116
|
+
this.#deliver(this.#held);
|
|
117
|
+
this.#held = null;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
#close(endMs) {
|
|
121
|
+
const open = this.#current;
|
|
122
|
+
if (!open)
|
|
123
|
+
return;
|
|
124
|
+
this.#current = null;
|
|
125
|
+
const closed = {
|
|
126
|
+
key: open.key,
|
|
127
|
+
app: open.app,
|
|
128
|
+
appId: open.appId,
|
|
129
|
+
...(open.host ? { host: open.host } : {}),
|
|
130
|
+
...(open.url ? { url: open.url } : {}),
|
|
131
|
+
startMs: open.startMs,
|
|
132
|
+
endMs: Math.max(open.startMs, endMs),
|
|
133
|
+
};
|
|
134
|
+
// A blip is dropped without touching the held segment, so A, blip, A still merges into one A.
|
|
135
|
+
if (closed.endMs - closed.startMs < this.#options.minSegmentMs)
|
|
136
|
+
return;
|
|
137
|
+
if (this.#held)
|
|
138
|
+
this.#deliver(this.#held);
|
|
139
|
+
this.#held = closed;
|
|
140
|
+
}
|
|
141
|
+
#open(target, at) {
|
|
142
|
+
const held = this.#held;
|
|
143
|
+
if (held && held.key === target.key && at - held.endMs < this.#options.mergeGapMs) {
|
|
144
|
+
this.#current = {
|
|
145
|
+
key: held.key,
|
|
146
|
+
app: held.app,
|
|
147
|
+
appId: held.appId,
|
|
148
|
+
...(held.host ? { host: held.host } : {}),
|
|
149
|
+
...(held.url ? { url: held.url } : {}),
|
|
150
|
+
startMs: held.startMs,
|
|
151
|
+
seenMs: at,
|
|
152
|
+
};
|
|
153
|
+
this.#held = null;
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
this.#current = { ...target, startMs: at, seenMs: at };
|
|
157
|
+
}
|
|
158
|
+
#deliver(segment) {
|
|
159
|
+
if (segment.endMs - segment.startMs < this.#options.minSegmentMs)
|
|
160
|
+
return;
|
|
161
|
+
this.#ready.push({
|
|
162
|
+
app: segment.app,
|
|
163
|
+
appId: segment.appId,
|
|
164
|
+
...(segment.host ? { host: segment.host } : {}),
|
|
165
|
+
...(segment.url ? { url: segment.url } : {}),
|
|
166
|
+
startMs: segment.startMs,
|
|
167
|
+
endMs: segment.endMs,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** A parsed http(s) URL. */
|
|
2
|
+
export interface ParsedUrl {
|
|
3
|
+
/** Lower-case host name, without port or credentials. */
|
|
4
|
+
host: string;
|
|
5
|
+
/** The URL without its fragment. */
|
|
6
|
+
href: string;
|
|
7
|
+
}
|
|
8
|
+
/** Parses an http(s) URL. Returns `null` for anything else, including malformed input. */
|
|
9
|
+
export declare function parseHttpUrl(url: string | null | undefined): ParsedUrl | null;
|
|
10
|
+
/** Returns the lower-case host of an http(s) URL and drops the rest. Returns `null` for other schemes or malformed input. */
|
|
11
|
+
export declare function hostFromUrl(url: string | null | undefined): string | null;
|
package/dist/host.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Parses an http(s) URL. Returns `null` for anything else, including malformed input. */
|
|
2
|
+
export function parseHttpUrl(url) {
|
|
3
|
+
if (!url)
|
|
4
|
+
return null;
|
|
5
|
+
try {
|
|
6
|
+
const parsed = new URL(url);
|
|
7
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
8
|
+
return null;
|
|
9
|
+
const host = parsed.hostname.toLowerCase();
|
|
10
|
+
if (!host)
|
|
11
|
+
return null;
|
|
12
|
+
parsed.hash = '';
|
|
13
|
+
return { host, href: parsed.href };
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** Returns the lower-case host of an http(s) URL and drops the rest. Returns `null` for other schemes or malformed input. */
|
|
20
|
+
export function hostFromUrl(url) {
|
|
21
|
+
return parseHttpUrl(url)?.host ?? null;
|
|
22
|
+
}
|
package/dist/ignore.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { IgnoreRule, WindowInfo } from './types.ts';
|
|
2
|
+
/**
|
|
3
|
+
* macOS system UI that takes the front for a moment (alerts, the login window, the screen saver).
|
|
4
|
+
* These are not apps the user chose to work in. Entries are matched against `appId` and `app`.
|
|
5
|
+
*/
|
|
6
|
+
export declare const DEFAULT_IGNORE: readonly string[];
|
|
7
|
+
/** Builds one predicate from a list of ignore rules. */
|
|
8
|
+
export declare function compileIgnore(rules: readonly IgnoreRule[]): (window: WindowInfo) => boolean;
|
package/dist/ignore.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* macOS system UI that takes the front for a moment (alerts, the login window, the screen saver).
|
|
3
|
+
* These are not apps the user chose to work in. Entries are matched against `appId` and `app`.
|
|
4
|
+
*/
|
|
5
|
+
export const DEFAULT_IGNORE = [
|
|
6
|
+
'com.apple.UserNotificationCenter',
|
|
7
|
+
'com.apple.notificationcenterui',
|
|
8
|
+
'com.apple.loginwindow',
|
|
9
|
+
'com.apple.screensaver.engine',
|
|
10
|
+
'com.apple.ScreenSaver.Engine',
|
|
11
|
+
'com.apple.SecurityAgent',
|
|
12
|
+
'com.apple.coreservices.uiagent',
|
|
13
|
+
'com.apple.controlcenter',
|
|
14
|
+
'UserNotificationCenter',
|
|
15
|
+
'loginwindow',
|
|
16
|
+
'ScreenSaverEngine',
|
|
17
|
+
];
|
|
18
|
+
/** Builds one predicate from a list of ignore rules. */
|
|
19
|
+
export function compileIgnore(rules) {
|
|
20
|
+
const names = new Set();
|
|
21
|
+
const patterns = [];
|
|
22
|
+
const predicates = [];
|
|
23
|
+
for (const rule of rules) {
|
|
24
|
+
if (typeof rule === 'string')
|
|
25
|
+
names.add(rule);
|
|
26
|
+
else if (rule instanceof RegExp)
|
|
27
|
+
patterns.push(rule);
|
|
28
|
+
else
|
|
29
|
+
predicates.push(rule);
|
|
30
|
+
}
|
|
31
|
+
return (window) => {
|
|
32
|
+
const ids = [window.app, window.appId ?? ''];
|
|
33
|
+
if (ids.some((id) => names.has(id)))
|
|
34
|
+
return true;
|
|
35
|
+
for (const pattern of patterns) {
|
|
36
|
+
// Reset first so a global or sticky RegExp gives the same answer on every call.
|
|
37
|
+
pattern.lastIndex = 0;
|
|
38
|
+
if (ids.some((id) => id && pattern.test(id)))
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
return predicates.some((predicate) => predicate(window));
|
|
42
|
+
};
|
|
43
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { sessionize } from './sessionize.ts';
|
|
2
|
+
export { createTracker, systemClock } from './tracker.ts';
|
|
3
|
+
export { aggregate } from './aggregate.ts';
|
|
4
|
+
export { hostFromUrl } from './host.ts';
|
|
5
|
+
export { DEFAULT_IGNORE } from './ignore.ts';
|
|
6
|
+
export { getWindowsSampler, toWindowInfo } from './windows.ts';
|
|
7
|
+
export { checkPlatformSupport, defaultIdleThresholdSeconds, isRemoteSession } from './platform.ts';
|
|
8
|
+
export type { AggregateBy, AggregateOptions, Clock, FlushOptions, IdleSource, IgnoreRule, Sample, Segment, SegmentationOptions, SessionizeOptions, Tracker, TrackerOptions, UrlMode, UsageTotal, WindowInfo, WindowSampler, } from './types.ts';
|
|
9
|
+
export type { PermissionFlag, WindowsSamplerOptions } from './windows.ts';
|
|
10
|
+
export type { PlatformOptions, PlatformSupport } from './platform.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { sessionize } from "./sessionize.js";
|
|
2
|
+
export { createTracker, systemClock } from "./tracker.js";
|
|
3
|
+
export { aggregate } from "./aggregate.js";
|
|
4
|
+
export { hostFromUrl } from "./host.js";
|
|
5
|
+
export { DEFAULT_IGNORE } from "./ignore.js";
|
|
6
|
+
export { getWindowsSampler, toWindowInfo } from "./windows.js";
|
|
7
|
+
export { checkPlatformSupport, defaultIdleThresholdSeconds, isRemoteSession } from "./platform.js";
|