runtime: plugin commands for the command palette (api.commands / scope.commands: register, list, run, owner = the starting plugin, removed on stop, caps, in-page shortcuts); host: start/stop scripts own and drop a plugin's commands; dev_start_script with sourceURL + devError for live reload; devErrors (file:line from a start failure)

This commit is contained in:
CRTkafa 2026-09-29 01:35:44 +07:00
parent cb0f7d358d
commit 2dd782db87
7 changed files with 534 additions and 8 deletions

View file

@ -445,37 +445,69 @@ fn js_string(value: &str) -> Result<String, String> {
/// Wraps a CommonJS-style plugin (`module.exports = class { start() {} stop() {} }`). /// Wraps a CommonJS-style plugin (`module.exports = class { start() {} stop() {} }`).
/// Native code evaluates the result in the site tab, so the page's CSP does not block it. /// Native code evaluates the result in the site tab, so the page's CSP does not block it.
/// ///
/// The module body, construction, `start()` and `stop()` run inside /// Construction and `start()` run inside `api.commands.withOwner(file, ...)` when the runtime has
/// a command registry, so palette commands registered meanwhile belong to this plugin and are
/// removed by [`stop_script`] (or at once when the start fails).
///
/// The module body, construction, `start()` and `stop()` also run inside
/// `window.<global>.withPlugin(id, grants, fn)` when the runtime has it: reads of /// `window.<global>.withPlugin(id, grants, fn)` when the runtime has it: reads of
/// `window.<global>.api` there return the plugin's view for its declared `@permissions` (`grants` /// `window.<global>.api` there return the plugin's view for its declared `@permissions` (`grants`
/// = null for a legacy plugin without the line: the full API). /// = null for a legacy plugin without the line: the full API).
pub fn start_script(host: &PluginHost, file: &str, source: &str) -> Result<String, String> { pub fn start_script(host: &PluginHost, file: &str, source: &str) -> Result<String, String> {
start_script_with(host, file, source, None)
}
/// [`start_script`] for the live-reload developer mode: the evaluated script ends with
/// `//# sourceURL=<prefix><file>` so stack traces name the file and line (line 1 of the file is
/// line 2 of the evaluated script), and a start failure is also handed to the runtime's
/// `devError(id, error)` (which shows it in the page).
pub fn dev_start_script(host: &PluginHost, file: &str, source: &str, source_url_prefix: &str) -> Result<String, String> {
if !source_url_prefix.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_/:.".contains(&b)) {
return Err("VALIDATION: invalid source URL prefix".into());
}
start_script_with(host, file, source, Some(source_url_prefix))
}
/// Line of the evaluated start script on which the plugin file's first line lands.
pub const START_SCRIPT_LINE_OFFSET: u32 = 1;
fn start_script_with(host: &PluginHost, file: &str, source: &str, dev: Option<&str>) -> Result<String, String> {
let id = js_string(file)?; let id = js_string(file)?;
let grants = serde_json::to_string(&parse_meta(file, source).permissions).map_err(|_| "PLUGINS: serialization failed")?; let grants = serde_json::to_string(&parse_meta(file, source).permissions).map_err(|_| "PLUGINS: serialization failed")?;
let PluginHost { runtime_global: global, origin, product, .. } = host; let PluginHost { runtime_global: global, origin, product, .. } = host;
// Only a valid file name (letters, digits, `_-. `) reaches the comment.
let source_url = match dev {
Some(prefix) if valid_file_name(file) => format!("\n//# sourceURL={prefix}{}", file.replace(' ', "%20")),
_ => String::new(),
};
let on_error = if dev.is_some() { "if(typeof XW.devError==='function')XW.devError(id,e);" } else { "" };
Ok(format!( Ok(format!(
"(()=>{{const XW=window.{global};if(!XW||window.top!==window||location.origin!=='{origin}')return;\ "(()=>{{const XW=window.{global};if(!XW||window.top!==window||location.origin!=='{origin}')return;\
const id={id};if(XW.plugins[id])return;\ const id={id};if(XW.plugins[id])return;\
const as=f=>typeof XW.withPlugin==='function'?XW.withPlugin(id,{grants},f):f();\ const C=XW.api&&XW.api.commands;const as=f=>typeof XW.withPlugin==='function'?XW.withPlugin(id,{grants},f):f();\
const own=f=>as(()=>C&&typeof C.withOwner==='function'?C.withOwner(id,f):f());\
try{{const module={{exports:{{}}}};const exports=module.exports;\ try{{const module={{exports:{{}}}};const exports=module.exports;\
as(()=>{{(function(module,exports){{\n{source}\n}})(module,exports);}});\ as(()=>{{(function(module,exports){{\n{source}\n}})(module,exports);}});\
let P=module.exports&&module.exports.default?module.exports.default:module.exports;\ let P=module.exports&&module.exports.default?module.exports.default:module.exports;\
const inst=as(()=>typeof P==='function'?(P.prototype&&(P.prototype.start||P.prototype.stop)?new P():P()):P);\ const inst=own(()=>typeof P==='function'?(P.prototype&&(P.prototype.start||P.prototype.stop)?new P():P()):P);\
XW.plugins[id]=inst||{{}};delete XW.errors[id];if(inst&&typeof inst.start==='function')as(()=>inst.start());\ XW.plugins[id]=inst||{{}};delete XW.errors[id];if(inst&&typeof inst.start==='function')own(()=>inst.start());\
console.info('[{product}] started',id);}}\ console.info('[{product}] started',id);}}\
catch(e){{XW.errors[id]=String(e&&e.stack||e);console.error('[{product}] plugin failed',id,e);}}}})();" catch(e){{XW.errors[id]=String(e&&e.stack||e);if(C&&typeof C.removeOwner==='function')C.removeOwner(id);{on_error}\
console.error('[{product}] plugin failed',id,e);}}}})();{source_url}"
)) ))
} }
/// Stops a plugin; whatever palette commands it forgot to unregister go with it.
pub fn stop_script(host: &PluginHost, file: &str) -> Result<String, String> { pub fn stop_script(host: &PluginHost, file: &str) -> Result<String, String> {
let id = js_string(file)?; let id = js_string(file)?;
let PluginHost { runtime_global: global, product, .. } = host; let PluginHost { runtime_global: global, product, .. } = host;
Ok(format!( Ok(format!(
"(()=>{{const XW=window.{global};if(!XW)return;const id={id};const p=XW.plugins[id];\ "(()=>{{const XW=window.{global};if(!XW)return;const id={id};const p=XW.plugins[id];\
if(!p)return;delete XW.plugins[id];\ const C=XW.api&&XW.api.commands;const drop=()=>{{if(C&&typeof C.removeOwner==='function')C.removeOwner(id);}};\
if(!p){{drop();return;}}delete XW.plugins[id];\
const as=f=>typeof XW.withPlugin==='function'?XW.withPlugin(id,undefined,f):f();\ const as=f=>typeof XW.withPlugin==='function'?XW.withPlugin(id,undefined,f):f();\
try{{if(typeof p.stop==='function')as(()=>p.stop());console.info('[{product}] stopped',id);}}\ try{{if(typeof p.stop==='function')as(()=>p.stop());console.info('[{product}] stopped',id);}}\
catch(e){{console.error('[{product}] plugin stop failed',id,e);}}}})();" catch(e){{console.error('[{product}] plugin stop failed',id,e);}}drop();}})();"
)) ))
} }
@ -571,6 +603,31 @@ mod tests {
assert!(css.contains("const id='demo-css'") && css.contains(r#"s.textContent="</style><script>";"#)); assert!(css.contains("const id='demo-css'") && css.contains(r#"s.textContent="</style><script>";"#));
} }
#[test]
fn palette_commands_belong_to_the_plugin_and_go_when_it_stops() {
let start = start_script(&HOST, "focus.plugin.js", "module.exports = class { start(){} };").unwrap();
// Construction and start() run with the plugin as the commands' owner.
assert!(start.contains("C.withOwner(id,f)") && start.contains("own(()=>inst.start())"));
// A failed start drops whatever it registered before throwing.
assert!(start.contains("catch(e){XW.errors[id]=String(e&&e.stack||e);if(C&&typeof C.removeOwner==='function')C.removeOwner(id);"));
assert!(!start.contains("sourceURL") && !start.contains("devError"));
let stop = stop_script(&HOST, "focus.plugin.js").unwrap();
// Removed after stop(), and also when the plugin was not running (a failed start).
assert!(stop.contains("if(!p){drop();return;}") && stop.ends_with("drop();})();"));
}
#[test]
fn dev_start_script_names_the_file_for_stack_traces() {
let source = "module.exports = class {\n start(){ throw new Error('x'); }\n};";
let dev = dev_start_script(&HOST, "My Plugin.plugin.js", source, "wb-dev/").unwrap();
assert!(dev.ends_with("\n//# sourceURL=wb-dev/My%20Plugin.plugin.js"));
assert!(dev.contains("XW.devError(id,e)"));
// The file's first line is line 1 + START_SCRIPT_LINE_OFFSET of the evaluated script.
let first = dev.lines().position(|line| line == "module.exports = class {").unwrap() as u32;
assert_eq!(first, START_SCRIPT_LINE_OFFSET);
assert!(dev_start_script(&HOST, "a.plugin.js", source, "x\n//# evil").is_err());
}
#[test] #[test]
fn permissions_header_is_parsed_strictly() { fn permissions_header_is_parsed_strictly() {
assert_eq!(parse_permissions("storage, ui clipboard,UI").unwrap(), vec!["storage", "ui", "clipboard"]); assert_eq!(parse_permissions("storage, ui clipboard,UI").unwrap(), vec!["storage", "ui", "clipboard"]);

View file

@ -0,0 +1,227 @@
// Plugin commands for the shell's command palette (Ctrl+K).
//
// A plugin registers `{ id, title, keywords, shortcut?, run }` with `api.commands.register` (or
// `scope.commands.register`, removed on dispose). The registry is local to the page: the runtime
// reports `list()` (ids, titles and keywords only, capped) about this tab to the host, and the
// shell asks this tab to `run(id)` when the user picks one in the palette. `run` always executes
// here, in the plugin's own page; nothing crosses to the shell but these strings.
//
// Every command belongs to the plugin that registered it: the host starts a plugin inside
// `withOwner(file, ...)`, and stopping the plugin removes all of its commands (`removeOwner`), so
// a plugin that forgets to unregister cannot leave a dead entry in the palette.
export type Dispose = () => void;
export type CommandDefinition = {
/** Unique within the plugin: letters, digits, `.`, `_`, `-`, 1–64 characters. */
id: string;
/** Shown in the palette (at most 80 characters are kept). */
title: string;
/** Extra words the palette matches (string or list; at most 160 characters are kept). */
keywords?: string | readonly string[];
/** Optional in-page shortcut such as `Alt+Shift+F` (works while this page has focus, not while typing). */
shortcut?: string;
run: () => unknown;
};
/** What the palette sees of a command: strings only. `id` is `<owner>:<command id>`. */
export type CommandInfo = { id: string; title: string; keywords: string };
export const COMMAND_LIMITS = Object.freeze({
/** Commands one plugin may register. */
perOwner: 16,
/** Commands one page may report. */
total: 48,
id: 64,
title: 80,
keywords: 160,
owner: 128,
});
/** Owner of commands registered outside any plugin start (e.g. later, from a timer). */
export const NO_OWNER = '_';
const COMMAND_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
/** Plugin file names (the host's `valid_file_name`) and `_`. */
const OWNER_ID = /^(?:_|[A-Za-z0-9_\- ][A-Za-z0-9_.\- ]{0,127})$/;
const clean = (value: string, max: number) =>
// eslint-disable-next-line no-control-regex
value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
export type Shortcut = { key: string; ctrl: boolean; alt: boolean; shift: boolean; meta: boolean };
/** Parses `Ctrl+Alt+Shift+Meta+<key>` (case-insensitive; `Cmd`/`Mod` = Meta/Ctrl). Null when invalid. */
export function parseShortcut(value: unknown): Shortcut | null {
if (typeof value !== 'string' || value.length > 40) return null;
const parts = value.split('+').map(part => part.trim()).filter(Boolean);
if (!parts.length) return null;
const shortcut: Shortcut = { key: '', ctrl: false, alt: false, shift: false, meta: false };
for (const [index, raw] of parts.entries()) {
const part = raw.toLowerCase();
const last = index === parts.length - 1;
if (!last) {
if (part === 'ctrl' || part === 'control' || part === 'mod') shortcut.ctrl = true;
else if (part === 'alt' || part === 'option') shortcut.alt = true;
else if (part === 'shift') shortcut.shift = true;
else if (part === 'meta' || part === 'cmd' || part === 'command') shortcut.meta = true;
else return null;
continue;
}
if (!/^(?:[a-z0-9]|f(?:[1-9]|1[0-2])|arrow(?:up|down|left|right)|enter|escape|space|[[\]\\;',./`=-])$/.test(part)) return null;
shortcut.key = part;
}
return shortcut.key ? shortcut : null;
}
/** Whether a keydown matches a parsed shortcut. Letters and digits match by physical key too. */
export function matchesShortcut(event: Pick<KeyboardEvent, 'key' | 'code' | 'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey'>, shortcut: Shortcut): boolean {
if (event.ctrlKey !== shortcut.ctrl || event.altKey !== shortcut.alt || event.shiftKey !== shortcut.shift || event.metaKey !== shortcut.meta) return false;
const key = shortcut.key;
if (/^[a-z]$/.test(key)) return event.code === `Key${key.toUpperCase()}` || event.key.toLowerCase() === key;
if (/^[0-9]$/.test(key)) return event.code === `Digit${key}` || event.key === key;
if (key === 'space') return event.key === ' ' || event.code === 'Space';
return event.key.toLowerCase() === key;
}
export type CommandRegistry = {
/** Registers a command for the current owner; returns its disposer. Throws on invalid input or caps. */
register(definition: CommandDefinition): Dispose;
/** The palette's view of every command (strings only), in registration order. */
list(): CommandInfo[];
/** Runs `<owner>:<id>` in this page. False when there is no such command. */
run(id: string): boolean;
/** Calls `callback(list())` after commands change (batched), until disposed. */
onChange(callback: (list: CommandInfo[]) => void): Dispose;
/** Host hook: runs `fn` with `owner` as the owner of commands registered meanwhile. */
withOwner<T>(owner: string, fn: () => T): T;
/** Host hook: removes every command of `owner` (called after a plugin stops). */
removeOwner(owner: string): void;
};
/** Registry internals the plugin API needs (not handed to plugins). */
export type CommandRegistryInternal = CommandRegistry & {
/** The owner commands registered right now would get. */
currentOwner(): string;
/** Registers for an explicit owner (a scope remembers the plugin that created it). */
registerFor(owner: string, definition: CommandDefinition): Dispose;
};
type Entry = { owner: string; id: string; title: string; keywords: string; shortcut: Shortcut | null; run: () => unknown };
export type CommandEnv = {
/** Where shortcut keydowns are listened to (the page's document). */
target?: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>;
/** True while the user types (no shortcut then). */
isTyping?: (event: KeyboardEvent) => boolean;
/** Batches change notifications; defaults to a microtask. */
schedule?: (fn: () => void) => void;
report?: (error: unknown) => void;
};
export function createCommandRegistry(env: CommandEnv = {}): CommandRegistryInternal {
const entries: Entry[] = [];
const listeners = new Set<(list: CommandInfo[]) => void>();
const report = env.report ?? ((error: unknown) => console.error('[wayBetter] command failed', error));
const schedule = env.schedule ?? ((fn: () => void) => { void Promise.resolve().then(fn); });
const owners: string[] = [];
let pending = false;
let keyListening = false;
const info = (entry: Entry): CommandInfo => ({ id: `${entry.owner}:${entry.id}`, title: entry.title, keywords: entry.keywords });
const list = () => entries.map(info);
const changed = () => {
syncKeys();
if (pending) return;
pending = true;
schedule(() => {
pending = false;
const snapshot = list();
for (const listener of [...listeners]) {
try { listener(snapshot); } catch (error) { report(error); }
}
});
};
const invoke = (entry: Entry) => {
try {
const result = entry.run();
if (result && typeof (result as Promise<unknown>).then === 'function') (result as Promise<unknown>).then(undefined, report);
} catch (error) { report(error); }
};
const onKeyDown = (event: Event) => {
const key = event as KeyboardEvent;
if (key.defaultPrevented || key.repeat || env.isTyping?.(key)) return;
const entry = entries.find(item => item.shortcut && matchesShortcut(key, item.shortcut));
if (!entry) return;
key.preventDefault();
key.stopPropagation();
invoke(entry);
};
function syncKeys() {
const wanted = !!env.target && entries.some(entry => entry.shortcut);
if (wanted === keyListening) return;
keyListening = wanted;
if (wanted) env.target!.addEventListener('keydown', onKeyDown, true);
else env.target!.removeEventListener('keydown', onKeyDown, true);
}
const currentOwner = () => owners[owners.length - 1] ?? NO_OWNER;
function registerFor(owner: string, definition: CommandDefinition): Dispose {
if (typeof owner !== 'string' || !OWNER_ID.test(owner)) throw new Error('commands.register: invalid owner');
if (!definition || typeof definition !== 'object') throw new Error('commands.register: expected { id, title, run }');
const { id, title, keywords, shortcut, run } = definition;
if (typeof id !== 'string' || !COMMAND_ID.test(id)) throw new Error(`commands.register: invalid id ${JSON.stringify(id)} (letters, digits, . _ -, at most ${COMMAND_LIMITS.id})`);
if (typeof run !== 'function') throw new Error('commands.register: run must be a function');
const shownTitle = typeof title === 'string' ? clean(title, COMMAND_LIMITS.title) : '';
if (!shownTitle) throw new Error('commands.register: title is required');
const words = typeof keywords === 'string' ? keywords : Array.isArray(keywords) ? keywords.filter(word => typeof word === 'string').join(' ') : '';
const parsed = shortcut === undefined ? null : parseShortcut(shortcut);
if (shortcut !== undefined && !parsed) throw new Error(`commands.register: invalid shortcut ${JSON.stringify(shortcut)}`);
const existing = entries.findIndex(entry => entry.owner === owner && entry.id === id);
if (existing < 0) {
if (entries.filter(entry => entry.owner === owner).length >= COMMAND_LIMITS.perOwner) throw new Error(`commands.register: at most ${COMMAND_LIMITS.perOwner} commands per plugin`);
if (entries.length >= COMMAND_LIMITS.total) throw new Error(`commands.register: at most ${COMMAND_LIMITS.total} commands per page`);
}
const entry: Entry = { owner, id, title: shownTitle, keywords: clean(words, COMMAND_LIMITS.keywords), shortcut: parsed, run: run as () => unknown };
// Registering the same id again replaces the command in place (a plugin reloading its settings).
if (existing >= 0) entries.splice(existing, 1, entry); else entries.push(entry);
changed();
return () => {
const index = entries.indexOf(entry);
if (index < 0) return;
entries.splice(index, 1);
changed();
};
}
return {
register: definition => registerFor(currentOwner(), definition),
registerFor,
currentOwner,
list,
run(fullId) {
if (typeof fullId !== 'string') return false;
const entry = entries.find(item => `${item.owner}:${item.id}` === fullId);
if (!entry) return false;
invoke(entry);
return true;
},
onChange(callback) {
listeners.add(callback);
return () => { listeners.delete(callback); };
},
withOwner(owner, fn) {
if (typeof owner !== 'string' || !OWNER_ID.test(owner)) return fn();
owners.push(owner);
try { return fn(); } finally { owners.pop(); }
},
removeOwner(owner) {
let removed = false;
for (let index = entries.length - 1; index >= 0; index -= 1) {
if (entries[index]!.owner === owner) { entries.splice(index, 1); removed = true; }
}
if (removed) changed();
},
};
}

View file

@ -0,0 +1,34 @@
// Live-reload developer mode: where a plugin's start failure happened, for the in-page error toast.
//
// The host evaluates a plugin with `//# sourceURL=<prefix><file>` (waybetter-host
// `dev_start_script`), so V8/JavaScriptCore stack frames name that URL with the line and column
// of the evaluated script; the plugin file's line 1 is line `1 + lineOffset` there.
export type DevErrorLocation = { file: string; line: number | null; column: number | null; message: string };
/** Default prefix the host uses for plugin source URLs. */
export const DEV_SOURCE_PREFIX = 'wb-dev/';
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/**
* The first stack frame inside `file` (evaluated as `<prefix><file>`), mapped back to the file's
* own line numbers. Line is null when no frame names the file (e.g. an error thrown from a timer
* in other code). The message is one line, at most 300 characters.
*/
export function devErrorLocation(error: unknown, file: string, prefix = DEV_SOURCE_PREFIX, lineOffset = 1): DevErrorLocation {
const text = error instanceof Error ? error.message : String(error);
const message = `${error instanceof Error && error.name && error.name !== 'Error' ? `${error.name}: ` : ''}${text}`.split('\n')[0]!.slice(0, 300);
const stack = error instanceof Error && typeof error.stack === 'string' ? error.stack : '';
const url = `${prefix}${file.replace(/ /g, '%20')}`;
const match = new RegExp(`${escapeRegExp(url)}:(\\d+):(\\d+)`).exec(stack);
if (!match) return { file, line: null, column: null, message };
const line = Number(match[1]) - lineOffset;
return { file, line: line >= 1 ? line : null, column: Number(match[2]), message };
}
/** `file:line:column — message` (parts that are unknown are left out). */
export function formatDevError(location: DevErrorLocation): string {
const where = location.line ? `${location.file}:${location.line}${location.column ? `:${location.column}` : ''}` : location.file;
return `${where} — ${location.message}`;
}

View file

@ -8,8 +8,9 @@
import { createThemeApi, type ThemeApi, type ThemeSource } from './themeApi.ts'; import { createThemeApi, type ThemeApi, type ThemeSource } from './themeApi.ts';
import { createUiKit, type UiKit } from './ui.ts'; import { createUiKit, type UiKit } from './ui.ts';
import { createCommandRegistry, type CommandDefinition, type CommandInfo, type CommandRegistry } from './commands.ts';
export type { ThemeApi, ThemeSource, UiKit }; export type { ThemeApi, ThemeSource, UiKit, CommandDefinition, CommandInfo, CommandRegistry };
export type Dispose = () => void; export type Dispose = () => void;
@ -36,6 +37,8 @@ export type PluginScope = {
onThemeChange(callback: Parameters<ThemeApi['onChange']>[0]): void; onThemeChange(callback: Parameters<ThemeApi['onChange']>[0]): void;
/** The UI kit, scoped: dialogs and toasts it opened are closed on dispose. */ /** The UI kit, scoped: dialogs and toasts it opened are closed on dispose. */
readonly ui: UiKit; readonly ui: UiKit;
/** Command palette entries of the plugin that created this scope, removed on dispose. */
readonly commands: { register(definition: CommandDefinition): Dispose };
dispose(): void; dispose(): void;
}; };
@ -61,6 +64,11 @@ export type CorePluginApi = {
ui: UiKit; ui: UiKit;
/** The active theme as values: `current()` and `onChange(fn)` (see themeApi.ts). */ /** The active theme as values: `current()` and `onChange(fn)` (see themeApi.ts). */
theme: ThemeApi; theme: ThemeApi;
/**
* Commands in the shell's command palette (Ctrl+K), listed under the plugin's name and run in
* this page (see commands.ts). Removed when the plugin stops.
*/
commands: CommandRegistry;
scope(): PluginScope; scope(): PluginScope;
}; };
@ -118,6 +126,15 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
}); });
const styleNodes = new Map<string, HTMLStyleElement>(); const styleNodes = new Map<string, HTMLStyleElement>();
const report = (error: unknown) => console.error(`[${site.product}] plugin callback failed`, error); const report = (error: unknown) => console.error(`[${site.product}] plugin callback failed`, error);
const registry = createCommandRegistry({ target: doc, isTyping: event => isTypingTarget(event.target) || isTypingTarget(doc.activeElement), report });
const commands: CommandRegistry = Object.freeze({
register: registry.register,
list: registry.list,
run: registry.run,
onChange: registry.onChange,
withOwner: registry.withOwner,
removeOwner: registry.removeOwner,
});
const routeListeners = new Set<(href: string, previous: string) => void>(); const routeListeners = new Set<(href: string, previous: string) => void>();
let lastHref = win.location.href; let lastHref = win.location.href;
@ -271,9 +288,12 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
}, },
ui, ui,
theme, theme,
commands,
scope() { scope() {
let disposers: Dispose[] = []; let disposers: Dispose[] = [];
let scopedUi: UiKit | null = null; let scopedUi: UiKit | null = null;
// A scope belongs to the plugin being started when it is created (usually in start()).
const owner = registry.currentOwner();
return { return {
css(id, css) { css(id, css) {
api.injectCSS(id, css); api.injectCSS(id, css);
@ -310,6 +330,13 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
} }
return scopedUi; return scopedUi;
}, },
commands: Object.freeze({
register(definition: CommandDefinition) {
const dispose = registry.registerFor(owner, definition);
disposers.push(dispose);
return dispose;
},
}),
dispose() { dispose() {
const pending = disposers.reverse(); const pending = disposers.reverse();
disposers = []; disposers = [];

View file

@ -0,0 +1,146 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { COMMAND_LIMITS, NO_OWNER, createCommandRegistry, matchesShortcut, parseShortcut } from '../src/commands.ts';
import { createCorePluginApi, type PluginApiSite } from '../src/pluginApi.ts';
const sync = { schedule: (fn: () => void) => fn() };
test('commands belong to the plugin being started and are listed as strings only', () => {
const registry = createCommandRegistry(sync);
let ran = 0;
registry.withOwner('bt-focus-mode.plugin.js', () => {
registry.register({ id: 'toggle', title: ' Focus Mode:\ntoggle ', keywords: ['distraction', 'hide', 42 as unknown as string], run: () => { ran += 1; } });
});
registry.register({ id: 'later', title: 'Registered later', run: () => {} });
assert.deepEqual(registry.list(), [
{ id: 'bt-focus-mode.plugin.js:toggle', title: 'Focus Mode: toggle', keywords: 'distraction hide' },
{ id: `${NO_OWNER}:later`, title: 'Registered later', keywords: '' },
]);
for (const info of registry.list()) assert.deepEqual(Object.keys(info).sort(), ['id', 'keywords', 'title']);
assert.equal(registry.run('bt-focus-mode.plugin.js:toggle'), true);
assert.equal(ran, 1);
assert.equal(registry.run('bt-focus-mode.plugin.js:missing'), false);
assert.equal(registry.run('toggle'), false, 'the owner is part of the id');
});
test('stopping a plugin removes its commands; others stay', () => {
const registry = createCommandRegistry(sync);
const seen: number[] = [];
registry.onChange(list => seen.push(list.length));
registry.withOwner('a.plugin.js', () => { registry.register({ id: 'one', title: 'One', run() {} }); registry.register({ id: 'two', title: 'Two', run() {} }); });
registry.withOwner('b.plugin.js', () => registry.register({ id: 'one', title: 'B one', run() {} }));
registry.removeOwner('a.plugin.js');
assert.deepEqual(registry.list().map(item => item.id), ['b.plugin.js:one']);
assert.deepEqual(seen, [1, 2, 3, 1]);
registry.removeOwner('nobody.plugin.js');
assert.equal(seen.length, 4, 'no change, no notification');
});
test('disposers, re-registration and caps', () => {
const registry = createCommandRegistry(sync);
const dispose = registry.withOwner('a.plugin.js', () => registry.register({ id: 'x', title: 'X', run() {} }));
registry.withOwner('a.plugin.js', () => registry.register({ id: 'x', title: 'X again', run() {} }));
assert.deepEqual(registry.list().map(item => item.title), ['X again'], 'same id replaces in place');
dispose();
assert.equal(registry.list().length, 1, 'a stale disposer does not remove the replacement');
registry.removeOwner('a.plugin.js');
registry.withOwner('a.plugin.js', () => {
for (let i = 0; i < COMMAND_LIMITS.perOwner; i += 1) registry.register({ id: `c${i}`, title: `C${i}`, run() {} });
assert.throws(() => registry.register({ id: 'overflow', title: 'Overflow', run() {} }), /per plugin/);
});
for (let owner = 0; registry.list().length < COMMAND_LIMITS.total; owner += 1) {
registry.withOwner(`p${owner}.plugin.js`, () => {
for (let i = 0; i < COMMAND_LIMITS.perOwner && registry.list().length < COMMAND_LIMITS.total; i += 1) registry.register({ id: `c${i}`, title: 'T', run() {} });
});
}
assert.throws(() => registry.withOwner('z.plugin.js', () => registry.register({ id: 'one', title: 'One', run() {} })), /per page/);
const fresh = createCommandRegistry(sync);
for (const bad of [
{ id: '', title: 'T', run() {} },
{ id: 'has space', title: 'T', run() {} },
{ id: 'x'.repeat(65), title: 'T', run() {} },
{ id: 'ok', title: ' ', run() {} },
{ id: 'ok', title: 'T', run: 'nope' },
{ id: 'ok', title: 'T', shortcut: 'Hyper+Q', run() {} },
]) assert.throws(() => fresh.register(bad as never));
fresh.register({ id: 'long', title: 't'.repeat(500), keywords: 'k'.repeat(500), run() {} });
const [long] = fresh.list();
assert.equal(long!.title.length, COMMAND_LIMITS.title);
assert.equal(long!.keywords.length, COMMAND_LIMITS.keywords);
assert.throws(() => fresh.withOwner('bad/owner', () => fresh.registerFor('bad/owner', { id: 'a', title: 'A', run() {} })), /owner/);
});
test('a failing command reports and never throws into the caller', async () => {
const errors: unknown[] = [];
const registry = createCommandRegistry({ ...sync, report: error => errors.push(error) });
registry.register({ id: 'boom', title: 'Boom', run() { throw new Error('boom'); } });
registry.register({ id: 'async', title: 'Async', run: async () => { throw new Error('later'); } });
assert.equal(registry.run('_:boom'), true);
assert.equal(registry.run('_:async'), true);
await new Promise(resolve => setTimeout(resolve, 0));
assert.equal(errors.length, 2);
});
test('shortcuts parse strictly and match physical keys; typing and repeats never run them', () => {
assert.deepEqual(parseShortcut('Alt+Shift+F'), { key: 'f', ctrl: false, alt: true, shift: true, meta: false });
assert.equal(parseShortcut('Ctrl+'), null);
assert.equal(parseShortcut('Ctrl+Shift'), null);
assert.equal(parseShortcut('Ctrl+Enter')?.key, 'enter');
const ev = (over: Partial<KeyboardEvent>) => ({ key: '', code: '', ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, ...over });
const altShiftF = parseShortcut('alt+shift+f')!;
assert.ok(matchesShortcut(ev({ key: 'Ï', code: 'KeyF', altKey: true, shiftKey: true }), altShiftF), 'Alt changes the character on macOS');
assert.ok(!matchesShortcut(ev({ key: 'F', code: 'KeyF', shiftKey: true }), altShiftF));
const listeners = new Map<string, (event: Event) => void>();
const target = { addEventListener: (type: string, fn: EventListenerOrEventListenerObject) => listeners.set(type, fn as (event: Event) => void), removeEventListener: (type: string) => listeners.delete(type) };
let typing = false;
let ran = 0;
const registry = createCommandRegistry({ ...sync, target, isTyping: () => typing });
assert.equal(listeners.size, 0, 'no key listener without a shortcut');
const dispose = registry.register({ id: 'f', title: 'F', shortcut: 'Alt+Shift+F', run: () => { ran += 1; } });
const press = (over: Record<string, unknown>) => {
let prevented = false;
listeners.get('keydown')!({ key: 'F', code: 'KeyF', ctrlKey: false, altKey: true, shiftKey: true, metaKey: false, repeat: false, defaultPrevented: false, preventDefault: () => { prevented = true; }, stopPropagation() {}, ...over } as unknown as Event);
return prevented;
};
assert.equal(press({}), true);
press({ repeat: true });
typing = true; press({}); typing = false;
assert.equal(ran, 1);
dispose();
assert.equal(listeners.size, 0, 'listener removed with the last shortcut');
});
const SITE: PluginApiSite = {
name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo-plugin:', styleDataKey: 'demoPlugin',
toastId: 'demo-toast', toastBackground: '#111', itemSelector: 'article', chordKeys: [],
};
function fakeWindow() {
const target = { addEventListener() {}, removeEventListener() {} };
const doc = { ...target, activeElement: null, documentElement: {}, head: { appendChild() {} }, querySelectorAll: () => [], createElement: () => ({ dataset: {}, remove() {} }) };
return { ...target, document: doc, location: { href: 'https://site.test/' }, localStorage: null, requestAnimationFrame: () => 1, cancelAnimationFrame() {}, MutationObserver: class { observe() {} disconnect() {} } } as unknown as Window & typeof globalThis;
}
test('api.commands and scope.commands: a scope keeps its plugin and removes its commands on dispose', async () => {
const api = createCorePluginApi(fakeWindow(), SITE);
assert.ok(Object.isFrozen(api.commands));
// As the host's start script does: construct + start() inside withOwner.
const scope = api.commands.withOwner('bt-thread-reader.plugin.js', () => {
const created = api.scope();
created.commands.register({ id: 'open', title: 'Thread Reader: open', run() {} });
return created;
});
// Registered later (e.g. after an await) through the scope: still the same plugin.
scope.commands.register({ id: 'settings', title: 'Thread Reader: settings', run() {} });
api.commands.register({ id: 'loose', title: 'Loose', run() {} });
assert.deepEqual(api.commands.list().map(item => item.id), ['bt-thread-reader.plugin.js:open', 'bt-thread-reader.plugin.js:settings', '_:loose']);
const lists: string[][] = [];
api.commands.onChange(list => lists.push(list.map(item => item.id)));
scope.dispose();
await Promise.resolve();
assert.deepEqual(api.commands.list().map(item => item.id), ['_:loose']);
assert.deepEqual(lists, [['_:loose']], 'one batched change for the whole dispose');
});

View file

@ -0,0 +1,27 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { devErrorLocation, formatDevError } from '../src/devErrors.ts';
test('a start failure is mapped back to the plugin file line (evaluated with a sourceURL)', () => {
// What the host evaluates: one wrapper line, then the file (dev_start_script, START_SCRIPT_LINE_OFFSET = 1).
const file = 'My Plugin.plugin.js';
const source = 'module.exports = class {\n start() {\n null.boom;\n }\n};';
let caught: unknown;
try {
// eslint-disable-next-line no-eval
const Plugin = (0, eval)(`(function(){const module={exports:{}};(function(module){\n${source}\n})(module);return module.exports;})\n//# sourceURL=wb-dev/My%20Plugin.plugin.js`)();
new Plugin().start();
} catch (error) { caught = error; }
assert.ok(caught instanceof TypeError);
const location = devErrorLocation(caught, file);
assert.equal(location.line, 3, 'line 3 of the file, not of the wrapper');
assert.ok(location.column && location.column > 0);
assert.match(formatDevError(location), /^My Plugin\.plugin\.js:3:\d+ — TypeError: /);
});
test('errors without a frame in the file keep the file name and a one-line message', () => {
const location = devErrorLocation('bad\nsecond line', 'a.plugin.js');
assert.deepEqual(location, { file: 'a.plugin.js', line: null, column: null, message: 'bad' });
assert.equal(formatDevError(location), 'a.plugin.js — bad');
assert.equal(devErrorLocation(new Error('x'.repeat(1000)), 'a.plugin.js').message.length, 300);
});

View file

@ -32,6 +32,14 @@
"types": "./dist/runtime/column.d.ts", "types": "./dist/runtime/column.d.ts",
"import": "./dist/runtime/column.js" "import": "./dist/runtime/column.js"
}, },
"./runtime/commands": {
"types": "./dist/runtime/commands.d.ts",
"import": "./dist/runtime/commands.js"
},
"./runtime/devErrors": {
"types": "./dist/runtime/devErrors.d.ts",
"import": "./dist/runtime/devErrors.js"
},
"./runtime/domHub": { "./runtime/domHub": {
"types": "./dist/runtime/domHub.d.ts", "types": "./dist/runtime/domHub.d.ts",
"import": "./dist/runtime/domHub.js" "import": "./dist/runtime/domHub.js"