Something went wrong. Try again.
Mirror of https://github.com/improsocial/improAn extensible Bluesky client for web
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316import { describe, it, afterEach } from "node:test";import assert from "node:assert/strict";import { PluginService, PermissionsDeclinedError,} from "/js/plugins/pluginService.js";import { Signal } from "/js/signals.js";import { respondToConfirm } from "../../testHelpers.js";
class FakePreferences { constructor(state) { this.state = state; } getInstalledPlugins() { return this.state.installedPlugins; } setInstalledPlugins(plugins) { this.state.installedPlugins = plugins; // Return a fresh identity to mirror the real provider, which clones // preferences on every write so dependent signals invalidate. return new FakePreferences(this.state); } getPluginSettings(pluginId) { return this.state.pluginSettings[pluginId]; } setPluginSettings(pluginId, data) { this.state.pluginSettings[pluginId] = data; return this; } clearPluginSettings(pluginId) { delete this.state.pluginSettings[pluginId]; return this; }}
function makeProvider() { const state = { installedPlugins: [], pluginSettings: {} }; const preferences = new FakePreferences(state); const $preferences = new Signal.State(preferences); return { state, provider: { $preferences, requirePreferences: () => preferences, updatePreferences: async (saved) => { $preferences.set(saved); }, }, };}
// Build a PluginService with its async-heavy dependencies replaced by// inert fakes so we can exercise the install/update orchestration logic// without spinning up sandbox iframes or real fetches.function makeService({ remoteListings = [], localListings = null, liveManifests = {}, liveManifestsByRepo = {},} = {}) { const { state, provider } = makeProvider(); const service = new PluginService(provider, null); const loadCalls = []; const reloadCalls = []; const unloadCalls = []; const reconcileCalls = []; service.pluginBridge = { isLoaded: () => false, unloadPlugin: (id) => { unloadCalls.push(id); }, loadPlugin: async (id, version, repo) => { loadCalls.push({ id, version, repo }); }, reloadPlugin: async (id, version, repo) => { reloadCalls.push({ id, version, repo }); }, loadPlugins: async (entries) => ({ loadedPlugins: entries, erroredPlugins: [], }), }; service.remoteRegistry = { getListing: async (id) => remoteListings.find((listing) => listing.id === id) ?? null, getListings: async () => remoteListings, }; service.localPluginsEnabled = localListings != null; service.localRegistry = localListings ? { getListings: async () => localListings, getListing: async (id) => localListings.find((listing) => listing.id === id) ?? null, } : null; service.sourceProvider = { getLiveManifest: async (id) => { if (!liveManifests[id]) throw new Error(`no manifest for ${id}`); return liveManifests[id]; }, getLiveManifestFromRepo: async (repo) => { if (!liveManifestsByRepo[repo]) { throw new Error(`no manifest for ${repo}`); } return liveManifestsByRepo[repo]; }, getCacheUrls: async (id, version, repo) => [ `https://cache.test/${id}/${version}/${repo}`, ], }; service.pluginCache = { reconcile: async (urls) => { reconcileCalls.push(urls); }, }; return { service, state, provider, loadCalls, reloadCalls, unloadCalls, reconcileCalls, };}
describe("installPlugin", () => { it("persists manifest metadata and loads the plugin", async () => { const { service, state, loadCalls } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifests: { alpha: { id: "alpha", name: "Alpha", version: "1.0.0", author: "ow", description: "the first", }, }, }); await service.installPlugin("alpha"); assert.deepEqual(state.installedPlugins, [ { id: "alpha", name: "Alpha", version: "1.0.0", author: "ow", description: "the first", repo: "ow/alpha", enabled: true, permissions: {}, }, ]); assert.deepEqual(loadCalls, [ { id: "alpha", version: "1.0.0", repo: "ow/alpha" }, ]); });
it("$pluginsInfo reflects newly installed plugin synchronously", async () => { const { service } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifests: { alpha: { id: "alpha", name: "Alpha", version: "1.0.0", author: "ow", description: "the first", }, }, }); assert.deepEqual(service.$pluginsInfo.get(), []); await service.installPlugin("alpha"); const info = service.$pluginsInfo.get(); assert.deepEqual(info.length, 1); assert.deepEqual(info[0].id, "alpha"); assert.deepEqual(info[0].name, "Alpha"); assert.deepEqual(info[0].version, "1.0.0"); assert.deepEqual(info[0].enabled, true); });
it("throws and rolls back the preference entry when load fails", async () => { const { service, state } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifests: { alpha: { id: "alpha", name: "Alpha", version: "1.0.0" }, }, }); service.pluginBridge.loadPlugin = async () => { throw new Error("boom"); }; let caught = null; try { await service.installPlugin("alpha"); } catch (error) { caught = error; } assert(caught?.message.includes("boom")); assert.deepEqual(state.installedPlugins, []); });
it("rejects when the plugin is not in the remote registry", async () => { const { service } = makeService(); let caught = null; try { await service.installPlugin("alpha"); } catch (error) { caught = error; } assert(caught?.message.includes("unknown plugin")); });
it("aborts install when the permission prompt is declined", async () => { const { service, state, loadCalls } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifests: { alpha: { id: "alpha", name: "Alpha", version: "1.0.0", permissions: { fetch: ["https://api.example.com/*"] }, }, }, }); const installing = service.installPlugin("alpha"); await respondToConfirm(false); let caught = null; try { await installing; } catch (e) { caught = e; } assert(caught instanceof PermissionsDeclinedError); assert.deepEqual(state.installedPlugins, []); assert.deepEqual(loadCalls, []); });
it("does not prompt on install when manifest has no permissions", async () => { const { service, state } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifests: { alpha: { id: "alpha", name: "Alpha", version: "1.0.0" }, }, }); await service.installPlugin("alpha"); assert.deepEqual(state.installedPlugins.length, 1); });});
describe("updatePlugin", () => { it("refreshes name/description/author/version from the live manifest", async () => { const { service, state, reloadCalls } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifests: { alpha: { id: "alpha", name: "Alpha", version: "1.0.0", author: "ow", description: "the first", }, }, }); await service.installPlugin("alpha");
service.sourceProvider.getLiveManifest = async () => ({ id: "alpha", name: "Alpha Renamed", version: "1.1.0", author: "ow2", description: "new description", });
const result = await service.updatePlugin("alpha"); assert.deepEqual(result, { updated: true, version: "1.1.0" }); assert.deepEqual(state.installedPlugins[0], { id: "alpha", name: "Alpha Renamed", version: "1.1.0", author: "ow2", description: "new description", repo: "ow/alpha", enabled: true, permissions: {}, }); assert.deepEqual(reloadCalls, [ { id: "alpha", version: "1.1.0", repo: "ow/alpha" }, ]); });
it("does nothing when live manifest is not newer", async () => { const { service, state, reloadCalls } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifests: { alpha: { id: "alpha", name: "Alpha", version: "1.0.0" }, }, }); await service.installPlugin("alpha");
const result = await service.updatePlugin("alpha"); assert.deepEqual(result, { updated: false }); assert.deepEqual(state.installedPlugins[0].version, "1.0.0"); assert.deepEqual(reloadCalls.length, 0); });
it("does not prompt when no new permissions were added", async () => { const { service } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifests: { alpha: { id: "alpha", name: "Alpha", version: "1.0.0", permissions: { fetch: ["https://api.example.com/*"] }, }, }, }); const installing = service.installPlugin("alpha"); await respondToConfirm(true); await installing; service.sourceProvider.getLiveManifest = async () => ({ id: "alpha", name: "Alpha", version: "1.1.0", permissions: { fetch: ["https://api.example.com/*"] }, });
const result = await service.updatePlugin("alpha"); assert.deepEqual(result, { updated: true, version: "1.1.0" }); });
it("aborts update and keeps old version when the prompt is declined", async () => { const { service, state, reloadCalls } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifests: { alpha: { id: "alpha", name: "Alpha", version: "1.0.0", permissions: { fetch: ["https://api.example.com/*"] }, }, }, }); const installing = service.installPlugin("alpha"); await respondToConfirm(true); await installing; service.sourceProvider.getLiveManifest = async () => ({ id: "alpha", name: "Alpha", version: "1.1.0", permissions: { fetch: ["https://api.example.com/*", "https://newhost.com/*"], }, });
const updating = service.updatePlugin("alpha"); await respondToConfirm(false); let caught = null; try { await updating; } catch (e) { caught = e; } assert(caught instanceof PermissionsDeclinedError); assert.deepEqual(state.installedPlugins[0].version, "1.0.0"); assert.deepEqual(state.installedPlugins[0].permissions, { fetch: ["https://api.example.com/*"], }); assert.deepEqual(reloadCalls.length, 0); });
it("persists updated permissions when the prompt is accepted", async () => { const { service, state } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifests: { alpha: { id: "alpha", name: "Alpha", version: "1.0.0", permissions: { fetch: ["https://api.example.com/*"] }, }, }, }); const installing = service.installPlugin("alpha"); await respondToConfirm(true); await installing; service.sourceProvider.getLiveManifest = async () => ({ id: "alpha", name: "Alpha", version: "1.1.0", permissions: { fetch: ["https://api.example.com/*", "https://newhost.com/*"], }, });
const updating = service.updatePlugin("alpha"); await respondToConfirm(true); await updating; assert.deepEqual(state.installedPlugins[0].permissions, { fetch: ["https://api.example.com/*", "https://newhost.com/*"], }); });});
describe("loadEnabledPlugins", () => { it("only loads entries marked enabled", async () => { const { service, state } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: false }, ]; const loadPluginsCalls = []; service.pluginBridge.loadPlugins = async (entries) => { loadPluginsCalls.push(entries); return { loadedPlugins: entries, erroredPlugins: [] }; }; await service.loadEnabledPlugins(); assert.deepEqual(loadPluginsCalls.length, 1); assert.deepEqual( loadPluginsCalls[0].map((entry) => entry.id), ["a"], ); });
it("skips __LOCAL entries when localPluginsEnabled is false", async () => { const { service, state } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b__LOCAL", version: "1.0.0", repo: null, enabled: true }, ]; const loadPluginsCalls = []; service.pluginBridge.loadPlugins = async (entries) => { loadPluginsCalls.push(entries); return { loadedPlugins: entries, erroredPlugins: [] }; }; await service.loadEnabledPlugins(); assert.deepEqual( loadPluginsCalls[0].map((entry) => entry.id), ["a"], ); });
it("loads __LOCAL entries when localPluginsEnabled is true", async () => { const { service, state } = makeService({ localListings: [] }); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b__LOCAL", version: "1.0.0", repo: null, enabled: true }, ]; const loadPluginsCalls = []; service.pluginBridge.loadPlugins = async (entries) => { loadPluginsCalls.push(entries); return { loadedPlugins: entries, erroredPlugins: [] }; }; await service.loadEnabledPlugins(); assert.deepEqual( loadPluginsCalls[0].map((entry) => entry.id), ["a", "b__LOCAL"], ); });
it("keeps plugins enabled when the bridge reports they errored", async () => { const { service, state } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: true }, ]; service.pluginBridge.loadPlugins = async () => ({ loadedPlugins: [], erroredPlugins: [{ pluginId: "b", error: new Error("nope") }], }); await service.loadEnabledPlugins(); assert.deepEqual( state.installedPlugins.find((entry) => entry.id === "b").enabled, true, ); assert.deepEqual( state.installedPlugins.find((entry) => entry.id === "a").enabled, true, ); });
it("shows one error toast per distinct load-error message", async () => { const { service, state } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: true }, { id: "c", version: "1.0.0", repo: "ow/c", enabled: true }, ]; service.pluginBridge.loadPlugins = async () => ({ loadedPlugins: [], erroredPlugins: [ { pluginId: "a", error: new Error("Failed to load plugin source") }, { pluginId: "b", error: new Error("Failed to load plugin source") }, { pluginId: "c", error: new Error("Failed to load plugin manifest") }, ], }); document.body.innerHTML = ""; await service.loadEnabledPlugins(); const toasts = [...document.body.querySelectorAll('[data-testid="toast"]')]; assert.deepEqual( toasts.map((toast) => toast.textContent.trim()), [ "Failed to load plugin(s): a, b - Failed to load plugin source", "Failed to load plugin(s): c - Failed to load plugin manifest", ], ); document.body.innerHTML = ""; });
it("with ?disable-plugins, disables all enabled plugins in one save and skips loading", async () => { const { service, state } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: false }, { id: "c", version: "1.0.0", repo: "ow/c", enabled: true }, ]; const loadPluginsCalls = []; service.pluginBridge.loadPlugins = async (entries) => { loadPluginsCalls.push(entries); return { loadedPlugins: entries, erroredPlugins: [] }; }; let saveCalls = 0; const originalSave = service.prefManager.preferencesProvider.updatePreferences; service.prefManager.preferencesProvider.updatePreferences = async ( prefs, ) => { saveCalls++; return originalSave(prefs); }; window.history.replaceState({}, "", "http://localhost/?disable-plugins"); try { await service.loadEnabledPlugins(); } finally { window.history.replaceState({}, "", "http://localhost/"); } assert.deepEqual(loadPluginsCalls.length, 0); assert.deepEqual(saveCalls, 1); assert.deepEqual(state.installedPlugins, [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: false }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: false }, { id: "c", version: "1.0.0", repo: "ow/c", enabled: false }, ]); });
it("with ?disable-plugins and no enabled plugins, performs no save and no load", async () => { const { service, state } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: false }, ]; const loadPluginsCalls = []; service.pluginBridge.loadPlugins = async (entries) => { loadPluginsCalls.push(entries); return { loadedPlugins: entries, erroredPlugins: [] }; }; let saveCalls = 0; service.prefManager.preferencesProvider.updatePreferences = async () => { saveCalls++; }; window.history.replaceState({}, "", "http://localhost/?disable-plugins"); try { await service.loadEnabledPlugins(); } finally { window.history.replaceState({}, "", "http://localhost/"); } assert.deepEqual(loadPluginsCalls.length, 0); assert.deepEqual(saveCalls, 0); });
it("reconciles cache against all installed (including disabled)", async () => { const { service, state, reconcileCalls } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: false }, ]; await service.loadEnabledPlugins(); assert.deepEqual(reconcileCalls.length, 1); assert.deepEqual(reconcileCalls[0], [ "https://cache.test/a/1.0.0/ow/a", "https://cache.test/b/1.0.0/ow/b", ]); });});
describe("uninstallPlugin", () => { it("unloads, removes preference, clears settings, and reconciles", async () => { const { service, state, unloadCalls, reconcileCalls } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: true }, ]; state.pluginSettings = { a: { color: "red" }, b: { color: "blue" } }; await service.uninstallPlugin("a"); assert.deepEqual(unloadCalls, ["a"]); assert.deepEqual( state.installedPlugins.map((entry) => entry.id), ["b"], ); assert.deepEqual(state.pluginSettings, { b: { color: "blue" } }); // Cache should be reconciled against the remaining plugin only assert.deepEqual(reconcileCalls.length, 1); assert.deepEqual(reconcileCalls[0], ["https://cache.test/b/1.0.0/ow/b"]); });});
describe("enablePlugin", () => { it("flips enabled and loads the plugin", async () => { const { service, state, loadCalls } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: false }, ]; await service.enablePlugin("a"); assert.deepEqual(state.installedPlugins[0].enabled, true); assert.deepEqual(loadCalls, [{ id: "a", version: "1.0.0", repo: "ow/a" }]); });
it("rolls back to disabled when load fails", async () => { const { service, state } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: false }, ]; service.pluginBridge.loadPlugin = async () => { throw new Error("boom"); }; let caught = null; try { await service.enablePlugin("a"); } catch (error) { caught = error; } assert(caught?.message.includes("boom")); assert.deepEqual(state.installedPlugins[0].enabled, false); });});
describe("reloadPlugins", () => { it("reloads only enabled plugins", async () => { const { service, state, reloadCalls } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: false }, ]; await service.reloadPlugins(); assert.deepEqual( reloadCalls.map((call) => call.id), ["a"], ); });
it("disables plugins that throw and re-throws the first failure", async () => { const { service, state } = makeService(); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: true }, ]; service.pluginBridge.reloadPlugin = async (id) => { if (id === "b") throw new Error("b broke"); }; let caught = null; try { await service.reloadPlugins(); } catch (error) { caught = error; } assert(caught?.message.includes("b broke")); assert.deepEqual( state.installedPlugins.find((entry) => entry.id === "b").enabled, false, ); assert.deepEqual( state.installedPlugins.find((entry) => entry.id === "a").enabled, true, ); });});
describe("checkForUpdates", () => { it("populates $availableUpdates with plugins whose live version is newer", async () => { const { service, state } = makeService({ liveManifests: { a: { id: "a", name: "A", version: "2.0.0" }, b: { id: "b", name: "B", version: "1.0.0" }, }, }); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: true }, ]; const updates = await service.checkForUpdates(); assert.deepEqual([...updates.entries()], [["a", "2.0.0"]]); assert.deepEqual(service.$availableUpdates.get(), updates); });
it("skips plugins whose live manifest fails to fetch", async () => { const { service, state } = makeService({ liveManifests: { a: { id: "a", name: "A", version: "2.0.0" }, // b intentionally missing — getLiveManifest will throw }, }); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: true }, ]; const updates = await service.checkForUpdates(); assert.deepEqual([...updates.keys()], ["a"]); });});
describe("updateAllPlugins", () => { it("returns empty buckets when there are no available updates", async () => { const { service } = makeService(); const result = await service.updateAllPlugins(); assert.deepEqual(result, { updated: [], failed: [], declined: [] }); });
it("partitions results into updated and failed buckets", async () => { const { service, state } = makeService({ liveManifests: { a: { id: "a", name: "A", version: "2.0.0" }, b: { id: "b", name: "B", version: "2.0.0" }, }, }); state.installedPlugins = [ { id: "a", version: "1.0.0", repo: "ow/a", enabled: true }, { id: "b", version: "1.0.0", repo: "ow/b", enabled: true }, ]; await service.checkForUpdates(); // Make b's reload fail; a should still update successfully. service.pluginBridge.reloadPlugin = async (id) => { if (id === "b") throw new Error("reload failed"); }; const result = await service.updateAllPlugins(); assert.deepEqual(result.updated, ["a"]); assert.deepEqual(result.failed, ["b"]); });});
describe("$pluginsInfo", () => { it("hides __LOCAL plugins when localPluginsEnabled is false", () => { const { service, state } = makeService({}); state.installedPlugins = [ { id: "alpha", name: "Alpha", version: "1.0.0", enabled: true }, { id: "gamma__LOCAL", name: "Gamma", version: "0.1.0", enabled: true }, ]; const info = service.$pluginsInfo.get(); assert.deepEqual(info.length, 1); assert.deepEqual(info[0].id, "alpha"); });
it("includes __LOCAL plugins when localPluginsEnabled is true", () => { const { service, state } = makeService({ localListings: [] }); state.installedPlugins = [ { id: "alpha", name: "Alpha", version: "1.0.0", enabled: true }, { id: "gamma__LOCAL", name: "Gamma", version: "0.1.0", enabled: true }, ]; const info = service.$pluginsInfo.get(); assert.deepEqual(info.length, 2); });});
describe("registry listings loader/selector", () => { it("returns null from the selector before the loader runs", () => { const { service } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha", name: "Alpha" }], }); assert.deepEqual(service.$registryListings.get(), null); });
it("merges remote + local listings and marks installed entries", async () => { const { service, provider } = makeService({ remoteListings: [ { id: "alpha", repo: "ow/alpha", name: "Alpha" }, { id: "beta", repo: "ow/beta", name: "Beta" }, ], localListings: [{ id: "gamma__LOCAL", name: "Gamma" }], }); provider.$preferences.set( provider .requirePreferences() .setInstalledPlugins([ { id: "alpha", version: "1.0.0", repo: "ow/alpha", enabled: true }, ]), ); await service.loadRegistryListings(); const listings = service.$registryListings.get(); assert.deepEqual(listings.length, 3); const byId = Object.fromEntries( listings.map((listing) => [listing.id, listing]), ); assert.deepEqual(byId.alpha.installed, true); assert.deepEqual(byId.beta.installed, false); assert.deepEqual(byId.gamma__LOCAL.installed, false); });
it("reflects updated install state on subsequent selector reads", async () => { const { service, provider } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha", name: "Alpha" }], }); await service.loadRegistryListings(); assert.deepEqual(service.$registryListings.get()[0].installed, false); provider.$preferences.set( provider .requirePreferences() .setInstalledPlugins([ { id: "alpha", version: "1.0.0", repo: "ow/alpha", enabled: true }, ]), ); assert.deepEqual(service.$registryListings.get()[0].installed, true); });
it("updates installed plugin repo when remote listing repo changes", async () => { const { service, provider } = makeService({ remoteListings: [{ id: "alpha", repo: "newowner/alpha", name: "Alpha" }], }); provider.$preferences.set( provider.requirePreferences().setInstalledPlugins([ { id: "alpha", version: "1.0.0", repo: "oldowner/alpha", enabled: true, }, ]), ); await service.loadRegistryListings(); const installed = provider.requirePreferences().getInstalledPlugins(); assert.deepEqual(installed[0].repo, "newowner/alpha"); });
it("does not rewrite installed repos when listings match", async () => { const { service, provider } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha", name: "Alpha" }], }); provider.$preferences.set( provider .requirePreferences() .setInstalledPlugins([ { id: "alpha", version: "1.0.0", repo: "ow/alpha", enabled: true }, ]), ); const before = provider.$preferences.get(); await service.loadRegistryListings(); assert.deepEqual(provider.$preferences.get(), before); });
it("sorts listings alphabetically by name, ignoring case", async () => { const { service } = makeService({ remoteListings: [ { id: "gamma", repo: "ow/gamma", name: "gamma" }, { id: "alpha", repo: "ow/alpha", name: "Alpha" }, ], localListings: [{ id: "beta__LOCAL", name: "Beta" }], }); await service.loadRegistryListings(); const listings = service.$registryListings.get(); assert.deepEqual( listings.map((listing) => listing.name), ["Alpha", "Beta", "gamma"], ); });
it("returns only remote listings when localRegistry is absent", async () => { const { service } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha", name: "Alpha" }], }); await service.loadRegistryListings(); const listings = service.$registryListings.get(); assert.deepEqual(listings.length, 1); assert.deepEqual(listings[0].id, "alpha"); });});
describe("installUnregisteredPlugin", () => { it("installs from a github.com URL using manifest metadata", async () => { const { service, state, loadCalls } = makeService({ liveManifestsByRepo: { "ow/alpha": { id: "alpha", name: "Alpha", version: "1.0.0", author: "ow", description: "the first", }, }, }); const result = await service.installUnregisteredPlugin( "https://github.com/ow/alpha", ); assert.deepEqual(result, { id: "alpha", name: "Alpha" }); assert.deepEqual(state.installedPlugins, [ { id: "alpha", name: "Alpha", version: "1.0.0", author: "ow", description: "the first", repo: "ow/alpha", enabled: true, permissions: {}, }, ]); assert.deepEqual(loadCalls, [ { id: "alpha", version: "1.0.0", repo: "ow/alpha" }, ]); });
it("strips .git and extra path segments from the URL", async () => { const { service, state } = makeService({ liveManifestsByRepo: { "ow/alpha": { id: "alpha", name: "Alpha", version: "1.0.0" }, }, }); await service.installUnregisteredPlugin( "https://github.com/ow/alpha.git/tree/main", ); assert.deepEqual(state.installedPlugins[0].repo, "ow/alpha"); });
it("installs from a tangled.org URL using a tangled repo spec", async () => { const { service, state, loadCalls } = makeService({ liveManifestsByRepo: { "tangled:@ow.example.com/alpha": { id: "alpha", name: "Alpha", version: "1.0.0", }, }, }); const result = await service.installUnregisteredPlugin( "https://tangled.org/@ow.example.com/alpha", ); assert.deepEqual(result, { id: "alpha", name: "Alpha" }); assert.deepEqual( state.installedPlugins[0].repo, "tangled:@ow.example.com/alpha", ); assert.deepEqual(loadCalls, [ { id: "alpha", version: "1.0.0", repo: "tangled:@ow.example.com/alpha", }, ]); });
it("accepts tangled.sh URLs", async () => { const { service, state } = makeService({ liveManifestsByRepo: { "tangled:@ow.example.com/alpha": { id: "alpha", name: "Alpha", version: "1.0.0", }, }, }); await service.installUnregisteredPlugin( "https://tangled.sh/@ow.example.com/alpha", ); assert.deepEqual( state.installedPlugins[0].repo, "tangled:@ow.example.com/alpha", ); });
it("rejects URLs from unsupported hosts", async () => { const { service, state } = makeService(); let caught = null; try { await service.installUnregisteredPlugin("https://example.com/ow/alpha"); } catch (error) { caught = error; } assert(caught?.message.includes("Invalid repo URL")); assert.deepEqual(state.installedPlugins, []); });
it("rejects malformed URL strings", async () => { const { service } = makeService(); let caught = null; try { await service.installUnregisteredPlugin("not a url"); } catch (error) { caught = error; } assert(caught?.message.includes("Invalid repo URL")); });
it("throws when manifest is missing required fields", async () => { const { service, state } = makeService(); service.sourceProvider.getLiveManifestFromRepo = async () => { throw new Error('missing required field "version"'); }; let caught = null; try { await service.installUnregisteredPlugin("https://github.com/ow/alpha"); } catch (error) { caught = error; } assert(caught?.message.includes("Failed to fetch manifest")); assert.deepEqual(state.installedPlugins, []); });
it("rejects when the plugin id is already installed", async () => { const { service, state } = makeService({ liveManifestsByRepo: { "ow/alpha": { id: "alpha", name: "Alpha", version: "1.0.0" }, }, }); state.installedPlugins = [ { id: "alpha", name: "Alpha", version: "0.9.0", repo: "ow/alpha", enabled: true, }, ]; let caught = null; try { await service.installUnregisteredPlugin("https://github.com/ow/alpha"); } catch (error) { caught = error; } assert(caught?.message.includes("already installed")); assert.deepEqual(state.installedPlugins.length, 1); });
it("rolls back the preference entry when load fails", async () => { const { service, state } = makeService({ liveManifestsByRepo: { "ow/alpha": { id: "alpha", name: "Alpha", version: "1.0.0" }, }, }); service.pluginBridge.loadPlugin = async () => { throw new Error("boom"); }; let caught = null; try { await service.installUnregisteredPlugin("https://github.com/ow/alpha"); } catch (error) { caught = error; } assert(caught?.message.includes("boom")); assert.deepEqual(state.installedPlugins, []); });
it("rejects when the plugin id is already in the remote registry", async () => { const { service, state } = makeService({ remoteListings: [{ id: "alpha", repo: "ow/alpha" }], liveManifestsByRepo: { "someone/alpha-fork": { id: "alpha", name: "Alpha Fork", version: "1.0.0", }, }, }); let caught = null; try { await service.installUnregisteredPlugin( "https://github.com/someone/alpha-fork", ); } catch (error) { caught = error; } assert(caught?.message.includes("in the registry")); assert.deepEqual(state.installedPlugins, []); });
it("rejects when the plugin id is in the local registry", async () => { const { service, state } = makeService({ localListings: [{ id: "alpha", repo: "ow/alpha-local" }], liveManifestsByRepo: { "someone/alpha-fork": { id: "alpha", name: "Alpha Fork", version: "1.0.0", }, }, }); let caught = null; try { await service.installUnregisteredPlugin( "https://github.com/someone/alpha-fork", ); } catch (error) { caught = error; } assert(caught?.message.includes("in the registry")); assert.deepEqual(state.installedPlugins, []); });});
describe("getFilteredFeedItems", () => { const feedURI = "at://did:test/app.bsky.feed.generator/test";
function addFilter(service, pluginId, invoke) { const entry = { pluginId, invoke }; service.registries.feedFilters.add(entry); return entry; }
it("returns an empty object when no filters are registered", async () => { const { service } = makeService(); const result = await service.getFilteredFeedItems(feedURI, { feed: [] }); assert.deepEqual(result, {}); });
it("passes feed.feed (not the wrapper) to each filter", async () => { const { service } = makeService(); const feedItems = [{ post: { uri: "p1" } }]; let captured = null; addFilter(service, "alpha", async (_uri, items) => { captured = items; return {}; });
await service.getFilteredFeedItems(feedURI, { feed: feedItems });
assert.deepEqual(captured, feedItems); });
it("merges hide verdicts from multiple filters", async () => { const { service } = makeService(); addFilter(service, "alpha", async () => ({ p1: false })); addFilter(service, "beta", async () => ({ p2: false }));
const result = await service.getFilteredFeedItems(feedURI, { feed: [] });
assert.deepEqual(result, { p1: false, p2: false }); });
it("ignores non-false verdicts", async () => { const { service } = makeService(); addFilter(service, "alpha", async () => ({ p1: true, p2: false, p3: null, p4: { hidden: true }, }));
const result = await service.getFilteredFeedItems(feedURI, { feed: [] });
assert.deepEqual(result, { p2: false }); });
it("does not let one filter's keep override another filter's hide", async () => { const { service } = makeService(); addFilter(service, "alpha", async () => ({ p1: false, p2: true })); addFilter(service, "beta", async () => ({ p1: true, p2: false }));
const result = await service.getFilteredFeedItems(feedURI, { feed: [] });
assert.deepEqual(result, { p1: false, p2: false }); });
it("continues past filters that throw", async () => { const { service } = makeService(); addFilter(service, "alpha", async () => { throw new Error("boom"); }); addFilter(service, "beta", async () => ({ p1: false }));
const originalError = console.error; console.error = () => {}; let result; try { result = await service.getFilteredFeedItems(feedURI, { feed: [] }); } finally { console.error = originalError; }
assert.deepEqual(result, { p1: false }); });
it("skips filters that return null or non-object values", async () => { const { service } = makeService(); addFilter(service, "alpha", async () => null); addFilter(service, "beta", async () => "not-an-object"); addFilter(service, "gamma", async () => ({ p1: false }));
const result = await service.getFilteredFeedItems(feedURI, { feed: [] });
assert.deepEqual(result, { p1: false }); });});
describe("getClaimedFacetTypes", () => { function makeServiceWithRealBridge() { const { provider } = makeProvider(); return new PluginService(provider, null); } function registerTransform(service, pluginId, message) { const handler = service.pluginBridge._registrationTargets.get("richTextTransform"); return handler({ pluginId, call: () => {} }, message); }
it("is empty when no transforms are registered", () => { const service = makeServiceWithRealBridge(); assert.deepEqual([...service.getClaimedFacetTypes()], []); });
it("unions handlesFacetTypes across registered transforms", () => { const service = makeServiceWithRealBridge(); registerTransform(service, "alpha", { handlerId: 1, handlesFacetTypes: ["blue.moji.richtext.facet", "dev.impro.foo"], }); registerTransform(service, "beta", { handlerId: 2, handlesFacetTypes: ["dev.impro.foo"], }); assert.deepEqual([...service.getClaimedFacetTypes()].sort(), [ "blue.moji.richtext.facet", "dev.impro.foo", ]); });
it("drops entries when a transform unregisters", () => { const service = makeServiceWithRealBridge(); const dispose = registerTransform(service, "alpha", { handlerId: 1, handlesFacetTypes: ["blue.moji.richtext.facet"], }); dispose(); assert.deepEqual([...service.getClaimedFacetTypes()], []); });
it("tolerates a transform registered without handlesFacetTypes", () => { const service = makeServiceWithRealBridge(); registerTransform(service, "alpha", { handlerId: 1 }); assert.deepEqual([...service.getClaimedFacetTypes()], []); });});
describe("slot registry", () => { // These tests exercise the registration target wired by _setupRegistries, // so they need the real PluginBridge instead of the makeService stub. function makeServiceWithRealBridge() { const { provider } = makeProvider(); return new PluginService(provider, null); }
function register(service, plugin, message) { const handler = service.pluginBridge._registrationTargets.get("slot"); return handler(plugin, message); }
function makePlugin(pluginId, calls = []) { return { pluginId, call: (handlerId, ...args) => { calls.push({ handlerId, args }); return Promise.resolve({ tag: "div", attrs: {}, text: pluginId }); }, }; }
it("returns an empty list for unknown slots", () => { const service = makeServiceWithRealBridge(); assert.deepEqual(service.getSlotEntries("nope"), []); });
it("records registrations in order", async () => { const service = makeServiceWithRealBridge(); register(service, makePlugin("alpha"), { target: "slot", name: "x", handlerId: 1, }); register(service, makePlugin("beta"), { target: "slot", name: "x", handlerId: 2, }); const entries = service.getSlotEntries("x"); assert.deepEqual( entries.map((entry) => entry.pluginId), ["alpha", "beta"], ); });
it("invokes the plugin handler with the slot context", async () => { const service = makeServiceWithRealBridge(); const calls = []; register(service, makePlugin("alpha", calls), { target: "slot", name: "x", handlerId: 7, }); const [entry] = service.getSlotEntries("x"); await entry.invoke({ uri: "at://test" }); assert.deepEqual(calls, [{ handlerId: 7, args: [{ uri: "at://test" }] }]); });
it("dispose removes the entry and prunes the slot when empty", () => { const service = makeServiceWithRealBridge(); const dispose = register(service, makePlugin("alpha"), { target: "slot", name: "x", handlerId: 1, }); assert.deepEqual(service.getSlotEntries("x").length, 1); dispose(); assert.deepEqual(service.getSlotEntries("x"), []); assert.deepEqual(service.$slots.get("x"), null); });
it("updates the $slots signal on register and unregister", () => { const service = makeServiceWithRealBridge(); const updates = []; const initial = service.$slots.get("x"); const dispose = register(service, makePlugin("alpha"), { target: "slot", name: "x", handlerId: 1, }); updates.push( service.$slots.get("x")?.map((entry) => entry.pluginId) ?? null, ); dispose(); updates.push( service.$slots.get("x")?.map((entry) => entry.pluginId) ?? null, ); assert.deepEqual(initial, null); assert.deepEqual(updates, [["alpha"], null]); });});
describe("app.data host methods", () => { function makeServiceWithRealBridge() { const { provider } = makeProvider(); return new PluginService(provider, null); }
// Stubs a ComputedMap: get(key) returns the value directly. function makeStubComputedMap(lookup) { const calls = []; const map = { get: (key) => { calls.push(key); return lookup(key); }, }; return { map, calls }; }
it("getProfile host method returns the hydrated profile from derived", async () => { const service = makeServiceWithRealBridge(); const profiles = makeStubComputedMap((did) => ({ did, handle: "alice.test", })); service.setDataLayer({ derived: { $hydratedPosts: makeStubComputedMap(() => null).map, $hydratedProfiles: profiles.map, }, }); const handler = service.pluginBridge._hostCallHandlers.get("getProfile"); const result = await handler(null, { did: "did:plc:abc" }); assert.deepEqual(profiles.calls, ["did:plc:abc"]); assert.deepEqual(result, { did: "did:plc:abc", handle: "alice.test" }); });
it("getPost returns null when dataLayer has not been set", async () => { const service = makeServiceWithRealBridge(); const handler = service.pluginBridge._hostCallHandlers.get("getPost"); const result = await handler(null, { uri: "at://example" }); assert.deepEqual(result, null); });
it("getPost fetches the post on a cache miss", async () => { const service = makeServiceWithRealBridge(); const ensureCalls = []; service.setDataLayer({ derived: { $hydratedPosts: makeStubComputedMap(() => null).map, $hydratedProfiles: makeStubComputedMap(() => null).map, }, declarative: { ensurePost: async (uri) => { ensureCalls.push(uri); return { uri, record: { text: "fetched" } }; }, }, }); const handler = service.pluginBridge._hostCallHandlers.get("getPost"); const result = await handler(null, { uri: "at://example/post/1" }); assert.deepEqual(ensureCalls, ["at://example/post/1"]); assert.deepEqual(result, { uri: "at://example/post/1", record: { text: "fetched" }, }); });
it("getPost returns null when the post cannot be loaded", async () => { const service = makeServiceWithRealBridge(); service.setDataLayer({ derived: { $hydratedPosts: makeStubComputedMap(() => null).map, $hydratedProfiles: makeStubComputedMap(() => null).map, }, declarative: { ensurePost: async () => { throw new Error("Post not found"); }, }, }); const handler = service.pluginBridge._hostCallHandlers.get("getPost"); const result = await handler(null, { uri: "at://example/post/gone" }); assert.deepEqual(result, null); });
it("getProfile fetches on a cache miss and returns the basic hydrated profile", async () => { const service = makeServiceWithRealBridge(); let loaded = false; const profiles = makeStubComputedMap((did) => loaded ? { did, handle: "alice.test" } : null, ); const ensureCalls = []; service.setDataLayer({ derived: { $hydratedPosts: makeStubComputedMap(() => null).map, $hydratedProfiles: profiles.map, }, declarative: { ensureDetailedProfile: async (did) => { ensureCalls.push(did); loaded = true; }, }, }); const handler = service.pluginBridge._hostCallHandlers.get("getProfile"); const result = await handler(null, { did: "did:plc:abc" }); assert.deepEqual(ensureCalls, ["did:plc:abc"]); assert.deepEqual(result, { did: "did:plc:abc", handle: "alice.test" }); });
it("getKnownFollowers resolves via the declarative layer", async () => { const service = makeServiceWithRealBridge(); const knownFollowers = { followers: [{ did: "did:plc:follower" }] }; const ensureCalls = []; service.setDataLayer({ declarative: { ensureKnownFollowers: async (did) => { ensureCalls.push(did); return knownFollowers; }, }, }); const handler = service.pluginBridge._hostCallHandlers.get("getKnownFollowers"); const result = await handler(null, { did: "did:plc:abc" }); assert.deepEqual(ensureCalls, ["did:plc:abc"]); assert.deepEqual(result, knownFollowers); });
it("getKnownFollowers returns null when the list cannot be loaded", async () => { const service = makeServiceWithRealBridge(); service.setDataLayer({ declarative: { ensureKnownFollowers: async () => { throw new Error("Known followers not found"); }, }, }); const handler = service.pluginBridge._hostCallHandlers.get("getKnownFollowers"); const result = await handler(null, { did: "did:plc:missing" }); assert.deepEqual(result, null); });
it("getProfile returns null when the profile cannot be loaded", async () => { const service = makeServiceWithRealBridge(); service.setDataLayer({ derived: { $hydratedPosts: makeStubComputedMap(() => null).map, $hydratedProfiles: makeStubComputedMap(() => null).map, }, declarative: { ensureDetailedProfile: async () => { throw new Error("Profile not found"); }, }, }); const handler = service.pluginBridge._hostCallHandlers.get("getProfile"); const result = await handler(null, { did: "did:plc:missing" }); assert.deepEqual(result, null); });});
describe("action host methods", () => { const feedbackPlugin = { pluginId: "test-plugin", permissions: { actions: ["feedFeedback"] }, }; const postUri = "at://did:plc:author/app.bsky.feed.post/1"; const feedUri = "at://did:plc:feedgen/app.bsky.feed.generator/cool-feed";
function makeService({ feedItem = null, feedGenerator = null, hydratedProfiles = {}, } = {}) { const { provider } = makeProvider(); const service = new PluginService(provider, null); const calls = { showLess: [], showMore: [], mute: [], unmute: [], block: [], unblock: [], }; service.setDataLayer({ dataStore: { $feeds: { get: (uri) => uri === feedUri && feedItem ? { feed: [feedItem] } : null, }, }, derived: { $feedGenerators: { get: (uri) => (uri === feedUri ? feedGenerator : null), }, $hydratedDetailedProfiles: { get: () => null }, $hydratedProfiles: { get: (did) => hydratedProfiles[did] ?? null }, }, mutations: { sendShowLessInteraction: async (...args) => calls.showLess.push(args), sendShowMoreInteraction: async (...args) => calls.showMore.push(args), muteProfile: async (profile) => calls.mute.push(profile), unmuteProfile: async (profile) => calls.unmute.push(profile), blockProfile: async (profile) => calls.block.push(profile), unblockProfile: async (profile) => calls.unblock.push(profile), }, }); return { service, calls }; }
function getHandler(service, name) { return service.pluginBridge._hostCallHandlers.get(name); }
it("showLessLikeThis resolves feedContext and proxy from the feed", async () => { const { service, calls } = makeService({ feedItem: { post: { uri: postUri }, feedContext: "ctx" }, feedGenerator: { uri: feedUri, did: "did:web:feed.example" }, }); await getHandler(service, "showLessLikeThis")(feedbackPlugin, { postUri, feedUri, }); assert.deepEqual(calls.showLess, [ [postUri, feedUri, "ctx", "did:web:feed.example#bsky_fg"], ]); });
it("showLessLikeThis and showMoreLikeThis reject when feedUri is missing", async () => { const { service, calls } = makeService(); await assert.rejects( getHandler(service, "showLessLikeThis")(feedbackPlugin, { postUri }), /requires a feedUri/, ); await assert.rejects( getHandler(service, "showMoreLikeThis")(feedbackPlugin, { postUri }), /requires a feedUri/, ); assert.deepEqual(calls.showLess, []); assert.deepEqual(calls.showMore, []); });
it("both methods reject when postUri is missing", async () => { const { service, calls } = makeService(); await assert.rejects( getHandler(service, "showLessLikeThis")(feedbackPlugin, { feedUri }), /requires a postUri/, ); await assert.rejects( getHandler(service, "showMoreLikeThis")(feedbackPlugin, { feedUri }), /requires a postUri/, ); assert.deepEqual(calls.showLess, []); assert.deepEqual(calls.showMore, []); });
it("muteActor and blockActor reject when did is missing", async () => { const { service } = makeService(); await assert.rejects( getHandler(service, "muteActor")( { pluginId: "test-plugin", permissions: { actions: ["mute"] } }, {}, ), /muteActor requires a did/, ); await assert.rejects( getHandler(service, "blockActor")( { pluginId: "test-plugin", permissions: { actions: ["block"] } }, {}, ), /blockActor requires a did/, ); });
it("showLessLikeThis with an uncached feed still resolves the generator proxy", async () => { const { service, calls } = makeService({ feedGenerator: { uri: feedUri, did: "did:web:feed.example" }, }); await getHandler(service, "showLessLikeThis")(feedbackPlugin, { postUri, feedUri, }); assert.deepEqual(calls.showLess, [ [postUri, feedUri, null, "did:web:feed.example#bsky_fg"], ]); });
it("showMoreLikeThis resolves attribution the same way", async () => { const { service, calls } = makeService({ feedItem: { post: { uri: postUri }, feedContext: "ctx" }, feedGenerator: { uri: feedUri, did: "did:web:feed.example" }, }); await getHandler(service, "showMoreLikeThis")(feedbackPlugin, { postUri, feedUri, }); assert.deepEqual(calls.showMore, [ [postUri, feedUri, "ctx", "did:web:feed.example#bsky_fg"], ]); });
it("both methods require the feedFeedback action permission", async () => { const { service, calls } = makeService(); const noPermissionPlugin = { pluginId: "test-plugin", permissions: { actions: ["mute"] }, }; for (const name of ["showLessLikeThis", "showMoreLikeThis"]) { await assert.rejects( getHandler(service, name)(noPermissionPlugin, { postUri, feedUri }), /"feedFeedback" action permission/, ); } assert.deepEqual(calls.showLess, []); assert.deepEqual(calls.showMore, []); });
it("muteActor routes the mute flag to muteProfile and unmuteProfile", async () => { const did = "did:plc:target"; const profile = { did, handle: "target.example" }; const { service, calls } = makeService({ hydratedProfiles: { [did]: profile }, }); const mutePlugin = { pluginId: "test-plugin", permissions: { actions: ["mute"] }, }; await getHandler(service, "muteActor")(mutePlugin, { did, mute: true }); await getHandler(service, "muteActor")(mutePlugin, { did, mute: false }); assert.deepEqual(calls.mute, [profile]); assert.deepEqual(calls.unmute, [profile]); });
it("blockActor routes the block flag to blockProfile and unblockProfile", async () => { const did = "did:plc:target"; const { service, calls } = makeService(); const blockPlugin = { pluginId: "test-plugin", permissions: { actions: ["block"] }, }; await getHandler(service, "blockActor")(blockPlugin, { did, block: true }); await getHandler(service, "blockActor")(blockPlugin, { did, block: false }); assert.deepEqual(calls.block, [{ did }]); assert.deepEqual(calls.unblock, [{ did }]); });
it("muteActor and blockActor require their action permissions", async () => { const { service, calls } = makeService(); const noPermissionPlugin = { pluginId: "test-plugin", permissions: { actions: ["feedFeedback"] }, }; const did = "did:plc:target"; await assert.rejects( getHandler(service, "muteActor")(noPermissionPlugin, { did }), /"mute" action permission/, ); await assert.rejects( getHandler(service, "blockActor")(noPermissionPlugin, { did }), /"block" action permission/, ); assert.deepEqual(calls.mute, []); assert.deepEqual(calls.block, []); });
it("all action methods reject when signed out", async () => { const { provider } = makeProvider(); const service = new PluginService(provider, null); const allActionsPlugin = { pluginId: "test-plugin", permissions: { actions: ["mute", "block", "feedFeedback"] }, }; const argsByMethod = { muteActor: { did: "did:plc:target" }, blockActor: { did: "did:plc:target" }, showLessLikeThis: { postUri, feedUri }, showMoreLikeThis: { postUri, feedUri }, }; for (const [name, args] of Object.entries(argsByMethod)) { await assert.rejects( getHandler(service, name)(allActionsPlugin, args), /Not signed in/, ); } });});
describe("getRecord host method", () => { function makeServiceWithRealBridge() { const { provider } = makeProvider(); return new PluginService(provider, null); }
function jsonResponse(status, body) { return { ok: status >= 200 && status < 300, status, json: async () => body, }; }
const VALID_COLLECTION = "blue.moji.collection.item"; const VALID_RKEY = "blobcat";
let didCounter = 0; function uniqueDid() { didCounter++; return `did:plc:test${didCounter.toString().padStart(6, "0")}`; }
const originalFetch = globalThis.fetch; afterEach(() => { globalThis.fetch = originalFetch; });
function stubFetch(handler) { const calls = []; globalThis.fetch = async (input) => { const url = typeof input === "string" ? input : input.toString(); calls.push(url); return handler(url); }; return { calls }; }
it("fetches the record from Slingshot", async () => { const service = makeServiceWithRealBridge(); const did = uniqueDid(); const record = { uri: `at://${did}/${VALID_COLLECTION}/${VALID_RKEY}`, cid: "bafyfake", value: { name: "blobcat" }, }; const { calls } = stubFetch(async () => jsonResponse(200, record)); const handler = service.pluginBridge._hostCallHandlers.get("getRecord"); const result = await handler(null, { repo: did, collection: VALID_COLLECTION, rkey: VALID_RKEY, }); assert.deepEqual(result, record); const url = new URL(calls[0]); assert.deepEqual(url.origin, "https://slingshot.microcosm.blue"); assert.deepEqual(url.pathname, "/xrpc/com.atproto.repo.getRecord"); assert.deepEqual(url.searchParams.get("repo"), did); assert.deepEqual(url.searchParams.get("collection"), VALID_COLLECTION); assert.deepEqual(url.searchParams.get("rkey"), VALID_RKEY); });
it("returns null on RecordNotFound", async () => { const service = makeServiceWithRealBridge(); const did = uniqueDid(); stubFetch(async () => jsonResponse(400, { error: "RecordNotFound", message: "gone" }), ); const handler = service.pluginBridge._hostCallHandlers.get("getRecord"); const result = await handler(null, { repo: did, collection: VALID_COLLECTION, rkey: VALID_RKEY, }); assert.deepEqual(result, null); });
it("rejects on other errors so the plugin can retry", async () => { const service = makeServiceWithRealBridge(); const did = uniqueDid(); stubFetch(async () => jsonResponse(502, null)); const handler = service.pluginBridge._hostCallHandlers.get("getRecord"); let caught = null; try { await handler(null, { repo: did, collection: VALID_COLLECTION, rkey: VALID_RKEY, }); } catch (e) { caught = e; } assert(caught !== null); });
it("rejects invalid repo/collection/rkey inputs without hitting the network", async () => { const service = makeServiceWithRealBridge(); let fetched = false; globalThis.fetch = async () => { fetched = true; return jsonResponse(200, {}); }; const handler = service.pluginBridge._hostCallHandlers.get("getRecord"); const invalidInputs = [ { repo: "not-a-did", collection: VALID_COLLECTION, rkey: VALID_RKEY }, { repo: "did:plc:abc", collection: "not.enough", rkey: VALID_RKEY }, { repo: "did:plc:abc", collection: VALID_COLLECTION, rkey: "" }, { repo: "did:plc:abc", collection: VALID_COLLECTION, rkey: "has/slash" }, ]; for (const inputs of invalidInputs) { let caught = null; try { await handler(null, inputs); } catch (e) { caught = e; } assert( caught !== null, `expected rejection for ${JSON.stringify(inputs)}`, ); } assert.deepEqual(fetched, false); });});
describe("getPostComposerInit", () => { function addListener(service, pluginId, handler) { let listeners = service.registries.eventListeners.get("post-composer-open"); if (!listeners) { listeners = new Map(); service.registries.eventListeners.set("post-composer-open", listeners); } listeners.set(pluginId, handler); }
it("returns null when no listeners are registered", async () => { const { service } = makeService(); const result = await service.getPostComposerInit({ kind: "post" }); assert.deepEqual(result, null); });
it("returns null when listeners contribute no ops and no cursor", async () => { const { service } = makeService(); addListener(service, "noop", async () => ({ ops: [], cursor: null })); addListener(service, "alsoNoop", async () => null); const result = await service.getPostComposerInit({ kind: "post" }); assert.deepEqual(result, null); });
it("appends text from a single listener", async () => { const { service } = makeService(); addListener(service, "sig", async () => ({ ops: [{ op: "append", text: "\n\n— signed" }], cursor: null, })); const result = await service.getPostComposerInit({ kind: "post" }); assert.deepEqual(result, { text: "\n\n— signed", cursor: null }); });
it("composes set/append/prepend across multiple listeners in order", async () => { const { service } = makeService(); addListener(service, "alpha", async () => ({ ops: [{ op: "set", text: "middle" }], cursor: null, })); addListener(service, "beta", async () => ({ ops: [{ op: "append", text: " end" }], cursor: null, })); addListener(service, "gamma", async () => ({ ops: [{ op: "prepend", text: "start " }], cursor: null, })); const result = await service.getPostComposerInit({ kind: "post" }); assert.deepEqual(result.text, "start middle end"); });
it("last setCursor wins; nulls do not clobber prior cursor", async () => { const { service } = makeService(); addListener(service, "alpha", async () => ({ ops: [{ op: "append", text: "a" }], cursor: 0, })); addListener(service, "beta", async () => ({ ops: [{ op: "append", text: "b" }], cursor: null, })); addListener(service, "gamma", async () => ({ ops: [{ op: "append", text: "c" }], cursor: -1, })); const result = await service.getPostComposerInit({ kind: "post" }); assert.deepEqual(result, { text: "abc", cursor: -1 }); });
it("ignores listeners that throw", async () => { const { service } = makeService(); addListener(service, "alpha", async () => { throw new Error("boom"); }); addListener(service, "beta", async () => ({ ops: [{ op: "append", text: "ok" }], cursor: null, })); const originalError = console.error; console.error = () => {}; let result; try { result = await service.getPostComposerInit({ kind: "post" }); } finally { console.error = originalError; } assert.deepEqual(result, { text: "ok", cursor: null }); });
it("passes context through to each listener", async () => { const { service } = makeService(); let captured = null; addListener(service, "alpha", async (context) => { captured = context; return { ops: [], cursor: null }; }); const context = { kind: "reply", replyTo: { uri: "at://x" } }; await service.getPostComposerInit(context); // The service normalizes the context, so absent fields arrive as // explicit undefined keys assert.deepEqual(captured, { kind: "reply", replyTo: { uri: "at://x" }, replyRoot: undefined, quotedPost: undefined, }); });});
describe("rich text transform pipeline", () => { const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
function makeContext({ uri = "at://did:test/app.bsky.feed.post/1", surface = "largePost", text = "hello", facets = [], } = {}) { return { surface, uri, did: "did:test", numberOfLines: null, source: { text, facets }, }; }
function addTransform(service, pluginId, invoke) { const entry = { pluginId, invoke }; service.registries.richTextTransforms.add(entry); return entry; }
function silencingErrors(run) { const originalError = console.error; console.error = () => {}; return Promise.resolve() .then(run) .finally(() => { console.error = originalError; }); }
it("resolves null with no transforms registered", async () => { const { service } = makeService(); const tokens = [{ type: "text", value: "hello" }]; assert.deepEqual( await service.transformRichTextTokens(tokens, makeContext()), null, ); });
it("resolves the transformed tokens and caches them per post and surface", async () => { const { service } = makeService(); const batches = []; addTransform(service, "alpha", async (batch) => { batches.push(batch); return batch.map(({ tokens }) => ({ value: [...tokens, { type: "text", value: "!" }], })); }); const tokens = [{ type: "text", value: "hello" }]; const context = makeContext();
const transformed = await service.transformRichTextTokens(tokens, context); assert.deepEqual(transformed, [ { type: "text", value: "hello" }, { type: "text", value: "!" }, ]);
// Second request hits the cache: same result, no extra plugin call. assert.deepEqual( await service.transformRichTextTokens(tokens, context), transformed, ); assert.deepEqual(batches.length, 1); });
it("batches all posts of a render burst into one call per plugin", async () => { const { service } = makeService(); const batches = []; addTransform(service, "alpha", async (batch) => { batches.push(batch); return batch.map(({ tokens }) => ({ value: tokens })); });
await Promise.all([ service.transformRichTextTokens( [{ type: "text", value: "one" }], makeContext({ uri: "at://post/1", text: "one" }), ), service.transformRichTextTokens( [{ type: "text", value: "two" }], makeContext({ uri: "at://post/2", text: "two" }), ), ]);
assert.deepEqual(batches.length, 1); assert.deepEqual(batches[0].length, 2); assert.deepEqual(batches[0][0].tokens, [{ type: "text", value: "one" }]); assert.deepEqual(batches[0][1].tokens, [{ type: "text", value: "two" }]); });
it("shares one run between concurrent requests for the same post and surface", async () => { const { service } = makeService(); const batches = []; addTransform(service, "alpha", async (batch) => { batches.push(batch); return batch.map(({ tokens }) => ({ value: tokens })); }); const tokens = [{ type: "text", value: "hello" }]; const context = makeContext();
const [first, second] = await Promise.all([ service.transformRichTextTokens(tokens, context), service.transformRichTextTokens(tokens, context), ]);
assert.deepEqual(first, second); assert.deepEqual(batches.length, 1); assert.deepEqual(batches[0].length, 1); });
it("chains transforms in registration order", async () => { const { service } = makeService(); addTransform(service, "alpha", async (batch) => batch.map(({ tokens }) => ({ value: [...tokens, { type: "text", value: "A" }], })), ); addTransform(service, "beta", async (batch) => batch.map(({ tokens }) => ({ value: [...tokens, { type: "text", value: "B" }], })), );
const transformed = await service.transformRichTextTokens( [{ type: "text", value: "hello" }], makeContext(), );
assert.deepEqual( transformed.map((token) => token.value), ["hello", "A", "B"], ); });
it("fails open when a transform throws", async () => { const { service } = makeService(); addTransform(service, "alpha", async () => { throw new Error("boom"); }); addTransform(service, "beta", async (batch) => batch.map(({ tokens }) => ({ value: [...tokens, { type: "text", value: "B" }], })), );
const transformed = await silencingErrors(() => service.transformRichTextTokens( [{ type: "text", value: "hello" }], makeContext(), ), );
assert.deepEqual( transformed.map((token) => token.value), ["hello", "B"], ); });
it("fails open per item on error entries and malformed tokens", async () => { const { service } = makeService(); addTransform(service, "alpha", async (batch) => batch.map(({ context }) => context.uri.endsWith("/1") ? { error: "no thanks" } : { value: [{ type: "bogus" }] }, ), );
const [first, second] = await silencingErrors(() => Promise.all([ service.transformRichTextTokens( [{ type: "text", value: "one" }], makeContext({ uri: "at://post/1", text: "one" }), ), service.transformRichTextTokens( [{ type: "text", value: "two" }], makeContext({ uri: "at://post/2", text: "two" }), ), ]), );
assert.deepEqual(first, [{ type: "text", value: "one" }]); assert.deepEqual(second, [{ type: "text", value: "two" }]); });
it("re-hydrates returned facet tokens to the host originals", async () => { const { service } = makeService(); const facet = { index: { byteStart: 0, byteEnd: 4 }, features: [{ $type: "app.bsky.richtext.facet#tag", tag: "tag" }], }; const facetToken = { type: "facet", facet, text: "#tag" }; // Simulate the structured-clone boundary: the plugin returns a copy. addTransform(service, "alpha", async (batch) => batch.map(({ tokens }) => ({ value: JSON.parse(JSON.stringify(tokens)), })), );
const transformed = await service.transformRichTextTokens( [facetToken, { type: "text", value: " in front" }], makeContext({ text: "#tag in front", facets: [facet] }), );
assert( transformed[0] === facetToken, "facet token should be the host object", ); });
it("rejects a result containing an unrecognized facet", async () => { const { service } = makeService(); addTransform(service, "alpha", async (batch) => batch.map(() => ({ value: [ { type: "facet", facet: { index: { byteStart: 0, byteEnd: 99 }, features: [] }, text: "forged", }, ], })), ); const tokens = [{ type: "text", value: "hello" }];
const transformed = await silencingErrors(() => service.transformRichTextTokens(tokens, makeContext()), );
assert.deepEqual(transformed, tokens); });
it("stamps inline/block tokens with the emitting transform's pluginId and preserves earlier ids", async () => { const { service } = makeService(); const node = { tag: "code", text: "x" }; addTransform(service, "alpha", async (batch) => batch.map(() => ({ value: [{ type: "inline", node }] })), ); addTransform(service, "beta", async (batch) => batch.map(({ tokens }) => ({ value: [...tokens, { type: "block", node }], })), );
const transformed = await service.transformRichTextTokens( [{ type: "text", value: "hello" }], makeContext(), );
assert.deepEqual( transformed.map((token) => token.pluginId), ["alpha", "beta"], ); });
it("re-stamps a forged pluginId naming another plugin", async () => { const { service } = makeService(); const node = { tag: "code", text: "x" }; addTransform(service, "alpha", async (batch) => batch.map(() => ({ value: [{ type: "inline", pluginId: "victim", node }], })), );
const transformed = await service.transformRichTextTokens( [{ type: "text", value: "hello" }], makeContext(), );
assert.deepEqual( transformed.map((token) => token.pluginId), ["alpha"], ); });
it("clears cached results when the transform set changes", async () => { const { service } = makeService(); const batches = []; addTransform(service, "alpha", async (batch) => { batches.push(batch); return batch.map(({ tokens }) => ({ value: tokens })); }); const tokens = [{ type: "text", value: "hello" }]; const context = makeContext();
await service.transformRichTextTokens(tokens, context); service._invalidateRichTextTransforms(); await service.transformRichTextTokens(tokens, context);
assert.deepEqual(batches.length, 2); });
it("resolves in-flight requests with null when transforms change mid-run", async () => { const { service } = makeService(); let releaseTransform; const gate = new Promise((resolve) => { releaseTransform = resolve; }); addTransform(service, "alpha", async (batch) => { await gate; return batch.map(({ tokens }) => ({ value: tokens })); }); const request = service.transformRichTextTokens( [{ type: "text", value: "hello" }], makeContext(), ); await flush(); service._invalidateRichTextTransforms(); releaseTransform();
assert.deepEqual(await request, null); assert.deepEqual(service._richTextTokensCache.size, 0); });
it("re-runs when the cached entry no longer matches the source text", async () => { const { service } = makeService(); const batches = []; addTransform(service, "alpha", async (batch) => { batches.push(batch); return batch.map(({ tokens }) => ({ value: tokens })); }); const context = makeContext({ text: "before" });
await service.transformRichTextTokens( [{ type: "text", value: "before" }], context, ); const transformed = await service.transformRichTextTokens( [{ type: "text", value: "after" }], makeContext({ text: "after" }), );
assert.deepEqual(batches.length, 2); assert.deepEqual(transformed, [{ type: "text", value: "after" }]); });
it("renderRichTextNodeToken mounts a sanitized element and reuses it per token and host", () => { const { service } = makeService(); service.setRenderContext({}); const token = { type: "inline", pluginId: "alpha", node: { tag: "code", attrs: {}, text: "x", children: [], events: {} }, }; const host = document.createElement("div");
const element = service.renderRichTextNodeToken(token, host); assert.deepEqual(element.localName, "code"); assert.deepEqual(element.textContent, "x"); assert(service.renderRichTextNodeToken(token, host) === element); const otherHost = document.createElement("div"); const otherElement = service.renderRichTextNodeToken(token, otherHost); assert.deepEqual(otherElement.localName, "code"); assert(otherElement !== element); });});