Feature modules: a feature table (areas, flags, modes), a registry that runs a module only on its surfaces, one shared observer for every feature and plugin, settings from a schema, selector health with self-pause

- featureTable.ts: areas, per-feature flags, core flags, modes as presets; sparse storage, ownership (an area that is off turns off what it owns), mode switching that keeps or drops manual changes, table validation
- featureModules.ts: createFeatureRegistry (flag + surface gating, scoped context, palette commands under the area with a budget of 5, settings dialog, probes, hotfix selector overrides and kill flags)
- settingsForm.ts: a settings schema normalizes stored values and draws the controls from the UI kit
- domHub observeSelector; api.observe goes through the shared hub (a root of the caller's own keeps its observer)
- createFeatureFlags: a delivery is the whole state (a flag it does not name is at its default), resolve() for ownership, current()
This commit is contained in:
CRTkafa 2026-09-30 18:11:42 +07:00
parent 7cc82a9f2a
commit 43fa215f3b
8 changed files with 1339 additions and 30 deletions

View file

@ -122,6 +122,53 @@ function hubFor(win: DomWindow): Hub {
return hub; return hub;
} }
type SelectorSub = { selector: string; callback: (element: Element) => void; seen: WeakSet<Element>; report(error: unknown): void };
type SelectorHub = { subs: SelectorSub[]; handle: DomWatchHandle | null };
// One per window and heavy-page behaviour: every selector observer of that kind shares its watch.
const selectorHubs = new WeakMap<object, Map<boolean, SelectorHub>>();
export type ObserveOptions = {
/** Skip on the site's heavy pages (default false). */
offOnHeavy?: boolean;
/** A callback that throws is handed here (default: the hub's console line). */
report?(error: unknown): void;
};
/**
* Calls `callback` once for every element matching `selector`, now and as the page renders more.
* Every call shares the hub's one MutationObserver and one frame: a page with a hundred selector
* observers still has one observer, and a mutation costs one frame in which each observer looks
* for elements it has not seen yet. Returns the disposer.
*/
export function observeSelector(win: DomWindow, selector: string, callback: (element: Element) => void, options: ObserveOptions = {}): () => void {
const offOnHeavy = !!options.offOnHeavy;
let kinds = selectorHubs.get(win);
if (!kinds) { kinds = new Map(); selectorHubs.set(win, kinds); }
let hub = kinds.get(offOnHeavy);
if (!hub) { hub = { subs: [], handle: null }; kinds.set(offOnHeavy, hub); }
const owner = hub;
const report = options.report ?? ((error: unknown) => console.error(`[${config.label}] DOM feature failed`, error));
const sub: SelectorSub = { selector, callback, seen: new WeakSet(), report };
const scan = (target: SelectorSub) => {
for (const element of Array.from(win.document.querySelectorAll(target.selector))) {
if (target.seen.has(element)) continue;
target.seen.add(element);
try { target.callback(element); } catch (error) { target.report(error); }
}
};
owner.subs.push(sub);
owner.handle ??= watchDom(win, () => { for (const item of owner.subs.slice()) scan(item); }, { offOnHeavy });
if (!(offOnHeavy && isHeavyPath(win.location.pathname ?? ''))) scan(sub);
let active = true;
return () => {
if (!active) return;
active = false;
const index = owner.subs.indexOf(sub);
if (index >= 0) owner.subs.splice(index, 1);
if (!owner.subs.length) { owner.handle?.dispose(); owner.handle = null; }
};
}
/** /**
* Runs `run` in the next animation frame after body mutations of the watched kinds (child list * Runs `run` in the next animation frame after body mutations of the watched kinds (child list
* always), or whenever `schedule()` is called (scroll, popstate, input, ...). Several calls in one * always), or whenever `schedule()` is called (scroll, popstate, input, ...). Several calls in one

View file

@ -0,0 +1,476 @@
// Feature modules: the code side of the feature table (featureTable.ts). An app's area plugins
// ("Navigation+") are sets of small modules, one per feature; the registry starts a module only
// while its flag is on, its area's switch is on and the page is on one of its surfaces, and
// disposes everything it did when any of those stops being true. A hundred features then cost what
// the ones on screen cost:
//
// const registry = createFeatureRegistry({ win, table, api, label, surfaces, message });
// registry.define({ id: 'navigation.keyboardPlus', start(ctx) { ctx.onKey(...); } });
// registry.setFlags(effectiveFlags(table, flags)); // from the app's feature flags
//
// A module's `start(ctx)` gets a context whose every helper is undone on stop: CSS, listeners,
// nodes, DOM watching through the shared hub (one MutationObserver for every feature, domHub.ts),
// palette commands under its area's name, its words, its storage and its settings. A module with a
// `settings` schema gets a settings dialog drawn from the UI kit (settingsForm.ts); each area with
// such a feature gets one "settings" palette command.
//
// Health: a module names the selectors it depends on (`probes`). After the page has settled, a
// probe that matches nothing is a miss; three misses in a row (three visits) pause that one feature
// for the session, with one toast and a note in the settings dialog. The site's markup changed; the
// rest of the area keeps working. A signed hotfix may replace a probe's selector
// (`selectors["<feature id>.<probe>"]`) or switch a feature off (`flags["<feature id>"] = false`).
import { isHeavyPath, observeSelector, watchDom, type DomWatch, type DomWatchHandle, type DomWindow } from './domHub.ts';
import { areaFlag, type AreaSpec, type FeatureSpec, type FeatureTable, type Flags } from './featureTable.ts';
import { formatMessage, type Params } from './i18n.ts';
import type { CommandDefinition } from './commands.ts';
import type { PluginI18n } from './pluginI18n.ts';
import type { Dispose, PluginScope, PluginStorage } from './pluginApi.ts';
import { buildSettingsForm, normalizeSettings, validateSchema, type SettingValues, type SettingsSchema } from './settingsForm.ts';
import type { UiKit } from './ui.ts';
/** Palette commands one area may register: its "settings" entry and four actions (the tab reports at most 48). */
export const AREA_COMMAND_BUDGET = 5;
/** Misses in a row (separate visits) before a feature pauses itself. */
export const PROBE_STRIKES = 3;
/** The registry's own words in the page (English source; `kit.feature.*` in the framework catalogs). */
export const FEATURE_MESSAGES = {
'kit.feature.paused': '{feature} ({area}) is paused: this page changed.',
'kit.feature.pausedOne': 'A feature of {area} is paused: this page changed.',
'kit.feature.needsEnglish': '{feature} needs the site in English.',
'kit.feature.settings': '{name} settings',
'kit.feature.save': 'Save',
'kit.cancel': 'Cancel',
'kit.failed': 'Something went wrong.',
} as const;
/** A selector a feature depends on; `english`: it reads an English label, so it only counts on an English page. */
export type Probe = string | { selector: string; english?: boolean };
export type FeatureSettings = {
/** The stored values, normalized by the schema. */
get(): SettingValues;
/** Saves (merged over the current values). False when storage refused it. */
set(patch: SettingValues): boolean;
/** Calls `callback(values)` after a save, until the feature stops. */
onChange(callback: (values: SettingValues) => void): void;
/** Opens this feature's settings dialog. */
open(): void;
};
export type FeatureContext<Api> = {
/** The flag id and the feature's own name (`navigation.focusMode` -> `focusMode`). */
readonly id: string;
readonly name: string;
readonly area: AreaSpec;
/** The app's plugin API, unrestricted: a feature module is the app's own code. */
readonly api: Api;
/** This feature's stylesheet (one per `name`, replaced in place, cleared by an empty string; removed on stop). */
css(css: string, name?: string): void;
/** `callback` once per element matching `selector`, through the shared hub; paused on heavy pages unless the feature says `heavy`. */
observe(selector: string, callback: (element: Element) => void): void;
/** A raw hub subscription (domHub `watchDom`), disposed on stop. */
watch(run: () => void, options?: DomWatch): DomWatchHandle;
on(target: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
onKey(callback: (event: KeyboardEvent, item: Element | null) => void): void;
onRouteChange(callback: (href: string, previous: string) => void): void;
/** Tracks a node the feature inserted; removed on stop. */
add<T extends Node>(node: T): T;
/** Runs `fn` on stop. */
defer(fn: Dispose): void;
/** The UI kit; what the feature opened is closed on stop. */
readonly ui: UiKit;
/** A palette command under the area's name (counts towards `AREA_COMMAND_BUDGET`), removed on stop. */
command(definition: CommandDefinition): void;
/** The feature's word `key`: `plugin.<area namespace>.<name>.<key>` in the app's catalog. */
t(key: string, params?: Params): string;
/** The feature's storage (its module's `storage` namespace). */
readonly storage: PluginStorage;
/** Its settings (a module with a `settings` schema; otherwise empty values). */
readonly settings: FeatureSettings;
/** The selector of probe `name` (a hotfix override wins). */
selector(name: string): string;
/** The surfaces the page is on right now. */
surfaces(): readonly string[];
};
export type FeatureModule<Api> = {
/** The flag id; the table must list it with `backing: 'module'`. */
id: string;
/** Selectors it depends on, by name (read them back with `ctx.selector(name)`). */
probes?: Readonly<Record<string, Probe>>;
/** Storage namespace (default `<area namespace>.<name>`; a ported plugin keeps its old one). */
storage?: string;
/** The key its settings are stored under (default `settings`). */
settingsKey?: string;
settings?: SettingsSchema;
start(ctx: FeatureContext<Api>): void;
};
/** What the registry needs of the plugin API (the core API has all of it). */
export type RegistryApi = {
scope(): PluginScope;
injectCSS(id: string, css: string): void;
clearCSS(id: string): void;
storage(namespace: string): PluginStorage;
onRouteChange(callback: (href: string, previous: string) => void): Dispose;
ui: UiKit;
i18n: PluginI18n;
commands: { withOwner<T>(owner: string, fn: () => T): T };
};
export type HotfixData = { selectors?: Readonly<Record<string, unknown>>; flags?: Readonly<Record<string, unknown>> };
export type FeatureHealth = { id: string; area: string; state: 'paused' | 'needs-english'; probes: string[] };
export type FeatureRegistryOptions<Api extends RegistryApi> = {
win: Window & typeof globalThis;
table: FeatureTable;
api: Api;
/** Console prefix (the app's name). */
label: string;
/** The surfaces the page is on (`['timeline', 'home']`); the app's classifier. */
surfaces(): readonly string[];
/** The app catalog's message for `key` in the active language (the registry's `kit.feature.*` words). */
message?(key: string): string | undefined;
locale?(): string;
/** The signed hotfix data, when the app has any (selector overrides and kill flags). */
hotfix?(): HotfixData | null | undefined;
/** The page has rendered its content (the site's main column is there); default: the body has children. */
settled?(): boolean;
/** The page's language is English (probes marked `english` only count then); default: `<html lang>` starts with `en`. */
english?(): boolean;
/** ms after the page settled before probes are judged (default 3000) and between settle checks (default 500). */
settleMs?: number;
pollMs?: number;
timers?: { setTimeout(fn: () => void, ms: number): unknown; clearTimeout(id: unknown): void };
};
export type FeatureRegistry<Api> = {
define(module: FeatureModule<Api>): void;
/** The effective flags (featureTable `effectiveFlags`): starts and stops modules to match. */
setFlags(flags: Readonly<Flags>): void;
/** Re-checks surfaces (the registry also does it on every route change). */
refresh(): void;
/** The ids of the modules running right now. */
active(): string[];
/** Paused features and features waiting for an English page. */
health(): FeatureHealth[];
/** Opens the settings dialog of an area (or of one feature). False when nothing in it has settings right now. */
openSettings(area: string, feature?: string): boolean;
/** Stops everything (the runtime is going away; tests). */
dispose(): void;
};
type Running<Api> = {
module: FeatureModule<Api>;
spec: FeatureSpec;
area: AreaSpec;
scope: PluginScope;
commands: number;
listeners: Set<(values: SettingValues) => void>;
settings: FeatureSettings;
visit: number;
timer: unknown;
};
const featureName = (id: string) => id.slice(id.indexOf('.') + 1);
export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureRegistryOptions<Api>): FeatureRegistry<Api> {
const { win, table, api, label } = options;
const doc = win.document;
const timers = options.timers ?? { setTimeout: (fn: () => void, ms: number) => win.setTimeout(fn, ms), clearTimeout: (id: unknown) => win.clearTimeout(id as number) };
const settleMs = options.settleMs ?? 3000;
const pollMs = options.pollMs ?? 500;
const specs = new Map(table.features.map(feature => [feature.id, feature]));
const areas = new Map(table.areas.map(area => [area.id, area]));
const modules = new Map<string, FeatureModule<Api>>();
const running = new Map<string, Running<Api>>();
const areaScopes = new Map<string, PluginScope>();
const strikes = new Map<string, number>();
const paused = new Map<string, string[]>();
const waiting = new Map<string, string[]>();
let flags: Readonly<Flags> = {};
let stopRoutes: Dispose | null = null;
let visit = 0;
const text = (key: keyof typeof FEATURE_MESSAGES, params: Params = {}) =>
formatMessage(options.message?.(key) ?? FEATURE_MESSAGES[key], params, options.locale?.() ?? 'en');
const hotfix = (): HotfixData => { try { return options.hotfix?.() ?? {}; } catch { return {}; } };
const english = () => options.english?.() ?? /^en\b/i.test(doc.documentElement?.getAttribute?.('lang') ?? 'en');
const settled = () => options.settled?.() ?? !!doc.body?.firstElementChild;
const words = (area: AreaSpec) => api.i18n.namespace(area.namespace);
/** A feature's label in the page, when the page has it (`plugin.*` words only reach a site tab). */
const featureLabel = (spec: FeatureSpec, area: AreaSpec) => {
const i18n = words(area);
const key = `feature.${featureName(spec.id)}.label`;
return i18n.has(key) ? i18n.t(key) : null;
};
const selectorOf = (module: FeatureModule<Api>, name: string) => {
const override = hotfix().selectors?.[`${module.id}.${name}`];
if (typeof override === 'string' && override.trim()) return override;
const probe = module.probes?.[name];
if (probe === undefined) throw new Error(`${module.id}: no probe named ${JSON.stringify(name)}`);
return typeof probe === 'string' ? probe : probe.selector;
};
function wanted(module: FeatureModule<Api>): boolean {
const spec = specs.get(module.id)!;
if (flags[module.id] !== true || paused.has(module.id) || hotfix().flags?.[module.id] === false) return false;
if (!spec.heavy && isHeavyPath(win.location.pathname ?? '')) return false;
if (!spec.surfaces?.length) return true;
const on = options.surfaces();
return spec.surfaces.some(surface => on.includes(surface));
}
function settingsOf(module: FeatureModule<Api>, area: AreaSpec, listeners: Set<(values: SettingValues) => void>): FeatureSettings {
const schema = module.settings ?? [];
const store = () => api.storage(module.storage ?? `${area.namespace}.${featureName(module.id)}`);
const key = module.settingsKey ?? 'settings';
const get = () => normalizeSettings(schema, store().get<unknown>(key, null));
return {
get,
set(patch) {
const next = normalizeSettings(schema, { ...get(), ...patch });
const saved = store().set(key, next);
for (const listener of [...listeners]) {
try { listener(next); } catch (error) { console.error(`[${label}] ${module.id} settings listener failed`, error); }
}
return saved;
},
onChange(callback) { listeners.add(callback); },
open() { openSettings(area.id, module.id); },
};
}
function start(module: FeatureModule<Api>) {
const spec = specs.get(module.id)!;
const area = areas.get(spec.area!)!;
const scope = api.commands.withOwner(area.owner, () => api.scope());
const listeners = new Set<(values: SettingValues) => void>();
const entry: Running<Api> = { module, spec, area, scope, commands: 0, listeners, settings: settingsOf(module, area, listeners), visit: -1, timer: null };
const name = featureName(module.id);
const domWin = win as unknown as DomWindow;
const styles = new Set<string>();
const ctx: FeatureContext<Api> = {
id: module.id,
name,
area,
api,
css(css, part = '') {
const styleId = `wbf-${module.id}${part ? `-${part}` : ''}`;
if (!styles.has(styleId)) { styles.add(styleId); scope.defer(() => api.clearCSS(styleId)); }
if (css) api.injectCSS(styleId, css); else api.clearCSS(styleId);
},
observe(selector, callback) {
scope.defer(observeSelector(domWin, selector, callback, { offOnHeavy: !spec.heavy, report: error => console.error(`[${label}] ${module.id} failed`, error) }));
},
watch(run, watchOptions = {}) {
const handle = watchDom(domWin, run, { offOnHeavy: !spec.heavy, ...watchOptions });
scope.defer(() => handle.dispose());
return handle;
},
on: (target, type, listener, listenerOptions) => scope.on(target, type, listener, listenerOptions),
onKey: callback => scope.onKey(callback),
onRouteChange: callback => scope.onRouteChange(callback),
add: node => scope.add(node),
defer: fn => scope.defer(fn),
get ui() { return scope.ui; },
command(definition) {
const reserved = table.features.some(feature => feature.area === area.id && feature.settings) ? 1 : 0;
const used = [...running.values()].filter(other => other.area.id === area.id).reduce((sum, other) => sum + other.commands, 0);
if (used + reserved >= AREA_COMMAND_BUDGET) throw new Error(`${area.name}: at most ${AREA_COMMAND_BUDGET} palette commands per area`);
scope.commands.register(definition);
entry.commands += 1;
},
t: (key, params) => words(area).t(`${name}.${key}`, params),
get storage() { return api.storage(module.storage ?? `${area.namespace}.${name}`); },
settings: entry.settings,
selector: probe => selectorOf(module, probe),
surfaces: () => options.surfaces(),
};
running.set(module.id, entry);
try {
module.start(ctx);
} catch (error) {
console.error(`[${label}] ${module.id} failed`, error);
stop(module.id);
return;
}
scheduleProbes(entry);
}
function stop(id: string) {
const entry = running.get(id);
if (!entry) return;
running.delete(id);
if (entry.timer !== null) timers.clearTimeout(entry.timer);
entry.listeners.clear();
entry.scope.dispose();
}
// ---- Health ----------------------------------------------------------------------------------
function scheduleProbes(entry: Running<Api>) {
if (!entry.module.probes || !Object.keys(entry.module.probes).length || entry.visit === visit) return;
entry.visit = visit;
if (entry.timer !== null) timers.clearTimeout(entry.timer);
const mine = visit;
let tries = 0;
const waitForSettle = () => {
entry.timer = null;
if (running.get(entry.module.id) !== entry || mine !== visit) return;
if (!settled()) {
tries += 1;
// A page that never settles (an error page, a sign-in wall) is no verdict.
if (tries <= 20) entry.timer = timers.setTimeout(waitForSettle, pollMs);
return;
}
entry.timer = timers.setTimeout(judge, settleMs);
};
const judge = () => {
entry.timer = null;
if (running.get(entry.module.id) !== entry || mine !== visit) return;
const id = entry.module.id;
const missing: string[] = [];
const needEnglish: string[] = [];
const inEnglish = english();
for (const [name, probe] of Object.entries(entry.module.probes ?? {})) {
if (typeof probe !== 'string' && probe.english && !inEnglish) { needEnglish.push(name); continue; }
let found = false;
try { found = !!doc.querySelector(selectorOf(entry.module, name)); } catch { found = false; }
if (!found) missing.push(name);
}
if (needEnglish.length) waiting.set(id, needEnglish); else waiting.delete(id);
if (!missing.length) { strikes.delete(id); return; }
const count = (strikes.get(id) ?? 0) + 1;
strikes.set(id, count);
if (count < PROBE_STRIKES) return;
paused.set(id, missing);
stop(id);
syncAreas();
console.warn(`[${label}] ${id} paused: nothing matches ${missing.join(', ')}`);
const feature = featureLabel(entry.spec, entry.area);
try {
api.ui.toast(feature ? text('kit.feature.paused', { feature, area: entry.area.name }) : text('kit.feature.pausedOne', { area: entry.area.name }), { tone: 'warning', duration: 8000 });
} catch { /* a page without a body yet: the note in the settings dialog remains */ }
};
entry.timer = timers.setTimeout(waitForSettle, pollMs);
}
// ---- Settings dialog and the area's command --------------------------------------------------
function openSettings(areaId: string, only?: string): boolean {
const area = areas.get(areaId);
if (!area) return false;
const entries = [...running.values()].filter(entry => entry.area.id === areaId && entry.module.settings?.length && (!only || entry.module.id === only));
const notes = health().filter(note => note.area === areaId);
if (!entries.length && !notes.length) return false;
const ui = api.ui;
const h = ui.h;
const forms = entries.map(entry => {
const name = featureName(entry.module.id);
const i18n = words(area);
return { entry, title: featureLabel(entry.spec, area) ?? name, form: buildSettingsForm(h, entry.module.settings!, entry.settings.get(), key => i18n.t(`${name}.${key}`)) };
});
const single = forms.length === 1 && !notes.length ? forms[0]! : null;
ui.dialog({
title: text('kit.feature.settings', { name: single ? single.title : area.name }),
content: body => {
forms.forEach((item, index) => {
if (index > 0) body.append(h('div', { class: 'wb-divider' }));
if (!single) body.append(h('p', { class: 'wb-label' }, item.title));
body.append(...item.form.nodes);
});
for (const note of notes) {
const spec = specs.get(note.id)!;
const feature = featureLabel(spec, area) ?? featureName(note.id);
body.append(h('p', { class: 'wb-hint' }, note.state === 'paused' ? text('kit.feature.paused', { feature, area: area.name }) : text('kit.feature.needsEnglish', { feature })));
}
},
actions: forms.length ? [
{ label: text('kit.cancel') },
{
label: text('kit.feature.save'), tone: 'primary', default: true,
onClick: handle => {
const failed = forms.filter(item => !item.entry.settings.set(item.form.read()));
if (failed.length) { handle.setError(text('kit.failed')); return false; }
return undefined;
},
},
] : undefined,
});
return true;
}
/** Each area with a running feature that has settings gets its one "settings" palette command. */
function syncAreas() {
for (const area of table.areas) {
const needs = [...running.values()].some(entry => entry.area.id === area.id && entry.module.settings?.length);
const scope = areaScopes.get(area.id);
if (needs && !scope) {
const created = api.commands.withOwner(area.owner, () => api.scope());
areaScopes.set(area.id, created);
try {
created.commands.register({ id: 'settings', title: text('kit.feature.settings', { name: area.name }), keywords: `settings options configure ${area.name}`, run: () => { openSettings(area.id); } });
} catch (error) { console.error(`[${label}] ${area.name} settings command failed`, error); }
} else if (!needs && scope) {
scope.dispose();
areaScopes.delete(area.id);
}
}
}
function health(): FeatureHealth[] {
const out: FeatureHealth[] = [];
for (const [id, probes] of paused) out.push({ id, area: specs.get(id)!.area!, state: 'paused', probes });
for (const [id, probes] of waiting) if (!paused.has(id)) out.push({ id, area: specs.get(id)!.area!, state: 'needs-english', probes });
return out;
}
function refresh() {
for (const module of modules.values()) {
const on = running.has(module.id);
const want = wanted(module);
if (want && !on) start(module);
else if (!want && on) stop(module.id);
else if (want && on) scheduleProbes(running.get(module.id)!);
}
syncAreas();
}
return {
define(module) {
const spec = specs.get(module.id);
if (!spec || spec.backing !== 'module' || spec.area === null || !areas.has(spec.area)) throw new Error(`${label}: ${module.id} is not a feature module in the table`);
if (modules.has(module.id)) throw new Error(`${label}: ${module.id} is defined twice`);
const problems = validateSchema(module.settings ?? []);
if (problems.length) throw new Error(`${label}: ${module.id} settings: ${problems.join('; ')}`);
if (!!module.settings?.length !== !!spec.settings) throw new Error(`${label}: ${module.id}: the table's "settings" and the module's schema disagree`);
modules.set(module.id, module);
stopRoutes ??= api.onRouteChange(() => { visit += 1; refresh(); });
if (wanted(module)) { start(module); syncAreas(); }
},
setFlags(next) {
flags = { ...next };
refresh();
},
refresh,
active: () => [...running.keys()],
health,
openSettings,
dispose() {
stopRoutes?.();
stopRoutes = null;
for (const id of [...running.keys()]) stop(id);
for (const scope of areaScopes.values()) scope.dispose();
areaScopes.clear();
modules.clear();
},
};
}
/** Whether an area's switch is on in `flags` (a missing value counts as on). */
export const areaEnabled = (flags: Readonly<Flags>, area: string) => flags[areaFlag(area)] !== false;

View file

@ -0,0 +1,233 @@
// The feature table: one data description of everything an app lets its owner switch, shared by the
// page runtime (which flags exist, who owns them), the panel (the area cards, the Fixes list, the
// onboarding modes) and the app's native side (the migration list it generates from it). Pure data
// and pure functions: no DOM, no storage.
//
// - An AREA is one card in the Plugins list ("Navigation+"): a master switch and the features it
// owns. Its switch is the flag `area.<id>`.
// - A FEATURE is one on/off flag. It belongs to an area, or to nobody (`area: null`: a core flag
// such as a reliability fix, which no plugin switch can turn off). Where its code lives is its
// `backing`: a feature module in the registry (featureModules.ts), a part of the app runtime
// (request hubs, native commands, document-start timing), or an old plugin file that has not
// been ported yet (then it is not a flag at all: its switch is that file's enabled state).
// - A MODE is a preset (Basic / Advanced / Power User): the flag values it starts from. A mode is a
// starting point, not a lock: every flag stays individually switchable afterwards.
//
// Flags are stored sparsely (`sparseFlags`): only values that differ from the table's defaults.
/** Flags a store may hold (the native cap, waybetter-host `settings::MAX_FEATURES`). */
export const FLAG_LIMIT = 256;
/** Characters in a flag key (the native cap). */
export const FLAG_KEY_LIMIT = 64;
export type FeatureBacking = 'module' | 'app' | 'plugin';
export type FeatureSpec = {
/** The flag key. Existing names stay as they are; new ones are `<area>.<feature>`. */
id: string;
/** The owning area, or null for a core flag. */
area: string | null;
/** The rows it is listed with inside its card (words: `features.group.<group>`). */
group?: string;
/** Its value when nothing is stored. */
default: boolean;
/**
* Where its code lives: `module` = a feature module (featureModules.ts); `app` = a part of the
* app runtime that installs on the flag; `plugin` = an old plugin file until it is ported.
*/
backing: FeatureBacking;
/** `backing: 'plugin'`: that file. Its enabled state is the switch; `id` is the flag it becomes. */
file?: string;
/** The old plugin file this feature replaces: the one-time migration turns its enabled state into this flag. */
supersedes?: string;
/** Surfaces it runs on (ids from the app's surface classifier); omitted = every page. */
surfaces?: readonly string[];
/** Also runs on the site's heavy pages (domHub `heavyPath`). */
heavy?: boolean;
/** Catalog key of its label (default `features.<id>.label`). */
label?: string;
/** Catalog key of its description (default `features.<id>.description`). */
description?: string;
/** It has settings of its own (a settings schema on its module): the card offers "Settings". */
settings?: boolean;
/** Extra words the panel search matches (an old plugin's name). */
keywords?: string;
/** The gated plugin API it uses (shown on the card). */
permissions?: readonly string[];
};
export type AreaSpec = {
/** `navigation`: lowercase letters, digits and `-`. */
id: string;
/** The card's name: a product name, the same in every language. */
name: string;
/** Catalog key of the card's description. */
description: string;
/** A 16x16 stroke path for the card's icon. */
icon?: string;
/**
* The owner of its palette commands and the file it ships as once it is a plugin file
* (`bt-navigation-plus.plugin.js`). A valid plugin file name.
*/
owner: string;
/** Its words in the page: `plugin.<namespace>.*` (`navigation-plus`). */
namespace: string;
};
export type ModeSpec = {
id: string;
/** Catalog keys of its name and one-line description. */
name: string;
description: string;
/** The preselected one on the first-run screen. */
recommended?: boolean;
/** Flag values that differ from the table's defaults. */
flags: Readonly<Record<string, boolean>>;
};
export type FeatureTable = {
areas: readonly AreaSpec[];
features: readonly FeatureSpec[];
modes: readonly ModeSpec[];
};
export type Flags = Record<string, boolean>;
/** The flag that is an area's master switch. */
export const areaFlag = (area: string) => `area.${area}`;
/** Features that are flags (everything but the ones still backed by an old plugin file). */
export const flagFeatures = (table: FeatureTable) => table.features.filter(feature => feature.backing !== 'plugin');
export const areaFeatures = (table: FeatureTable, area: string) => table.features.filter(feature => feature.area === area);
export const coreFeatures = (table: FeatureTable) => table.features.filter(feature => feature.area === null);
/** The catalog keys of a feature's label and description. */
export function featureWords(feature: FeatureSpec): { label: string; description: string } {
return { label: feature.label ?? `features.${feature.id}.label`, description: feature.description ?? `features.${feature.id}.description` };
}
/** Every flag with its default: the features that are flags, and each area's switch (on). */
export function tableDefaults(table: FeatureTable): Flags {
const out: Flags = {};
for (const feature of flagFeatures(table)) out[feature.id] = feature.default;
for (const area of table.areas) out[areaFlag(area.id)] = true;
return out;
}
/** The full flag map for `input`: unknown keys are dropped, anything not a boolean takes the default. */
export function normalizeFlags(table: FeatureTable, input: unknown): Flags {
const source = input && typeof input === 'object' ? input as Record<string, unknown> : {};
const out = tableDefaults(table);
for (const key of Object.keys(out)) if (typeof source[key] === 'boolean') out[key] = source[key] as boolean;
return out;
}
/** What is stored: only the flags whose value differs from the default. */
export function sparseFlags(table: FeatureTable, flags: Readonly<Record<string, unknown>>): Flags {
const defaults = tableDefaults(table);
const out: Flags = {};
for (const [key, fallback] of Object.entries(defaults)) {
const value = flags[key];
if (typeof value === 'boolean' && value !== fallback) out[key] = value;
}
return out;
}
/**
* What runs: a feature owned by an area is off while that area's switch is off. Core flags and the
* area switches themselves pass through.
*/
export function effectiveFlags(table: FeatureTable, flags: Readonly<Flags>): Flags {
const out: Flags = { ...flags };
for (const feature of flagFeatures(table)) {
if (feature.area !== null && flags[areaFlag(feature.area)] === false) out[feature.id] = false;
}
return out;
}
export const modeById = (table: FeatureTable, id: string | null | undefined) => table.modes.find(mode => mode.id === id) ?? null;
/** The full flag map a mode starts from (an unknown or null mode: the defaults). */
export function modeFlags(table: FeatureTable, mode: string | null | undefined): Flags {
const out = tableDefaults(table);
const preset = modeById(table, mode)?.flags ?? {};
for (const [key, value] of Object.entries(preset)) if (key in out) out[key] = value;
return out;
}
/** The flags whose value is not what `mode` starts from: the owner's own changes. */
export function manualChanges(table: FeatureTable, flags: Readonly<Flags>, mode: string | null | undefined): string[] {
const preset = modeFlags(table, mode);
return Object.keys(preset).filter(key => typeof flags[key] === 'boolean' && flags[key] !== preset[key]);
}
/**
* The flags after choosing mode `to` while on mode `from` (null = never chosen). `keep`: the
* owner's own changes (whatever differs from `from`) stay on top of the new mode; otherwise the
* new mode's values apply as they are.
*/
export function switchMode(table: FeatureTable, flags: Readonly<Flags>, from: string | null | undefined, to: string, keep: boolean): Flags {
const next = modeFlags(table, to);
if (keep) for (const key of manualChanges(table, flags, from)) next[key] = flags[key]!;
return next;
}
/** The old plugin files the table's features replace, for the app's native migration list. */
export function supersededFiles(table: FeatureTable): { file: string; flag: string }[] {
return table.features.filter(feature => feature.supersedes && feature.backing !== 'plugin').map(feature => ({ file: feature.supersedes!, flag: feature.id }));
}
const FLAG_ID = /^[A-Za-z][A-Za-z0-9]*(?:\.[A-Za-z][A-Za-z0-9]*)?$/;
const AREA_ID = /^[a-z][a-z0-9-]{0,31}$/;
const MODE_ID = /^[a-z][a-z0-9-]{0,31}$/;
const PLUGIN_FILE = /^[A-Za-z0-9_\- ][A-Za-z0-9_.\- ]{0,117}\.plugin\.js$/;
/** Problems in a table (an empty list: valid). Run it in the app's tests. */
export function validateTable(table: FeatureTable): string[] {
const problems: string[] = [];
const areas = new Set<string>();
for (const area of table.areas) {
if (!AREA_ID.test(area.id)) problems.push(`area ${JSON.stringify(area.id)}: invalid id`);
if (areas.has(area.id)) problems.push(`area ${area.id}: listed twice`);
areas.add(area.id);
if (!PLUGIN_FILE.test(area.owner)) problems.push(`area ${area.id}: owner must be a plugin file name`);
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(area.namespace)) problems.push(`area ${area.id}: invalid namespace`);
if (!area.name.trim() || !area.description.trim()) problems.push(`area ${area.id}: name and description are required`);
}
const ids = new Set<string>();
const files = new Set<string>();
for (const feature of table.features) {
if (!FLAG_ID.test(feature.id) || feature.id.length > FLAG_KEY_LIMIT) problems.push(`feature ${JSON.stringify(feature.id)}: invalid id`);
if (feature.id.startsWith('area.')) problems.push(`feature ${feature.id}: "area." is kept for the area switches`);
if (ids.has(feature.id)) problems.push(`feature ${feature.id}: owned twice`);
ids.add(feature.id);
if (feature.area !== null && !areas.has(feature.area)) problems.push(`feature ${feature.id}: unknown area ${feature.area}`);
if (feature.backing === 'plugin') {
if (!feature.file || !PLUGIN_FILE.test(feature.file)) problems.push(`feature ${feature.id}: a plugin-backed feature names its file`);
if (feature.area === null) problems.push(`feature ${feature.id}: a plugin-backed feature belongs to an area`);
if (feature.default) problems.push(`feature ${feature.id}: a plugin file is off until its owner turns it on`);
} else if (feature.file) problems.push(`feature ${feature.id}: only a plugin-backed feature names a file`);
for (const file of [feature.file, feature.supersedes]) {
if (!file) continue;
if (!PLUGIN_FILE.test(file)) problems.push(`feature ${feature.id}: invalid file ${JSON.stringify(file)}`);
if (files.has(file)) problems.push(`feature ${feature.id}: ${file} is named twice`);
files.add(file);
}
if (feature.backing !== 'module' && feature.settings) problems.push(`feature ${feature.id}: only a feature module has a settings schema`);
}
const defaults = tableDefaults(table);
if (Object.keys(defaults).length > FLAG_LIMIT) problems.push(`${Object.keys(defaults).length} flags: at most ${FLAG_LIMIT}`);
const modes = new Set<string>();
for (const mode of table.modes) {
if (!MODE_ID.test(mode.id)) problems.push(`mode ${JSON.stringify(mode.id)}: invalid id`);
if (modes.has(mode.id)) problems.push(`mode ${mode.id}: listed twice`);
modes.add(mode.id);
for (const [key, value] of Object.entries(mode.flags)) {
if (!(key in defaults)) problems.push(`mode ${mode.id}: unknown flag ${key}`);
else if (value === defaults[key]) problems.push(`mode ${mode.id}: ${key} is already the default`);
}
}
if (table.modes.length && table.modes.filter(mode => mode.recommended).length !== 1) problems.push('exactly one mode is the recommended one');
return problems;
}

View file

@ -9,6 +9,7 @@
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 { adoptStyles, type RootStyles } from './styles.ts'; import { adoptStyles, type RootStyles } from './styles.ts';
import { observeSelector } from './domHub.ts';
import { createCommandRegistry, type CommandDefinition, type CommandInfo, type CommandRegistry } from './commands.ts'; import { createCommandRegistry, type CommandDefinition, type CommandInfo, type CommandRegistry } from './commands.ts';
import { createPluginI18n, type I18nSource, type PluginI18n, type PluginMessages } from './pluginI18n.ts'; import { createPluginI18n, type I18nSource, type PluginI18n, type PluginMessages } from './pluginI18n.ts';
@ -60,7 +61,10 @@ export type CorePluginApi = {
storage(namespace: string): PluginStorage; storage(namespace: string): PluginStorage;
/** Called after the page changes route (pushState/replaceState/back/forward). */ /** Called after the page changes route (pushState/replaceState/back/forward). */
onRouteChange(callback: (href: string, previous: string) => void): Dispose; onRouteChange(callback: (href: string, previous: string) => void): Dispose;
/** Calls `callback` once for every element matching `selector`, now and as the page renders more. */ /**
* Calls `callback` once for every element matching `selector`, now and as the page renders more.
* Page-wide observers share one MutationObserver (domHub.ts); pass `root` only for a tree of your own.
*/
observe(selector: string, callback: (element: Element) => void, root?: ParentNode): Dispose; observe(selector: string, callback: (element: Element) => void, root?: ParentNode): Dispose;
/** /**
* Single-key shortcuts: `callback(event, focusedItem)` runs only when the user is not typing, no * Single-key shortcuts: `callback(event, focusedItem)` runs only when the user is not typing, no
@ -263,13 +267,16 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
}; };
}, },
observe(selector, callback, root) { observe(selector, callback, root) {
// The whole page: the shared hub (one MutationObserver and one frame for every plugin and
// feature). A root of the caller's own (a shadow root, a detached tree) keeps its own observer.
if (!root || root === doc) return observeSelector(win, selector, callback, { report });
const seen = new WeakSet<Element>(); const seen = new WeakSet<Element>();
let frame = 0; let frame = 0;
let disposed = false; let disposed = false;
const scan = () => { const scan = () => {
frame = 0; frame = 0;
if (disposed) return; if (disposed) return;
for (const element of Array.from((root ?? doc).querySelectorAll(selector))) { for (const element of Array.from(root.querySelectorAll(selector))) {
if (seen.has(element)) continue; if (seen.has(element)) continue;
seen.add(element); seen.add(element);
try { callback(element); } catch (error) { report(error); } try { callback(element); } catch (error) { report(error); }
@ -278,7 +285,7 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
const observer = new win.MutationObserver(() => { const observer = new win.MutationObserver(() => {
if (!frame) frame = win.requestAnimationFrame(scan); if (!frame) frame = win.requestAnimationFrame(scan);
}); });
observer.observe((root as Node | undefined) ?? doc.documentElement, { childList: true, subtree: true }); observer.observe(root as Node, { childList: true, subtree: true });
scan(); scan();
return () => { return () => {
disposed = true; disposed = true;

View file

@ -0,0 +1,135 @@
// A settings schema: what a feature (or a plugin) lets its owner adjust, as data. The same schema
// gives the stored values their shape (`normalizeSettings`: anything missing or of the wrong type
// takes the field's default, so an old or damaged store never breaks a feature) and draws the
// controls from the UI kit's form parts (`buildSettingsForm`: check boxes, number, text, select and
// list fields inside a kit dialog). Labels and hints are catalog keys the caller translates.
import type { UiKit } from './ui.ts';
type FieldBase = {
/** The key in the stored values. */
key: string;
/** Catalog key of the label. */
label: string;
/** Catalog key of a line under the label. */
hint?: string;
};
export type SettingField =
| (FieldBase & { type: 'toggle'; default: boolean })
| (FieldBase & { type: 'number'; default: number; min?: number; max?: number; step?: number })
| (FieldBase & { type: 'text'; default: string; maxLength?: number; multiline?: boolean; placeholder?: string })
| (FieldBase & { type: 'select'; default: string; options: ReadonlyArray<{ value: string; label: string }> })
/** Lines of text (patterns, handles): one per line in the form. */
| (FieldBase & { type: 'list'; default: readonly string[]; maxItems?: number; maxLength?: number })
| { type: 'divider' };
export type SettingsSchema = readonly SettingField[];
export type SettingValue = boolean | number | string | string[];
export type SettingValues = Record<string, SettingValue>;
export const SETTINGS_LIMITS = Object.freeze({ fields: 64, text: 2000, listItems: 500, listItem: 500 });
type ValueField = Exclude<SettingField, { type: 'divider' }>;
const valueFields = (schema: SettingsSchema) => schema.filter((field): field is ValueField => field.type !== 'divider');
function fieldValue(field: ValueField, value: unknown): SettingValue {
switch (field.type) {
case 'toggle':
return typeof value === 'boolean' ? value : field.default;
case 'number': {
if (typeof value !== 'number' || !Number.isFinite(value)) return field.default;
return Math.min(field.max ?? Infinity, Math.max(field.min ?? -Infinity, value));
}
case 'text':
return typeof value === 'string' ? value.slice(0, Math.min(field.maxLength ?? SETTINGS_LIMITS.text, SETTINGS_LIMITS.text)) : field.default;
case 'select':
return typeof value === 'string' && field.options.some(option => option.value === value) ? value : field.default;
case 'list': {
if (!Array.isArray(value)) return [...field.default];
const max = Math.min(field.maxLength ?? SETTINGS_LIMITS.listItem, SETTINGS_LIMITS.listItem);
return value.filter((item): item is string => typeof item === 'string' && item.trim() !== '').map(item => item.slice(0, max)).slice(0, Math.min(field.maxItems ?? SETTINGS_LIMITS.listItems, SETTINGS_LIMITS.listItems));
}
}
}
/** The values for `schema` from whatever was stored: every field present, every value of its type and in range. */
export function normalizeSettings(schema: SettingsSchema, stored: unknown): SettingValues {
const source = stored && typeof stored === 'object' ? stored as Record<string, unknown> : {};
const out: SettingValues = {};
for (const field of valueFields(schema)) out[field.key] = fieldValue(field, source[field.key]);
return out;
}
/** Problems in a schema (an empty list: valid). */
export function validateSchema(schema: SettingsSchema): string[] {
const problems: string[] = [];
const keys = new Set<string>();
const fields = valueFields(schema);
if (fields.length > SETTINGS_LIMITS.fields) problems.push(`at most ${SETTINGS_LIMITS.fields} fields`);
for (const field of fields) {
if (!/^[A-Za-z][A-Za-z0-9]{0,39}$/.test(field.key)) problems.push(`invalid key ${JSON.stringify(field.key)}`);
if (keys.has(field.key)) problems.push(`${field.key}: listed twice`);
keys.add(field.key);
if (!field.label) problems.push(`${field.key}: a label is required`);
if (field.type === 'select' && !field.options.some(option => option.value === field.default)) problems.push(`${field.key}: the default is not an option`);
if (field.type === 'number' && (field.min ?? -Infinity) > (field.max ?? Infinity)) problems.push(`${field.key}: min is above max`);
}
return problems;
}
export type SettingsForm = {
/** The controls, in schema order: append them to a dialog's body. */
nodes: HTMLElement[];
/** The values as the controls show them now (normalized). */
read(): SettingValues;
};
/**
* The controls for `schema` showing `values`, built with the kit's element builder and styled by the
* kit's form classes. `text(key)` translates a label, hint or option key.
*/
export function buildSettingsForm(h: UiKit['h'], schema: SettingsSchema, values: SettingValues, text: (key: string) => string): SettingsForm {
const readers: Array<[ValueField, () => unknown]> = [];
const nodes: HTMLElement[] = [];
for (const field of schema) {
if (field.type === 'divider') { nodes.push(h('div', { class: 'wb-divider' })); continue; }
const value = values[field.key];
const hint = field.hint ? text(field.hint) : '';
if (field.type === 'toggle') {
const input = h('input', { type: 'checkbox', checked: value === true }) as HTMLInputElement;
nodes.push(h('label', { class: 'wb-check' }, input, h('span', null, text(field.label), hint ? h('small', null, hint) : null)));
readers.push([field, () => input.checked]);
continue;
}
let control: HTMLElement;
if (field.type === 'number') {
const input = h('input', { type: 'number', value: String(value), min: field.min, max: field.max, step: field.step ?? 1 }) as HTMLInputElement;
readers.push([field, () => (input.value.trim() === '' ? NaN : Number(input.value))]);
control = input;
} else if (field.type === 'select') {
const select = h('select', null, field.options.map(option => h('option', { value: option.value, selected: option.value === value }, text(option.label)))) as HTMLSelectElement;
readers.push([field, () => select.value]);
control = select;
} else if (field.type === 'list') {
const area = h('textarea', { class: 'wb-mono', rows: 5, spellcheck: false, value: (value as string[]).join('\n') }) as HTMLTextAreaElement;
readers.push([field, () => area.value.split(/\r?\n/).map(line => line.trim()).filter(Boolean)]);
control = area;
} else {
const input = (field.multiline
? h('textarea', { rows: 4, value: String(value), maxLength: field.maxLength, placeholder: field.placeholder })
: h('input', { type: 'text', value: String(value), maxLength: field.maxLength, placeholder: field.placeholder })) as HTMLInputElement | HTMLTextAreaElement;
readers.push([field, () => input.value]);
control = input;
}
nodes.push(h('label', { class: 'wb-field' }, h('span', { class: 'wb-label' }, text(field.label)), control, hint ? h('p', { class: 'wb-hint' }, hint) : null));
}
return {
nodes,
read() {
const raw: Record<string, unknown> = {};
for (const [field, read] of readers) raw[field.key] = read();
return normalizeSettings(schema, raw);
},
};
}

View file

@ -55,14 +55,22 @@ export type FeatureFlagsOptions<Flags extends Record<string, boolean>> = {
label: string; label: string;
/** Parts that install when their flag turns on and dispose when it turns off, in install order. */ /** Parts that install when their flag turns on and dispose when it turns off, in install order. */
installers: ReadonlyArray<FlagInstaller<Flags>>; installers: ReadonlyArray<FlagInstaller<Flags>>;
/** Every applied config, before the installers (flags that are CSS, or that another part reads). */ /** Every applied config (the full map), before the installers (flags that are CSS, or that another part reads). */
apply?(config: Partial<Flags>): void; apply?(config: Flags): void;
/**
* What owns what: given the delivered flags over the defaults, the flags that really run (an
* area whose switch is off turns its features off; featureTable `effectiveFlags`).
*/
resolve?(flags: Flags): Flags;
/** The page's document: a column's flags delivered at document start wait for `<html>` to exist. */ /** The page's document: a column's flags delivered at document start wait for `<html>` to exist. */
document?: Document; document?: Document;
}; };
export type FeatureFlags<Flags extends Record<string, boolean>> = { export type FeatureFlags<Flags extends Record<string, boolean>> = {
/** The flags native code delivers (the owner's tweaks); a deck column's overrides stay on top. */ /**
* The flags native code delivers (the owner's choices); a deck column's overrides stay on top.
* A delivery is the whole state, stored sparsely: a flag it does not name is at its default.
*/
apply(config: Partial<Flags>): void; apply(config: Partial<Flags>): void;
/** /**
* A deck column's flag overrides (allow-listed natively; unknown keys and non-booleans are * A deck column's flag overrides (allow-listed natively; unknown keys and non-booleans are
@ -75,6 +83,8 @@ export type FeatureFlags<Flags extends Record<string, boolean>> = {
set(flag: keyof Flags & string, enabled: boolean): void; set(flag: keyof Flags & string, enabled: boolean): void;
/** Whether a flag's installer is installed right now. */ /** Whether a flag's installer is installed right now. */
installed(flag: keyof Flags & string): boolean; installed(flag: keyof Flags & string): boolean;
/** Every flag as it runs right now (defaults, the delivery, ownership, the column). */
current(): Flags;
}; };
export function createFeatureFlags<Flags extends Record<string, boolean>>(options: FeatureFlagsOptions<Flags>): FeatureFlags<Flags> { export function createFeatureFlags<Flags extends Record<string, boolean>>(options: FeatureFlagsOptions<Flags>): FeatureFlags<Flags> {
@ -99,38 +109,43 @@ export function createFeatureFlags<Flags extends Record<string, boolean>>(option
let globalFlags: Partial<Flags> = {}; let globalFlags: Partial<Flags> = {};
let columnFlags: Partial<Flags> = {}; let columnFlags: Partial<Flags> = {};
const merged = (previous: Partial<Flags> = {}): Partial<Flags> => { const known = (input: unknown): Partial<Flags> => {
const restore = Object.fromEntries(Object.keys(previous).map(key => [key, defaults[key]])) as Partial<Flags>; const out: Record<string, boolean> = {};
return { ...restore, ...globalFlags, ...columnFlags }; if (input && typeof input === 'object') {
}; for (const [key, value] of Object.entries(input)) if (key in defaults && typeof value === 'boolean') out[key] = value;
const applyAll = (config: Partial<Flags>) => {
options.apply?.(config);
for (const [flag] of installers) {
const enabled = config[flag];
if (typeof enabled === 'boolean') set(flag, enabled);
} }
return out as Partial<Flags>;
};
// What runs: the defaults, the delivered flags over them, what owns what (`resolve`), and a
// column's own choices on top.
const current = (): Flags => {
const base = { ...defaults, ...globalFlags } as Flags;
return { ...(options.resolve ? options.resolve(base) : base), ...columnFlags };
};
const applyAll = () => {
const config = current();
options.apply?.(config);
for (const [flag] of installers) set(flag, config[flag]);
}; };
return { return {
apply(config) { apply(config) {
globalFlags = { ...globalFlags, ...config }; globalFlags = known(config);
applyAll(Object.keys(columnFlags).length ? merged() : config); applyAll();
}, },
setColumnFlags(flags) { setColumnFlags(flags) {
const next: Partial<Flags> = {}; const next = known(flags);
if (flags && typeof flags === 'object') {
for (const [key, value] of Object.entries(flags)) if (key in defaults && typeof value === 'boolean') (next as Record<string, boolean>)[key] = value;
}
const previous = columnFlags; const previous = columnFlags;
columnFlags = next; columnFlags = next;
if (!Object.keys(previous).length && !Object.keys(next).length) return; if (!Object.keys(previous).length && !Object.keys(next).length) return;
const apply = () => { try { applyAll(merged(previous)); } catch (error) { console.error(`[${label}] column flags failed`, error); } }; const apply = () => { try { applyAll(); } catch (error) { console.error(`[${label}] column flags failed`, error); } };
const doc = options.document; const doc = options.document;
if (!doc || doc.documentElement) apply(); if (!doc || doc.documentElement) apply();
else doc.addEventListener('DOMContentLoaded', apply, { once: true }); else doc.addEventListener('DOMContentLoaded', apply, { once: true });
}, },
set, set,
installed: flag => active.has(flag), installed: flag => active.has(flag),
current,
}; };
} }

View file

@ -0,0 +1,386 @@
// The feature table (areas, flags, modes), the settings schema and the feature-module registry:
// flag and surface gating, ownership, one shared observer, the command budget, settings, hotfix
// overrides and the selector health check.
import assert from 'node:assert/strict';
import test from 'node:test';
import { observeSelector, type DomWindow } from '../src/domHub.ts';
import { AREA_COMMAND_BUDGET, PROBE_STRIKES, createFeatureRegistry, type FeatureModule, type HotfixData } from '../src/featureModules.ts';
import {
areaFlag, effectiveFlags, manualChanges, modeFlags, normalizeFlags, sparseFlags, supersededFiles, switchMode, tableDefaults, validateTable,
type FeatureTable,
} from '../src/featureTable.ts';
import { createCorePluginApi, type CorePluginApi, type PluginApiSite } from '../src/pluginApi.ts';
import { normalizeSettings, validateSchema, type SettingsSchema } from '../src/settingsForm.ts';
const TABLE: FeatureTable = {
areas: [
{ id: 'navigation', name: 'Navigation+', description: 'plugin.navigation-plus.description', owner: 'wb-navigation-plus.plugin.js', namespace: 'navigation-plus' },
{ id: 'reader', name: 'Reader+', description: 'plugin.reader-plus.description', owner: 'wb-reader-plus.plugin.js', namespace: 'reader-plus' },
],
features: [
{ id: 'fixScroll', area: null, group: 'fixes', default: true, backing: 'app' },
{ id: 'hideTrends', area: 'navigation', default: false, backing: 'module', surfaces: ['timeline'] },
{ id: 'navigation.focusMode', area: 'navigation', default: false, backing: 'module', settings: true, supersedes: 'wb-focus-mode.plugin.js' },
{ id: 'navigation.keys', area: 'navigation', default: false, backing: 'module' },
{ id: 'hideAds', area: 'reader', default: true, backing: 'app' },
{ id: 'reader.cleanLinks', area: 'reader', default: false, backing: 'plugin', file: 'wb-clean-links.plugin.js' },
],
modes: [
{ id: 'basic', name: 'mode.basic', description: 'mode.basic.text', flags: { 'area.navigation': false, 'area.reader': false } },
{ id: 'advanced', name: 'mode.advanced', description: 'mode.advanced.text', recommended: true, flags: {} },
{ id: 'power', name: 'mode.power', description: 'mode.power.text', flags: { 'navigation.keys': true } },
],
};
test('feature table: defaults, normalizing, sparse storage and ownership', () => {
assert.deepEqual(validateTable(TABLE), []);
const defaults = tableDefaults(TABLE);
assert.deepEqual(defaults, { fixScroll: true, hideTrends: false, 'navigation.focusMode': false, 'navigation.keys': false, hideAds: true, 'area.navigation': true, 'area.reader': true },
'a feature still backed by a plugin file is not a flag; every area has its switch, on');
assert.deepEqual(normalizeFlags(TABLE, { hideTrends: true, hideAds: 'yes', unknown: true, 'reader.cleanLinks': true }), { ...defaults, hideTrends: true }, 'unknown keys dropped, non-booleans take the default');
assert.deepEqual(sparseFlags(TABLE, { ...defaults, hideTrends: true, hideAds: false }), { hideTrends: true, hideAds: false }, 'only what differs from the default is stored');
assert.deepEqual(sparseFlags(TABLE, defaults), {});
// An area that is off turns off what it owns; core flags and other areas are untouched.
const off = effectiveFlags(TABLE, { ...defaults, hideTrends: true, [areaFlag('reader')]: false });
assert.equal(off.hideAds, false);
assert.equal(off.hideTrends, true);
assert.equal(off.fixScroll, true, 'no plugin switch turns a core flag off');
assert.deepEqual(supersededFiles(TABLE), [{ file: 'wb-focus-mode.plugin.js', flag: 'navigation.focusMode' }]);
});
test('feature table: a mode is a starting point; changing it keeps or drops the manual changes', () => {
const defaults = tableDefaults(TABLE);
assert.deepEqual(modeFlags(TABLE, 'advanced'), defaults);
assert.deepEqual(modeFlags(TABLE, null), defaults, 'never chosen: the defaults');
assert.equal(modeFlags(TABLE, 'basic')['area.reader'], false);
// The owner, on Advanced, turned trends hiding on and ads hiding off.
const mine = { ...defaults, hideTrends: true, hideAds: false };
assert.deepEqual(manualChanges(TABLE, mine, 'advanced').sort(), ['hideAds', 'hideTrends']);
const kept = switchMode(TABLE, mine, 'advanced', 'power', true);
assert.deepEqual(kept, { ...defaults, 'navigation.keys': true, hideTrends: true, hideAds: false });
const reset = switchMode(TABLE, mine, 'advanced', 'power', false);
assert.deepEqual(reset, { ...defaults, 'navigation.keys': true });
// From Basic back to Advanced with "keep": the areas Basic switched off are not manual changes.
const basic = switchMode(TABLE, mine, 'advanced', 'basic', false);
assert.deepEqual(manualChanges(TABLE, basic, 'basic'), []);
assert.deepEqual(switchMode(TABLE, basic, 'basic', 'advanced', true), defaults);
});
test('feature table: problems are reported', () => {
const bad: FeatureTable = {
areas: [{ id: 'Nav', name: 'Nav', description: 'd', owner: 'nav.js', namespace: 'nav' }, ...TABLE.areas],
features: [
...TABLE.features,
{ id: 'hideTrends', area: 'reader', default: false, backing: 'app' },
{ id: 'area.x', area: null, default: false, backing: 'app' },
{ id: 'lost', area: 'nowhere', default: false, backing: 'app' },
{ id: 'reader.x', area: 'reader', default: true, backing: 'plugin' },
{ id: 'reader.y', area: 'reader', default: false, backing: 'app', settings: true },
],
modes: [...TABLE.modes, { id: 'odd', name: 'n', description: 'd', recommended: true, flags: { nope: true, hideAds: true } }],
};
const problems = validateTable(bad).join('\n');
for (const expected of ['area "Nav": invalid id', 'owner must be a plugin file name', 'hideTrends: owned twice', 'area.x: "area." is kept', 'lost: unknown area', 'reader.x: a plugin-backed feature names its file',
'reader.x: a plugin file is off', 'reader.y: only a feature module has a settings schema', 'mode odd: unknown flag nope', 'mode odd: hideAds is already the default', 'exactly one mode is the recommended one']) {
assert.ok(problems.includes(expected), `${expected}\n${problems}`);
}
});
const SCHEMA: SettingsSchema = [
{ key: 'enabled', type: 'toggle', default: true, label: 'enabled' },
{ type: 'divider' },
{ key: 'days', type: 'number', default: 30, min: 1, max: 365, label: 'days' },
{ key: 'mode', type: 'select', default: 'calm', options: [{ value: 'calm', label: 'calm' }, { value: 'zen', label: 'zen' }], label: 'mode' },
{ key: 'note', type: 'text', default: '', maxLength: 5, label: 'note' },
{ key: 'patterns', type: 'list', default: [], maxItems: 2, label: 'patterns' },
];
test('settings schema: stored values are normalized to the schema, whatever was stored', () => {
assert.deepEqual(validateSchema(SCHEMA), []);
assert.deepEqual(normalizeSettings(SCHEMA, null), { enabled: true, days: 30, mode: 'calm', note: '', patterns: [] });
assert.deepEqual(normalizeSettings(SCHEMA, { enabled: 'no', days: 9999, mode: 'loud', note: 'too long', patterns: ['a', '', 3, 'b', 'c'], extra: 1 }),
{ enabled: true, days: 365, mode: 'calm', note: 'too l', patterns: ['a', 'b'] });
assert.deepEqual(normalizeSettings(SCHEMA, { enabled: false, days: 7, mode: 'zen' }), { enabled: false, days: 7, mode: 'zen', note: '', patterns: [] });
const bad: SettingsSchema = [{ key: 'a', type: 'toggle', default: true, label: 'a' }, { key: 'a', type: 'number', default: 1, min: 5, max: 2, label: '' }, { key: '1x', type: 'select', default: 'z', options: [], label: 'x' }];
const problems = validateSchema(bad).join('\n');
for (const expected of ['a: listed twice', 'a: a label is required', 'a: min is above max', 'invalid key "1x"', '1x: the default is not an option']) assert.ok(problems.includes(expected), `${expected}\n${problems}`);
});
// ---------------------------------------------------------------------------------------------
// A small page: one document, a body that can hold matching elements, counted observers.
type Listener = (event: unknown) => void;
class FakeTarget {
listeners = new Map<string, Set<Listener>>();
addEventListener(type: string, fn: Listener) { (this.listeners.get(type) ?? this.listeners.set(type, new Set()).get(type)!).add(fn); }
removeEventListener(type: string, fn: Listener) { this.listeners.get(type)?.delete(fn); }
emit(type: string, event: unknown = {}) { for (const fn of [...(this.listeners.get(type) ?? [])]) fn(event); }
count(type: string) { return this.listeners.get(type)?.size ?? 0; }
}
const SITE: PluginApiSite = {
name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo-plugin:', styleDataKey: 'demoPlugin',
toastId: 'demo-toast', toastBackground: '#111', itemSelector: 'article', chordKeys: [],
};
function page() {
const styles: { dataset: Record<string, string>; textContent: string; isConnected: boolean; remove(): void }[] = [];
const matches = new Map<string, object[]>();
const observers: Array<() => void> = [];
const store = new Map<string, string>();
const doc = new FakeTarget() as FakeTarget & Record<string, unknown>;
Object.assign(doc, {
activeElement: null,
documentElement: { getAttribute: () => 'en' },
body: { firstElementChild: {} },
head: { appendChild(node: { isConnected: boolean }) { node.isConnected = true; } },
querySelectorAll: (selector: string) => matches.get(selector) ?? [],
querySelector: (selector: string) => (matches.get(selector) ?? [])[0] ?? null,
createElement: () => {
const node = { dataset: {} as Record<string, string>, textContent: '', isConnected: false, remove() { node.isConnected = false; } };
styles.push(node);
return node;
},
});
const win = new FakeTarget() as FakeTarget & Record<string, unknown>;
const location = { href: 'https://site.test/home', pathname: '/home' };
Object.assign(win, {
document: doc,
location,
localStorage: { get length() { return store.size; }, key: (i: number) => [...store.keys()][i] ?? null, getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); }, removeItem: (k: string) => { store.delete(k); } },
requestAnimationFrame: (fn: () => void) => { fn(); return 1; },
cancelAnimationFrame: () => {},
MutationObserver: class { constructor(fn: () => void) { observers.push(() => fn()); } observe() {} disconnect() {} },
});
const api = createCorePluginApi(win as unknown as Window & typeof globalThis, SITE);
return {
api, win: win as unknown as Window & typeof globalThis, doc, styles, matches, observers, store, location,
/** The site rendered something: every observer fires (one frame). */
mutate() { for (const fire of observers) fire(); },
go(path: string) { location.href = `https://site.test${path}`; location.pathname = path; win.emit('popstate'); },
liveStyles: () => styles.filter(style => style.isConnected && style.textContent).map(style => style.textContent),
};
}
type Timer = { fn: () => void; ms: number; id: number; at: number };
function fakeTimers() {
let now = 0;
let next = 1;
let queue: Timer[] = [];
return {
setTimeout(fn: () => void, ms: number) { const id = next++; queue.push({ fn, ms, id, at: now + ms }); return id; },
clearTimeout(id: unknown) { queue = queue.filter(timer => timer.id !== id); },
advance(ms: number) {
const end = now + ms;
for (;;) {
const due = queue.filter(timer => timer.at <= end).sort((a, b) => a.at - b.at)[0];
if (!due) break;
queue = queue.filter(timer => timer !== due);
now = due.at;
due.fn();
}
now = end;
},
pending: () => queue.length,
};
}
function registryFor(env: ReturnType<typeof page>, extra: { surfaces?: () => string[]; hotfix?: () => HotfixData; timers?: ReturnType<typeof fakeTimers> } = {}) {
return createFeatureRegistry<CorePluginApi>({
win: env.win, table: TABLE, api: env.api, label: 'Demo',
surfaces: extra.surfaces ?? (() => (env.location.pathname === '/home' ? ['timeline', 'home'] : ['profile'])),
hotfix: extra.hotfix, timers: extra.timers, settleMs: 3000, pollMs: 500,
});
}
test('registry: a module runs only while its flag is on and the page is on one of its surfaces, and leaves nothing behind', () => {
const env = page();
const registry = registryFor(env);
const log: string[] = [];
registry.define({ id: 'hideTrends', start(ctx) { log.push('+trends'); ctx.css('.trends{display:none}'); ctx.defer(() => log.push('-trends')); } });
registry.define({ id: 'navigation.keys', start(ctx) { log.push('+keys'); ctx.onKey(() => {}); ctx.defer(() => log.push('-keys')); } });
assert.deepEqual(registry.active(), [], 'off until the flags say so');
assert.equal(env.doc.count('keydown'), 0, 'an idle feature holds no listener');
registry.setFlags(effectiveFlags(TABLE, { ...tableDefaults(TABLE), hideTrends: true, 'navigation.keys': true }));
assert.deepEqual(registry.active().sort(), ['hideTrends', 'navigation.keys']);
assert.deepEqual(env.liveStyles(), ['.trends{display:none}']);
assert.equal(env.styles.at(-1)!.dataset.demoPlugin, 'wbf-hideTrends');
assert.equal(env.doc.count('keydown'), 1);
env.go('/someone');
assert.deepEqual(registry.active(), ['navigation.keys'], 'not a timeline: the surface-bound feature stopped');
assert.deepEqual(env.liveStyles(), []);
env.go('/home');
assert.deepEqual(registry.active().sort(), ['hideTrends', 'navigation.keys']);
// The area's switch off: everything it owns stops, without touching the features' own flags.
registry.setFlags(effectiveFlags(TABLE, { ...tableDefaults(TABLE), hideTrends: true, 'navigation.keys': true, 'area.navigation': false }));
assert.deepEqual(registry.active(), []);
assert.deepEqual(env.liveStyles(), []);
assert.equal(env.doc.count('keydown'), 0);
assert.deepEqual(log, ['+trends', '+keys', '-trends', '+trends', '-trends', '-keys']);
assert.throws(() => registry.define({ id: 'hideAds', start() {} }), /hideAds is not a feature module in the table/);
assert.throws(() => registry.define({ id: 'hideTrends', start() {} }), /defined twice/);
registry.dispose();
});
test('registry: one MutationObserver however many features observe; plugins share it too', () => {
const env = page();
const registry = registryFor(env);
const seen: string[] = [];
const first = {};
env.matches.set('article', [first]);
registry.define({ id: 'hideTrends', start(ctx) { ctx.observe('article', () => seen.push('a')); ctx.observe('aside', () => seen.push('aside')); } });
registry.define({ id: 'navigation.keys', start(ctx) { ctx.observe('article', () => seen.push('b')); ctx.watch(() => seen.push('frame')); } });
registry.setFlags({ hideTrends: true, 'navigation.keys': true });
const stopPlugin = env.api.observe('article', () => seen.push('plugin'));
assert.equal(env.observers.length, 1, 'one observer for three selector observers, a raw watch and a plugin');
assert.deepEqual(seen, ['a', 'b', 'plugin'], 'what is already there is reported at once, once');
env.matches.set('article', [first, {}]);
env.matches.set('aside', [{}]);
env.mutate();
assert.deepEqual(seen.slice(3).sort(), ['a', 'aside', 'b', 'frame', 'plugin'], 'only the new elements');
stopPlugin();
registry.dispose();
const before = seen.length;
env.mutate();
assert.equal(seen.length, before, 'nothing runs after dispose');
});
test('registry: a failing module is contained; heavy pages pause features that did not ask for them', () => {
const env = page();
const errors: unknown[] = [];
const original = console.error;
console.error = (...args: unknown[]) => { errors.push(args[0]); };
try {
const registry = registryFor(env, { surfaces: () => ['timeline'] });
registry.define({ id: 'hideTrends', start(ctx) { ctx.css('x{}'); throw new Error('markup changed'); } });
registry.define({ id: 'navigation.keys', start() {} });
registry.setFlags({ hideTrends: true, 'navigation.keys': true });
assert.deepEqual(registry.active(), ['navigation.keys']);
assert.match(String(errors[0]), /\[Demo\] hideTrends failed/);
assert.deepEqual(env.liveStyles(), [], 'what it did before failing is undone');
registry.dispose();
} finally { console.error = original; }
});
test('registry: settings come from the schema, are stored under the module\'s namespace and reach the running feature', () => {
const env = page();
const registry = registryFor(env);
const applied: unknown[] = [];
const module: FeatureModule<CorePluginApi> = {
id: 'navigation.focusMode',
storage: 'focus-mode',
settings: [{ key: 'enabled', type: 'toggle', default: true, label: 'enabled' }, { key: 'trends', type: 'toggle', default: true, label: 'trends' }],
start(ctx) {
applied.push(ctx.settings.get());
ctx.settings.onChange(values => applied.push(values));
ctx.command({ id: 'focusMode.toggle', title: 'Toggle Focus Mode', run: () => { ctx.settings.set({ enabled: !ctx.settings.get().enabled }); } });
},
};
env.store.set('demo-plugin:focus-mode:settings', JSON.stringify({ enabled: true, trends: false, gone: 1 }));
registry.define(module);
assert.throws(() => registryFor(env).define({ id: 'navigation.keys', settings: [{ key: 'a', type: 'toggle', default: true, label: 'a' }], start() {} }), /the table's "settings" and the module's schema disagree/);
registry.setFlags({ 'navigation.focusMode': true });
assert.deepEqual(applied, [{ enabled: true, trends: false }], 'an old plugin\'s stored settings are read as they are');
// The area got its one settings command next to the feature's own; both belong to the area's owner.
assert.deepEqual(env.api.commands.list().map(command => command.id).sort(), ['wb-navigation-plus.plugin.js:focusMode.toggle', 'wb-navigation-plus.plugin.js:settings']);
assert.equal(env.api.commands.list().find(command => command.id.endsWith(':settings'))!.title, 'Navigation+ settings');
env.api.commands.run('wb-navigation-plus.plugin.js:focusMode.toggle');
assert.deepEqual(applied.at(-1), { enabled: false, trends: false });
assert.equal(env.store.get('demo-plugin:focus-mode:settings'), '{"enabled":false,"trends":false}');
registry.setFlags({});
assert.deepEqual(env.api.commands.list(), [], 'commands go with the feature');
registry.dispose();
});
test(`registry: an area registers at most ${AREA_COMMAND_BUDGET} palette commands`, () => {
const env = page();
const errors: unknown[] = [];
const original = console.error;
console.error = (...args: unknown[]) => { errors.push(args[1]); };
try {
const registry = registryFor(env);
// Navigation+ has a feature with settings, so one of the five is kept for its settings command.
registry.define({ id: 'navigation.keys', start(ctx) { for (let n = 0; n < AREA_COMMAND_BUDGET; n += 1) ctx.command({ id: `keys.${n}`, title: `Key ${n}`, run() {} }); } });
registry.setFlags({ 'navigation.keys': true });
assert.match(String(errors[0]), /at most 5 palette commands per area/);
assert.deepEqual(registry.active(), [], 'the feature that went over the budget does not run');
assert.deepEqual(env.api.commands.list(), []);
registry.dispose();
} finally { console.error = original; }
});
test(`registry: a probe that matches nothing ${PROBE_STRIKES} visits in a row pauses that one feature; a hotfix selector or kill flag applies`, () => {
const env = page();
const timers = fakeTimers();
let hotfix: HotfixData = {};
const warnings: unknown[] = [];
const original = console.warn;
console.warn = (...args: unknown[]) => { warnings.push(args[0]); };
try {
const registry = registryFor(env, { timers, hotfix: () => hotfix, surfaces: () => ['timeline'] });
const used: string[] = [];
registry.define({ id: 'hideTrends', probes: { module: '[data-testid="trend"]', label: { selector: '[aria-label="Trending"]', english: true } }, start(ctx) { used.push(ctx.selector('module')); } });
registry.define({ id: 'navigation.keys', start() {} });
env.matches.set('[aria-label="Trending"]', [{}]);
registry.setFlags({ hideTrends: true, 'navigation.keys': true });
const visit = () => { env.go(env.location.pathname === '/home' ? '/explore' : '/home'); timers.advance(500 + 3000); };
timers.advance(3500);
assert.deepEqual(registry.health(), [], 'one miss is not a verdict');
visit();
// The selector comes back for a visit: the count starts over.
env.matches.set('[data-testid="trend"]', [{}]);
visit();
env.matches.delete('[data-testid="trend"]');
visit();
visit();
assert.deepEqual(registry.active().sort(), ['hideTrends', 'navigation.keys']);
visit();
assert.deepEqual(registry.active(), ['navigation.keys'], 'the feature paused itself; the rest of the area runs');
assert.deepEqual(registry.health(), [{ id: 'hideTrends', area: 'navigation', state: 'paused', probes: ['module'] }]);
assert.match(String(warnings[0]), /\[Demo\] hideTrends paused: nothing matches module/);
registry.setFlags({ hideTrends: true, 'navigation.keys': true });
assert.deepEqual(registry.active(), ['navigation.keys'], 'paused for the session');
assert.equal(timers.pending(), 0, 'no timer left behind');
registry.dispose();
// A signed hotfix replaces the selector, or switches the feature off.
hotfix = { selectors: { 'hideTrends.module': '[data-testid="trendV2"]' } };
const patched = registryFor(env, { timers, hotfix: () => hotfix, surfaces: () => ['timeline'] });
patched.define({ id: 'hideTrends', probes: { module: '[data-testid="trend"]' }, start(ctx) { used.push(ctx.selector('module')); } });
patched.setFlags({ hideTrends: true });
assert.deepEqual(used, ['[data-testid="trend"]', '[data-testid="trendV2"]']);
hotfix = { flags: { hideTrends: false } };
patched.refresh();
assert.deepEqual(patched.active(), []);
patched.dispose();
} finally { console.warn = original; }
});
test('registry: a probe that reads an English label waits for an English page instead of counting misses', () => {
const env = page();
const timers = fakeTimers();
(env.doc.documentElement as { getAttribute(): string }).getAttribute = () => 'tr';
const registry = registryFor(env, { timers, surfaces: () => ['timeline'] });
registry.define({ id: 'hideTrends', probes: { label: { selector: '[aria-label="Trending"]', english: true } }, start() {} });
registry.setFlags({ hideTrends: true });
for (let n = 0; n < 5; n += 1) { env.go(n % 2 ? '/home' : '/explore'); timers.advance(3500); }
assert.deepEqual(registry.active(), ['hideTrends']);
assert.deepEqual(registry.health(), [{ id: 'hideTrends', area: 'navigation', state: 'needs-english', probes: ['label'] }]);
registry.dispose();
});
test('observeSelector: heavy pages skip observers that ask for it', () => {
const env = page();
const seen: string[] = [];
env.matches.set('article', [{}]);
env.location.pathname = '/home';
const stop = observeSelector(env.win as unknown as DomWindow, 'article', () => seen.push('x'), { offOnHeavy: true });
assert.deepEqual(seen, ['x']);
stop();
stop();
});

View file

@ -41,7 +41,7 @@ test('feature flags: parts install on enable and dispose on disable, in order, a
assert.ok(flags.installed('gate') && !flags.installed('pill')); assert.ok(flags.installed('gate') && !flags.installed('pill'));
flags.apply({ gate: false, css: false }); flags.apply({ gate: false, css: false });
assert.deepEqual(log, ['+gate', '-gate']); assert.deepEqual(log, ['+gate', '-gate']);
assert.deepEqual(applied, [{ gate: false, css: false }]); assert.deepEqual(applied, [{ gate: false, pill: false, css: false }], 'the full map: a flag the delivery does not name is at its default');
flags.apply({ gate: true, pill: true }); flags.apply({ gate: true, pill: true });
assert.deepEqual(log, ['+gate', '-gate', '+gate']); assert.deepEqual(log, ['+gate', '-gate', '+gate']);
assert.equal(flags.installed('pill'), false); assert.equal(flags.installed('pill'), false);
@ -57,13 +57,16 @@ test('feature flags: a deck column overrides global flags; dropped overrides go
const flags = createFeatureFlags<Flags>({ defaults: { gate: true, pill: false, css: true }, label: 'Demo', installers: [], apply: config => applied.push(config) }); const flags = createFeatureFlags<Flags>({ defaults: { gate: true, pill: false, css: true }, label: 'Demo', installers: [], apply: config => applied.push(config) });
flags.apply({ pill: true }); flags.apply({ pill: true });
flags.setColumnFlags({ pill: false, css: false, unknown: true, gate: 'yes' }); flags.setColumnFlags({ pill: false, css: false, unknown: true, gate: 'yes' });
assert.deepEqual(applied.at(-1), { pill: false, css: false }, 'only known booleans; the column wins'); assert.deepEqual(applied.at(-1), { gate: true, pill: false, css: false }, 'only known booleans; the column wins');
flags.apply({ css: true }); flags.apply({ pill: true, css: true });
assert.deepEqual(applied.at(-1), { pill: false, css: false }, 'a global change does not undo the column'); assert.deepEqual(applied.at(-1), { gate: true, pill: false, css: false }, 'a global change does not undo the column');
flags.setColumnFlags({ pill: false }); flags.setColumnFlags({ pill: false });
assert.deepEqual(applied.at(-1), { pill: false, css: true }, 'css is the global value again'); assert.deepEqual(applied.at(-1), { gate: true, pill: false, css: true }, 'css is the global value again');
flags.setColumnFlags(null); flags.setColumnFlags(null);
assert.deepEqual(applied.at(-1), { pill: true, css: true }, 'an ordinary tab again: the global flags'); assert.deepEqual(applied.at(-1), { gate: true, pill: true, css: true }, 'an ordinary tab again: the global flags');
flags.apply({});
assert.deepEqual(applied.at(-1), { gate: true, pill: false, css: true }, 'a delivery is the whole state: what it does not name is at its default');
assert.deepEqual(flags.current(), { gate: true, pill: false, css: true });
const before = applied.length; const before = applied.length;
flags.setColumnFlags(undefined); flags.setColumnFlags(undefined);
assert.equal(applied.length, before, 'nothing to change'); assert.equal(applied.length, before, 'nothing to change');
@ -75,9 +78,16 @@ test('feature flags: a deck column overrides global flags; dropped overrides go
waiting.setColumnFlags({ css: false }); waiting.setColumnFlags({ css: false });
assert.deepEqual(late, []); assert.deepEqual(late, []);
waiting.apply({ pill: true }); waiting.apply({ pill: true });
assert.deepEqual(late.at(-1), { pill: true, css: false }, 'recorded at once: a global delivery already respects it'); assert.deepEqual(late.at(-1), { gate: true, pill: true, css: false }, 'recorded at once: a global delivery already respects it');
listeners[0]!(); listeners[0]!();
assert.deepEqual(late.at(-1), { pill: true, css: false }); assert.deepEqual(late.at(-1), { gate: true, pill: true, css: false });
// Ownership: `resolve` decides what runs; a column's own choice still wins.
const owned: Array<Partial<Flags>> = [];
const gated = createFeatureFlags<Flags>({ defaults: { gate: true, pill: false, css: true }, label: 'Demo', installers: [], apply: config => owned.push(config), resolve: all => (all.gate ? all : { ...all, css: false }) });
gated.apply({ gate: false });
assert.deepEqual(owned.at(-1), { gate: false, pill: false, css: false }, 'the owner is off, so what it owns is off');
gated.setColumnFlags({ css: true });
assert.deepEqual(owned.at(-1), { gate: false, pill: false, css: true });
}); });
function runtimeWindow(queued: Record<string, unknown> = {}) { function runtimeWindow(queued: Record<string, unknown> = {}) {