From 1486f31a660085a65cc71586c4321c99197af362 Mon Sep 17 00:00:00 2001 From: CRT Date: Mon, 28 Sep 2026 21:40:51 +0700 Subject: [PATCH 01/42] host: place child webviews on Linux in a GtkOverlay over the shell tauri 2 (runtime-wry build_gtk with the window's GtkBox) packs every child webview into the window box, stacked and with set_position/set_size ignored, so tab webviews landed under the shell instead of over their panes. place_child/attach_shell move them into a GtkOverlay (shell as base layer) and allocate each at its exact rect via get-child-position; placed_rect reports the placement (GTK children have no position). Windows/macOS keep set_position/set_size. Co-Authored-By: Claude Opus 5.5 --- crates/waybetter-host/Cargo.lock | 1 + crates/waybetter-host/Cargo.toml | 6 +- crates/waybetter-host/src/host.rs | 97 +++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 1 deletion(-) diff --git a/crates/waybetter-host/Cargo.lock b/crates/waybetter-host/Cargo.lock index 0e05bdd..7803c2c 100644 --- a/crates/waybetter-host/Cargo.lock +++ b/crates/waybetter-host/Cargo.lock @@ -3807,6 +3807,7 @@ version = "0.1.0" dependencies = [ "base64 0.22.1", "chrono", + "gtk", "minisign-verify", "serde", "serde_json", diff --git a/crates/waybetter-host/Cargo.toml b/crates/waybetter-host/Cargo.toml index 365c53b..339ba98 100644 --- a/crates/waybetter-host/Cargo.toml +++ b/crates/waybetter-host/Cargo.toml @@ -14,7 +14,7 @@ path = "src/lib.rs" [features] default = [] # Tauri glue (webview helpers, window system menu). Off for headless tests. -tauri = ["dep:tauri", "dep:windows", "dep:webview2-com"] +tauri = ["dep:tauri", "dep:windows", "dep:webview2-com", "dep:gtk"] [dependencies] serde = { version = "1", features = ["derive"] } @@ -31,5 +31,9 @@ windows = { version = "0.62", features = ["Win32_Foundation", "Win32_UI_WindowsA # The WebView2 COM interfaces wry already links (hidden tabs: low memory target). webview2-com = { version = "0.39", optional = true } +[target.'cfg(target_os = "linux")'.dependencies] +# The GTK version tauri/wry link: child webviews are laid out in a GtkOverlay (host::place_child). +gtk = { version = "0.18", optional = true } + [dev-dependencies] tempfile = "3" diff --git a/crates/waybetter-host/src/host.rs b/crates/waybetter-host/src/host.rs index 1127b03..b61d15a 100644 --- a/crates/waybetter-host/src/host.rs +++ b/crates/waybetter-host/src/host.rs @@ -185,6 +185,103 @@ pub fn system_menu(webview: &Webview, x: f64, y: f64) -> Result<( Ok(()) } +/// Places a child webview (tab, popover) at a rectangle of its window, in logical px. +/// +/// Windows/macOS: the native child bounds. Linux: tauri 2 packs every child webview into the +/// window's GtkBox (`build_gtk` with a box: stacked one under another, bounds ignored), so the host +/// moves each one into the GtkOverlay made by [`attach_shell`] and places it there. +pub fn place_child(webview: &Webview, x: f64, y: f64, width: f64, height: f64) { + #[cfg(target_os = "linux")] + linux::place(webview, x, y, width, height); + #[cfg(not(target_os = "linux"))] + { + let _ = webview.set_position(tauri::LogicalPosition::new(x, y)); + let _ = webview.set_size(tauri::LogicalSize::new(width, height)); + } +} + +/// Linux: the shell webview becomes the base layer of a GtkOverlay filling the window, which +/// [`place_child`] layers tab webviews over. Call once, right after the shell is added. No-op +/// elsewhere. +pub fn attach_shell(shell: &Webview) { + #[cfg(target_os = "linux")] + linux::attach_shell(shell); + #[cfg(not(target_os = "linux"))] + let _ = shell; +} + +/// Where [`place_child`] last put a child webview, in logical px (x, y, width, height). Linux +/// only: there `Webview::position` is not the placement (always 0,0 outside X11 child windows). +#[cfg(target_os = "linux")] +pub fn placed_rect(webview: &Webview) -> Option<(f64, f64, f64, f64)> { + linux::placed(webview.label()) +} + +#[cfg(target_os = "linux")] +mod linux { + use gtk::prelude::*; + use std::collections::HashMap; + use std::sync::{Mutex, OnceLock}; + use tauri::{Runtime, Webview}; + + type Rect = (f64, f64, f64, f64); + /// A child's placement in whole px (x, y, width, height), kept on the GTK widget. + type GtkRect = (i32, i32, i32, i32); + const RECT_KEY: &str = "waybetter-rect"; + + fn rects() -> std::sync::MutexGuard<'static, HashMap> { + static RECTS: OnceLock>> = OnceLock::new(); + RECTS.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + pub fn placed(label: &str) -> Option { + rects().get(label).copied() + } + + pub fn attach_shell(shell: &Webview) { + let _ = shell.with_webview(|platform| { + let widget = platform.inner().upcast::(); + let Some(vbox) = widget.parent().and_then(|parent| parent.downcast::().ok()) else { return }; + let overlay = gtk::Overlay::new(); + // Exactly the placed rectangle: the default position uses the child's preferred size, + // which WebKit (not the placement) decides. + overlay.connect_get_child_position(|_, child| { + // SAFETY: "waybetter-rect" is only ever set by `place`, always as `GtkRect`. + let (x, y, w, h) = unsafe { *child.data::(RECT_KEY)?.as_ptr() }; + Some(gtk::gdk::Rectangle::new(x, y, w, h)) + }); + // `widget` holds a reference, so removing it from the box does not destroy it. + vbox.remove(&widget); + overlay.add(&widget); + vbox.pack_start(&overlay, true, true, 0); + overlay.show(); + }); + } + + pub fn place(webview: &Webview, x: f64, y: f64, width: f64, height: f64) { + rects().insert(webview.label().to_owned(), (x, y, width, height)); + // Whole px, with the right/bottom edges rounded the same way as the left/top ones. + let (left, top) = (x.round(), y.round()); + let (w, h) = (((x + width).round() - left).max(1.0), ((y + height).round() - top).max(1.0)); + let _ = webview.with_webview(move |platform| { + let widget = platform.inner().upcast::(); + // SAFETY: read back only as `GtkRect` (the overlay's get-child-position handler). + unsafe { widget.set_data::(RECT_KEY, (left as i32, top as i32, w as i32, h as i32)) }; + let Some(parent) = widget.parent() else { return }; + if parent.downcast_ref::().is_none() { + // First placement: out of the window box (where tauri packed it), into the overlay. + let Ok(vbox) = parent.downcast::() else { return }; + let Some(overlay) = vbox.children().into_iter().find_map(|child| child.downcast::().ok()) else { + return; + }; + vbox.remove(&widget); + overlay.add_overlay(&widget); + } + widget.queue_resize(); + }); + } +} + /// Shows or hides a tab webview and sets its WebView2 memory target to match /// ([`tabs::memory_target`]): hidden tabs run at `COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_LOW` /// (ICoreWebView2_19, WebView2 Runtime 114+; older runtimes just skip it). Other platforms only From 3ae7744387023e545e0fe6519f35e27099cd3e0c Mon Sep 17 00:00:00 2001 From: CRT Date: Mon, 28 Sep 2026 21:47:09 +0700 Subject: [PATCH 02/42] runtime: plugin UI kit (api.ui: toast, alert, confirm, prompt, dialog, modal) and theme API (api.theme, --wb-* vars); theme JSON Schema; waybetter 0.2.0 The kit draws in one shadow DOM host in the active theme's colors, corners and font and repaints live; accessible dialogs (focus trap and return, Esc/Enter rules, alertdialog for alerts and confirms), stacking with inert, toasts with actions, reduced motion, text-only content (ui.h), and scope.ui closes a plugin's dialogs on dispose. api.toast routes to it. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- packages/runtime/src/pluginApi.ts | 75 ++- packages/runtime/src/themeApi.ts | 226 +++++++ packages/runtime/src/ui.ts | 908 +++++++++++++++++++++++++++ packages/runtime/tests/ui.test.ts | 200 ++++++ packages/waybetter/README.md | 66 +- packages/waybetter/package.json | 17 +- packages/waybetter/theme.schema.json | 156 +++++ 8 files changed, 1627 insertions(+), 25 deletions(-) create mode 100644 packages/runtime/src/themeApi.ts create mode 100644 packages/runtime/src/ui.ts create mode 100644 packages/runtime/tests/ui.test.ts create mode 100644 packages/waybetter/theme.schema.json diff --git a/README.md b/README.md index 7dcf9ea..3d3ed3b 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,9 @@ crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfi packages/runtime/src/ page runtime core (TypeScript, no dependencies) site.ts SiteAdapter (the page half of the adapter) + configureRuntime domHub.ts netHub.ts one MutationObserver/frame, one fetch/XHR hook per page - pluginApi.ts core of window..api for plugins + pluginApi.ts core of window..api for plugins (incl. ui and theme) + ui.ts plugin UI kit: toasts, alert/confirm/prompt, dialogs (shadow DOM, themed) + themeApi.ts the active theme as values + --wb-* CSS variables (api.theme) themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis paneNav.ts split view: park the site's navigation rail in redundant panes linkRouting.ts divert in-page clicks to a pane/tab/browser per setting diff --git a/packages/runtime/src/pluginApi.ts b/packages/runtime/src/pluginApi.ts index 388f1ad..b722f36 100644 --- a/packages/runtime/src/pluginApi.ts +++ b/packages/runtime/src/pluginApi.ts @@ -2,6 +2,14 @@ // re-implement DOM watching, route tracking, local storage and cleanup. Everything here is local to // the page: no network requests, no account actions. A site adapter adds its own readers (e.g. a // post/message parser) on top of this core. +// +// `ui` (toasts, alerts, confirmations, prompts, dialogs; ui.ts) and `theme` (the active theme as +// values; themeApi.ts) are part of the core: the site adapter only supplies its theme source. + +import { createThemeApi, type ThemeApi, type ThemeSource } from './themeApi.ts'; +import { createUiKit, type UiKit } from './ui.ts'; + +export type { ThemeApi, ThemeSource, UiKit }; export type Dispose = () => void; @@ -24,6 +32,10 @@ export type PluginScope = { add(node: T): T; /** Runs `fn` on dispose (restore attributes, clear timers, ...). */ defer(fn: Dispose): void; + /** Calls `callback(theme)` after the theme changes, until dispose. */ + onThemeChange(callback: Parameters[0]): void; + /** The UI kit, scoped: dialogs and toasts it opened are closed on dispose. */ + readonly ui: UiKit; dispose(): void; }; @@ -43,10 +55,20 @@ export type CorePluginApi = { */ onKey(callback: (event: KeyboardEvent, item: Element | null) => void): Dispose; copyText(text: string): Promise; + /** A short status message (the UI kit's toast; `ms` is how long it stays). */ toast(message: string, ms?: number): void; + /** Toasts, alerts, confirmations, prompts and dialogs in the active theme (see ui.ts). */ + ui: UiKit; + /** The active theme as values: `current()` and `onChange(fn)` (see themeApi.ts). */ + theme: ThemeApi; scope(): PluginScope; }; +/** What the site adapter adds to the core: its theme engine, when it has one. */ +export type CorePluginExtras = { + theme?: ThemeSource; +}; + export type PluginApiSite = { /** The runtime global, for error messages (`.waitFor timed out`). */ name: string; @@ -56,7 +78,9 @@ export type PluginApiSite = { storagePrefix: string; /** `data-*` key (camelCase) marking plugin `', + '', + '', + '
', + ' ', + ' ', + ' ', + '
', + ' ', + ' ', + ' ', + '
', + '', + '', + ); +} + +/** @param {AppOptions} o */ +function shellCss(o) { + return lines( + ':root { color-scheme: dark; --toolbar-h: 44px; --accent: ' + o.site.accent + '; font: 14px/1.4 system-ui, sans-serif; }', + 'html, body { margin: 0; height: 100%; background: #0d0f14; color: #e8eaf0; }', + 'body { display: flex; flex-direction: column; overflow: hidden; }', + '.toolbar { flex: 0 0 var(--toolbar-h); display: flex; align-items: center; gap: 8px; padding: 0 10px; border-bottom: 1px solid #262a35; }', + '.chips { display: flex; gap: 4px; min-width: 0; flex: 1; overflow: hidden; }', + '.chip { padding: 3px 10px; border-radius: 999px; background: #1b1f29; white-space: nowrap; }', + '.chip:first-child { background: var(--accent); color: #000; font-weight: 600; }', + '.account { color: #9aa1b2; }', + 'button { font: inherit; color: inherit; background: #1b1f29; border: 1px solid #2f3442; border-radius: 8px; padding: 5px 12px; cursor: pointer; }', + '.plugins { display: grid; gap: 8px; padding: 16px; }', + '.plugins label { display: flex; gap: 8px; align-items: center; }', + '.status { padding: 8px 12px; background: #3a1418; color: #ffd7d7; }', + '.pane { flex: 1; min-height: 0; }', + ); +} + +/** @param {AppOptions} o */ +function examplePlugin(o) { + return lines( + '/**', + ' * @name Example', + ` * @description Example plugin for ${o.product}: outlines each item and says hello. Turn it on in Plugins.`, + ' * @version 1.0.0', + ` * @author ${o.product}`, + ' */', + 'module.exports = class Example {', + ' start() {', + ' const api = window.wayBetter.api;', + ' this.scope = api.scope();', + ` this.scope.css('example', ${str(`${o.site.selectors.item} { outline: 1px dashed var(--wb-accent); }`)});`, + " this.scope.ui.toast('Example plugin started', { tone: 'success' });", + ' }', + '', + ' stop() {', + ' this.scope.dispose();', + ' }', + '};', + ); +} + +function tabBridge() { + return lines( + '// Injected into every tab (top frame only): reports URL and title changes of single-page apps', + '// to the address bar. It can call only `tab_report` (capability tab-chrome), about this tab.', + '(() => {', + ' if (window.top !== window || window.__wbTabBridge) return;', + ' window.__wbTabBridge = true;', + ' const invoke = (command, args) => {', + ' const ipc = window.__TAURI_INTERNALS__;', + " if (ipc && typeof ipc.invoke === 'function') ipc.invoke(command, args).catch(() => {});", + ' };', + " let last = '';", + ' const report = () => {', + ' const key = `${location.href}\\n${document.title}`;', + ' if (key === last) return;', + ' last = key;', + " invoke('tab_report', { report: { url: location.href, title: document.title } });", + ' };', + ' const soon = () => setTimeout(report, 50);', + " for (const method of ['pushState', 'replaceState']) {", + ' const original = history[method];', + ' history[method] = function (...args) {', + ' const result = original.apply(this, args);', + ' soon();', + ' return result;', + ' };', + ' }', + " addEventListener('popstate', soon);", + " addEventListener('DOMContentLoaded', report);", + '})();', + ); +} + +function buildMjs() { + return lines( + '// Builds the two bundles: the page runtime (one IIFE that native code injects into tabs) and the', + '// shell (the local page Tauri serves from dist/).', + "import { build } from 'esbuild';", + "import { copyFileSync, mkdirSync } from 'node:fs';", + '', + "mkdirSync('dist', { recursive: true });", + 'await build({', + " entryPoints: ['src/runtime/main.ts'],", + ' bundle: true,', + " format: 'iife',", + " target: 'es2022',", + ` outfile: ${str(APP_OUTPUTS.runtime)},`, + " legalComments: 'none',", + '});', + 'await build({', + " entryPoints: ['src/shell/main.ts'],", + ' bundle: true,', + " format: 'esm',", + " target: 'es2022',", + " outfile: 'dist/shell.js',", + '});', + "copyFileSync('src/shell/index.html', 'dist/index.html');", + "copyFileSync('src/shell/shell.css', 'dist/shell.css');", + "console.log('built dist/ and " + APP_OUTPUTS.runtime + "');", + ); +} + +/** @param {AppOptions} o */ +function readme(o) { + const submodule = o.hostSource === 'submodule'; + return lines( + `# ${o.product}`, + '', + `${o.site.hosts[0]} in one light native window, extended in place: a wayBetter app made with`, + '`npm create waybetter`. It is the same system as every wayBetter app: a Tauri 2 window with a', + 'trusted local **shell** and one native child webview per **tab**, the **page runtime** injected', + 'into tabs on the site, and a small **site adapter**.', + '', + '## Run it', + '', + '```sh', + ...(submodule ? [`git init && git submodule add ${o.gitUrl} waybetter # the framework (host crate)`] : []), + 'npm install', + 'npm run build # dist/ (shell) and ' + APP_OUTPUTS.runtime + ' (page runtime)', + 'npm run tauri dev # the app', + 'npm run test:rust # site adapter + plugin host tests, headless', + '```', + '', + 'Requires Node 18+, Rust 1.88+ and the Tauri 2 prerequisites for your platform.', + '', + '## Layout', + '', + '```', + 'src/site.ts SiteAdapter: the page half of the adapter (PLACEHOLDER selectors)', + 'src/address.ts address bar chips for the site\'s pages', + 'src/runtime/main.ts page runtime: window.' + o.runtimeGlobal + ' (+ window.wayBetter), plugin API, account report', + 'src/shell/ the shell page: toolbar, plugins, tabs_sync', + 'plugins/example.plugin.js written (disabled) into a new plugins folder', + 'src-tauri/src/site.rs SiteSpec: the native half (hosts, runtime global, account rules)', + 'src-tauri/src/plugins.rs the plugin store (PluginHost)', + 'src-tauri/src/desktop.rs window, shell, tab webviews and the commands', + 'src-tauri/capabilities/ shell / tab-chrome / site-tab, keyed by webview label', + '```', + '', + '## Make it yours', + '', + `1. Open ${o.origin} in a browser's devtools and replace every PLACEHOLDER in \`src/site.ts\``, + ' and `src-tauri/src/site.rs` (selectors, handle rules, the avatar CDN).', + '2. Keep `hosts` and the runtime global identical in `site.ts` and `site.rs`.', + '3. Add site-only commands like `site_ready`: `host::site_tab_only(&SITE, &webview)?` first,', + ' then list them in `build.rs` and `capabilities/site-tab.json`.', + '4. Next steps from the framework: account profiles (`waybetter_host::profiles`), split panes', + ' (`waybetter/shell/paneModel`), the rail hider (`waybetter/runtime/paneNav`), themes', + ' (`waybetter/runtime/themeApi`, `theme.schema.json`), signed updates (`waybetter_host::update`).', + '', + '## Security model', + '', + '- Only the local `shell` webview may call shell commands (`host::shell_only`).', + '- Any tab may only report about itself (`tab_report`); the URL used is the webview\'s own.', + '- Tabs on the exact site origin may call the short list in `site-tab.json`, re-checked natively.', + '- Plugins are files the owner copies into the plugins folder; native code evaluates them only', + ' in the site\'s top frame.', + '', + 'License: GPL-3.0-or-later (waybetter-host is GPL-3.0-or-later).', + ); +} + +/** @param {AppOptions} o */ +export function appFiles(o) { + const png = iconPng(64, o.site.accent); + const json = value => `${JSON.stringify(value, null, 2)}\n`; + const pkg = { + name: o.slug, + version: '0.1.0', + private: true, + type: 'module', + license: 'GPL-3.0-or-later', + description: `${o.product}: ${o.site.hosts[0]} in a light native window, extended in place.`, + scripts: { + build: 'node scripts/build.mjs', + typecheck: 'tsc -p tsconfig.json', + tauri: 'tauri', + 'test:rust': 'cargo test --manifest-path src-tauri/Cargo.toml --no-default-features', + }, + dependencies: { waybetter: '^0.2.0' }, + devDependencies: { '@tauri-apps/cli': '^2.0.0', esbuild: '^0.25.0', typescript: '^5.9.0' }, + }; + const tsconfig = { + compilerOptions: { + target: 'ES2022', + lib: ['ES2022', 'DOM', 'DOM.Iterable'], + module: 'ESNext', + moduleResolution: 'Bundler', + allowImportingTsExtensions: true, + noEmit: true, + strict: true, + noUnusedLocals: true, + skipLibCheck: true, + isolatedModules: true, + types: [], + }, + include: ['src'], + }; + return [ + { path: 'README.md', content: readme(o) }, + { path: 'package.json', content: json(pkg) }, + { path: 'tsconfig.json', content: json(tsconfig) }, + { path: '.gitignore', content: lines('node_modules/', 'dist/', 'src-tauri/target/', 'src-tauri/gen/', APP_OUTPUTS.runtime) }, + { path: 'scripts/build.mjs', content: buildMjs() }, + { path: 'src/site.ts', content: siteTs(o) }, + { path: 'src/address.ts', content: addressTs(o) }, + { path: 'src/runtime/main.ts', content: runtimeTs() }, + { path: 'src/shell/main.ts', content: shellTs(o) }, + { path: 'src/shell/index.html', content: indexHtml(o) }, + { path: 'src/shell/shell.css', content: shellCss(o) }, + { path: 'src/tauri.d.ts', content: tauriTypes() }, + { path: 'plugins/example.plugin.js', content: examplePlugin(o) }, + { path: 'src-tauri/Cargo.toml', content: cargoToml(o) }, + { path: 'src-tauri/build.rs', content: buildRs() }, + { path: 'src-tauri/tauri.conf.json', content: json(tauriConf(o)) }, + ...capabilities(o), + { path: 'src-tauri/icons/icon.png', content: png }, + { path: 'src-tauri/icons/icon.ico', content: iconIco(png, 64) }, + { path: 'src-tauri/src/main.rs', content: mainRs(o) }, + { path: 'src-tauri/src/lib.rs', content: libRs(o) }, + { path: 'src-tauri/src/site.rs', content: siteRs(o) }, + { path: 'src-tauri/src/plugins.rs', content: pluginsRs(o) }, + { path: 'src-tauri/src/desktop.rs', content: desktopRs(o) }, + { path: 'src-tauri/runtime/tab-bridge.js', content: tabBridge() }, + // Replaced by `npm run build`; here so `cargo check` works before the first build. + { path: APP_OUTPUTS.runtime, content: lines('// Placeholder: `npm run build` writes the page runtime here (src/runtime/main.ts).') }, + ]; +} diff --git a/packages/create-waybetter/src/cli.js b/packages/create-waybetter/src/cli.js new file mode 100644 index 0000000..26ec01e --- /dev/null +++ b/packages/create-waybetter/src/cli.js @@ -0,0 +1,253 @@ +// `npm create waybetter`: scaffolds a wayBetter plugin, theme or app. Interactive when run in a +// terminal without the answers; fully flag-driven otherwise (`--yes` takes the defaults). + +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { createInterface } from 'node:readline/promises'; +import { parseArgs } from 'node:util'; +import { SITE_PRESETS, appFiles, normalizeAppOptions } from './app.js'; +import { UsageError, slugify } from './names.js'; +import { PLUGIN_APPS, normalizePluginOptions, pluginFiles } from './plugin.js'; +import { THEME_MODES, THEME_PRESETS, normalizeThemeOptions, themeFiles } from './theme.js'; + +export const KINDS = ['plugin', 'theme', 'app']; + +/** @type {import('node:util').ParseArgsConfig['options']} */ +const OPTIONS = ({ + type: { type: 'string', short: 't' }, + name: { type: 'string', short: 'n' }, + description: { type: 'string' }, + author: { type: 'string' }, + 'plugin-version': { type: 'string' }, + ts: { type: 'boolean' }, + typescript: { type: 'boolean' }, + app: { type: 'string' }, + mode: { type: 'string' }, + preset: { type: 'string' }, + bg: { type: 'string' }, + text: { type: 'string' }, + accent: { type: 'string' }, + font: { type: 'string' }, + 'post-font': { type: 'string' }, + radius: { type: 'string' }, + schema: { type: 'string' }, + site: { type: 'string', short: 's' }, + global: { type: 'string' }, + identifier: { type: 'string' }, + 'host-source': { type: 'string' }, + 'host-path': { type: 'string' }, + 'git-url': { type: 'string' }, + yes: { type: 'boolean', short: 'y' }, + force: { type: 'boolean' }, + 'dry-run': { type: 'boolean' }, + help: { type: 'boolean', short: 'h' }, + version: { type: 'boolean', short: 'v' }, +}); + +export const HELP = `Usage: npm create waybetter [plugin|theme|app] [dir] -- [options] + npx create-waybetter [plugin|theme|app] [dir] [options] + +Scaffolds a wayBetter plugin, theme or whole app. Asks for anything missing when run in a +terminal; --yes takes the defaults instead. + +Common + -t, --type plugin, theme or app + -n, --name display name (plugin/theme name, or the app's product name) + --author plugin/theme author (default "you") + --description + -y, --yes no questions; use defaults for anything not given + --force write into a directory that is not empty + --dry-run print the files instead of writing them + -h, --help this help + -v, --version print the create-waybetter version + +Plugin (one *.plugin.js with the header the plugin store reads) + --plugin-version plugin version (default 1.0.0) + --ts a TypeScript project (types from the waybetter package) + --app x: wayBetter for X (adds api.tweet/account/users); any: another app + +Theme (JSON with "$schema" pointing at the waybetter theme schema) + --preset ${Object.keys(THEME_PRESETS).join(', ')} (seed colors, default midnight) + --mode ${THEME_MODES.join(', ')} + --bg, --text, --accent <#hex> seed colors; the rest of the palette is derived + --font interface fonts, e.g. "Geist, system-ui" + --post-font post text fonts + --radius <0-28> card corner radius (default 16) + --schema "$schema" as the unpkg URL (default) or ./node_modules path + +App (Tauri 2 + waybetter-host + the waybetter runtime and shell models) + -s, --site ${Object.keys(SITE_PRESETS).join(', ')} or any host name + --global the page runtime's window global (default from the name) + --identifier Tauri bundle identifier (default com.example.) + --host-source submodule (default: ../waybetter as a git submodule), path or git + --host-path with --host-source path: the waybetter repository (or its host crate) + --git-url the waybetter repository for submodule/git + +Examples + npm create waybetter plugin -- --name "Hide Trends" + npm create waybetter theme my-theme -- --name "Midnight Mint" --accent "#3ddc97" --yes + npm create waybetter app wb-kick -- --site kick.com --yes +`; + +/** @typedef {{ stdout: { write(text: string): unknown }, stderr: { write(text: string): unknown }, stdin: NodeJS.ReadableStream & { isTTY?: boolean }, cwd: string }} Io */ + +function packageVersion() { + try { + return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version; + } catch { + return 'unknown'; + } +} + +/** Minimal line prompts over readline (no dependencies). */ +function prompter(io) { + /** @type {import('node:readline/promises').Interface | null} */ + let rl = null; + const ask = async (question, fallback = '') => { + rl ??= createInterface({ input: io.stdin, output: /** @type {any} */ (io.stdout) }); + const answer = (await rl.question(`${question}${fallback ? ` (${fallback})` : ''}: `)).trim(); + return answer || fallback; + }; + return { + ask, + async choose(question, choices, fallback) { + for (;;) { + const answer = (await ask(`${question} [${choices.join('/')}]`, fallback)).toLowerCase(); + if (choices.includes(answer)) return answer; + io.stdout.write(` Choose one of: ${choices.join(', ')}\n`); + } + }, + async confirm(question, fallback) { + const answer = (await ask(`${question} [y/n]`, fallback ? 'y' : 'n')).toLowerCase(); + return answer.startsWith('y'); + }, + close() { rl?.close(); }, + }; +} + +/** + * Runs the CLI. Returns the exit code; never calls process.exit (tests call it in-process). + * @param {string[]} argv arguments after the program name + * @param {Partial} [ioInput] + */ +export async function main(argv, ioInput = {}) { + /** @type {Io} */ + const io = { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin, cwd: process.cwd(), ...ioInput }; + let parsed; + try { + parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true }); + } catch (error) { + io.stderr.write(`${/** @type {Error} */ (error).message}\n\nRun with --help for usage.\n`); + return 1; + } + /** @type {Record} */ + const values = parsed.values; + const positionals = parsed.positionals; + if (values.help) { io.stdout.write(HELP); return 0; } + if (values.version) { io.stdout.write(`${packageVersion()}\n`); return 0; } + + const interactive = !values.yes && Boolean(io.stdin.isTTY); + const ui = prompter(io); + try { + // `npm create waybetter plugin [dir]`: a leading kind is the type. + let type = values.type ?? (KINDS.includes(positionals[0] ?? '') ? positionals.shift() : undefined); + if (!type) { + if (!interactive) throw new UsageError('--type is required (plugin, theme or app) when not asking questions.'); + type = await ui.choose('What do you want to make?', KINDS, 'plugin'); + } + if (!KINDS.includes(type)) throw new UsageError(`--type must be one of: ${KINDS.join(', ')}.`); + const ask = async (value, question, fallback) => value ?? (interactive ? await ui.ask(question, fallback) : fallback); + + /** @type {Array<{ path: string, content: string | Uint8Array }>} */ + let files; + let defaultDir; + let next; + const warnings = []; + if (type === 'plugin') { + const name = await ask(values.name, 'Plugin name', 'My Plugin'); + const options = normalizePluginOptions({ + name, + description: await ask(values.description, 'Description', `${name}, a wayBetter plugin.`), + author: await ask(values.author, 'Author', 'you'), + version: values['plugin-version'], + typescript: values.ts ?? values.typescript ?? (interactive ? await ui.confirm('TypeScript?', false) : false), + app: values.app ?? (interactive ? await ui.choose('Which app is it for? (x = wayBetter for X)', PLUGIN_APPS, 'x') : 'x'), + }); + files = pluginFiles(options); + defaultDir = options.id; + next = options.typescript + ? ['npm install', 'npm run build', `copy dist/${options.file} into wayBetter → Plugins → Open folder, then Rescan`] + : [`copy ${options.file} into wayBetter → Plugins → Open folder, then Rescan`]; + } else if (type === 'theme') { + const name = await ask(values.name, 'Theme name', 'My Theme'); + const preset = await ask(values.preset, `Start from (${Object.keys(THEME_PRESETS).join(', ')})`, 'midnight'); + const seed = THEME_PRESETS[/** @type {keyof typeof THEME_PRESETS} */ (preset)] ?? THEME_PRESETS.midnight; + const options = normalizeThemeOptions({ + name, + preset, + author: await ask(values.author, 'Author', 'you'), + description: values.description, + mode: values.mode, + bg: await ask(values.bg, 'Background color', seed.bg), + text: await ask(values.text, 'Text color', seed.text), + accent: await ask(values.accent, 'Accent color', seed.accent), + font: values.font, + postFont: values['post-font'], + radius: values.radius, + schema: values.schema, + }); + warnings.push(...options.warnings); + files = themeFiles(options); + defaultDir = options.id; + next = [`import ${options.id}.theme.json in wayBetter → Appearance → Import`]; + } else { + const site = await ask(values.site, `Site (${Object.keys(SITE_PRESETS).join(', ')} or any host)`, 'kick.com'); + const label = SITE_PRESETS[/** @type {keyof typeof SITE_PRESETS} */ (site.replace(/^www\./, ''))]?.label; + const options = normalizeAppOptions({ + site, + name: await ask(values.name, 'App name', label ? `wayBetter for ${label}` : undefined), + global: values.global, + identifier: values.identifier, + hostSource: values['host-source'], + hostPath: values['host-path'], + gitUrl: values['git-url'], + }); + files = appFiles(options); + defaultDir = options.slug; + next = [ + ...(options.hostSource === 'submodule' ? [`git init && git submodule add ${options.gitUrl} waybetter`] : []), + 'npm install', 'npm run build', 'npm run tauri dev', + 'then replace the PLACEHOLDER selectors in src/site.ts and src-tauri/src/site.rs', + ]; + } + + const dirArg = positionals[0] ?? (interactive ? await ui.ask('Directory', defaultDir) : defaultDir); + const target = resolve(io.cwd, dirArg || defaultDir || slugify(type)); + if (values['dry-run']) { + io.stdout.write(`Would write ${files.length} files to ${target}:\n`); + for (const file of files) io.stdout.write(` ${file.path}\n`); + return 0; + } + if (existsSync(target) && readdirSync(target).length > 0 && !values.force) { + throw new UsageError(`${target} is not empty. Pick another directory or pass --force.`); + } + for (const file of files) { + const path = join(target, file.path); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, file.content); + } + const shown = relative(io.cwd, target) || '.'; + io.stdout.write(`\nCreated a wayBetter ${type} in ${shown} (${files.length} files).\n`); + for (const warning of warnings) io.stdout.write(` note: ${warning}\n`); + io.stdout.write(`\nNext:\n${shown === '.' ? '' : ` cd ${shown}\n`}${next.map(step => ` ${step}\n`).join('')}`); + return 0; + } catch (error) { + if (error instanceof UsageError) { + io.stderr.write(`${error.message}\n`); + return 1; + } + throw error; + } finally { + ui.close(); + } +} diff --git a/packages/create-waybetter/src/names.js b/packages/create-waybetter/src/names.js new file mode 100644 index 0000000..70c99c5 --- /dev/null +++ b/packages/create-waybetter/src/names.js @@ -0,0 +1,73 @@ +// Names and small validators shared by the generators. Pure; no I/O. + +/** A usage error: shown to the user as-is, exit code 1, no stack. */ +export class UsageError extends Error {} + +/** `Hide Trends!` -> `hide-trends` (ASCII letters and digits, dashes between). */ +export function slugify(value, max = 64) { + return String(value) + .normalize('NFKD') + .replace(/\p{M}/gu, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, max) + .replace(/-+$/, ''); +} + +/** `hide trends 2` -> `HideTrends2`; always a valid JS/Rust type identifier. */ +export function pascalCase(value) { + const words = String(value).normalize('NFKD').replace(/\p{M}/gu, '').replace(/[^A-Za-z0-9]+/g, ' ').trim().split(/\s+/).filter(Boolean); + const name = words.map(word => word[0].toUpperCase() + word.slice(1)).join(''); + return /^[A-Za-z]/.test(name) ? name : `Plugin${name}`; +} + +/** `wayBetter for Kick` -> `wayBetterForKick` (camelCase, for `data-*` keys). */ +export function camelCase(value) { + const name = pascalCase(value); + return name[0].toLowerCase() + name.slice(1); +} + +/** + * A value for a `@name` / `@description` / ... plugin header line, or a theme string. The plugin + * store reads each header line up to its end, drops control characters and keeps 300 characters + * (waybetter-host `plugins::parse_meta`), so values are one line and cannot end the comment. + */ +export function headerValue(label, value, { max = 300, required = false } = {}) { + const text = String(value ?? '').trim(); + if (required && !text) throw new UsageError(`${label} is required.`); + if (/[\u0000-\u001f\u007f]/.test(text)) throw new UsageError(`${label} must be one line of text.`); + if (text.includes('*/')) throw new UsageError(`${label} cannot contain "*/".`); + if (text.length > max) throw new UsageError(`${label} is longer than ${max} characters.`); + return text; +} + +/** Semver-ish plugin version (`1.0.0`, `0.3.1-beta.2`). */ +export function versionValue(value) { + const text = String(value ?? '1.0.0').trim() || '1.0.0'; + if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(text)) throw new UsageError(`Version "${text}" is not like 1.0.0.`); + return text; +} + +export const HEX = /^#[0-9a-fA-F]{6}$/; + +/** `#abc` / `abc123` / `#ABC123` -> `#aabbcc` style lowercase six-digit hex. */ +export function hexValue(label, value) { + let text = String(value ?? '').trim().toLowerCase(); + if (!text.startsWith('#')) text = `#${text}`; + const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(text); + if (short) text = `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`; + if (!HEX.test(text)) throw new UsageError(`${label} must be a hex color like #1d9bf0 (got "${value}").`); + return text; +} + +/** A JS/TS string literal. */ +export const str = value => JSON.stringify(String(value)); + +/** A Rust string literal (JSON escapes are valid Rust escapes for the characters we allow). */ +export function rustStr(value) { + return JSON.stringify(String(value)).replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => `\\u{${hex}}`); +} + +/** Joins lines with `\n` and ends the file with one newline. */ +export const lines = (...parts) => `${parts.flat().join('\n').replace(/\n+$/, '')}\n`; diff --git a/packages/create-waybetter/src/plugin.js b/packages/create-waybetter/src/plugin.js new file mode 100644 index 0000000..8c4f643 --- /dev/null +++ b/packages/create-waybetter/src/plugin.js @@ -0,0 +1,426 @@ +// `npm create waybetter -- plugin`: one BetterDiscord-style `*.plugin.js` file (a class with +// start/stop and the header the plugin store reads), optionally as a small TypeScript project +// whose build writes that file. The example uses the real plugin API: `api.scope()`, storage, +// observe, onKey, the UI kit (`scope.ui`: toast with an action, a settings dialog built with +// `ui.h`) and the theme API (`api.theme`, `--wb-*` CSS variables). + +import { UsageError, headerValue, lines, pascalCase, slugify, str, versionValue } from './names.js'; + +/** Which app the plugin targets: wayBetter for X adds post/account readers to the core API. */ +export const PLUGIN_APPS = ['x', 'any']; + +/** + * @typedef {{ name: string, description?: string, author?: string, version?: string, + * typescript?: boolean, app?: string }} PluginInput + * @typedef {{ name: string, description: string, author: string, version: string, + * typescript: boolean, app: 'x' | 'any', id: string, className: string, file: string }} PluginOptions + * @typedef {{ path: string, content: string | Uint8Array }} OutputFile + */ + +/** @param {PluginInput} input @returns {PluginOptions} */ +export function normalizePluginOptions(input) { + const name = headerValue('Plugin name', input.name, { max: 60, required: true }); + const id = slugify(name, 48); + if (!id) throw new UsageError(`Plugin name "${name}" needs at least one letter or digit.`); + const app = String(input.app ?? 'x'); + if (!PLUGIN_APPS.includes(app)) throw new UsageError(`--app must be one of: ${PLUGIN_APPS.join(', ')}.`); + return { + name, + description: headerValue('Description', input.description || `${name}, a wayBetter plugin.`, { max: 200 }), + author: headerValue('Author', input.author || 'you', { max: 60 }), + version: versionValue(input.version), + typescript: Boolean(input.typescript), + app: /** @type {'x' | 'any'} */ (app), + id, + className: pascalCase(name), + // A bare `name.plugin.js`: letters, digits, `-` only (waybetter-host `valid_file_name`). + file: `${id}.plugin.js`, + }; +} + +/** @param {PluginOptions} o */ +function header(o) { + return lines( + '/**', + ` * @name ${o.name}`, + ` * @description ${o.description}`, + ` * @version ${o.version}`, + ` * @author ${o.author}`, + ' */', + ); +} + +/** The item a badge is added to, and how its text is read. @param {PluginOptions} o */ +function itemParts(o) { + if (o.app === 'x') { + return { + selector: `'article[data-testid="tweet"]'`, + selectorNote: '// One post on X.', + text: 'this.api.tweet(item)?.text ?? \'\'', + anchor: `item.querySelector('[data-testid="User-Name"]') ?? item`, + }; + } + return { + selector: `'[data-example-item]'`, + selectorNote: '// PLACEHOLDER: a selector for one item of your app\'s site (a post, a message, a video).', + text: `item.textContent ?? ''`, + anchor: 'item', + }; +} + +/** @param {PluginOptions} o */ +function jsSource(o) { + const item = itemParts(o); + return lines( + header(o).trimEnd(), + '// Made with `npm create waybetter`. The API is documented in PLUGINS.md (wayBetter for X:', + '// docs/PLUGINS.md) and in the waybetter package README (plugin UI kit, themes).', + '', + `const ID = ${str(o.id)}; // storage namespace and CSS id`, + `const ITEM = ${item.selector}; ${item.selectorNote}`, + '', + `module.exports = class ${o.className} {`, + ' start() {', + ' const api = window.wayBetter.api;', + ' this.api = api;', + ' // A scope collects everything the plugin adds; stop() undoes it all with scope.dispose().', + ' this.scope = api.scope();', + ' this.store = api.storage(ID);', + ' this.settings = { badges: true, ...this.store.get(\'settings\', {}) };', + '', + ' // Plugin CSS follows the active theme through the --wb-* variables.', + ' this.scope.css(ID, `', + ' .${ID}-badge { margin-inline-start: 8px; padding: 1px 8px; border: 1px solid var(--wb-border);', + ' border-radius: var(--wb-button-radius); background: var(--wb-surface); color: var(--wb-muted);', + ' font: 500 12px/18px var(--wb-font); white-space: nowrap; }', + ' html[data-${ID}-off] .${ID}-badge { display: none; }', + ' `);', + ' this.apply();', + ' this.scope.defer(() => document.documentElement.removeAttribute(`data-${ID}-off`));', + '', + ' // Once for every matching element, now and as the page renders more (batched per frame).', + ' this.scope.observe(ITEM, item => this.decorate(item));', + '', + ' // A single-key shortcut, skipped while typing: Shift+W opens the settings.', + ' this.scope.onKey(event => { if (event.key === \'W\') this.openSettings(); });', + '', + ' if (!this.store.get(\'welcomed\', false)) {', + ' this.store.set(\'welcomed\', true);', + ` this.scope.ui.toast(${str(`${o.name} is on`)}, { tone: 'success', action: { label: 'Settings', onClick: () => this.openSettings() } });`, + ' }', + ' }', + '', + ' decorate(item) {', + ` const text = ${item.text};`, + ' const words = text.trim() ? text.trim().split(/\\s+/).length : 0;', + ' // scope.add: removed again on dispose.', + ' const badge = this.scope.add(document.createElement(\'span\'));', + ' badge.className = `${ID}-badge`;', + ' badge.textContent = `${words} ${words === 1 ? \'word\' : \'words\'}`;', + ` ${item.anchor}.append(badge);`, + ' }', + '', + ' apply() {', + ' document.documentElement.toggleAttribute(`data-${ID}-off`, !this.settings.badges);', + ' }', + '', + ' openSettings() {', + ' const ui = this.scope.ui; // scoped: the dialog closes if the plugin stops', + ' const h = ui.h; // safe element builder: strings become text, on* functions listeners', + ' const theme = this.api.theme.current();', + ' const badges = h(\'input\', { type: \'checkbox\', checked: this.settings.badges });', + ' ui.dialog({', + ` title: ${str(o.name)},`, + ' message: `Drawn in the active theme: ${theme.name || theme.id}, ${theme.mode}.`,', + ' content: body => body.append(', + ' h(\'label\', { class: \'wb-check\' }, badges, h(\'span\', null, \'Show word counts\', h(\'small\', null, \'A small badge on each item.\'))),', + ' ),', + ' actions: [', + ' { label: \'Cancel\' },', + ' { label: \'Save\', tone: \'primary\', default: true, onClick: handle => {', + ' const next = { ...this.settings, badges: badges.checked };', + ' if (!this.store.set(\'settings\', next)) {', + ' handle.setError(\'Could not save.\');', + ' return false; // keeps the dialog open', + ' }', + ' this.settings = next;', + ' this.apply();', + ' ui.toast(\'Saved\', { tone: \'success\' });', + ' } },', + ' ],', + ' });', + ' }', + '', + ' stop() {', + ' this.scope?.dispose();', + ' this.scope = null;', + ' }', + '};', + ); +} + +/** @param {PluginOptions} o */ +function tsSource(o) { + const item = itemParts(o); + return lines( + header(o).trimEnd(), + '// Made with `npm create waybetter`. `npm run build` writes dist/' + o.file + ' (header first).', + '', + "import type { PluginScope, PluginStorage } from 'waybetter/runtime/pluginApi';", + "import type { PluginApi } from './waybetter-env';", + '', + `const ID = ${str(o.id)}; // storage namespace and CSS id`, + `const ITEM = ${item.selector}; ${item.selectorNote}`, + '', + 'type Settings = { badges: boolean };', + '', + `export default class ${o.className} {`, + ' private api!: PluginApi;', + ' private scope: PluginScope | null = null;', + ' private store!: PluginStorage;', + ' private settings: Settings = { badges: true };', + '', + ' start(): void {', + ' const api = window.wayBetter.api;', + ' this.api = api;', + ' // A scope collects everything the plugin adds; stop() undoes it all with scope.dispose().', + ' const scope = this.scope = api.scope();', + ' this.store = api.storage(ID);', + ' this.settings = { badges: true, ...this.store.get>(\'settings\', {}) };', + '', + ' // Plugin CSS follows the active theme through the --wb-* variables.', + ' scope.css(ID, `', + ' .${ID}-badge { margin-inline-start: 8px; padding: 1px 8px; border: 1px solid var(--wb-border);', + ' border-radius: var(--wb-button-radius); background: var(--wb-surface); color: var(--wb-muted);', + ' font: 500 12px/18px var(--wb-font); white-space: nowrap; }', + ' html[data-${ID}-off] .${ID}-badge { display: none; }', + ' `);', + ' this.apply();', + ' scope.defer(() => document.documentElement.removeAttribute(`data-${ID}-off`));', + '', + ' // Once for every matching element, now and as the page renders more (batched per frame).', + ' scope.observe(ITEM, item => this.decorate(scope, item));', + '', + ' // A single-key shortcut, skipped while typing: Shift+W opens the settings.', + ' scope.onKey(event => { if (event.key === \'W\') this.openSettings(); });', + '', + ' if (!this.store.get(\'welcomed\', false)) {', + ' this.store.set(\'welcomed\', true);', + ` scope.ui.toast(${str(`${o.name} is on`)}, { tone: 'success', action: { label: 'Settings', onClick: () => this.openSettings() } });`, + ' }', + ' }', + '', + ' private decorate(scope: PluginScope, item: Element): void {', + ` const text = ${item.text};`, + ' const words = text.trim() ? text.trim().split(/\\s+/).length : 0;', + ' // scope.add: removed again on dispose.', + ' const badge = scope.add(document.createElement(\'span\'));', + ' badge.className = `${ID}-badge`;', + ' badge.textContent = `${words} ${words === 1 ? \'word\' : \'words\'}`;', + ` ${item.anchor}.append(badge);`, + ' }', + '', + ' private apply(): void {', + ' document.documentElement.toggleAttribute(`data-${ID}-off`, !this.settings.badges);', + ' }', + '', + ' private openSettings(): void {', + ' if (!this.scope) return;', + ' const ui = this.scope.ui; // scoped: the dialog closes if the plugin stops', + ' const h = ui.h; // safe element builder: strings become text, on* functions listeners', + ' const theme = this.api.theme.current();', + ' const badges = h(\'input\', { type: \'checkbox\', checked: this.settings.badges }) as HTMLInputElement;', + ' ui.dialog({', + ` title: ${str(o.name)},`, + ' message: `Drawn in the active theme: ${theme.name || theme.id}, ${theme.mode}.`,', + ' content: body => body.append(', + ' h(\'label\', { class: \'wb-check\' }, badges, h(\'span\', null, \'Show word counts\', h(\'small\', null, \'A small badge on each item.\'))),', + ' ),', + ' actions: [', + ' { label: \'Cancel\' },', + ' { label: \'Save\', tone: \'primary\', default: true, onClick: handle => {', + ' const next: Settings = { ...this.settings, badges: badges.checked };', + ' if (!this.store.set(\'settings\', next)) {', + ' handle.setError(\'Could not save.\');', + ' return false; // keeps the dialog open', + ' }', + ' this.settings = next;', + ' this.apply();', + ' ui.toast(\'Saved\', { tone: \'success\' });', + ' return true;', + ' } },', + ' ],', + ' });', + ' }', + '', + ' stop(): void {', + ' this.scope?.dispose();', + ' this.scope = null;', + ' }', + '}', + ); +} + +/** Types of `window.wayBetter` for the TypeScript project. @param {PluginOptions} o */ +function envTypes(o) { + const x = o.app === 'x'; + return lines( + '// `window.wayBetter`: the page runtime plugins run against. The core API and its types come', + '// from the `waybetter` package; an app adds its own readers on top (wayBetter for X: posts,', + '// the signed-in account and users, see docs/PLUGINS.md).', + "import type { CorePluginApi } from 'waybetter/runtime/pluginApi';", + x ? "import type { SeenAccount } from 'waybetter/runtime/accountReport';" : '', + '', + x ? lines( + '/** A rendered post, read by `api.tweet(element)`. */', + 'export type TweetInfo = {', + ' id: string;', + ' url: string;', + ' handle: string;', + ' name: string;', + ' /** Emoji as characters, t.co links as the destination X shows. */', + ' text: string;', + ' /** ISO timestamp of the post\'s `