mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
feat: more remote options
This commit is contained in:
1 parent
3869a1f8d6
commit
fc72d5ac5e
19 files changed
+558
-23
No files matched your search
@@ -283,10 +283,87 @@ export function createRemoteConfigHandlers(apiBase: () => string): Record<
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchRemoteThemePackage(
|
||||
req: { packageId?: string },
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const packageId = typeof req.packageId === "string" ? req.packageId.trim() : "";
|
||||
if (!packageId) {
|
||||
sendResponse({ error: "Missing packageId" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const hostname = await readLastHostname();
|
||||
const params = new URLSearchParams({
|
||||
installId: await getOrCreateInstallId(),
|
||||
extensionVersion: extensionVersion(),
|
||||
channel: extensionChannel(),
|
||||
});
|
||||
if (hostname) params.set("hostname", hostname);
|
||||
const base = apiBase();
|
||||
const url = `${base}/api/bsplus/remote-theme-packages/${encodeURIComponent(packageId)}?${params}`;
|
||||
if (!isAllowedFetchUrl(url)) {
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return;
|
||||
}
|
||||
const r = await fetch(url, { cache: "no-store", headers: { Accept: "application/json" } });
|
||||
if (!r.ok) {
|
||||
sendResponse({ error: `HTTP ${r.status}` });
|
||||
return;
|
||||
}
|
||||
const json = await parseJson(r);
|
||||
if (!json || typeof json !== "object") {
|
||||
sendResponse({ error: "Invalid package response" });
|
||||
return;
|
||||
}
|
||||
sendResponse({ package: json });
|
||||
} catch (e) {
|
||||
sendResponse({
|
||||
error: e instanceof Error ? e.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchRemoteThemePackageUrl(
|
||||
req: { url?: string },
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const url = typeof req.url === "string" ? req.url.trim() : "";
|
||||
if (!url || !isAllowedFetchUrl(url)) {
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const r = await fetch(url, { cache: "no-store" });
|
||||
if (!r.ok) {
|
||||
sendResponse({ error: `HTTP ${r.status}` });
|
||||
return;
|
||||
}
|
||||
const theme = await parseJson(r);
|
||||
if (!theme || typeof theme !== "object") {
|
||||
sendResponse({ error: "Invalid theme JSON" });
|
||||
return;
|
||||
}
|
||||
sendResponse({ theme });
|
||||
} catch (e) {
|
||||
sendResponse({
|
||||
error: e instanceof Error ? e.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
refreshRemoteConfig: handleRefresh,
|
||||
getRemoteConfigSnapshot: handleGetSnapshot,
|
||||
setRemoteConfigPageContext: handleSetPageContext,
|
||||
fetchRemoteThemePackage: handleFetchRemoteThemePackage,
|
||||
fetchRemoteThemePackageUrl: handleFetchRemoteThemePackageUrl,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
dismissOptionalRemoteTheme,
|
||||
getRemoteConfigSnapshot,
|
||||
isEffectiveBsplusEnabled,
|
||||
isRemoteKillActive,
|
||||
resolveEffectiveRemoteTheme,
|
||||
setLocalOverrideOnoff,
|
||||
} from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { getRemoteStatusMessage } from "@/seqta/utils/remoteConfig/apply";
|
||||
@@ -14,16 +16,23 @@
|
||||
let localOverride = $state(false);
|
||||
|
||||
const snapshot = $derived(getRemoteConfigSnapshot());
|
||||
const activeTheme = $derived(resolveEffectiveRemoteTheme(snapshot));
|
||||
const killActive = $derived(isRemoteKillActive());
|
||||
const statusMessage = $derived(getRemoteStatusMessage(snapshot));
|
||||
const allowOverride = $derived(snapshot.global.allowLocalOverride !== false);
|
||||
const showStrip = $derived(
|
||||
killActive ||
|
||||
activeTheme?.mode === "optional" ||
|
||||
!!statusMessage ||
|
||||
!!snapshot.global.maintenance?.body ||
|
||||
!!snapshot.global.maintenance?.title,
|
||||
);
|
||||
|
||||
async function turnOffOptionalTheme() {
|
||||
await dismissOptionalRemoteTheme(snapshot);
|
||||
location.reload();
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
void browser.storage.local.get("bsplus_local_override_onoff").then((stored) => {
|
||||
localOverride = stored.bsplus_local_override_onoff === true;
|
||||
@@ -47,10 +56,21 @@
|
||||
role="status"
|
||||
>
|
||||
<p class="leading-relaxed">
|
||||
{statusMessage ??
|
||||
"BetterSEQTA+ is temporarily limited. You can review settings for details."}
|
||||
{activeTheme?.mode === "optional" && activeTheme.message?.body
|
||||
? activeTheme.message.body
|
||||
: statusMessage ??
|
||||
"BetterSEQTA+ is temporarily limited. You can review settings for details."}
|
||||
</p>
|
||||
<div class="mt-2 flex flex-wrap items-center gap-2">
|
||||
{#if activeTheme?.mode === "optional" && snapshot.remoteTheme?.allowUserOptOut !== false}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-amber-600 px-3 py-1.5 text-xs font-semibold text-white transition-all duration-200 hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:ring-offset-2 dark:focus:ring-offset-zinc-900"
|
||||
onclick={() => void turnOffOptionalTheme()}
|
||||
>
|
||||
Turn off school theme
|
||||
</button>
|
||||
{/if}
|
||||
{#if killActive && !isEffectiveBsplusEnabled() && allowOverride}
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -11,8 +11,12 @@
|
||||
import { isLocalCustomTheme } from '@/interface/utils/themeListFilters'
|
||||
import { closeExtensionPopup } from '@/seqta/utils/Closers/closeExtensionPopup'
|
||||
import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors'
|
||||
import { getRemoteConfigSnapshot, resolveEffectiveRemoteTheme } from '@/seqta/utils/remoteConfig/runtime'
|
||||
|
||||
const themeManager = ThemeManager.getInstance();
|
||||
const remoteThemeForced = $derived(
|
||||
resolveEffectiveRemoteTheme(getRemoteConfigSnapshot())?.mode === "forced",
|
||||
);
|
||||
|
||||
let themes = $state<ThemeList | null>(null);
|
||||
let { isEditMode, showNavigation = true } = $props<{
|
||||
@@ -37,7 +41,7 @@
|
||||
});
|
||||
|
||||
const handleThemeClick = async (theme: CustomTheme, e: MouseEvent) => {
|
||||
if (isEditMode) return;
|
||||
if (isEditMode || remoteThemeForced) return;
|
||||
if (theme.id === themes?.selectedTheme) {
|
||||
themeManager.setTransitionPoint(e.clientX, e.clientY);
|
||||
await themeManager.disableTheme();
|
||||
@@ -163,7 +167,12 @@
|
||||
role="list"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="{useTwoColumnLayout ? 'grid grid-cols-2 gap-3' : 'flex flex-col gap-2 px-2'}">
|
||||
{#if remoteThemeForced}
|
||||
<p class="mb-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-900 dark:text-amber-100">
|
||||
Your school has applied a theme. Theme selection is locked until it is removed.
|
||||
</p>
|
||||
{/if}
|
||||
<div class="{useTwoColumnLayout ? 'grid grid-cols-2 gap-3' : 'flex flex-col gap-2 px-2'} {remoteThemeForced ? 'pointer-events-none opacity-50' : ''}">
|
||||
{#if themes}
|
||||
{#each themes.themes as theme (theme.id)}
|
||||
<button
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
const isEngage = isSeqtaEngageExperience();
|
||||
const onoffGate = $derived(checkRemoteFeature("settings.control.onoff"));
|
||||
const onoffGreyedOut = $derived(onoffGate.mode === "greyout");
|
||||
const sidebarEditHidden = $derived(checkRemoteFeature("ui.sidebar.edit").hide);
|
||||
|
||||
const generalOptions = $derived([
|
||||
{
|
||||
@@ -42,7 +43,7 @@
|
||||
onChange: (isOn: boolean) => (settingsState.performanceMode = isOn),
|
||||
},
|
||||
},
|
||||
...(!isEngage
|
||||
...(!isEngage && !sidebarEditHidden
|
||||
? [
|
||||
{
|
||||
title: "Edit Sidebar Layout",
|
||||
|
||||
@@ -14,6 +14,10 @@ import browser from "webextension-polyfill";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { verboseInfo } from "@/utils/verboseLog";
|
||||
import { isRemotePluginStartAllowed } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import {
|
||||
isRemoteRouteEnhancementsStripped,
|
||||
ROUTE_STRIP_KEEP_PLUGINS,
|
||||
} from "@/seqta/utils/remoteConfig/routeGate";
|
||||
import { isPluginAllowedInPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||
|
||||
interface PluginSettingsStorage {
|
||||
@@ -245,6 +249,12 @@ export class PluginManager {
|
||||
if (!isRemotePluginStartAllowed(plugin.id)) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
isRemoteRouteEnhancementsStripped() &&
|
||||
!ROUTE_STRIP_KEEP_PLUGINS.has(plugin.id)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (!plugin.disableToggle) return true;
|
||||
const all = settingsState.getAll() as unknown as Record<string, unknown>;
|
||||
const stored = all[`plugin.${plugin.id}.settings`] as PluginSettingsStorage | undefined;
|
||||
@@ -340,6 +350,13 @@ export class PluginManager {
|
||||
Array.from(this.plugins.keys()).forEach((id) => this.stopPlugin(id));
|
||||
}
|
||||
|
||||
public async stopPluginsExcept(keepIds: ReadonlySet<string>): Promise<void> {
|
||||
const stops = Array.from(this.plugins.keys())
|
||||
.filter((id) => !keepIds.has(id))
|
||||
.map((id) => this.stopPlugin(id));
|
||||
await Promise.allSettled(stops);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a registered plugin by its ID.
|
||||
*
|
||||
|
||||
+20
-11
@@ -209,12 +209,8 @@ function SortMessagePageItems(messagesParentElement: any) {
|
||||
|
||||
async function LoadPageElements(): Promise<void> {
|
||||
await AddBetterSEQTAElements();
|
||||
void import("@/seqta/ui/sidebar/applyNativeSidebar").then((mod) => {
|
||||
void mod.applyNativeSidebar();
|
||||
});
|
||||
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
|
||||
void mod.mountCustomTitleBar();
|
||||
});
|
||||
const { syncRouteEnhancementChrome } = await import("@/seqta/utils/remoteConfig/routeGate");
|
||||
await syncRouteEnhancementChrome();
|
||||
const sublink: string | undefined = getEngageRoutePage();
|
||||
|
||||
if (isSeqtaEngageExperience() && !engageHashListenerAttached) {
|
||||
@@ -748,11 +744,16 @@ export function init() {
|
||||
// Learn only: apply sidebar CSS vars early; Engage keeps its native React menu.
|
||||
if (!onLogin && !isSeqtaEngageExperience()) {
|
||||
document.documentElement.classList.add("bsplus-custom-title-pending");
|
||||
void import("@/seqta/ui/sidebar/applyNativeSidebar").then((mod) => {
|
||||
mod.prepareNativeSidebarEarly();
|
||||
});
|
||||
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
|
||||
mod.prepareCustomTitleBarEarly();
|
||||
void import("@/seqta/utils/remoteConfig/routeGate").then(async (gate) => {
|
||||
if (gate.isRemoteRouteEnhancementsStripped()) return;
|
||||
if (gate.remoteChromeGateAllowed("ui.sidebar.styled")) {
|
||||
const mod = await import("@/seqta/ui/sidebar/applyNativeSidebar");
|
||||
mod.prepareNativeSidebarEarly();
|
||||
}
|
||||
if (gate.remoteChromeGateAllowed("ui.titlebar.custom")) {
|
||||
const mod = await import("@/seqta/ui/titlebar/mountCustomTitleBar");
|
||||
mod.prepareCustomTitleBarEarly();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
document.documentElement.classList.remove("bsplus-custom-title-pending");
|
||||
@@ -778,7 +779,15 @@ export function init() {
|
||||
});
|
||||
|
||||
let hashColorTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let routeChromeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
window.addEventListener("hashchange", () => {
|
||||
if (routeChromeTimer) clearTimeout(routeChromeTimer);
|
||||
routeChromeTimer = setTimeout(() => {
|
||||
routeChromeTimer = null;
|
||||
void import("@/seqta/utils/remoteConfig/routeGate").then((m) =>
|
||||
m.syncRouteEnhancementChrome(),
|
||||
);
|
||||
}, 120);
|
||||
if (!settingsState.adaptiveThemeColour) return;
|
||||
if (hashColorTimer) clearTimeout(hashColorTimer);
|
||||
hashColorTimer = setTimeout(() => {
|
||||
|
||||
@@ -24,6 +24,7 @@ import { LUCIDE_SUN_ICON_SVG } from "@/lib/icons/lucideSun";
|
||||
import { ensureTitlebarFounderBadgeMounted, refreshTitlebarFounderBadge } from "@/seqta/ui/founderBadge/mountTitlebarFounderBadge";
|
||||
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { remoteChromeGateAllowed } from "@/seqta/utils/remoteConfig/routeGate";
|
||||
import { rafThrottle } from "@/seqta/utils/rafThrottle";
|
||||
import {
|
||||
installSidebarDrillReturn,
|
||||
@@ -162,7 +163,9 @@ export async function AddBetterSEQTAElements() {
|
||||
setupEventListeners();
|
||||
await addDarkLightToggle();
|
||||
customizeMenuToggle();
|
||||
maybeSetupSidebarAccessibility();
|
||||
if (remoteChromeGateAllowed("ui.sidebar.styled")) {
|
||||
maybeSetupSidebarAccessibility();
|
||||
}
|
||||
}
|
||||
|
||||
addExtensionSettings();
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type BadgeItem,
|
||||
} from "@/seqta/utils/founderBadges";
|
||||
import { openFounderBadgeModal } from "@/seqta/ui/founderBadge/openFounderBadgeModal";
|
||||
import { remoteChromeGateAllowed } from "@/seqta/utils/remoteConfig/routeGate";
|
||||
|
||||
let subscribed = false;
|
||||
let refreshPending = false;
|
||||
@@ -155,7 +156,13 @@ async function syncTitlebarFounderBadge(): Promise<void> {
|
||||
slot.hidden = true;
|
||||
}
|
||||
|
||||
if (settingsState.showTitlebarFounderBadge === false || !cloudAuth.state.isLoggedIn) return;
|
||||
if (
|
||||
settingsState.showTitlebarFounderBadge === false ||
|
||||
!cloudAuth.state.isLoggedIn ||
|
||||
!remoteChromeGateAllowed("ui.titlebar.founderBadge")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
let user = cloudAuth.state.user;
|
||||
const needsProfileSync =
|
||||
|
||||
@@ -12,6 +12,7 @@ export function openRemoteCampaignPopup(
|
||||
): void {
|
||||
const title = campaign.header?.title ?? "BetterSEQTA+";
|
||||
const subtitle = campaign.header?.subtitle ?? "";
|
||||
let acknowledged = false;
|
||||
|
||||
const header = stringToHTML(
|
||||
/* html */ `<div class="whatsnewHeader"><h1>${title}</h1>${subtitle ? `<p>${subtitle}</p>` : ""}</div>`,
|
||||
@@ -66,7 +67,7 @@ export function openRemoteCampaignPopup(
|
||||
requestSettingsDestination({ section: btn.section });
|
||||
await openSettingsPopup();
|
||||
}
|
||||
await markCampaignSeen(campaign.id, campaign.requireAcknowledge === true);
|
||||
if (campaign.requireAcknowledge) acknowledged = true;
|
||||
await closePopup();
|
||||
},
|
||||
}));
|
||||
@@ -77,7 +78,10 @@ export function openRemoteCampaignPopup(
|
||||
animateSelector: ".whatsnewImgContainer, .whatsnewTextContainer *",
|
||||
actions,
|
||||
afterClose: () => {
|
||||
void markCampaignSeen(campaign.id);
|
||||
void markCampaignSeen(
|
||||
campaign.id,
|
||||
campaign.requireAcknowledge ? acknowledged : undefined,
|
||||
);
|
||||
onDismissed?.();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ export type WhatsNewRelease = {
|
||||
|
||||
export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [
|
||||
{
|
||||
"title": "3.7.6 - Community Theme Submitter Badges,",
|
||||
"title": "3.7.6 - Timetable Sharing Fixes, Better Update resilience & Community Theme Submitter Badges,",
|
||||
"items": [
|
||||
"Improved releiability of opening the connection for Timetable Sharing.",
|
||||
"Added a new submitter badge for community theme submitters.",
|
||||
|
||||
@@ -11,6 +11,9 @@ import {
|
||||
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY,
|
||||
BSPLUS_REMOTE_THEME_BEFORE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_STATE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_USER_OFF_KEY,
|
||||
} from "@/seqta/utils/remoteConfig/storageKeys";
|
||||
|
||||
/** Matches the contract in docs/CLOUD_SETTINGS_SYNC_SERVER.md */
|
||||
@@ -64,6 +67,9 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [
|
||||
BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
|
||||
BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY,
|
||||
BSPLUS_REMOTE_THEME_BEFORE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_STATE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_USER_OFF_KEY,
|
||||
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
|
||||
] as const;
|
||||
|
||||
@@ -88,6 +94,9 @@ const CLIENT_ONLY_CLOUD_KEYS_EXACT = [
|
||||
"bsplus_lastCloudPoll",
|
||||
BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY,
|
||||
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
|
||||
"bsplus_remote_theme_before_v1",
|
||||
"bsplus_remote_theme_state_v1",
|
||||
"bsplus_remote_theme_user_off",
|
||||
] as const;
|
||||
|
||||
/** After restoring from cloud, keep local session so the user stays signed in. */
|
||||
@@ -358,6 +367,19 @@ export function migrateLegacyToPluginSettings(data: Record<string, unknown>): Re
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a flat settings record (e.g. remote theme restore snapshot).
|
||||
*/
|
||||
export async function applyLocalSettingsRecord(flat: Record<string, unknown>): Promise<void> {
|
||||
await applyDownloadedEnvelope(flat);
|
||||
}
|
||||
|
||||
/** Snapshot of keys eligible for cloud upload — used for remote theme restore capture. */
|
||||
export async function captureSyncableSettingsSnapshot(): Promise<Record<string, unknown>> {
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
return normalizeStorageForSync(all);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the downloaded cloud snapshot by setting each key individually,
|
||||
* preserving auth keys and device-only sensitive caches.
|
||||
|
||||
@@ -121,6 +121,14 @@ describe("hydrateRemoteConfigFromStorage", () => {
|
||||
jest.doMock("@/seqta/utils/listeners/SettingsState", () => ({
|
||||
settingsState: { onoff: true },
|
||||
}));
|
||||
jest.doMock("./routeGate", () => ({
|
||||
syncRouteEnhancementChrome: jest.fn(async () => {}),
|
||||
}));
|
||||
jest.doMock("./remoteTheme", () => ({
|
||||
scheduleReconcileRemoteTheme: jest.fn(),
|
||||
dismissOptionalRemoteTheme: jest.fn(),
|
||||
resolveEffectiveRemoteTheme: jest.fn(),
|
||||
}));
|
||||
const { hydrateRemoteConfigFromStorage, notifyRemoteConfigPageContext } = await import("./runtime");
|
||||
await hydrateRemoteConfigFromStorage();
|
||||
notifyRemoteConfigPageContext("learn.example.edu.au");
|
||||
|
||||
@@ -21,6 +21,26 @@ describe("normalizeRemoteConfigSnapshot", () => {
|
||||
expect(snap.global.mode).toBe("off");
|
||||
expect(snap.global.statusMessage).toBe("Maintenance");
|
||||
});
|
||||
|
||||
it("normalizes remoteTheme directive", () => {
|
||||
const snap = normalizeRemoteConfigSnapshot({
|
||||
configVersion: "10",
|
||||
remoteTheme: {
|
||||
packageId: "pkg",
|
||||
packageVersion: "1",
|
||||
mode: "optional",
|
||||
},
|
||||
});
|
||||
expect(snap.remoteTheme?.packageId).toBe("pkg");
|
||||
expect(snap.remoteTheme?.mode).toBe("optional");
|
||||
});
|
||||
|
||||
it("drops invalid remoteTheme", () => {
|
||||
const snap = normalizeRemoteConfigSnapshot({
|
||||
remoteTheme: { mode: "forced" },
|
||||
});
|
||||
expect(snap.remoteTheme).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeGithubConfigFiles", () => {
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { RemoteConfigSnapshot, RemoteFeatureGate, RemoteGlobalConfig } from "./types";
|
||||
import type {
|
||||
RemoteConfigSnapshot,
|
||||
RemoteFeatureGate,
|
||||
RemoteGlobalConfig,
|
||||
RemoteThemeDirective,
|
||||
} from "./types";
|
||||
|
||||
export const DEFAULT_REMOTE_CONFIG: RemoteConfigSnapshot = {
|
||||
configVersion: "0",
|
||||
@@ -6,6 +11,7 @@ export const DEFAULT_REMOTE_CONFIG: RemoteConfigSnapshot = {
|
||||
global: { mode: "on", allowLocalOverride: true },
|
||||
features: {},
|
||||
campaigns: [],
|
||||
remoteTheme: null,
|
||||
};
|
||||
|
||||
function normalizeGlobal(raw: unknown): RemoteGlobalConfig {
|
||||
@@ -83,6 +89,38 @@ function normalizeFeatures(raw: unknown): Record<string, RemoteFeatureGate> {
|
||||
return out;
|
||||
}
|
||||
|
||||
function normalizeRemoteTheme(raw: unknown): RemoteThemeDirective | null {
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
const r = raw as Record<string, unknown>;
|
||||
const mode = r.mode;
|
||||
if (mode !== "off" && mode !== "optional" && mode !== "forced") return null;
|
||||
const packageId = typeof r.packageId === "string" ? r.packageId.trim() : "";
|
||||
const packageVersion =
|
||||
typeof r.packageVersion === "string" ? r.packageVersion.trim() : "";
|
||||
if (!packageId || !packageVersion) return null;
|
||||
if (mode === "off") return null;
|
||||
const msg = r.message;
|
||||
return {
|
||||
packageId,
|
||||
packageVersion,
|
||||
mode,
|
||||
activeFrom: typeof r.activeFrom === "string" ? r.activeFrom : undefined,
|
||||
activeTo: typeof r.activeTo === "string" ? r.activeTo : undefined,
|
||||
allowUserOptOut: r.allowUserOptOut !== false,
|
||||
message:
|
||||
msg && typeof msg === "object"
|
||||
? {
|
||||
title: typeof (msg as { title?: string }).title === "string"
|
||||
? (msg as { title: string }).title
|
||||
: undefined,
|
||||
body: typeof (msg as { body?: string }).body === "string"
|
||||
? (msg as { body: string }).body
|
||||
: undefined,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeRemoteConfigSnapshot(raw: unknown): RemoteConfigSnapshot {
|
||||
if (!raw || typeof raw !== "object") return { ...DEFAULT_REMOTE_CONFIG };
|
||||
const r = raw as Record<string, unknown>;
|
||||
@@ -102,6 +140,7 @@ export function normalizeRemoteConfigSnapshot(raw: unknown): RemoteConfigSnapsho
|
||||
global: normalizeGlobal(data.global),
|
||||
features: normalizeFeatures(data.features),
|
||||
campaigns: Array.isArray(data.campaigns) ? (data.campaigns as RemoteConfigSnapshot["campaigns"]) : [],
|
||||
remoteTheme: normalizeRemoteTheme(data.remoteTheme),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -116,5 +155,6 @@ export function mergeGithubConfigFiles(
|
||||
global: files.global ?? {},
|
||||
features: files.features ?? {},
|
||||
campaigns: files.campaigns ?? [],
|
||||
remoteTheme: files.remoteTheme ?? null,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import {
|
||||
applyLocalSettingsRecord,
|
||||
captureSyncableSettingsSnapshot,
|
||||
} from "@/seqta/utils/cloudSettingsSync";
|
||||
import { settingsState, initializeSettingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import type { RemoteConfigSnapshot, RemoteThemeDirective } from "./types";
|
||||
import {
|
||||
BSPLUS_REMOTE_THEME_BEFORE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_STATE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_USER_OFF_KEY,
|
||||
} from "./storageKeys";
|
||||
|
||||
type BeforeSnapshot = {
|
||||
capturedAt: string;
|
||||
directiveKey: string;
|
||||
storage: Record<string, unknown>;
|
||||
selectedTheme: string;
|
||||
};
|
||||
|
||||
type ActiveThemeState = {
|
||||
directiveKey: string;
|
||||
packageId: string;
|
||||
installedThemeId: string;
|
||||
mode: "optional" | "forced";
|
||||
};
|
||||
|
||||
export type RemoteThemePackageResponse = {
|
||||
packageId: string;
|
||||
version: string;
|
||||
theme?: Record<string, unknown>;
|
||||
downloadUrl?: string;
|
||||
};
|
||||
|
||||
let reconcileChain: Promise<void> = Promise.resolve();
|
||||
|
||||
function remoteThemeDirectiveKey(
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
directive: RemoteThemeDirective,
|
||||
): string {
|
||||
return `${snapshot.configVersion}|${directive.packageId}|${directive.packageVersion}|${directive.mode}`;
|
||||
}
|
||||
|
||||
function isWithinWindow(directive: RemoteThemeDirective, now = Date.now()): boolean {
|
||||
if (directive.activeFrom) {
|
||||
const from = Date.parse(directive.activeFrom);
|
||||
if (!Number.isNaN(from) && now < from) return false;
|
||||
}
|
||||
if (directive.activeTo) {
|
||||
const until = Date.parse(directive.activeTo);
|
||||
if (!Number.isNaN(until) && now > until) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function resolveEffectiveRemoteTheme(
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
): RemoteThemeDirective | null {
|
||||
const d = snapshot.remoteTheme;
|
||||
if (!d || d.mode === "off") return null;
|
||||
if (!isWithinWindow(d)) return null;
|
||||
return d;
|
||||
}
|
||||
|
||||
async function loadBeforeSnapshot(): Promise<BeforeSnapshot | null> {
|
||||
const stored = await browser.storage.local.get(BSPLUS_REMOTE_THEME_BEFORE_V1_KEY);
|
||||
const raw = stored[BSPLUS_REMOTE_THEME_BEFORE_V1_KEY];
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
const b = raw as BeforeSnapshot;
|
||||
if (!b.directiveKey || !b.storage || typeof b.storage !== "object") return null;
|
||||
return b;
|
||||
}
|
||||
|
||||
async function captureBeforeSnapshot(directiveKey: string): Promise<void> {
|
||||
const existing = await loadBeforeSnapshot();
|
||||
if (existing?.directiveKey === directiveKey) return;
|
||||
|
||||
const storage = await captureSyncableSettingsSnapshot();
|
||||
const before: BeforeSnapshot = {
|
||||
capturedAt: new Date().toISOString(),
|
||||
directiveKey,
|
||||
storage,
|
||||
selectedTheme: settingsState.selectedTheme ?? "",
|
||||
};
|
||||
await browser.storage.local.set({ [BSPLUS_REMOTE_THEME_BEFORE_V1_KEY]: before });
|
||||
}
|
||||
|
||||
async function clearRemoteThemeLocalState(): Promise<void> {
|
||||
await browser.storage.local.remove([
|
||||
BSPLUS_REMOTE_THEME_BEFORE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_STATE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_USER_OFF_KEY,
|
||||
]);
|
||||
}
|
||||
|
||||
async function loadUserOffKey(): Promise<string | null> {
|
||||
const stored = await browser.storage.local.get(BSPLUS_REMOTE_THEME_USER_OFF_KEY);
|
||||
const raw = stored[BSPLUS_REMOTE_THEME_USER_OFF_KEY];
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
const key = (raw as { directiveKey?: string }).directiveKey;
|
||||
return typeof key === "string" ? key : null;
|
||||
}
|
||||
|
||||
export async function dismissOptionalRemoteTheme(snapshot: RemoteConfigSnapshot): Promise<void> {
|
||||
const directive = resolveEffectiveRemoteTheme(snapshot);
|
||||
if (!directive || directive.mode !== "optional") return;
|
||||
const key = remoteThemeDirectiveKey(snapshot, directive);
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_THEME_USER_OFF_KEY]: { directiveKey: key },
|
||||
});
|
||||
await restoreRemoteThemeSnapshot();
|
||||
}
|
||||
|
||||
async function restoreRemoteThemeSnapshot(): Promise<void> {
|
||||
const before = await loadBeforeSnapshot();
|
||||
if (before) {
|
||||
await applyLocalSettingsRecord(before.storage);
|
||||
await initializeSettingsState();
|
||||
const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager");
|
||||
const tm = ThemeManager.getInstance();
|
||||
if (before.selectedTheme) {
|
||||
await tm.setTheme(before.selectedTheme, false);
|
||||
} else {
|
||||
await tm.disableTheme();
|
||||
}
|
||||
}
|
||||
await clearRemoteThemeLocalState();
|
||||
}
|
||||
|
||||
async function fetchPackage(packageId: string): Promise<RemoteThemePackageResponse | null> {
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "fetchRemoteThemePackage",
|
||||
packageId,
|
||||
})) as { package?: RemoteThemePackageResponse; error?: string } | undefined;
|
||||
if (res?.error || !res?.package) return null;
|
||||
return res.package;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveThemeContent(
|
||||
pkg: RemoteThemePackageResponse,
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
if (pkg.theme && typeof pkg.theme === "object") return pkg.theme;
|
||||
if (!pkg.downloadUrl) return null;
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "fetchRemoteThemePackageUrl",
|
||||
url: pkg.downloadUrl,
|
||||
})) as { theme?: Record<string, unknown>; error?: string };
|
||||
if (res?.theme && typeof res.theme === "object") return res.theme;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function applyRemoteThemePackage(
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
directive: RemoteThemeDirective,
|
||||
): Promise<void> {
|
||||
const directiveKey = remoteThemeDirectiveKey(snapshot, directive);
|
||||
const stored = await browser.storage.local.get(BSPLUS_REMOTE_THEME_STATE_V1_KEY);
|
||||
const state = stored[BSPLUS_REMOTE_THEME_STATE_V1_KEY] as ActiveThemeState | undefined;
|
||||
if (state?.directiveKey === directiveKey) return;
|
||||
|
||||
await captureBeforeSnapshot(directiveKey);
|
||||
|
||||
const pkg = await fetchPackage(directive.packageId);
|
||||
if (!pkg) return;
|
||||
|
||||
const themeContent = await resolveThemeContent(pkg);
|
||||
if (!themeContent || typeof themeContent.id !== "string") return;
|
||||
|
||||
const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager");
|
||||
const tm = ThemeManager.getInstance();
|
||||
await tm.installTheme(themeContent as Parameters<typeof tm.installTheme>[0], {
|
||||
fromStore: false,
|
||||
forceTheme: directive.mode === "forced",
|
||||
});
|
||||
await tm.setTheme(String(themeContent.id), false);
|
||||
|
||||
const active: ActiveThemeState = {
|
||||
directiveKey,
|
||||
packageId: directive.packageId,
|
||||
installedThemeId: String(themeContent.id),
|
||||
mode: directive.mode,
|
||||
};
|
||||
await browser.storage.local.set({ [BSPLUS_REMOTE_THEME_STATE_V1_KEY]: active });
|
||||
await browser.storage.local.remove(BSPLUS_REMOTE_THEME_USER_OFF_KEY);
|
||||
}
|
||||
|
||||
async function reconcileRemoteThemeInner(snapshot: RemoteConfigSnapshot): Promise<void> {
|
||||
const directive = resolveEffectiveRemoteTheme(snapshot);
|
||||
const userOff = await loadUserOffKey();
|
||||
|
||||
if (!directive) {
|
||||
const stateRaw = await browser.storage.local.get(BSPLUS_REMOTE_THEME_STATE_V1_KEY);
|
||||
if (stateRaw[BSPLUS_REMOTE_THEME_STATE_V1_KEY]) {
|
||||
await restoreRemoteThemeSnapshot();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const directiveKey = remoteThemeDirectiveKey(snapshot, directive);
|
||||
if (directive.mode === "optional" && userOff === directiveKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
await applyRemoteThemePackage(snapshot, directive);
|
||||
}
|
||||
|
||||
export function scheduleReconcileRemoteTheme(snapshot: RemoteConfigSnapshot): void {
|
||||
reconcileChain = reconcileChain
|
||||
.then(() => reconcileRemoteThemeInner(snapshot))
|
||||
.catch((e) => console.warn("[BetterSEQTA+] remote theme reconcile failed:", e));
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { checkRemoteFeature } from "./runtime";
|
||||
|
||||
export const ROUTE_STRIP_KEEP_PLUGINS = new Set(["themes", "animated-background"]);
|
||||
|
||||
export function parseSeqtaPageKeyFromHash(hash = location.hash): string | null {
|
||||
const match =
|
||||
hash.match(/[#?]page=\/([^/?&#]+)/i) ?? hash.match(/page=\/([^/?&#]+)/i);
|
||||
if (!match?.[1]) return null;
|
||||
return match[1].trim().toLowerCase();
|
||||
}
|
||||
|
||||
export function isRemoteRouteEnhancementsStripped(pageKey?: string | null): boolean {
|
||||
const key = pageKey ?? parseSeqtaPageKeyFromHash();
|
||||
if (!key) return false;
|
||||
return checkRemoteFeature(`page.${key}`).mode === "block";
|
||||
}
|
||||
|
||||
export function remoteChromeGateAllowed(
|
||||
key: "ui.sidebar.styled" | "ui.titlebar.custom" | "ui.titlebar.founderBadge",
|
||||
): boolean {
|
||||
const mode = checkRemoteFeature(key).mode;
|
||||
return mode !== "hide" && mode !== "block";
|
||||
}
|
||||
|
||||
export async function syncRouteEnhancementChrome(): Promise<void> {
|
||||
if (isRemoteRouteEnhancementsStripped()) {
|
||||
const { clearNativeSidebar } = await import("@/seqta/ui/sidebar/applyNativeSidebar");
|
||||
clearNativeSidebar();
|
||||
const { unmountCustomTitleBar } = await import("@/seqta/ui/titlebar/mountCustomTitleBar");
|
||||
unmountCustomTitleBar();
|
||||
const { pluginManager } = await import("@/plugins/index");
|
||||
await pluginManager.stopPluginsExcept(ROUTE_STRIP_KEEP_PLUGINS);
|
||||
return;
|
||||
}
|
||||
|
||||
if (remoteChromeGateAllowed("ui.sidebar.styled")) {
|
||||
const { applyNativeSidebar } = await import("@/seqta/ui/sidebar/applyNativeSidebar");
|
||||
await applyNativeSidebar();
|
||||
}
|
||||
if (remoteChromeGateAllowed("ui.titlebar.custom")) {
|
||||
const { mountCustomTitleBar } = await import("@/seqta/ui/titlebar/mountCustomTitleBar");
|
||||
void mountCustomTitleBar();
|
||||
}
|
||||
const { pluginManager } = await import("@/plugins/index");
|
||||
await pluginManager.startAllPlugins();
|
||||
}
|
||||
@@ -23,6 +23,12 @@ import {
|
||||
resolveFeatureMode,
|
||||
shouldHideFeature,
|
||||
} from "./apply";
|
||||
import { scheduleReconcileRemoteTheme } from "./remoteTheme";
|
||||
|
||||
export {
|
||||
dismissOptionalRemoteTheme,
|
||||
resolveEffectiveRemoteTheme,
|
||||
} from "./remoteTheme";
|
||||
|
||||
let snapshot: RemoteConfigSnapshot = normalizeRemoteConfigSnapshot(null);
|
||||
let localOverride = false;
|
||||
@@ -31,6 +37,11 @@ let campaignSeen: CampaignSeenRecord = {};
|
||||
|
||||
const SNAPSHOT_FETCH_TIMEOUT_MS = 200;
|
||||
|
||||
function kickRemoteSideEffects(): void {
|
||||
scheduleReconcileRemoteTheme(snapshot);
|
||||
void import("./routeGate").then((m) => m.syncRouteEnhancementChrome());
|
||||
}
|
||||
|
||||
export function getRemoteConfigSnapshot(): RemoteConfigSnapshot {
|
||||
return snapshot;
|
||||
}
|
||||
@@ -119,6 +130,7 @@ export async function hydrateRemoteConfigFromStorage(): Promise<RemoteConfigSnap
|
||||
(stored[BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY] as Record<string, string>) ?? {},
|
||||
(stored[BSPLUS_CAMPAIGN_SEEN_KEY] as CampaignSeenRecord) ?? {},
|
||||
);
|
||||
kickRemoteSideEffects();
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
@@ -137,7 +149,10 @@ export function notifyRemoteConfigPageContext(hostname: string): void {
|
||||
export async function markCampaignSeen(campaignId: string, ack?: boolean): Promise<void> {
|
||||
campaignSeen = {
|
||||
...campaignSeen,
|
||||
[campaignId]: { seenAt: new Date().toISOString(), ack },
|
||||
[campaignId]: {
|
||||
seenAt: new Date().toISOString(),
|
||||
...(ack === true ? { ack: true } : ack === false ? { ack: false } : {}),
|
||||
},
|
||||
};
|
||||
await browser.storage.local.set({ [BSPLUS_CAMPAIGN_SEEN_KEY]: campaignSeen });
|
||||
}
|
||||
@@ -154,6 +169,7 @@ export function installRemoteConfigStorageListener(onEffectiveChange: () => void
|
||||
if (area !== "local") return;
|
||||
if (!Object.keys(changes).some((k) => REMOTE_STORAGE_WATCH_KEYS.has(k))) return;
|
||||
void hydrateRemoteConfigFromStorage().then(() => {
|
||||
kickRemoteSideEffects();
|
||||
const next = isEffectiveBsplusEnabled();
|
||||
if (next !== priorEnabled) {
|
||||
priorEnabled = next;
|
||||
|
||||
@@ -9,6 +9,10 @@ export const BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY = "bsplus_remote_config_fetched
|
||||
export const BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY = "bsplus_remote_config_last_hostname";
|
||||
export const BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY = "bsplus_remote_last_primary_ok";
|
||||
|
||||
export const BSPLUS_REMOTE_THEME_BEFORE_V1_KEY = "bsplus_remote_theme_before_v1";
|
||||
export const BSPLUS_REMOTE_THEME_STATE_V1_KEY = "bsplus_remote_theme_state_v1";
|
||||
export const BSPLUS_REMOTE_THEME_USER_OFF_KEY = "bsplus_remote_theme_user_off";
|
||||
|
||||
export const REMOTE_CONFIG_ALARM = "bsplus_remote_config_poll";
|
||||
export const REMOTE_CONFIG_POLL_MINUTES = 20;
|
||||
export const REGISTER_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
@@ -49,6 +49,18 @@ export type RemoteCampaign = {
|
||||
maxVersion?: string;
|
||||
};
|
||||
|
||||
export type RemoteThemeMode = "off" | "optional" | "forced";
|
||||
|
||||
export type RemoteThemeDirective = {
|
||||
packageId: string;
|
||||
packageVersion: string;
|
||||
mode: RemoteThemeMode;
|
||||
activeFrom?: string;
|
||||
activeTo?: string;
|
||||
message?: { title?: string; body?: string };
|
||||
allowUserOptOut?: boolean;
|
||||
};
|
||||
|
||||
export type RemoteConfigSnapshot = {
|
||||
configVersion: string;
|
||||
etag?: string;
|
||||
@@ -56,6 +68,7 @@ export type RemoteConfigSnapshot = {
|
||||
global: RemoteGlobalConfig;
|
||||
features: Record<string, RemoteFeatureGate>;
|
||||
campaigns: RemoteCampaign[];
|
||||
remoteTheme?: RemoteThemeDirective | null;
|
||||
};
|
||||
|
||||
export type CampaignSeenRecord = Record<
|
||||
|
||||
Reference in new issue
Block a user