@ai-ecoverse/slicc-capture 1.2.0 → 1.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.
Files changed (3) hide show
  1. package/README.md +25 -1
  2. package/package.json +11 -4
  3. package/page/index.mjs +199 -0
package/README.md CHANGED
@@ -105,7 +105,7 @@ As `sccapture`, the messages start with `sccapture:`. A line of progress from th
105
105
 
106
106
  ### The request
107
107
 
108
- The commands run in a kernel worker, which has no `getDisplayMedia`, so they ask seven's page over [`/dev/embedder`](https://github.com/ai-ecoverse/slicc-kernel#devembedder) (slicc-kernel 1.153.0, [#1527](https://github.com/ai-ecoverse/slicc-kernel/issues/1527)): one open file description per request, a JSON header line `{ kind, …options }`, then the body, and the reply read to end-of-file. The page side, the prompt, `getDisplayMedia`, the frame, the crop and the encoding, is a page module that slicc-bios registers for `capture.screen` and wraps with its own prompt, user activation, `selfBrowserSurface: 'exclude'` and a check of the picked surface against protected origins; it answers this contract:
108
+ The commands run in a kernel worker, which has no `getDisplayMedia`, so they ask seven's page over [`/dev/embedder`](https://github.com/ai-ecoverse/slicc-kernel#devembedder) (slicc-kernel 1.153.0, [#1527](https://github.com/ai-ecoverse/slicc-kernel/issues/1527)): one open file description per request, a JSON header line `{ kind, …options }`, then the body, and the reply read to end-of-file. The page side, the prompt, `getDisplayMedia`, the frame, the crop and the encoding, is [a page module](#the-page-module) that slicc-bios registers for `capture.screen` and wraps with its own prompt, user activation, `selfBrowserSurface: 'exclude'` and a check of the picked surface against protected origins; it answers this contract:
109
109
 
110
110
  - **`capture.screen`:** the header is plain JSON, with no body, and the reply is the encoded image's bytes, nothing else. The command opens the device read-write (`exec 3<>/dev/embedder`), writes the header from a child `sh` that stays until the reply is read (so the page's progress reaches stderr), and reads the reply with a `cat <&3` that it starts in the background, so that a signal to the command can stop it.
111
111
 
@@ -122,6 +122,29 @@ The commands run in a kernel worker, which has no `getDisplayMedia`, so they ask
122
122
  For example, `screencapture -C -T 2 -R 0,0,800,600 shot.jpg` sends `{"kind":"capture.screen","type":"image/jpeg","quality":0.92,"cursor":"always","delay":2,"rect":{"x":0,"y":0,"width":800,"height":600}}`. The page rejects with a `NotAllowedError` or `AbortError` for **Cancel**, a closed picker, a refused permission or a protected surface (`EACCES`); a `NotSupportedError` without `getDisplayMedia` (`ENOTSUP`); and any other error, such as a `TimeoutError` `timed out waiting for the picker` after 5 minutes, with the message the command prints (`EIO`). It aborts the capture when its `signal` does.
123
123
  - **`clipboard.write`:** `-c` sends `{"kind":"clipboard.write","type":"image/png"}` and the PNG as the body, and reads the reply, which is empty, to end-of-file. slicc-bios answers it; with no page that does, the header write fails with `ENOTSUP`. The device is opened read-write and the reply read only after the whole body is written, so a page that answers without reading the body ([slicc-kernel#1536](https://github.com/ai-ecoverse/slicc-kernel/issues/1536)) is the only way a body over 1 MiB could block; the embedder's handler reads it.
124
124
 
125
+ ### The page module
126
+
127
+ `@ai-ecoverse/slicc-capture/page` is that page module: one plain ES module (`page/index.mjs`), with no build step and no dependencies, which runs in Chrome and loads in Node. It answers `capture.screen` and nothing else; `clipboard.write` is the embedder's own.
128
+
129
+ ```js
130
+ import capture, { create, handle, kinds } from '@ai-ecoverse/slicc-capture/page';
131
+
132
+ createKernel({
133
+ requests: {
134
+ kinds: capture.kinds,
135
+ handle: (request) => capture.handle({ ...request, display: guardedGetDisplayMedia }),
136
+ },
137
+ });
138
+ ```
139
+
140
+ - **The exports:** `kinds` is `{ 'capture.screen': {} }`, with no policy; `handle(request)` is a [`/dev/embedder` hook](https://github.com/ai-ecoverse/slicc-kernel#devembedder)'s `handle`; the default export is `{ kinds, handle }`. `create({ ImageCapture, OffscreenCanvas, document, timeout })` returns another `{ kinds, handle }` that uses those instead of the page's globals, and `timeout` (in ms, 5 minutes by default) for the picker; the tests inject fakes through it.
141
+ - **`display` is required:** the request is the kernel's (`{ kind, options, body, stamp, signal, progress }`) plus `display(constraints)`, the embedder's `getDisplayMedia`, which resolves to a `MediaStream`. The module never calls `navigator.mediaDevices.getDisplayMedia` itself; without `display`, or without `OffscreenCanvas` and a way to grab a frame (`ImageCapture`, else `document`), it rejects with a `NotSupportedError` `screen capture is not supported in this browser` (`ENOTSUP`).
142
+ - **The header:** `type` (PNG by default), `quality`, `cursor`, `surface`, `delay` and `rect` as in [the table above](#the-request); other keys are ignored. A `type` it doesn't encode rejects with a `NotSupportedError` `unsupported type: <type>`, and a value of the wrong shape with a `TypeError` `invalid <field>: <json>` (`EIO`), before `display` is called.
143
+ - **The capture:** it calls `display({ video: { cursor, displaySurface }, audio: false })` (each field only when the header has it: `cursor` as is, `surface` as `displaySurface`) after `progress('waiting for the picker…')`. No stream within the timeout rejects with a `TimeoutError` `timed out waiting for the picker`, one without a video track with a `NotFoundError` `the capture has no video track` (`ENOENT`), and one whose track has ended, or ends before the frame (the user's **Stop sharing**), with an `AbortError` `the capture was stopped` (`EACCES`). With a `delay`, it says `waiting <delay> s…` and waits that long. It grabs one frame with `ImageCapture.grabFrame()`, else from a muted `<video>` once it has data, crops it to `rect` (outside the frame: a `RangeError` `-R: rectangle outside the capture`), draws it on an `OffscreenCanvas` and encodes it with `convertToBlob({ type, quality })`. A browser that encodes another type than asked rejects with a `NotSupportedError` `<type> is not supported by this browser`. It resolves with the bytes, a `Uint8Array`.
144
+ - **Stopping:** every track of the stream is stopped when `handle` settles, whether it resolved, failed or was aborted, and so is a stream that `display` delivers after the timeout or an abort. When `signal` aborts, `handle` rejects with an `AbortError` carrying the reason's message (`interrupted`, `closed`, or the embedder's own).
145
+
146
+ **What slicc-bios does around it:** bios registers its own `kinds` table, of which the module's is a subset, and ignores the module's policies. It owns the prompt (`screencapture wants to capture your screen`, **Choose…**, **Cancel**), the user activation `getDisplayMedia` needs, the session tag and the protected origins, and calls `handle` only after its checks pass. Its `display` is a guarded `getDisplayMedia`: it adds `selfBrowserSurface: 'exclude'`, checks the picked surface's capture handle against the protected origins, and rejects with a `NotAllowedError` on a match. Its `signal` also aborts when its prompt is withdrawn.
147
+
125
148
  ### Options
126
149
 
127
150
  Every option of macOS's `screencapture`, and what it does in SLICC and with `sccapture` on each host. On macOS, `sccapture` passes the options through to `screencapture` unchanged, except the ones the macOS column names. "No-op" means the option is accepted and changes nothing. "Not supported" means `<cmd>: <opt>: not supported in SLICC` (or `on Linux`, `on Windows`, `on macOS`) on stderr, exit 2, before anything is captured; "not with `<tool>`" means `sccapture: <opt>: not supported with <tool>`, exit 2, when no tool on `PATH` supports every option given (it names the first one tried).
@@ -225,6 +248,7 @@ npm run test:unit
225
248
  - `npm install` also installs the git hooks into this worktree's own `node_modules/` through slicc-shared-web's `slicc-install-hooks` and the committed `.githooks/`.
226
249
  - `npm run lint`: Biome, the no-comment check and the other [slicc-shared-web](https://github.com/ai-ecoverse/slicc-shared-web) checks, then `shellcheck -s sh` and `dash -n` on `install.sh` and `bin/*`.
227
250
  - `npm test`: the integration tests in `test/integration/`. `commands.test.mjs` runs `screencapture` and `sccapture` on `@ai-ecoverse/slicc-kernel/node` (the version `engines.slicc-kernel` names, pinned) with wasm-bash and wasm-coreutils, and a fake `capture.screen` and `clipboard.write` handler (`createNodeKernel({ requests })`): every option's header, the bytes written unchanged, the errnos and their messages, `-c`, `-v`, and slicc-kernel 1.152.2, which has no `/dev/embedder`. `test/integration/repo.test.mjs` checks the workflow, the release config, the pinned devDependencies and what `npm pack` ships. The host tests run `host/` against fake `screencapture`, `grim`, `slurp`, `gnome-screenshot`, `import`, `scrot`, `wl-copy`, `xclip`, `xdg-open`, `powershell.exe` and `pwsh.exe` on a temporary `PATH`, and `--upgrade` against installers served from a local HTTP server, with the platform forced, so each branch is checked on any machine; only CI touches a real screen. `install.test.mjs` runs `install.sh` on a tarball packed from the tree, with the Node on `PATH` and with a Node download from a fake `nodejs.org`, and `--upgrade` against a release served from a local directory; `install.ps1` is checked statically, and run when `pwsh` is on `PATH`.
251
+ - `page.test.mjs` registers [the page module](#the-page-module) through `createNodeKernel({ requests })`, with a fake `display` and fake `ImageCapture`, `OffscreenCanvas` and `<video>` injected through `create`, and runs the real `screencapture`: the constraints, the crop, the type and quality, the delay and its progress, an interrupt in the picker and in the delay, **Stop sharing**, the picker's timeout, the errnos and their messages end to end, and that every track is stopped. `browser.test.mjs` runs the module in Chrome, through slicc-shared-web's harness, with a `display` that returns a canvas's `captureStream()`: PNG, JPEG and WebP, the crop, the `<video>` fallback, an abort and the stopped track. It runs on CI only, and is skipped without `CI`.
228
252
  - `npm run test:unit`: the unit tests in the gitignored `test/unit/`, with coverage in `coverage/unit/lcov.info`. `npm run test:sh` runs the `test/unit/*.sh.mjs` ones, which trace `bin/` with `set -x` in the node kernel, and writes `coverage/sh/lcov.info`. The pre-commit hook wants 100% coverage of the changed lines of both, and runs `diff-cover` through `uvx`, so install [uv](https://docs.astral.sh/uv/) once.
229
253
 
230
254
  CI is `.github/workflows/ci.yml`, the only workflow, which runs [slicc-shared-web's pipeline](https://github.com/ai-ecoverse/slicc-shared-web#pipeline) at the devDependency's version: `npm run lint`, then `npm test`, then on a pull request the Claude and Codex reviews. The merge queue requires `ci / integration` and `ci / review`. On a push to `main`, semantic-release releases and publishes to npm through trusted publishing, with provenance from `ci.yml`, and attaches the installers.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-ecoverse/slicc-capture",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "screencapture for SLICC, and sccapture for SLICC and any host",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -15,6 +15,10 @@
15
15
  "bin": {
16
16
  "sccapture": "host/sccapture.mjs"
17
17
  },
18
+ "exports": {
19
+ "./page": "./page/index.mjs",
20
+ "./package.json": "./package.json"
21
+ },
18
22
  "fledgling": {
19
23
  "provider": "github",
20
24
  "workflow": "ci.yml",
@@ -35,12 +39,14 @@
35
39
  }
36
40
  },
37
41
  "unitSources": [
38
- "host"
42
+ "host",
43
+ "page"
39
44
  ]
40
45
  },
41
46
  "files": [
42
47
  "bin",
43
- "host"
48
+ "host",
49
+ "page"
44
50
  ],
45
51
  "scripts": {
46
52
  "prepare": "slicc-install-hooks",
@@ -55,8 +61,9 @@
55
61
  "release": "semantic-release"
56
62
  },
57
63
  "devDependencies": {
64
+ "@ai-ecoverse/slicc-cdp": "1.40.0",
58
65
  "@ai-ecoverse/slicc-kernel": "1.153.0",
59
- "@ai-ecoverse/slicc-shared-web": "2.11.3",
66
+ "@ai-ecoverse/slicc-shared-web": "2.12.0",
60
67
  "@ai-ecoverse/wasm-bash": "5.3.0-23",
61
68
  "@ai-ecoverse/wasm-coreutils": "9.12.0-15",
62
69
  "@biomejs/biome": "2.5.15",
package/page/index.mjs ADDED
@@ -0,0 +1,199 @@
1
+ const types = ['image/png', 'image/jpeg', 'image/webp'];
2
+ const cursors = ['always', 'motion', 'never'];
3
+ const surfaces = ['monitor', 'window', 'browser'];
4
+ const unsupported = 'screen capture is not supported in this browser';
5
+
6
+ export const kinds = { 'capture.screen': {} };
7
+
8
+ function fail(name, message) {
9
+ return new DOMException(message, name);
10
+ }
11
+
12
+ function aborted(signal) {
13
+ const reason = signal.reason;
14
+ if (reason?.name === 'AbortError') return reason;
15
+ return fail('AbortError', String(reason?.message ?? reason));
16
+ }
17
+
18
+ function race(promise, signal) {
19
+ return new Promise((resolve, reject) => {
20
+ const stop = () => reject(aborted(signal));
21
+ if (signal.aborted) stop();
22
+ signal.addEventListener('abort', stop, { once: true });
23
+ Promise.resolve(promise)
24
+ .then(resolve, reject)
25
+ .finally(() => signal.removeEventListener('abort', stop));
26
+ });
27
+ }
28
+
29
+ function sleep(ms, signal) {
30
+ let timer;
31
+ const wait = new Promise((resolve) => {
32
+ timer = setTimeout(resolve, ms);
33
+ });
34
+ return race(wait, signal).finally(() => clearTimeout(timer));
35
+ }
36
+
37
+ function stopAll(stream) {
38
+ for (const track of stream?.getTracks?.() ?? []) track.stop();
39
+ }
40
+
41
+ function invalid(field, value) {
42
+ return new TypeError(`invalid ${field}: ${JSON.stringify(value)}`);
43
+ }
44
+
45
+ const whole = (value, least) => Number.isInteger(value) && value >= least;
46
+
47
+ function parse(options = {}) {
48
+ const { type = 'image/png', quality, cursor, surface, delay, rect } = options;
49
+ if (!types.includes(type)) throw fail('NotSupportedError', `unsupported type: ${type}`);
50
+ if (quality !== undefined && !(typeof quality === 'number' && quality >= 0 && quality <= 1)) {
51
+ throw invalid('quality', quality);
52
+ }
53
+ if (cursor !== undefined && !cursors.includes(cursor)) throw invalid('cursor', cursor);
54
+ if (surface !== undefined && !surfaces.includes(surface)) throw invalid('surface', surface);
55
+ if (delay !== undefined && !(Number.isFinite(delay) && delay >= 0)) throw invalid('delay', delay);
56
+ if (
57
+ rect !== undefined &&
58
+ !(whole(rect?.x, 0) && whole(rect?.y, 0) && whole(rect?.width, 1) && whole(rect?.height, 1))
59
+ ) {
60
+ throw invalid('rect', rect);
61
+ }
62
+ const video = {};
63
+ if (cursor !== undefined) video.cursor = cursor;
64
+ if (surface !== undefined) video.displaySurface = surface;
65
+ return {
66
+ constraints: { video, audio: false },
67
+ type,
68
+ quality,
69
+ delay: delay ?? 0,
70
+ rect,
71
+ };
72
+ }
73
+
74
+ async function pick(display, constraints, signal, timeout) {
75
+ const pending = Promise.resolve().then(() => display(constraints));
76
+ let timer;
77
+ const late = new Promise((_, reject) => {
78
+ timer = setTimeout(
79
+ () => reject(fail('TimeoutError', 'timed out waiting for the picker')),
80
+ timeout
81
+ );
82
+ });
83
+ try {
84
+ return await race(Promise.race([pending, late]), signal);
85
+ } catch (error) {
86
+ pending.then(stopAll, () => {});
87
+ throw error;
88
+ } finally {
89
+ clearTimeout(timer);
90
+ }
91
+ }
92
+
93
+ async function grab(stream, track, env, signal) {
94
+ const ImageCapture = env('ImageCapture');
95
+ if (ImageCapture) {
96
+ const bitmap = await race(new ImageCapture(track).grabFrame(), signal);
97
+ return {
98
+ source: bitmap,
99
+ width: bitmap.width,
100
+ height: bitmap.height,
101
+ close: () => bitmap.close?.(),
102
+ };
103
+ }
104
+ const video = env('document').createElement('video');
105
+ const close = () => {
106
+ video.pause();
107
+ video.srcObject = null;
108
+ };
109
+ const ready = new Promise((resolve, reject) => {
110
+ video.onloadedmetadata = () => video.play().catch(reject);
111
+ video.onloadeddata = resolve;
112
+ video.onerror = () => reject(new Error('the capture could not be played'));
113
+ });
114
+ video.muted = true;
115
+ video.playsInline = true;
116
+ video.srcObject = stream;
117
+ try {
118
+ await race(ready, signal);
119
+ } catch (error) {
120
+ close();
121
+ throw error;
122
+ }
123
+ return { source: video, width: video.videoWidth, height: video.videoHeight, close };
124
+ }
125
+
126
+ async function encode(frame, request, env, signal) {
127
+ const { type, quality, rect } = request;
128
+ const { x, y, width, height } = rect ?? { x: 0, y: 0, width: frame.width, height: frame.height };
129
+ if (!(frame.width > 0 && frame.height > 0)) throw new Error('the capture has no frame');
130
+ if (x + width > frame.width || y + height > frame.height) {
131
+ throw new RangeError('-R: rectangle outside the capture');
132
+ }
133
+ const canvas = new (env('OffscreenCanvas'))(width, height);
134
+ canvas.getContext('2d').drawImage(frame.source, x, y, width, height, 0, 0, width, height);
135
+ const blob = await race(
136
+ canvas.convertToBlob(quality === undefined ? { type } : { type, quality }),
137
+ signal
138
+ );
139
+ if (blob.type !== type)
140
+ throw fail('NotSupportedError', `${type} is not supported by this browser`);
141
+ return new Uint8Array(await race(blob.arrayBuffer(), signal));
142
+ }
143
+
144
+ export function create(overrides = {}) {
145
+ const env = (name) => (name in overrides ? overrides[name] : globalThis[name]);
146
+ const timeout = overrides.timeout ?? 300000;
147
+
148
+ async function handle({
149
+ options,
150
+ signal = new AbortController().signal,
151
+ progress = () => {},
152
+ display,
153
+ }) {
154
+ const request = parse(options);
155
+ if (typeof display !== 'function') throw fail('NotSupportedError', unsupported);
156
+ if (!env('OffscreenCanvas') || !(env('ImageCapture') || env('document'))) {
157
+ throw fail('NotSupportedError', unsupported);
158
+ }
159
+ const local = new AbortController();
160
+ const forward = () => local.abort(signal.reason);
161
+ if (signal.aborted) forward();
162
+ signal.addEventListener('abort', forward, { once: true });
163
+ let stream;
164
+ let frame;
165
+ try {
166
+ if (local.signal.aborted) throw aborted(local.signal);
167
+ progress('waiting for the picker…');
168
+ stream = await pick(display, request.constraints, local.signal, timeout);
169
+ const track = stream?.getVideoTracks?.()[0];
170
+ if (!track) throw fail('NotFoundError', 'the capture has no video track');
171
+ if (track.readyState === 'ended') throw fail('AbortError', 'the capture was stopped');
172
+ track.addEventListener(
173
+ 'ended',
174
+ () => local.abort(fail('AbortError', 'the capture was stopped')),
175
+ {
176
+ once: true,
177
+ }
178
+ );
179
+ if (request.delay > 0) {
180
+ progress(`waiting ${request.delay} s…`);
181
+ await sleep(request.delay * 1000, local.signal);
182
+ }
183
+ frame = await grab(stream, track, env, local.signal);
184
+ return await encode(frame, request, env, local.signal);
185
+ } finally {
186
+ signal.removeEventListener('abort', forward);
187
+ frame?.close();
188
+ stopAll(stream);
189
+ }
190
+ }
191
+
192
+ return { kinds, handle };
193
+ }
194
+
195
+ const page = create();
196
+
197
+ export const handle = page.handle;
198
+
199
+ export default page;