waybetter/packages/shell/src/storeModel.ts

203 lines
10 KiB
TypeScript

// The wayBetter Store and install screen, pure part: the wire types of the native store commands
// (waybetter-host `store`), what each plugin permission means, where a dropped file goes, which id a
// new theme gets, whether a store item is installed, current or has an update, search, and preview
// lines. Native code validates everything again; nothing here decides what may be installed.
import { STORE_MESSAGES, type StoreKey, type StoreText } from './storeMessages.ts';
import type { StringsInfo } from './stringPacksModel.ts';
export type InstallKind = 'theme' | 'plugin' | 'strings';
export type SourceKind = 'store' | 'link' | 'file';
export type PermissionTone = 'plain' | 'warn' | 'ok';
export type PermissionBadge = { id: string; label: string; detail: string; tone: PermissionTone };
/** A store catalog item (waybetter-host `CatalogItem`; the catalog format is documented in docs/STORE.md). */
export type StoreItem = {
/** The wayBetter apps it is for; native code only hands an app its own items. */
apps?: string[];
kind: InstallKind; id: string; name: string; author: string; version: string; description: string;
category: string; tags: string[]; url: string; file?: string; sha256: string; size: number;
preview?: string; permissions?: string[] | null; colors?: { bg: string; surface?: string; text: string; accent: string } | null;
/** String packs: the pack's language tag. */
language?: string;
/** Any kind: its licence and who made, translated or reviewed it. */
license?: string; credits?: string;
};
export type InstallRecord = { kind: InstallKind; source: SourceKind; url?: string; storeId?: string; version: string; sha256: string; installedAt: string };
export type InstalledPlugin = { version: string; sha256: string; enabled: boolean };
/** What `store_catalog` returns (waybetter-host `StoreView`): this app's items and what is installed. */
export type StoreCatalogView = {
catalog: { format?: number; name: string; generatedAt: string; items: StoreItem[] } | null;
fetchedAt: string | null;
error: string | null;
plugins: Record<string, InstalledPlugin>;
records: { items: Record<string, InstallRecord> };
};
export type ScriptPluginMeta = {
file: string; name: string; description: string; version: string; author: string; enabled: boolean;
permissions: string[] | null; problems?: string[];
};
/** What `install_stage_*` / `store_stage` return (waybetter-host `InstallPreview`). */
export type InstallPreview = {
token: string;
kind: InstallKind;
source: { kind: SourceKind; url: string | null; label: string; signed: boolean };
sha256: string;
size: number;
file: string | null;
/** The exact text that will be written. */
text: string;
version: string;
plugin: ScriptPluginMeta | null;
theme: { name: string; author: string; description: string; cssChars: number } | null;
/** String packs: what the pack says about itself (coverage comes from the site's inventory). */
strings?: StringsInfo | null;
findings: string[];
existing: { version: string; enabled: boolean; same: boolean } | null;
store: StoreItem | null;
};
/** The `install-link` event and `install_pending` entries (waybetter-host `LinkEvent`). */
export type LinkEvent = { link?: { kind: InstallKind; url: string }; error?: string; setup?: string };
/** Plugin permissions (waybetter-host `PERMISSIONS`, runtime `permissions.ts`) and how much they allow. */
export const PERMISSION_TONES: Readonly<Record<string, PermissionTone>> = {
storage: 'plain',
ui: 'plain',
clipboard: 'plain',
account: 'warn',
commands: 'plain',
users: 'warn',
network: 'warn',
'network:none': 'ok',
};
/** `t(key)` for a key assembled at runtime, or `fallback` when the framework has no such message. */
function lookup(t: StoreText, key: string, params: Record<string, string> | undefined, fallback: string): string {
return key in STORE_MESSAGES ? t(key as StoreKey, params) : fallback;
}
/** Badges for a plugin's declared permissions; `null` = no `@permissions` line (legacy). `site`: the site's name. */
export function permissionBadges(permissions: readonly string[] | null | undefined, t: StoreText, site: string): PermissionBadge[] {
if (permissions == null) return [{ id: 'legacy', label: t('wb.permission.legacy.label'), detail: t('wb.permission.legacy.detail'), tone: 'warn' }];
if (permissions.length === 0) return [{ id: 'none', label: t('wb.permission.none.label'), detail: t('wb.permission.none.detail'), tone: 'ok' }];
return permissions.map(id => {
const tone = PERMISSION_TONES[id];
if (!tone) return { id, label: id, detail: t('wb.permission.unknown'), tone: 'warn' as const };
const name = id.replace(':none', 'None');
return { id, label: lookup(t, `wb.permission.${name}.label`, undefined, id), detail: lookup(t, `wb.permission.${name}.detail`, { site }, ''), tone };
});
}
/** A store category's name (`wb.store.category.<id>`); unknown ones show their id. */
export function categoryLabel(id: string, t: StoreText): string {
return lookup(t, `wb.store.category.${id}`, undefined, id);
}
/** What a dropped file is, by name: `.plugin.js` → plugin, `.strings.json` → string pack, `.json` → theme, else nothing. */
export function kindForFile(name: string): InstallKind | null {
const lower = name.toLowerCase();
if (lower.endsWith('.plugin.js')) return 'plugin';
if (lower.endsWith('.strings.json')) return 'strings';
if (lower.endsWith('.json')) return 'theme';
return null;
}
/** Largest file the shell reads before handing it to native validation (same caps as native). */
export const MAX_FILE_BYTES: Readonly<Record<InstallKind, number>> = { theme: 2 * 1024 * 1024, plugin: 2 * 1024 * 1024, strings: 2 * 1024 * 1024 };
/** A free theme id: `wanted`, else `wanted-2`, `-3`, … (the way an import names copies). */
export function freeThemeId(wanted: string, taken: Iterable<string>): string {
const used = new Set(taken);
if (!used.has(wanted)) return wanted;
for (let n = 2; ; n += 1) {
const id = `${wanted.slice(0, 36)}-${n}`;
if (!used.has(id)) return id;
}
}
/** `a` newer than `b` (numeric dot parts; same rule as native `newer_version`). */
export function newerVersion(a: string, b: string): boolean {
const parts = (value: string) => value.split(/[.+-]/).map(part => Number.parseInt(part, 10) || 0);
const [x, y] = [parts(a), parts(b)];
for (let i = 0; i < Math.max(x.length, y.length); i += 1) {
const [p, q] = [x[i] ?? 0, y[i] ?? 0];
if (p !== q) return p > q;
}
return false;
}
export type ItemState =
| { state: 'install' }
| { state: 'builtin' }
| { state: 'installed'; version: string; enabled?: boolean }
| { state: 'update'; version: string; enabled?: boolean }
/** Installed but changed locally (edited file, or a copy from somewhere else): the store leaves it alone unless asked. */
| { state: 'modified'; version: string; enabled?: boolean };
export type ItemContext = {
plugins: Record<string, InstalledPlugin>;
records: Record<string, InstallRecord>;
/** Theme ids that ship with the app (a store copy of one is "built in"). */
builtinThemes: readonly string[];
/** The owner's own theme ids right now. */
userThemes: readonly string[];
};
/**
* Where a store item stands on this machine. Plugins: by their file in the plugins folder.
* Themes: built-in ids are part of the app; otherwise the install record for a theme the owner
* still has.
*/
export function itemState(item: StoreItem, context: ItemContext): ItemState {
if (item.kind === 'plugin') {
const installed = item.file ? context.plugins[item.file] : undefined;
if (!installed) return { state: 'install' };
const base = { version: installed.version, enabled: installed.enabled };
if (installed.sha256 === item.sha256) return { state: 'installed', ...base };
if (newerVersion(item.version, installed.version)) return { state: 'update', ...base };
return { state: 'modified', ...base };
}
if (item.kind === 'strings') {
const record = context.records[`strings:${item.id}`];
if (!record) return { state: 'install' };
if (record.sha256 === item.sha256) return { state: 'installed', version: record.version };
return newerVersion(item.version, record.version) ? { state: 'update', version: record.version } : { state: 'installed', version: record.version };
}
if (context.builtinThemes.includes(item.id)) return { state: 'builtin' };
const id = installedThemeId(item, context.records, context.userThemes);
if (!id) return { state: 'install' };
const value = context.records[`theme:${id}`]!;
if (value.sha256 === item.sha256) return { state: 'installed', version: value.version };
return newerVersion(item.version, value.version) ? { state: 'update', version: value.version } : { state: 'installed', version: value.version };
}
/** The installed user theme id a store theme item was installed as (for updates in place). */
export function installedThemeId(item: StoreItem, records: Record<string, InstallRecord>, userThemes: readonly string[]): string | null {
for (const [key, value] of Object.entries(records)) {
if (key.startsWith('theme:') && value.storeId === item.id && userThemes.includes(key.slice(6))) return key.slice(6);
}
return null;
}
/** Search and category filter for the store list. */
export function filterItems(items: readonly StoreItem[], query: string, kind: InstallKind | 'all', category: string | 'all'): StoreItem[] {
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
return items.filter(item => (kind === 'all' || item.kind === kind) && (category === 'all' || item.category === category)
&& words.every(word => [item.name, item.description, item.author, item.category, item.language ?? '', ...item.tags, ...(item.permissions ?? [])].join(' ').toLowerCase().includes(word)));
}
export const formatBytes = (bytes: number) => bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(2)} MB`;
/** Lines of a preview with their numbers, the first `limit` only unless `all`. */
export function previewLines(text: string, limit: number, all = false): { lines: string[]; hidden: number } {
const lines = text.replace(/\r\n?/g, '\n').split('\n');
if (all || lines.length <= limit) return { lines, hidden: 0 };
return { lines: lines.slice(0, limit), hidden: lines.length - limit };
}
/** An error from a native command, without its `CODE: ` prefix. */
export const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error)).replace(/^[A-Z]+: /, '');