@d0nj/dsh-browser 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/dist/host.js ADDED
@@ -0,0 +1,222 @@
1
+ import { join } from 'node:path';
2
+ import { CdpClient } from './cdp.js';
3
+ import { IdleCloser } from './idle.js';
4
+ import { describeSearch, findExecutable, launchChrome, resolveCdpAddress, reuseBrowser, stopBrowser } from './launch.js';
5
+ import { Tab } from './tab.js';
6
+ export class BrowserHost {
7
+ #settings;
8
+ #deps;
9
+ #tabs = new Map();
10
+ #pendingTabs = new Map();
11
+ #idle;
12
+ #connection;
13
+ #closing;
14
+ #disposed = false;
15
+ constructor(settings, deps) {
16
+ this.#settings = settings;
17
+ this.#deps = deps;
18
+ this.#idle = new IdleCloser(settings.idleCloseMs, () => {
19
+ void this.closeIdleBrowser();
20
+ });
21
+ }
22
+ /** The tab settings every new tab receives. */
23
+ get tabSettings() {
24
+ return {
25
+ viewport: this.#settings.viewport,
26
+ dialogs: this.#settings.dialogs,
27
+ navigateTimeoutMs: this.#settings.navigateTimeoutMs,
28
+ };
29
+ }
30
+ /**
31
+ * The named tab, created on first use.
32
+ * @param name - model-facing tab name.
33
+ * @returns the live tab.
34
+ */
35
+ async tab(name) {
36
+ if (this.#disposed)
37
+ throw new Error('the browser plugin was disposed');
38
+ const existing = this.#tabs.get(name);
39
+ if (existing !== undefined && !existing.closed)
40
+ return existing;
41
+ if (existing !== undefined)
42
+ this.#tabs.delete(name);
43
+ const pending = this.#pendingTabs.get(name);
44
+ if (pending !== undefined)
45
+ return pending;
46
+ const created = this.#openTab(name).finally(() => {
47
+ this.#pendingTabs.delete(name);
48
+ });
49
+ this.#pendingTabs.set(name, created);
50
+ return created;
51
+ }
52
+ async #openTab(name) {
53
+ const connection = await this.#ensureConnection();
54
+ let targetId;
55
+ try {
56
+ const created = await connection.cdp.send('Target.createTarget', {
57
+ url: 'about:blank',
58
+ });
59
+ targetId = created.targetId;
60
+ }
61
+ catch (error) {
62
+ throw new Error(`cannot open a browser tab: ${error instanceof Error ? error.message : String(error)}`);
63
+ }
64
+ let tab;
65
+ try {
66
+ tab = await Tab.attach(connection.cdp, targetId, name, this.tabSettings);
67
+ }
68
+ catch (error) {
69
+ await connection.cdp.send('Target.closeTarget', { targetId }).catch(() => undefined);
70
+ throw new Error(`cannot attach to the new browser tab: ${error instanceof Error ? error.message : String(error)}`);
71
+ }
72
+ this.#tabs.set(name, tab);
73
+ return tab;
74
+ }
75
+ /**
76
+ * Every open tab with its current page.
77
+ * @returns the tab listing.
78
+ */
79
+ async listTabs() {
80
+ const entries = [...this.#tabs.entries()].filter(([, tab]) => !tab.closed);
81
+ return Promise.all(entries.map(async ([name, tab]) => {
82
+ const info = await tab.info();
83
+ return { name, ...info };
84
+ }));
85
+ }
86
+ /**
87
+ * Close one tab, or all of them.
88
+ * @param name - tab name to close; ignored when `all` is true.
89
+ * @param all - close every tab this plugin opened.
90
+ * @returns the names that were closed.
91
+ */
92
+ async closeTab(name, all) {
93
+ if (all) {
94
+ const names = [...this.#tabs.keys()];
95
+ for (const key of names)
96
+ await this.#closeOne(key);
97
+ return names;
98
+ }
99
+ const target = name ?? 'main';
100
+ if (!this.#tabs.has(target))
101
+ return [];
102
+ await this.#closeOne(target);
103
+ return [target];
104
+ }
105
+ async #closeOne(name) {
106
+ const tab = this.#tabs.get(name);
107
+ this.#tabs.delete(name);
108
+ if (tab === undefined)
109
+ return;
110
+ const connection = await this.#connection?.catch(() => undefined);
111
+ await tab.dispose();
112
+ await connection?.cdp.send('Target.closeTarget', { targetId: tab.targetId }).catch(() => undefined);
113
+ }
114
+ async #ensureConnection() {
115
+ if (this.#connection !== undefined) {
116
+ const current = await this.#connection.catch(() => undefined);
117
+ if (current !== undefined && !current.cdp.closed)
118
+ return current;
119
+ this.#connection = undefined;
120
+ }
121
+ const attempt = this.#connect();
122
+ this.#connection = attempt;
123
+ try {
124
+ return await attempt;
125
+ }
126
+ catch (error) {
127
+ if (this.#connection === attempt)
128
+ this.#connection = undefined;
129
+ throw error;
130
+ }
131
+ }
132
+ async #connect() {
133
+ if (this.#settings.cdpUrl !== undefined) {
134
+ const wsUrl = await resolveCdpAddress(this.#settings.cdpUrl);
135
+ return { ...(await this.#open(wsUrl)), child: undefined, managed: false };
136
+ }
137
+ const reused = await reuseBrowser(this.#settings.userDataDir);
138
+ if (reused !== undefined) {
139
+ this.#deps.logger.debug?.(`browser: reusing the browser already running on ${this.#settings.userDataDir}`);
140
+ return { ...(await this.#open(reused.wsUrl)), child: undefined, managed: true };
141
+ }
142
+ const executable = this.#settings.executablePath ?? (await findExecutable({ platform: process.platform, env: this.#deps.env, home: this.#deps.home, exists: this.#deps.exists }));
143
+ if (executable === undefined) {
144
+ throw new Error(`cannot open a browser: no Chrome, Edge, Brave, or Chromium was found. Install one, set executablePath in the browser plugin config, or set cdpUrl to attach to a browser started with --remote-debugging-port.${describeSearch({ platform: process.platform, env: this.#deps.env, home: this.#deps.home })}`);
145
+ }
146
+ const launched = await launchChrome({
147
+ executable,
148
+ userDataDir: this.#settings.userDataDir,
149
+ headless: this.#settings.headless,
150
+ windowSize: this.#settings.viewport,
151
+ extraArgs: this.#settings.launchArgs,
152
+ startupTimeoutMs: this.#settings.startupTimeoutMs,
153
+ });
154
+ const child = launched.child;
155
+ child?.once('exit', () => {
156
+ this.#tabs.clear();
157
+ this.#connection = undefined;
158
+ });
159
+ return { ...(await this.#open(launched.wsUrl)), child, managed: launched.owned };
160
+ }
161
+ /**
162
+ * Connect, and let every command this connection carries restart the idle deadline.
163
+ * @param wsUrl - browser WebSocket URL.
164
+ * @returns the client and its activity detacher.
165
+ */
166
+ async #open(wsUrl) {
167
+ const cdp = await CdpClient.connect(wsUrl);
168
+ const stopActivity = cdp.onActivity(() => this.#idle.end());
169
+ return { cdp, stopActivity };
170
+ }
171
+ /** Close a browser nothing has used for the configured idle period. */
172
+ async closeIdleBrowser() {
173
+ if (this.#disposed || this.#connection === undefined || this.#pendingTabs.size > 0)
174
+ return;
175
+ this.#deps.logger.debug?.(`browser: closing the browser after ${Math.round(this.#settings.idleCloseMs / 1_000)}s idle; the next call starts it again`);
176
+ await this.#teardown();
177
+ }
178
+ /** Stop every tab and the browser this plugin manages. */
179
+ async dispose() {
180
+ if (this.#disposed)
181
+ return;
182
+ this.#disposed = true;
183
+ this.#idle.stop();
184
+ await this.#teardown();
185
+ }
186
+ async #teardown() {
187
+ if (this.#closing !== undefined)
188
+ return this.#closing;
189
+ const closing = this.#closeEverything().finally(() => {
190
+ this.#closing = undefined;
191
+ });
192
+ this.#closing = closing;
193
+ return closing;
194
+ }
195
+ async #closeEverything() {
196
+ const connection = await this.#connection?.catch(() => undefined);
197
+ this.#connection = undefined;
198
+ for (const [name, tab] of this.#tabs) {
199
+ this.#tabs.delete(name);
200
+ await tab.dispose().catch(() => undefined);
201
+ }
202
+ if (connection === undefined)
203
+ return;
204
+ connection.stopActivity();
205
+ if (connection.managed)
206
+ await connection.cdp.send('Browser.close').catch(() => undefined);
207
+ connection.cdp.close();
208
+ await stopBrowser(connection.child);
209
+ }
210
+ }
211
+ /**
212
+ * Absolute profile directory for one configured profile name.
213
+ * @param userDataDir - configured root, when the operator set one.
214
+ * @param dshHome - harness home.
215
+ * @param profile - profile name.
216
+ * @returns the directory Chrome stores its profile in.
217
+ */
218
+ export function resolveUserDataDir(userDataDir, dshHome, profile) {
219
+ const root = userDataDir?.trim();
220
+ return root !== undefined && root !== '' ? root : join(dshHome, 'browser', profile);
221
+ }
222
+ //# sourceMappingURL=host.js.map
package/dist/idle.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Close something once it has been idle long enough.
3
+ *
4
+ * A browser costs a process, a window slot, and memory, so it should not outlive
5
+ * the work that needed it. A tool call holds the resource open for its whole
6
+ * duration, and any later call pushes the deadline back again.
7
+ *
8
+ * @module @d0nj/dsh-browser/idle
9
+ */
10
+ export declare class IdleCloser {
11
+ #private;
12
+ /**
13
+ * @param timeoutMs - idle budget in milliseconds; zero or less disables closing.
14
+ * @param onIdle - called once per expired idle period.
15
+ */
16
+ constructor(timeoutMs: number, onIdle: () => void);
17
+ /** Restart the deadline; call it for every unit of work. */
18
+ end(): void;
19
+ /** Stop permanently, for plugin disposal. */
20
+ stop(): void;
21
+ }
22
+ //# sourceMappingURL=idle.d.ts.map
package/dist/idle.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Close something once it has been idle long enough.
3
+ *
4
+ * A browser costs a process, a window slot, and memory, so it should not outlive
5
+ * the work that needed it. A tool call holds the resource open for its whole
6
+ * duration, and any later call pushes the deadline back again.
7
+ *
8
+ * @module @d0nj/dsh-browser/idle
9
+ */
10
+ export class IdleCloser {
11
+ #timeoutMs;
12
+ #onIdle;
13
+ #handle;
14
+ #stopped = false;
15
+ /**
16
+ * @param timeoutMs - idle budget in milliseconds; zero or less disables closing.
17
+ * @param onIdle - called once per expired idle period.
18
+ */
19
+ constructor(timeoutMs, onIdle) {
20
+ this.#timeoutMs = timeoutMs;
21
+ this.#onIdle = onIdle;
22
+ }
23
+ /** Restart the deadline; call it for every unit of work. */
24
+ end() {
25
+ this.#cancel();
26
+ if (this.#stopped || this.#timeoutMs <= 0)
27
+ return;
28
+ this.#handle = setTimeout(() => {
29
+ this.#handle = undefined;
30
+ if (!this.#stopped)
31
+ this.#onIdle();
32
+ }, this.#timeoutMs);
33
+ this.#handle.unref?.();
34
+ }
35
+ /** Stop permanently, for plugin disposal. */
36
+ stop() {
37
+ this.#stopped = true;
38
+ this.#cancel();
39
+ }
40
+ #cancel() {
41
+ if (this.#handle === undefined)
42
+ return;
43
+ clearTimeout(this.#handle);
44
+ this.#handle = undefined;
45
+ }
46
+ }
47
+ //# sourceMappingURL=idle.js.map
@@ -0,0 +1,76 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import z from '@deepseek-ai/schemastery';
3
+ import type { BrowserSettings } from './host.js';
4
+ /** Cordis plugin name — also the profile patch row id. */
5
+ export declare const name = "browser";
6
+ /** Services this row relies on. */
7
+ export declare const inject: string[];
8
+ /** Runtime schema for the browser row. */
9
+ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
10
+ toolName: z<string, string, "defined">;
11
+ executablePath: z<string, string, "plain">;
12
+ cdpUrl: z<string, string, "plain">;
13
+ headless: z<boolean, boolean, "defined">;
14
+ userDataDir: z<string, string, "plain">;
15
+ profile: z<string, string, "defined">;
16
+ width: z<number, number, "defined">;
17
+ height: z<number, number, "defined">;
18
+ dialogs: z<"accept" | "dismiss", "accept" | "dismiss", "defined">;
19
+ launchArgs: z<string[], string[], "plain">;
20
+ navigateTimeoutMs: z<number, number, "defined">;
21
+ startupTimeoutMs: z<number, number, "defined">;
22
+ maxSnapshotChars: z<number, number, "defined">;
23
+ idleCloseSeconds: z<number, number, "defined">;
24
+ }>>, Schemastery.ObjectT<NoInfer<{
25
+ toolName: z<string, string, "defined">;
26
+ executablePath: z<string, string, "plain">;
27
+ cdpUrl: z<string, string, "plain">;
28
+ headless: z<boolean, boolean, "defined">;
29
+ userDataDir: z<string, string, "plain">;
30
+ profile: z<string, string, "defined">;
31
+ width: z<number, number, "defined">;
32
+ height: z<number, number, "defined">;
33
+ dialogs: z<"accept" | "dismiss", "accept" | "dismiss", "defined">;
34
+ launchArgs: z<string[], string[], "plain">;
35
+ navigateTimeoutMs: z<number, number, "defined">;
36
+ startupTimeoutMs: z<number, number, "defined">;
37
+ maxSnapshotChars: z<number, number, "defined">;
38
+ idleCloseSeconds: z<number, number, "defined">;
39
+ }>>, "plain">;
40
+ /** Resolved row configuration. */
41
+ export interface PluginConfig {
42
+ toolName?: string | undefined;
43
+ executablePath?: string | undefined;
44
+ cdpUrl?: string | undefined;
45
+ headless?: boolean | undefined;
46
+ userDataDir?: string | undefined;
47
+ profile?: string | undefined;
48
+ width?: number | undefined;
49
+ height?: number | undefined;
50
+ dialogs?: 'accept' | 'dismiss' | undefined;
51
+ launchArgs?: string[] | undefined;
52
+ navigateTimeoutMs?: number | undefined;
53
+ startupTimeoutMs?: number | undefined;
54
+ maxSnapshotChars?: number | undefined;
55
+ idleCloseSeconds?: number | undefined;
56
+ }
57
+ /**
58
+ * Resolve the harness home the same way the rest of the Harness does.
59
+ * @param env - environment mapping to read.
60
+ * @returns the absolute harness home.
61
+ */
62
+ export declare function resolveDshHome(env?: NodeJS.ProcessEnv): string;
63
+ /**
64
+ * Resolve and clamp the row's configuration.
65
+ * @param config - validated row configuration.
66
+ * @returns the settings the host and tool use.
67
+ */
68
+ export declare function resolveSettings(config: PluginConfig): BrowserSettings;
69
+ /**
70
+ * Register the browser tool and hand the browser process to the plugin fiber, so
71
+ * disposing the row also stops the Chrome instance this row started.
72
+ * @param ctx - the plugin context.
73
+ * @param config - validated row configuration.
74
+ */
75
+ export declare function apply(ctx: Context, config: PluginConfig): void;
76
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Plugin entry: the `browser` tool over a real Chrome window.
3
+ *
4
+ * Chrome is started on the first browser call, with a profile directory of its
5
+ * own so the user's everyday browser keeps running, and stays alive with the
6
+ * plugin so consecutive actions share one page. Setting `cdpUrl` attaches to a
7
+ * browser the user already started instead.
8
+ *
9
+ * @module @d0nj/dsh-browser
10
+ */
11
+ import { constants } from 'node:fs';
12
+ import { access } from 'node:fs/promises';
13
+ import { homedir } from 'node:os';
14
+ import { join } from 'node:path';
15
+ import z from '@deepseek-ai/schemastery';
16
+ import { BrowserHost, resolveUserDataDir } from './host.js';
17
+ import { applyBrowserTool } from './tool.js';
18
+ /** Cordis plugin name — also the profile patch row id. */
19
+ export const name = 'browser';
20
+ /** Services this row relies on. */
21
+ export const inject = ['tools', 'systemPrompt'];
22
+ /** Runtime schema for the browser row. */
23
+ export const Config = z.object({
24
+ toolName: z.string().default('browser').description('Name the tool is registered under.'),
25
+ executablePath: z.string().description('Absolute path to Chrome, Edge, Brave, or Chromium; omit to auto-detect an installed browser.'),
26
+ cdpUrl: z
27
+ .string()
28
+ .description('Attach to a browser already started with --remote-debugging-port instead of launching one; accepts an HTTP origin such as http://127.0.0.1:9222 or a ws:// URL.'),
29
+ headless: z.boolean().default(true).description('Run the launched browser without a visible window; set false to watch it, or to sign in to a site once in the persistent profile.'),
30
+ userDataDir: z.string().description('Chrome profile directory; omit to keep one under the harness home. A persistent profile keeps site logins between sessions.'),
31
+ profile: z.string().default('default').description('Profile name under the harness home; separate names hold separate logins.'),
32
+ width: z.number().default(1280).min(320).max(3840).description('Window and viewport width in CSS pixels.'),
33
+ height: z.number().default(900).min(240).max(2160).description('Window and viewport height in CSS pixels.'),
34
+ dialogs: z.union([z.const('accept'), z.const('dismiss')]).default('accept').description('How alerts, confirms, and prompts are answered.'),
35
+ launchArgs: z.array(z.string()).description('Extra command-line flags for the launched browser.'),
36
+ navigateTimeoutMs: z.number().default(20_000).min(1_000).max(120_000).description('Budget in milliseconds for a navigation to finish loading.'),
37
+ startupTimeoutMs: z.number().default(20_000).min(2_000).max(120_000).description('Budget in milliseconds for Chrome to publish its DevTools endpoint.'),
38
+ maxSnapshotChars: z.number().default(12_000).min(2_000).max(80_000).description('Default character budget for one page outline.'),
39
+ idleCloseSeconds: z.number().default(60).min(0).max(3_600).description('Close the browser this many seconds after the last browser call; 0 keeps it running until the plugin unloads.'),
40
+ });
41
+ /** Environment variable that relocates the harness home, matching `dsh-home-paths`. */
42
+ const DSH_HOME_ENV = 'DSH_HOME';
43
+ /**
44
+ * Resolve the harness home the same way the rest of the Harness does.
45
+ * @param env - environment mapping to read.
46
+ * @returns the absolute harness home.
47
+ */
48
+ export function resolveDshHome(env = process.env) {
49
+ const override = env[DSH_HOME_ENV]?.trim();
50
+ return override !== undefined && override.length > 0 ? override : join(homedir(), '.dsh');
51
+ }
52
+ function integer(value, fallback, min, max) {
53
+ if (value === undefined || !Number.isFinite(value))
54
+ return fallback;
55
+ return Math.min(max, Math.max(min, Math.round(value)));
56
+ }
57
+ /**
58
+ * Resolve and clamp the row's configuration.
59
+ * @param config - validated row configuration.
60
+ * @returns the settings the host and tool use.
61
+ */
62
+ export function resolveSettings(config) {
63
+ const toolName = config.toolName?.trim();
64
+ const cdpUrl = config.cdpUrl?.trim();
65
+ const executablePath = config.executablePath?.trim();
66
+ return {
67
+ toolName: toolName === undefined || toolName === '' ? 'browser' : toolName,
68
+ executablePath: executablePath === undefined || executablePath === '' ? undefined : executablePath,
69
+ cdpUrl: cdpUrl === undefined || cdpUrl === '' ? undefined : cdpUrl,
70
+ userDataDir: resolveUserDataDir(config.userDataDir, resolveDshHome(), config.profile?.trim() === undefined || config.profile.trim() === '' ? 'default' : config.profile.trim()),
71
+ headless: config.headless !== false,
72
+ viewport: {
73
+ width: integer(config.width, 1280, 320, 3840),
74
+ height: integer(config.height, 900, 240, 2160),
75
+ },
76
+ dialogs: config.dialogs === 'dismiss' ? 'dismiss' : 'accept',
77
+ launchArgs: (config.launchArgs ?? []).filter((argument) => argument.trim() !== ''),
78
+ navigateTimeoutMs: integer(config.navigateTimeoutMs, 20_000, 1_000, 120_000),
79
+ startupTimeoutMs: integer(config.startupTimeoutMs, 20_000, 2_000, 120_000),
80
+ maxSnapshotChars: integer(config.maxSnapshotChars, 12_000, 2_000, 80_000),
81
+ idleCloseMs: integer(config.idleCloseSeconds, 60, 0, 3_600) * 1_000,
82
+ };
83
+ }
84
+ async function fileExists(path) {
85
+ try {
86
+ await access(path, constants.F_OK);
87
+ return true;
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ }
93
+ /**
94
+ * Register the browser tool and hand the browser process to the plugin fiber, so
95
+ * disposing the row also stops the Chrome instance this row started.
96
+ * @param ctx - the plugin context.
97
+ * @param config - validated row configuration.
98
+ */
99
+ export function apply(ctx, config) {
100
+ const settings = resolveSettings(config);
101
+ const host = new BrowserHost(settings, {
102
+ logger: ctx.logger(name),
103
+ env: process.env,
104
+ home: homedir(),
105
+ exists: fileExists,
106
+ });
107
+ ctx.effect(() => () => {
108
+ void host.dispose();
109
+ });
110
+ applyBrowserTool(ctx, host, settings);
111
+ }
112
+ //# sourceMappingURL=index.js.map
package/dist/keys.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Key-chord parsing and the CDP key event a chord produces.
3
+ *
4
+ * `Input.dispatchKeyEvent` needs four correlated fields per keystroke — `key`,
5
+ * `code`, `windowsVirtualKeyCode`, and the text the key produces — and Chrome
6
+ * drops the event when they disagree. This table is the single place that
7
+ * mapping lives.
8
+ *
9
+ * @module @d0nj/dsh-browser/keys
10
+ */
11
+ /** CDP modifier bitmask. */
12
+ export declare const MODIFIER: {
13
+ readonly Alt: 1;
14
+ readonly Control: 2;
15
+ readonly Meta: 4;
16
+ readonly Shift: 8;
17
+ };
18
+ /** One modifier name a chord may name. */
19
+ export type ModifierName = keyof typeof MODIFIER;
20
+ /** A resolved keystroke, ready for `Input.dispatchKeyEvent`. */
21
+ export interface KeyStroke {
22
+ /** `KeyboardEvent.key` value. */
23
+ readonly key: string;
24
+ /** `KeyboardEvent.code` value. */
25
+ readonly code: string;
26
+ /** Legacy virtual key code Chrome matches against. */
27
+ readonly keyCode: number;
28
+ /** Text the key inserts, when the chord produces text. */
29
+ readonly text?: string;
30
+ /** Bitmask of held modifiers. */
31
+ readonly modifiers: number;
32
+ }
33
+ /** Thrown for a key name the table does not know. */
34
+ export declare class KeyChordError extends Error {
35
+ constructor(message: string);
36
+ }
37
+ /**
38
+ * Parse a chord such as `Enter`, `Control+A`, or `Meta+Shift+ArrowLeft`.
39
+ * @param chord - the chord text.
40
+ * @returns the keystroke to dispatch.
41
+ */
42
+ export declare function parseKeyChord(chord: string): KeyStroke;
43
+ //# sourceMappingURL=keys.d.ts.map
package/dist/keys.js ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Key-chord parsing and the CDP key event a chord produces.
3
+ *
4
+ * `Input.dispatchKeyEvent` needs four correlated fields per keystroke — `key`,
5
+ * `code`, `windowsVirtualKeyCode`, and the text the key produces — and Chrome
6
+ * drops the event when they disagree. This table is the single place that
7
+ * mapping lives.
8
+ *
9
+ * @module @d0nj/dsh-browser/keys
10
+ */
11
+ /** CDP modifier bitmask. */
12
+ export const MODIFIER = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
13
+ /** Thrown for a key name the table does not know. */
14
+ export class KeyChordError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = 'KeyChordError';
18
+ }
19
+ }
20
+ const NAMED_KEYS = {
21
+ enter: { key: 'Enter', code: 'Enter', keyCode: 13, text: '\r' },
22
+ return: { key: 'Enter', code: 'Enter', keyCode: 13, text: '\r' },
23
+ tab: { key: 'Tab', code: 'Tab', keyCode: 9 },
24
+ escape: { key: 'Escape', code: 'Escape', keyCode: 27 },
25
+ esc: { key: 'Escape', code: 'Escape', keyCode: 27 },
26
+ backspace: { key: 'Backspace', code: 'Backspace', keyCode: 8 },
27
+ delete: { key: 'Delete', code: 'Delete', keyCode: 46 },
28
+ insert: { key: 'Insert', code: 'Insert', keyCode: 45 },
29
+ space: { key: ' ', code: 'Space', keyCode: 32, text: ' ' },
30
+ arrowup: { key: 'ArrowUp', code: 'ArrowUp', keyCode: 38 },
31
+ arrowdown: { key: 'ArrowDown', code: 'ArrowDown', keyCode: 40 },
32
+ arrowleft: { key: 'ArrowLeft', code: 'ArrowLeft', keyCode: 37 },
33
+ arrowright: { key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 },
34
+ up: { key: 'ArrowUp', code: 'ArrowUp', keyCode: 38 },
35
+ down: { key: 'ArrowDown', code: 'ArrowDown', keyCode: 40 },
36
+ left: { key: 'ArrowLeft', code: 'ArrowLeft', keyCode: 37 },
37
+ right: { key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 },
38
+ home: { key: 'Home', code: 'Home', keyCode: 36 },
39
+ end: { key: 'End', code: 'End', keyCode: 35 },
40
+ pageup: { key: 'PageUp', code: 'PageUp', keyCode: 33 },
41
+ pagedown: { key: 'PageDown', code: 'PageDown', keyCode: 34 },
42
+ };
43
+ for (let index = 1; index <= 12; index++) {
44
+ NAMED_KEYS[`f${index}`] = { key: `F${index}`, code: `F${index}`, keyCode: 111 + index };
45
+ }
46
+ /** Punctuation whose `code` is not derivable from the character. */
47
+ const PUNCTUATION = {
48
+ '-': { code: 'Minus', keyCode: 189 },
49
+ '=': { code: 'Equal', keyCode: 187 },
50
+ '[': { code: 'BracketLeft', keyCode: 219 },
51
+ ']': { code: 'BracketRight', keyCode: 221 },
52
+ '\\': { code: 'Backslash', keyCode: 220 },
53
+ ';': { code: 'Semicolon', keyCode: 186 },
54
+ "'": { code: 'Quote', keyCode: 222 },
55
+ ',': { code: 'Comma', keyCode: 188 },
56
+ '.': { code: 'Period', keyCode: 190 },
57
+ '/': { code: 'Slash', keyCode: 191 },
58
+ '`': { code: 'Backquote', keyCode: 192 },
59
+ };
60
+ const MODIFIER_ALIASES = {
61
+ alt: 'Alt',
62
+ option: 'Alt',
63
+ ctrl: 'Control',
64
+ control: 'Control',
65
+ cmd: 'Meta',
66
+ command: 'Meta',
67
+ meta: 'Meta',
68
+ super: 'Meta',
69
+ shift: 'Shift',
70
+ };
71
+ /**
72
+ * Resolve a single key token.
73
+ * @param token - key name or one character.
74
+ * @param shift - whether Shift is held, which selects the shifted glyph.
75
+ * @returns the key specification.
76
+ */
77
+ function resolveToken(token, shift) {
78
+ const named = NAMED_KEYS[token.toLowerCase()];
79
+ if (named !== undefined) {
80
+ return shift && named.key.length === 1 ? { ...named, key: named.key.toUpperCase() } : named;
81
+ }
82
+ if (token.length === 1) {
83
+ const character = shift ? token.toUpperCase() : token.toLowerCase();
84
+ const upper = character.toUpperCase();
85
+ if (upper >= 'A' && upper <= 'Z')
86
+ return { key: character, code: `Key${upper}`, keyCode: upper.charCodeAt(0), text: character };
87
+ if (character >= '0' && character <= '9')
88
+ return { key: character, code: `Digit${character}`, keyCode: character.charCodeAt(0), text: character };
89
+ const punctuation = PUNCTUATION[token];
90
+ if (punctuation !== undefined) {
91
+ return { key: character, code: punctuation.code, keyCode: punctuation.keyCode, text: character };
92
+ }
93
+ }
94
+ throw new KeyChordError(`unknown key "${token}"; use a single character, a name like Enter, Tab, Escape, Backspace, Delete, ArrowUp, Home, End, PageUp, PageDown, Space, F1–F12, or a chord like Control+A`);
95
+ }
96
+ /**
97
+ * Parse a chord such as `Enter`, `Control+A`, or `Meta+Shift+ArrowLeft`.
98
+ * @param chord - the chord text.
99
+ * @returns the keystroke to dispatch.
100
+ */
101
+ export function parseKeyChord(chord) {
102
+ const parts = chord.split('+').map((part) => part.trim());
103
+ const keyToken = parts.pop();
104
+ if (keyToken === undefined || keyToken === '')
105
+ throw new KeyChordError(`"${chord}" names no key`);
106
+ let modifiers = 0;
107
+ for (const part of parts) {
108
+ const modifier = MODIFIER_ALIASES[part.toLowerCase()];
109
+ if (modifier === undefined)
110
+ throw new KeyChordError(`"${part}" in "${chord}" is not a modifier; use Alt, Control, Meta, or Shift`);
111
+ modifiers |= MODIFIER[modifier];
112
+ }
113
+ const shift = (modifiers & MODIFIER.Shift) !== 0;
114
+ const spec = resolveToken(keyToken, shift);
115
+ const textual = spec.text !== undefined && (modifiers & (MODIFIER.Alt | MODIFIER.Control | MODIFIER.Meta)) === 0;
116
+ return {
117
+ key: spec.key,
118
+ code: spec.code,
119
+ keyCode: spec.keyCode,
120
+ modifiers,
121
+ ...(textual ? { text: spec.text } : {}),
122
+ };
123
+ }
124
+ //# sourceMappingURL=keys.js.map