waybetter-for-x/scripts/store/source.mjs
2026-09-30 23:01:13 +00:00

189 lines
14 KiB
JavaScript

// The Store's source: one folder per item under store/<app>/plugins/<id>/, store/<app>/themes/<id>/
// and store/<app>/strings/<id>/
// (layout and rules: store/README.md). A contributor adds one folder in one pull request; this module
// turns the folders into the entries `waybetter store build` takes (scripts/store.config.mjs) and
// lists what is wrong with them (scripts/check-store.mjs).
//
// item.json what the item file cannot say itself: category, tags (plugins), version (themes)
// <name>.plugin.js a plugin; name, author, version, description and permissions are its header
// theme.json a theme, as Appearance → Export writes it; name, author, description, mode
// <name>.strings.json a string pack (waybetter/docs/STRING-PACKS.md); name, authors, version,
// description and language are the pack's own
// preview.svg|.png optional 640×400 picture; without one the preview is drawn from the item
// media/… optional cover, screenshots and one video for the item's page on the site,
// named in item.json ("cover", "screenshots", "video"); never in the catalog
//
// First-party items keep their one source of truth in the app: `"bundled": "<file>"` takes the plugin
// the app ships (apps/desktop/src-tauri/bundled-plugins), `"builtin": true` exports the built-in
// theme with the folder's id. So the app's copy and the Store's copy cannot drift.
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { pluginHeader, validFileName } from '../../waybetter/packages/waybetter/cli/store.mjs';
import { pluginPreviewSvg, themePreviewSvg } from './preview.mjs';
export const ITEM_ID = /^[a-z0-9-]{1,40}$/;
/** Categories the apps translate (`wb.store.category.*`); the Store's filters are these. */
export const CATEGORIES = { plugin: ['reading', 'writing', 'filters', 'focus', 'tools'], theme: ['dark', 'light'], strings: ['language'] };
// cover, screenshots and video are for the website only (apps/web/store-media.ts): the catalog never names them.
const MEDIA_FIELDS = ['cover', 'screenshots', 'video'];
// license and credits go into the catalog as they are (optional on every kind).
const FIELDS = { plugin: ['bundled', 'file', 'category', 'tags', 'preview', 'license', 'credits', ...MEDIA_FIELDS], theme: ['builtin', 'version', 'category', 'tags', 'preview', 'license', 'credits', ...MEDIA_FIELDS], strings: ['category', 'tags', 'preview', 'license', 'credits', ...MEDIA_FIELDS] };
const PREVIEW_NAMES = ['preview.svg', 'preview.png'];
const HEX = /^#[0-9a-f]{6}$/i;
const dirs = path => (existsSync(path) ? readdirSync(path).filter(name => statSync(join(path, name)).isDirectory()).sort() : []);
function readItemJson(dir, kind, problems, where) {
const path = join(dir, 'item.json');
if (!existsSync(path)) { problems.push(`${where}: item.json is missing`); return null; }
let info;
try { info = JSON.parse(readFileSync(path, 'utf8')); } catch (error) { problems.push(`${where}/item.json: not valid JSON (${error.message})`); return null; }
if (!info || typeof info !== 'object' || Array.isArray(info)) { problems.push(`${where}/item.json: must be an object`); return null; }
for (const key of Object.keys(info)) if (!FIELDS[kind].includes(key)) problems.push(`${where}/item.json: unknown field "${key}" (allowed: ${FIELDS[kind].join(', ')})`);
if (info.tags !== undefined && (!Array.isArray(info.tags) || info.tags.some(tag => typeof tag !== 'string'))) { problems.push(`${where}/item.json: tags must be a list of words`); info.tags = []; }
if (info.license !== undefined && (typeof info.license !== 'string' || !info.license.trim() || [...info.license].length > 60)) problems.push(`${where}/item.json: "license" is 1 to 60 characters`);
if (info.credits !== undefined && (typeof info.credits !== 'string' || [...info.credits].length > 600)) problems.push(`${where}/item.json: "credits" is at most 600 characters`);
return info;
}
/** The folder's own preview picture (item.json `preview`, else preview.svg / preview.png), or null. */
function ownPreview(dir, info, kind, id, problems, where) {
const name = info.preview ?? PREVIEW_NAMES.find(file => existsSync(join(dir, file)));
if (!name) return null;
if (typeof name !== 'string' || !/^[\w.-]+\.(svg|png)$/.test(name) || !existsSync(join(dir, name))) {
problems.push(`${where}: preview "${name}" must be an .svg or .png file in this folder`);
return null;
}
return { path: `previews/${kind}-${id}.${name.endsWith('.png') ? 'png' : 'svg'}`, bytes: readFileSync(join(dir, name)), own: true };
}
/**
* Reads store/<app>/ under `root`. Returns the entries for `buildStore` (plus `dir` and `firstParty`
* for the checks) and the problems that stop a build.
*
* options: { root, app, bundledDir, builtinThemes, themeSchemaUrl, sanitizeTheme, superseded }
* (`superseded`: bundled plugin files a built-in feature replaced; they stay in the app for the
* one-time move of an install, and are not Store items any more.)
*/
export function readStoreSource(options) {
const { root, app, bundledDir, builtinThemes = [], themeSchemaUrl, sanitizeTheme = theme => theme, superseded = [] } = options;
const base = join(root, 'store', app);
const problems = [];
const entries = [];
// ---- Plugins (sorted by id) ---------------------------------------------------------------
const bundledSeen = new Set();
for (const id of dirs(join(base, 'plugins'))) {
const where = `store/${app}/plugins/${id}`;
const dir = join(base, 'plugins', id);
if (!ITEM_ID.test(id)) { problems.push(`${where}: the folder name is the item id: a-z, 0-9 and -, at most 40 characters`); continue; }
const info = readItemJson(dir, 'plugin', problems, where);
if (!info) continue;
const own = readdirSync(dir).filter(file => file.endsWith('.plugin.js'));
let bytes;
let file;
if (info.bundled !== undefined) {
if (typeof info.bundled !== 'string' || !validFileName(info.bundled) || !existsSync(join(bundledDir, info.bundled))) { problems.push(`${where}: "bundled" must name a plugin the app ships (${info.bundled})`); continue; }
if (own.length) { problems.push(`${where}: a bundled plugin's file lives in the app, not here (remove ${own.join(', ')})`); continue; }
bundledSeen.add(info.bundled);
bytes = readFileSync(join(bundledDir, info.bundled));
file = info.file;
if (!file) { problems.push(`${where}: a bundled plugin needs "file", the name it is installed under`); continue; }
} else {
if (own.length !== 1) { problems.push(`${where}: exactly one *.plugin.js file is needed (found ${own.length})`); continue; }
bytes = readFileSync(join(dir, own[0]));
file = info.file ?? own[0];
}
if (!validFileName(file)) { problems.push(`${where}: the file name must look like name.plugin.js (letters, digits, - _ . and spaces)`); continue; }
let meta;
try { meta = pluginHeader(bytes.toString('utf8')); } catch (error) { problems.push(`${where}/${file}: ${error.message}`); continue; }
if (!meta.name || !meta.version) { problems.push(`${where}/${file}: the header needs @name and @version`); continue; }
const category = info.category ?? '';
entries.push({
kind: 'plugin', id, name: meta.name, author: meta.author, version: meta.version, description: meta.description,
category, tags: info.tags ?? [], file, permissions: meta.permissions, path: `plugins/${file}`, bytes,
preview: ownPreview(dir, info, 'plugin', id, problems, where) ?? { path: `previews/plugin-${id}.svg`, bytes: pluginPreviewSvg({ ...meta, category }) },
...(info.license !== undefined ? { license: info.license } : {}), ...(info.credits !== undefined ? { credits: info.credits } : {}),
dir: where, firstParty: info.bundled !== undefined,
});
}
// Every plugin the app ships is in the Store (the app offers their updates from it).
if (existsSync(bundledDir)) {
for (const name of readdirSync(bundledDir).filter(file => file.endsWith('.plugin.js')).sort()) {
if (superseded.includes(name)) { if (bundledSeen.has(name)) problems.push(`store/${app}/plugins: ${name} became a built-in feature; its Store folder goes (the area's page is store/${app}/areas/)`); continue; }
if (!bundledSeen.has(name)) problems.push(`bundled plugin ${name} has no Store folder: add store/${app}/plugins/${name.replace(/\.plugin\.js$/, '')}/item.json with "bundled", "file", "category" and "tags"`);
}
}
// ---- Themes (built-in ones in the app's order, then the rest by id) ------------------------
const themeDirs = dirs(join(base, 'themes'));
const builtinIds = builtinThemes.map(theme => theme.id);
const ordered = [...builtinIds.filter(id => themeDirs.includes(id)), ...themeDirs.filter(id => !builtinIds.includes(id))];
for (const id of ordered) {
const where = `store/${app}/themes/${id}`;
const dir = join(base, 'themes', id);
if (!ITEM_ID.test(id)) { problems.push(`${where}: the folder name is the item id: a-z, 0-9 and -, at most 40 characters`); continue; }
const info = readItemJson(dir, 'theme', problems, where);
if (!info) continue;
if (typeof info.version !== 'string' || !info.version) { problems.push(`${where}/item.json: "version" is needed (for example "1.0.0")`); continue; }
const hasFile = existsSync(join(dir, 'theme.json'));
let theme;
let bytes;
let raw;
if (info.builtin !== undefined) {
theme = builtinThemes.find(candidate => candidate.id === id);
if (info.builtin !== true || !theme) { problems.push(`${where}: "builtin": true needs a built-in theme with the id ${id}`); continue; }
if (hasFile) { problems.push(`${where}: a built-in theme is exported from the app (remove theme.json)`); continue; }
// Exactly what Appearance → Export writes.
bytes = `${JSON.stringify({ $schema: themeSchemaUrl, ...theme }, null, 2)}\n`;
raw = theme;
} else {
if (!hasFile) { problems.push(`${where}: theme.json is missing (Appearance → Export in the app, or npm create waybetter theme)`); continue; }
bytes = readFileSync(join(dir, 'theme.json'));
try { raw = JSON.parse(bytes.toString('utf8')); } catch (error) { problems.push(`${where}/theme.json: not valid JSON (${error.message})`); continue; }
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || typeof raw.name !== 'string' || !raw.name.trim()) { problems.push(`${where}/theme.json: a theme is an object with a "name"`); continue; }
try { theme = sanitizeTheme(raw); } catch (error) { problems.push(`${where}/theme.json: ${error.message}`); continue; }
}
const light = theme.mode === 'light';
const c = theme.colors;
const category = info.category ?? (light ? 'light' : 'dark');
entries.push({
kind: 'theme', id, name: raw.name, author: typeof raw.author === 'string' ? raw.author : '', version: info.version,
description: typeof raw.description === 'string' ? raw.description : '', category, tags: info.tags ?? [info.builtin ? theme.mode : category],
path: `themes/${id}.json`, bytes,
preview: ownPreview(dir, info, 'theme', id, problems, where) ?? { path: `previews/theme-${id}.svg`, bytes: themePreviewSvg(theme) },
colors: c && HEX.test(c.page ?? c.bg) && HEX.test(c.text) && HEX.test(c.accent) ? { bg: c.page ?? c.bg, surface: c.surface, text: c.text, accent: c.accent } : null,
...(info.license !== undefined ? { license: info.license } : {}), ...(info.credits !== undefined ? { credits: info.credits } : {}),
dir: where, firstParty: info.builtin === true, theme: raw,
});
}
// ---- String packs (sorted by id): data that replaces the site's own words --------------------
for (const id of dirs(join(base, 'strings'))) {
const where = `store/${app}/strings/${id}`;
const dir = join(base, 'strings', id);
if (!ITEM_ID.test(id)) { problems.push(`${where}: the folder name is the item id: a-z, 0-9 and -, at most 40 characters`); continue; }
const info = readItemJson(dir, 'strings', problems, where);
if (!info) continue;
const own = readdirSync(dir).filter(file => file.endsWith('.strings.json'));
if (own.length !== 1) { problems.push(`${where}: exactly one *.strings.json file is needed (found ${own.length})`); continue; }
const bytes = readFileSync(join(dir, own[0]));
let pack;
try { pack = JSON.parse(bytes.toString('utf8')); } catch (error) { problems.push(`${where}/${own[0]}: not valid JSON (${error.message})`); continue; }
if (!pack || typeof pack !== 'object' || pack.format !== 1 || typeof pack.name !== 'string' || typeof pack.language !== 'string') { problems.push(`${where}/${own[0]}: a string pack has "format": 1, a "name" and a "language"`); continue; }
if (pack.site !== app) { problems.push(`${where}/${own[0]}: the pack is for "${pack.site}", this folder is ${app}'s`); continue; }
const category = info.category ?? 'language';
entries.push({
kind: 'strings', id, name: pack.name, author: Array.isArray(pack.authors) ? pack.authors.join(', ') : '', version: typeof pack.version === 'string' && pack.version ? pack.version : '1.0.0',
description: typeof pack.description === 'string' ? pack.description : '', category, tags: info.tags ?? [pack.language], language: pack.language,
path: `strings/${id}.strings.json`, bytes,
preview: ownPreview(dir, info, 'strings', id, problems, where) ?? { path: `previews/strings-${id}.svg`, bytes: pluginPreviewSvg({ name: pack.name, category: 'language' }) },
...(info.license !== undefined ? { license: info.license } : {}), ...(info.credits !== undefined ? { credits: info.credits } : {}),
dir: where, firstParty: false, pack, file: own[0],
});
}
// Every built-in theme except the site's own look ("x" is not something to install) is in the Store.
for (const theme of builtinThemes) {
if (theme.id !== 'x' && !themeDirs.includes(theme.id)) problems.push(`built-in theme ${theme.id} has no Store folder: add store/${app}/themes/${theme.id}/item.json with "builtin": true and "version"`);
}
return { entries, problems };
}