mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
chore: merge upstream main
This commit is contained in:
64 files changed
+587
-2543
No files matched your search
@@ -2,6 +2,10 @@ name: Build Extension
|
||||
description: Install dependencies, build Chrome and Firefox extensions, and package zips.
|
||||
|
||||
inputs:
|
||||
include_sources:
|
||||
description: Include the committed source and Firefox build instructions.
|
||||
required: false
|
||||
default: "false"
|
||||
gh_release_update_check:
|
||||
description: Enable GitHub release update checker in the built extension.
|
||||
required: false
|
||||
@@ -29,6 +33,9 @@ outputs:
|
||||
firefox_zip:
|
||||
description: Path to the Firefox extension zip
|
||||
value: ${{ steps.zip.outputs.firefox_zip }}
|
||||
sources_zip:
|
||||
description: Path to the Firefox source zip when include_sources is true
|
||||
value: ${{ steps.zip.outputs.sources_zip }}
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
@@ -56,4 +63,4 @@ runs:
|
||||
env:
|
||||
UPDATE_CHANNEL: ${{ inputs.update_channel }}
|
||||
BUILD_LABEL: ${{ inputs.build_label }}
|
||||
run: node scripts/package-extension-zips.mjs "${{ steps.version.outputs.version }}"
|
||||
run: node scripts/package-extension-zips.mjs "${{ steps.version.outputs.version }}" "${{ inputs.include_sources == 'true' && '--sources' || '' }}"
|
||||
@@ -0,0 +1,120 @@
|
||||
name: Publish Stores
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: store-release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: github.event_name == 'workflow_dispatch' || !github.event.release.prerelease
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
contents: write
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
outputs:
|
||||
publisher_version: ${{ steps.publisher.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Check release version
|
||||
if: github.event_name == 'release'
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.event.release.tag_name }}
|
||||
run: test "${RELEASE_TAG#v}" = "$(node -p "require('./package.json').version")"
|
||||
|
||||
- name: Build store packages
|
||||
id: build
|
||||
uses: ./.github/actions/build-extension
|
||||
with:
|
||||
include_sources: "true"
|
||||
|
||||
- name: Check build
|
||||
run: npm run lint && npm run test:unit && npm run test:smoke
|
||||
|
||||
- name: Verify Firefox source rebuild
|
||||
env:
|
||||
SOURCES_ZIP: ${{ steps.build.outputs.sources_zip }}
|
||||
run: |
|
||||
mkdir "$RUNNER_TEMP/source-rebuild"
|
||||
powershell -NoProfile -Command 'Expand-Archive -LiteralPath $env:SOURCES_ZIP -DestinationPath "$env:RUNNER_TEMP/source-rebuild"'
|
||||
cd "$RUNNER_TEMP/source-rebuild"
|
||||
npm ci
|
||||
npm run build:firefox
|
||||
diff -qr "$GITHUB_WORKSPACE/dist/firefox" dist/firefox
|
||||
|
||||
- name: Record publisher version and package checksums
|
||||
id: publisher
|
||||
run: |
|
||||
echo "version=$(node -p "require('./node_modules/publish-browser-extension/package.json').version")" >> "$GITHUB_OUTPUT"
|
||||
echo "Commit: $GITHUB_SHA" >> "$GITHUB_STEP_SUMMARY"
|
||||
sha256sum dist/*.zip | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Upload review artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: store-packages
|
||||
path: dist/*.zip
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Attach packages to release
|
||||
if: github.event_name == 'release'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ github.event.release.tag_name }}
|
||||
run: gh release upload "$RELEASE_TAG" dist/*.zip --clobber
|
||||
|
||||
publish:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
environment: store-publishing
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
store: [chrome, firefox]
|
||||
env:
|
||||
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' }}
|
||||
steps:
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 26.x
|
||||
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: store-packages
|
||||
path: dist
|
||||
|
||||
- name: Install publisher without lifecycle scripts
|
||||
env:
|
||||
PUBLISHER_VERSION: ${{ needs.build.outputs.publisher_version }}
|
||||
run: npm install --prefix "$RUNNER_TEMP/publisher" --ignore-scripts --no-audit --no-fund "publish-browser-extension@$PUBLISHER_VERSION"
|
||||
|
||||
- name: Submit Chrome
|
||||
if: matrix.store == 'chrome'
|
||||
env:
|
||||
CHROME_API_VERSION: v2
|
||||
CHROME_EXTENSION_ID: ${{ secrets.CHROME_EXTENSION_ID }}
|
||||
CHROME_PUBLISHER_ID: ${{ secrets.CHROME_PUBLISHER_ID }}
|
||||
CHROME_SERVICE_ACCOUNT_CLIENT_EMAIL: ${{ secrets.CHROME_SERVICE_ACCOUNT_CLIENT_EMAIL }}
|
||||
CHROME_SERVICE_ACCOUNT_PRIVATE_KEY: ${{ secrets.CHROME_SERVICE_ACCOUNT_PRIVATE_KEY }}
|
||||
run: '"$RUNNER_TEMP/publisher/node_modules/.bin/publish-extension" --chrome-zip dist/*-chrome.zip --dry-run "$DRY_RUN"'
|
||||
|
||||
- name: Submit Firefox with sources
|
||||
if: matrix.store == 'firefox'
|
||||
env:
|
||||
FIREFOX_EXTENSION_ID: ${{ secrets.FIREFOX_EXTENSION_ID }}
|
||||
FIREFOX_JWT_ISSUER: ${{ secrets.FIREFOX_JWT_ISSUER }}
|
||||
FIREFOX_JWT_SECRET: ${{ secrets.FIREFOX_JWT_SECRET }}
|
||||
FIREFOX_CHANNEL: listed
|
||||
run: '"$RUNNER_TEMP/publisher/node_modules/.bin/publish-extension" --firefox-zip dist/*-firefox.zip --firefox-sources-zip dist/*-sources.zip --dry-run "$DRY_RUN"'
|
||||
+32
-155
@@ -1,158 +1,35 @@
|
||||
/**
|
||||
* @fileoverview
|
||||
* This script is a command-line utility for publishing the BetterSEQTA+ extension.
|
||||
* It automates the process of finding the latest built extension ZIP files for specified
|
||||
* browsers, zipping the project source code (for Firefox), and then invoking the
|
||||
* `publish-extension` tool with the appropriate arguments.
|
||||
*
|
||||
* To use this script, invoke it with Node.js followed by browser arguments:
|
||||
* e.g., `node lib/publish.js --b chrome firefox`
|
||||
* or `node lib/publish.js --b chrome`
|
||||
* or `node lib/publish.js --b firefox`
|
||||
*/
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { globSync } from "node:fs";
|
||||
import semver from "semver";
|
||||
import { execSync } from "node:child_process";
|
||||
|
||||
function getLatestVersion(files) {
|
||||
console.log("Files passed to getLatestVersion:", files);
|
||||
|
||||
const versions = files
|
||||
.map((file) => {
|
||||
const match = file.match(/@([\d.]+)-/);
|
||||
console.log("Matching file:", file, "Version found:", match ? match[1] : "None");
|
||||
|
||||
if (!match) return null;
|
||||
|
||||
const fullVersion = match[1]; // Original version (e.g., 3.4.5.1)
|
||||
// Trim to 3 parts for semver comparison, as semver typically handles X.Y.Z
|
||||
const semverVersion = fullVersion.split(".").slice(0, 3).join(".");
|
||||
|
||||
return { fullVersion, semverVersion };
|
||||
})
|
||||
.filter(Boolean); // Remove null entries if any file didn't match
|
||||
|
||||
console.log(
|
||||
"Extracted versions:",
|
||||
versions.map((v) => v.semverVersion),
|
||||
);
|
||||
|
||||
if (versions.length === 0) {
|
||||
console.log("No versions extracted.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Find latest version using the trimmed semver format
|
||||
const latestSemver = semver.maxSatisfying(
|
||||
versions.map((v) => v.semverVersion),
|
||||
"*", // Satisfy any version, effectively finding the max
|
||||
);
|
||||
console.log("Latest SemVer-compatible version:", latestSemver);
|
||||
|
||||
if (!latestSemver) {
|
||||
console.log("Could not determine latest semver version.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get the original full version string that matches the identified latest SemVer version
|
||||
const latestVersionData = versions.find((v) => v.semverVersion === latestSemver);
|
||||
const latestFullVersion = latestVersionData ? latestVersionData.fullVersion : null;
|
||||
|
||||
console.log("Final selected latest version:", latestFullVersion);
|
||||
return latestFullVersion;
|
||||
}
|
||||
|
||||
function getLatestFiles(browser) {
|
||||
const pattern = `dist/betterseqtaplus@*-*${browser}.zip`;
|
||||
console.log("Glob pattern:", pattern);
|
||||
|
||||
const files = globSync(pattern);
|
||||
console.log("Files found for browser", browser, ":", files);
|
||||
|
||||
if (files.length === 0) {
|
||||
console.log("No files found for browser", browser);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const latestVersion = getLatestVersion(files);
|
||||
if (!latestVersion) {
|
||||
console.log("Could not determine latest version for browser", browser);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Find the exact file by matching the original full version string
|
||||
const latestFile = files.find((file) => file.includes(`@${latestVersion}-`));
|
||||
|
||||
console.log("Latest file for browser", browser, ":", latestFile);
|
||||
return latestFile;
|
||||
}
|
||||
|
||||
function zipSources() {
|
||||
const zipFileName = `dist/betterseqtaplus@latest-sources.zip`;
|
||||
|
||||
const excludePatterns = [
|
||||
"node_modules",
|
||||
"dist",
|
||||
".env*",
|
||||
".git",
|
||||
".github",
|
||||
".vscode",
|
||||
"LICENSE",
|
||||
"package.json",
|
||||
]
|
||||
.map((pattern) => `-x!${pattern}`) // Format for 7z exclude syntax
|
||||
.join(" ");
|
||||
|
||||
// Command to zip the current directory's contents into zipFileName, applying exclude patterns
|
||||
const zipCommand = `7zz a ${zipFileName} . ${excludePatterns}`;
|
||||
|
||||
console.log("Zipping project sources with command:", zipCommand);
|
||||
execSync(zipCommand, { stdio: "inherit" }); // Execute synchronously and show output
|
||||
|
||||
return zipFileName;
|
||||
}
|
||||
|
||||
function runPublishCommand(browsers) {
|
||||
const chromeZip = browsers.includes("chrome") ? getLatestFiles("chrome") : null;
|
||||
const firefoxZip = browsers.includes("firefox") ? getLatestFiles("firefox") : null;
|
||||
// Sources are typically only needed for Firefox submissions
|
||||
const firefoxSourcesZip = browsers.includes("firefox") ? zipSources() : null;
|
||||
|
||||
console.log("Chrome zip:", chromeZip);
|
||||
console.log("Firefox zip:", firefoxZip);
|
||||
console.log("Firefox sources zip:", firefoxSourcesZip);
|
||||
|
||||
if (browsers.length === 0) {
|
||||
console.log("No browsers specified. Exiting.");
|
||||
process.exit(0); // Exit gracefully if no action is needed
|
||||
}
|
||||
|
||||
// Check if required files are missing for the specified browsers
|
||||
if (
|
||||
(browsers.includes("chrome") && !chromeZip) ||
|
||||
(browsers.includes("firefox") && (!firefoxZip || !firefoxSourcesZip))
|
||||
) {
|
||||
console.error("Could not find required zip files for specified browsers.");
|
||||
process.exit(1); // Exit with error status
|
||||
}
|
||||
|
||||
let command = "publish-extension";
|
||||
if (chromeZip) {
|
||||
command += ` --chrome-zip ${chromeZip}`;
|
||||
}
|
||||
if (firefoxZip && firefoxSourcesZip) {
|
||||
command += ` --firefox-zip ${firefoxZip} --firefox-sources-zip ${firefoxSourcesZip}`;
|
||||
}
|
||||
|
||||
console.log("Running command:", command);
|
||||
execSync(command, { stdio: "inherit" }); // Execute and show output
|
||||
}
|
||||
|
||||
// Parse command-line arguments to determine which browsers to publish for
|
||||
process.chdir(fileURLToPath(new URL("..", import.meta.url)));
|
||||
const args = process.argv.slice(2);
|
||||
const browserIndex = args.indexOf("--b"); // Find the --b flag
|
||||
// If --b is found, take all subsequent arguments as browser names
|
||||
const browsers = browserIndex !== -1 ? args.slice(browserIndex + 1) : [];
|
||||
const browsers = args.filter((arg) => arg !== "--b" && arg !== "--dry-run");
|
||||
if (!browsers.length || browsers.some((browser) => !["chrome", "firefox"].includes(browser))) {
|
||||
throw new Error("Usage: npm run publish -- chrome firefox [--dry-run]");
|
||||
}
|
||||
|
||||
runPublishCommand(browsers);
|
||||
const { name, version } = JSON.parse(readFileSync("package.json", "utf8"));
|
||||
if (browsers.includes("firefox")) {
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
["scripts/package-extension-zips.mjs", version, "--sources-only"],
|
||||
{
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const flags = browsers.flatMap((browser) => [
|
||||
`--${browser}-zip`,
|
||||
`dist/${name}@${version}-${browser}.zip`,
|
||||
]);
|
||||
if (browsers.includes("firefox")) {
|
||||
flags.push("--firefox-sources-zip", `dist/${name}@${version}-sources.zip`);
|
||||
}
|
||||
if (args.includes("--dry-run")) flags.push("--dry-run");
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[fileURLToPath(import.meta.resolve("publish-browser-extension/cli")), ...flags],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
+1
-1
@@ -31,7 +31,7 @@
|
||||
"test:unit": "cross-env NODE_OPTIONS=--no-experimental-webstorage jest",
|
||||
"test:smoke": "node scripts/smoke-test.mjs",
|
||||
"test:ci": "npm run test:unit && npm run build && npm run test:smoke",
|
||||
"release": "gh release create $npm_package_version --repo BetterSEQTA/BetterSEQTA-Plus ./dist/*.zip --generate-notes",
|
||||
"release": "gh release create $npm_package_version --repo BetterSEQTA/BetterSEQTA-Plus --generate-notes",
|
||||
"publish": "node lib/publish.js --b",
|
||||
"zip": "node scripts/package-extension-zips.mjs"
|
||||
},
|
||||
|
||||
@@ -2,7 +2,14 @@
|
||||
* Package Chrome/Firefox build folders into Windows-friendly zip files.
|
||||
*/
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
|
||||
import {
|
||||
appendFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
unlinkSync,
|
||||
} from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@@ -12,22 +19,16 @@ function zipDirectory(sourceRel, outRel) {
|
||||
const sourceDir = join(root, sourceRel);
|
||||
const outZip = join(root, outRel);
|
||||
if (!existsSync(sourceDir)) throw new Error(`Missing build output: ${sourceRel}`);
|
||||
const manifest = JSON.parse(readFileSync(join(sourceDir, "manifest.json"), "utf8"));
|
||||
if (manifest.version !== version) throw new Error(`Rebuild ${sourceRel} for version ${version}`);
|
||||
|
||||
mkdirSync(dirname(outZip), { recursive: true });
|
||||
if (existsSync(outZip)) unlinkSync(outZip);
|
||||
|
||||
if (process.platform === "win32") {
|
||||
const esc = (s) => s.replace(/'/g, "''");
|
||||
execFileSync(
|
||||
"powershell",
|
||||
[
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
[
|
||||
"Add-Type -AssemblyName System.IO.Compression.FileSystem",
|
||||
`[IO.Compression.ZipFile]::CreateFromDirectory('${esc(sourceDir)}', '${esc(outZip)}')`,
|
||||
].join("; "),
|
||||
],
|
||||
join(process.env.SystemRoot, "System32", "tar.exe"),
|
||||
["-a", "-cf", outZip, "-C", sourceDir, "--", ...readdirSync(sourceDir)],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
} else {
|
||||
@@ -47,10 +48,41 @@ const base =
|
||||
const chromeZip = `dist/${base}-chrome.zip`;
|
||||
const firefoxZip = `dist/${base}-firefox.zip`;
|
||||
|
||||
zipDirectory("dist/chrome", chromeZip);
|
||||
zipDirectory("dist/firefox", firefoxZip);
|
||||
console.log(`Packaged ${chromeZip}\nPackaged ${firefoxZip}`);
|
||||
if (!process.argv.includes("--sources-only")) {
|
||||
zipDirectory("dist/chrome", chromeZip);
|
||||
zipDirectory("dist/firefox", firefoxZip);
|
||||
console.log(`Packaged ${chromeZip}\nPackaged ${firefoxZip}`);
|
||||
}
|
||||
|
||||
const sourcesZip = `dist/${base}-sources.zip`;
|
||||
if (process.argv.includes("--sources") || process.argv.includes("--sources-only")) {
|
||||
// Archive the committed source only, never local credentials or dependency folders.
|
||||
execFileSync("git", ["diff", "--quiet", "HEAD", "--"], { cwd: root, stdio: "inherit" });
|
||||
mkdirSync(join(root, "dist"), { recursive: true });
|
||||
const instructions =
|
||||
`Build environment: ${process.platform} ${process.arch}, Node.js ${process.version}.\n` +
|
||||
"On Windows, run these commands in Git Bash:\n\n" +
|
||||
"npm ci\n" +
|
||||
"GH_RELEASE_UPDATE_CHECK=false UPDATE_CHANNEL=stable npm run build\n\n" +
|
||||
"Firefox output: dist/firefox. No .env file is required.\n";
|
||||
execFileSync(
|
||||
"git",
|
||||
[
|
||||
"archive",
|
||||
"--format=zip",
|
||||
"--output",
|
||||
join(root, sourcesZip),
|
||||
`--add-virtual-file=BUILD.txt:${instructions}`,
|
||||
"HEAD",
|
||||
],
|
||||
{ cwd: root, stdio: "inherit" },
|
||||
);
|
||||
console.log(`Packaged ${sourcesZip}`);
|
||||
}
|
||||
|
||||
if (process.env.GITHUB_OUTPUT) {
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `chrome_zip=${chromeZip}\nfirefox_zip=${firefoxZip}\n`);
|
||||
appendFileSync(
|
||||
process.env.GITHUB_OUTPUT,
|
||||
`chrome_zip=${chromeZip}\nfirefox_zip=${firefoxZip}\nsources_zip=${sourcesZip}\n`,
|
||||
);
|
||||
}
|
||||
+11
-66
@@ -19,36 +19,13 @@ import {
|
||||
registerOutlookCalendarMessageHandlers,
|
||||
type CalendarMessageHandlerMap,
|
||||
} from "./background/calendarBackground";
|
||||
import { API_BASE } from "./config/apiBase";
|
||||
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
|
||||
import {
|
||||
createRemoteConfigHandlers,
|
||||
initRemoteConfigBackground,
|
||||
refreshRemoteConfig,
|
||||
} from "./background/remoteConfig";
|
||||
import { BSPLUS_INSTALL_REGISTERED_AT_KEY } from "@/seqta/utils/remoteConfig/storageKeys";
|
||||
import { DEFAULT_BACKGROUND_PENDING_KEY } from "@/seqta/ui/defaultBackgroundKey";
|
||||
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
|
||||
import { bsplusApiQueryParams, withBsplusApiQuery } from "@/seqta/utils/bsplusClientContext";
|
||||
import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync";
|
||||
import { runStorageMigrations } from "./background/storageMigrations";
|
||||
|
||||
/**
|
||||
* Session-only dev-mode override of the content API base.
|
||||
*
|
||||
* Stored in a module-level variable (not `chrome.storage`) so it is wiped
|
||||
* automatically when the browser/service-worker process restarts. Content
|
||||
* scripts re-sync this on every page load via `setDevApiBase` so the value
|
||||
* survives transient service-worker terminations within the same browser
|
||||
* session.
|
||||
*/
|
||||
const DEFAULT_API_BASE = "https://betterseqta.org";
|
||||
let DEV_API_BASE: string | null = null;
|
||||
function apiBase(): string {
|
||||
// Extension dev builds always hit production (see DevApiBase.ts).
|
||||
if (import.meta.env.DEV) return DEFAULT_API_BASE;
|
||||
return DEV_API_BASE ?? DEFAULT_API_BASE;
|
||||
}
|
||||
|
||||
function reloadSeqtaPages() {
|
||||
const result = browser.tabs.query({});
|
||||
function open(tabs: chrome.tabs.Tab[]) {
|
||||
@@ -113,11 +90,7 @@ function normalizeFetchThemesResponse(json: unknown): {
|
||||
function handleFetchThemes(_request: unknown, sendResponse: MessageSender): boolean {
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const params = await bsplusApiQueryParams();
|
||||
params.set("type", "betterseqta");
|
||||
params.set("limit", "100");
|
||||
params.set("nocache", String(Date.now()));
|
||||
const apiUrl = `${apiBase()}/api/themes?${params}`;
|
||||
const apiUrl = `${API_BASE}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`;
|
||||
const githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`;
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
@@ -166,10 +139,7 @@ function handleFetchThemeDetails(request: BackgroundRequest, sendResponse: Messa
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
const detailUrl = await withBsplusApiQuery(
|
||||
`${apiBase()}/api/themes/${encodeURIComponent(themeId)}`,
|
||||
);
|
||||
fetch(detailUrl, { cache: "no-store", headers })
|
||||
fetch(`${API_BASE}/api/themes/${themeId}`, { cache: "no-store", headers })
|
||||
.then((r) => r.json())
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
@@ -196,6 +166,8 @@ function isTrustedSender(sender?: chrome.runtime.MessageSender): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
const AUTH_FETCH_ORIGINS = [API_BASE, "https://accounts.betterseqta.org"];
|
||||
|
||||
function handleFetchFromUrl(
|
||||
request: BackgroundRequest,
|
||||
sendResponse: MessageSender,
|
||||
@@ -214,6 +186,10 @@ function handleFetchFromUrl(
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return false;
|
||||
}
|
||||
if (request.auth === true && !AUTH_FETCH_ORIGINS.includes(new URL(url).origin)) {
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const headers: Record<string, string> = { Accept: "application/json" };
|
||||
@@ -505,7 +481,7 @@ function handleCloudFavorite(request: BackgroundRequest, sendResponse: MessageSe
|
||||
return;
|
||||
}
|
||||
const isFavorite = action === "favorite";
|
||||
fetch(`${apiBase()}/api/themes/${themeId}/favorite`, {
|
||||
fetch(`${API_BASE}/api/themes/${themeId}/favorite`, {
|
||||
method: isFavorite ? "POST" : "DELETE",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
@@ -537,38 +513,12 @@ function isSeqtaOrigin(origin: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function handleSetDevApiBase(
|
||||
request: BackgroundRequest,
|
||||
_sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) return false;
|
||||
if (import.meta.env.DEV) {
|
||||
DEV_API_BASE = null;
|
||||
return false;
|
||||
}
|
||||
const url = typeof request?.url === "string" ? request.url.trim() : null;
|
||||
if (url && /^https?:\/\//.test(url)) {
|
||||
DEV_API_BASE = url.replace(/\/$/, "");
|
||||
} else {
|
||||
DEV_API_BASE = null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const customThemesHandlers = createCustomThemesHandlers({
|
||||
apiBase,
|
||||
getAccessTokenFromStorage,
|
||||
});
|
||||
|
||||
const remoteConfigHandlers = createRemoteConfigHandlers(apiBase);
|
||||
const customThemesHandlers = createCustomThemesHandlers({ getAccessTokenFromStorage });
|
||||
|
||||
const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
...customThemesHandlers,
|
||||
...remoteConfigHandlers,
|
||||
searchThemeStockPhotos: handleSearchThemeStockPhotos,
|
||||
reloadTabs: () => reloadSeqtaPages(),
|
||||
setDevApiBase: handleSetDevApiBase,
|
||||
extensionPages: (req) => {
|
||||
browser.tabs.query({}).then((tabs) => {
|
||||
for (const tab of tabs) {
|
||||
@@ -710,14 +660,10 @@ browser.runtime.onInstalled.addListener(function (event) {
|
||||
|
||||
if (event.reason === "update" && event.previousVersion) {
|
||||
void runStorageMigrations(event.previousVersion);
|
||||
void browser.storage.local.remove(BSPLUS_INSTALL_REGISTERED_AT_KEY).then(() => {
|
||||
void refreshRemoteConfig(apiBase);
|
||||
});
|
||||
reloadSeqtaPages();
|
||||
}
|
||||
|
||||
if (event.reason === "install") {
|
||||
void refreshRemoteConfig(apiBase);
|
||||
void browser.storage.local.set({ [DEFAULT_BACKGROUND_PENDING_KEY]: true });
|
||||
void defaultsReady
|
||||
.catch(() => undefined)
|
||||
@@ -734,6 +680,5 @@ browser.runtime.onStartup.addListener(() => {
|
||||
});
|
||||
|
||||
initCloudSettingsAutoSync({ reloadSeqtaPages });
|
||||
initRemoteConfigBackground(apiBase);
|
||||
initTimetableClassmatesBackgroundSync();
|
||||
void ensureSyncableStorageDefaults();
|
||||
@@ -16,7 +16,11 @@ import {
|
||||
getLastUploadedSnapshot,
|
||||
setKnownRemoteUpdatedAt,
|
||||
} from "@/seqta/utils/cloudSettingsSync";
|
||||
import { isRemoteCloudSyncDisabled } from "./remoteConfig";
|
||||
import { readRemoteStatus } from "@/seqta/utils/remoteStatus";
|
||||
|
||||
async function isCloudSyncDisabled(): Promise<boolean> {
|
||||
return (await readRemoteStatus()).disabledFeatures.includes("cloud.sync");
|
||||
}
|
||||
|
||||
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
export const CLOUD_SUMMARY_URL = `${ACCOUNTS_BASE}/api/user/cloud-summary`;
|
||||
@@ -226,8 +230,8 @@ async function putSettingsOnce(token: string): Promise<PutResult> {
|
||||
export async function performCloudSettingsUploadWithRetry(
|
||||
token: string,
|
||||
): Promise<{ success: boolean; error?: string; updated_at?: string; skipped?: boolean }> {
|
||||
if (await isRemoteCloudSyncDisabled()) {
|
||||
return { success: false, error: "Cloud sync disabled by remote config", skipped: true };
|
||||
if (await isCloudSyncDisabled()) {
|
||||
return { success: false, error: "Cloud sync is temporarily disabled", skipped: true };
|
||||
}
|
||||
let t = token;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
@@ -345,7 +349,7 @@ async function downloadIfNeeded(token: string): Promise<void> {
|
||||
}
|
||||
|
||||
async function runCloudSettingsPollInner(): Promise<void> {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
if (await isCloudSyncDisabled()) return;
|
||||
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
@@ -422,7 +426,7 @@ function scheduleDebouncedUpload(): void {
|
||||
/** Call after store theme install (and similar) so cloud upload runs even if storage events are flaky. */
|
||||
export function requestCloudSettingsDebouncedUpload(): void {
|
||||
void (async () => {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
if (await isCloudSyncDisabled()) return;
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
if (suppressAutoUploadDuringRestore) return;
|
||||
@@ -432,7 +436,7 @@ export function requestCloudSettingsDebouncedUpload(): void {
|
||||
}
|
||||
|
||||
async function runDebouncedUploadJob(): Promise<void> {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
if (await isCloudSyncDisabled()) return;
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
const token = await getAccessToken();
|
||||
@@ -464,7 +468,7 @@ function onStorageChanged(
|
||||
if (!keys.some((k) => isKeyIncludedInCloudUploadPayload(k))) return;
|
||||
|
||||
void (async () => {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
if (await isCloudSyncDisabled()) return;
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
if (suppressAutoUploadDuringRestore) return;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { API_BASE } from "@/config/apiBase";
|
||||
import { normalizeCustomThemeApiResponse } from "@/seqta/utils/customThemes/parseApiEnvelope";
|
||||
import { bsplusApiQueryParams } from "@/seqta/utils/bsplusClientContext";
|
||||
import { base64ToBlob } from "@/seqta/utils/base64";
|
||||
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
@@ -33,7 +33,6 @@ function buildFormDataFromPayload(payload: UploadPayload): FormData {
|
||||
}
|
||||
|
||||
export function createCustomThemesHandlers(deps: {
|
||||
apiBase: () => string;
|
||||
getAccessTokenFromStorage: () => Promise<string | null>;
|
||||
}): Record<string, (request: Record<string, unknown>, sendResponse: MessageSender) => boolean> {
|
||||
async function readCustomThemesResponse(r: Response): Promise<Record<string, unknown>> {
|
||||
@@ -67,7 +66,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
}
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
const url = `${deps.apiBase()}${path}`;
|
||||
const url = `${API_BASE}${path}`;
|
||||
const r = await fetch(url, {
|
||||
...init,
|
||||
headers,
|
||||
@@ -85,7 +84,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
return { success: false, error: "Not authenticated", httpStatus: 401 };
|
||||
}
|
||||
const form = buildFormDataFromPayload(payload);
|
||||
const url = `${deps.apiBase()}${path}`;
|
||||
const url = `${API_BASE}${path}`;
|
||||
const r = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
@@ -105,7 +104,6 @@ export function createCustomThemesHandlers(deps: {
|
||||
params.set("type", "betterseqta");
|
||||
params.set("page", String(request.page ?? 1));
|
||||
params.set("limit", String(request.limit ?? 20));
|
||||
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
||||
if (request.sort) params.set("sort", String(request.sort));
|
||||
const searchRaw = request.search;
|
||||
const search = typeof searchRaw === "string" ? searchRaw.trim() : "";
|
||||
@@ -134,7 +132,6 @@ export function createCustomThemesHandlers(deps: {
|
||||
params.set("page", String(request.page ?? 1));
|
||||
params.set("limit", String(request.limit ?? 20));
|
||||
params.set("type", "betterseqta");
|
||||
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
||||
if (request.status) params.set("status", String(request.status));
|
||||
sendResponse(await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true));
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,369 +0,0 @@
|
||||
import browser from "@/lib/browser";
|
||||
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
||||
import { bsplusApiQueryParams, bsplusExtensionPayload } from "@/seqta/utils/bsplusClientContext";
|
||||
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import {
|
||||
mergeGithubConfigFiles,
|
||||
normalizeRemoteConfigSnapshot,
|
||||
} from "@/seqta/utils/remoteConfig/normalize";
|
||||
import {
|
||||
BSPLUS_INSTALL_REGISTERED_AT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY,
|
||||
BS_STATUS_MANIFEST_URL,
|
||||
REGISTER_INTERVAL_MS,
|
||||
REMOTE_CONFIG_ALARM,
|
||||
REMOTE_CONFIG_POLL_MINUTES,
|
||||
} from "@/seqta/utils/remoteConfig/storageKeys";
|
||||
import type { RemoteConfigSnapshot } from "@/seqta/utils/remoteConfig/types";
|
||||
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
|
||||
async function linkCloudInstall(token: string, installId: string): Promise<void> {
|
||||
try {
|
||||
const extension = bsplusExtensionPayload();
|
||||
const r = await fetch(`${ACCOUNTS_BASE}/api/bsplus/installs/link`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
installId,
|
||||
extensionVersion: extension.version,
|
||||
extension,
|
||||
deviceName: await getBsplusDeviceName(),
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
}),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!r.ok) console.warn("[BetterSEQTA+] cloud install link failed:", r.status);
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] cloud install link failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function parseJson(r: Response): Promise<unknown> {
|
||||
const text = await r.text();
|
||||
try {
|
||||
return text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function readLastHostname(): Promise<string | undefined> {
|
||||
const stored = await browser.storage.local.get(BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY);
|
||||
const hostname = stored[BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY];
|
||||
return typeof hostname === "string" && hostname.length > 0 ? hostname : undefined;
|
||||
}
|
||||
|
||||
async function fetchGithubSnapshot(): Promise<RemoteConfigSnapshot | null> {
|
||||
try {
|
||||
const manifestRes = await fetch(BS_STATUS_MANIFEST_URL, { cache: "no-store" });
|
||||
if (!manifestRes.ok) return null;
|
||||
const manifest = (await parseJson(manifestRes)) as Record<string, unknown> | null;
|
||||
if (!manifest?.files || typeof manifest.files !== "object") return null;
|
||||
const base =
|
||||
BS_STATUS_MANIFEST_URL.replace(/manifest\.json$/, "") ||
|
||||
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/";
|
||||
const files: Record<string, unknown> = {};
|
||||
for (const [key, fileName] of Object.entries(manifest.files as Record<string, string>)) {
|
||||
if (typeof fileName !== "string") continue;
|
||||
const url = fileName.startsWith("http") ? fileName : `${base}${fileName}`;
|
||||
if (!isAllowedFetchUrl(url)) continue;
|
||||
const fr = await fetch(url, { cache: "no-store" });
|
||||
if (!fr.ok) continue;
|
||||
files[key] = await parseJson(fr);
|
||||
}
|
||||
return mergeGithubConfigFiles(manifest, files);
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] GitHub remote config fallback failed:", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function registerInstall(apiBase: string, primaryOk: boolean, force = false): Promise<void> {
|
||||
if (!primaryOk) return;
|
||||
const stored = await browser.storage.local.get(BSPLUS_INSTALL_REGISTERED_AT_KEY);
|
||||
const last = Number(stored[BSPLUS_INSTALL_REGISTERED_AT_KEY] ?? 0);
|
||||
if (!force && Date.now() - last < REGISTER_INTERVAL_MS) return;
|
||||
|
||||
const installId = await getOrCreateInstallId();
|
||||
const extension = bsplusExtensionPayload();
|
||||
const { bsplus_token, bsplus_user } = await browser.storage.local.get([
|
||||
"bsplus_token",
|
||||
"bsplus_user",
|
||||
]);
|
||||
const token =
|
||||
typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : undefined;
|
||||
const userId =
|
||||
bsplus_user && typeof bsplus_user === "object" && "id" in bsplus_user
|
||||
? String((bsplus_user as { id: string }).id)
|
||||
: undefined;
|
||||
|
||||
const hostname = await readLastHostname();
|
||||
|
||||
const body = {
|
||||
installId,
|
||||
extensionVersion: extension.version,
|
||||
extension,
|
||||
userId,
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
...(hostname ? { hostname } : {}),
|
||||
};
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
const r = await fetch(`${apiBase}/api/bsplus/installs/register`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (r.ok) {
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_INSTALL_REGISTERED_AT_KEY]: Date.now(),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] install register failed:", e);
|
||||
}
|
||||
if (token) void linkCloudInstall(token, installId);
|
||||
}
|
||||
|
||||
export async function refreshRemoteConfig(apiBase: () => string): Promise<{
|
||||
snapshot: RemoteConfigSnapshot;
|
||||
fromNetwork: boolean;
|
||||
primaryOk: boolean;
|
||||
}> {
|
||||
const base = apiBase();
|
||||
const hostname = await readLastHostname();
|
||||
const params = await bsplusApiQueryParams();
|
||||
if (hostname) params.set("hostname", hostname);
|
||||
|
||||
const stored = await browser.storage.local.get([
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
|
||||
]);
|
||||
const etag = stored[BSPLUS_REMOTE_CONFIG_ETAG_KEY] as string | undefined;
|
||||
const prior = stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY];
|
||||
|
||||
let primaryOk = false;
|
||||
let snapshot: RemoteConfigSnapshot | null = null;
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = { Accept: "application/json" };
|
||||
if (etag) headers["If-None-Match"] = etag;
|
||||
const r = await fetch(`${base}/api/bsplus/remote-config?${params}`, {
|
||||
cache: "no-store",
|
||||
headers,
|
||||
});
|
||||
if (r.status === 304 && prior) {
|
||||
primaryOk = true;
|
||||
snapshot = normalizeRemoteConfigSnapshot(prior);
|
||||
snapshot.source = "cache";
|
||||
} else if (r.ok) {
|
||||
primaryOk = true;
|
||||
const json = await parseJson(r);
|
||||
snapshot = normalizeRemoteConfigSnapshot(json);
|
||||
snapshot.source = "api";
|
||||
const newEtag = r.headers.get("ETag") ?? snapshot.etag;
|
||||
if (newEtag) snapshot.etag = newEtag;
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]: snapshot,
|
||||
[BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY]: Date.now(),
|
||||
[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: true,
|
||||
...(newEtag ? { [BSPLUS_REMOTE_CONFIG_ETAG_KEY]: newEtag } : {}),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] remote-config primary fetch failed:", e);
|
||||
}
|
||||
|
||||
if (!snapshot) {
|
||||
snapshot = await fetchGithubSnapshot();
|
||||
if (snapshot) {
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]: snapshot,
|
||||
[BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY]: Date.now(),
|
||||
[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: false,
|
||||
});
|
||||
} else if (prior) {
|
||||
snapshot = normalizeRemoteConfigSnapshot(prior);
|
||||
snapshot.source = "cache";
|
||||
} else {
|
||||
snapshot = normalizeRemoteConfigSnapshot(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (primaryOk) {
|
||||
await browser.storage.local.set({ [BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: true });
|
||||
}
|
||||
|
||||
void registerInstall(base, primaryOk);
|
||||
return { snapshot, fromNetwork: primaryOk, primaryOk };
|
||||
}
|
||||
|
||||
export function initRemoteConfigBackground(apiBase: () => string): void {
|
||||
void refreshRemoteConfig(apiBase);
|
||||
|
||||
browser.alarms.create(REMOTE_CONFIG_ALARM, {
|
||||
periodInMinutes: REMOTE_CONFIG_POLL_MINUTES,
|
||||
});
|
||||
|
||||
browser.alarms.onAlarm.addListener((alarm) => {
|
||||
if (alarm.name === REMOTE_CONFIG_ALARM) void refreshRemoteConfig(apiBase);
|
||||
});
|
||||
|
||||
browser.storage.onChanged.addListener((changes, area) => {
|
||||
if (area !== "local") return;
|
||||
if (changes.bsplus_token || changes.bsplus_user) {
|
||||
void (async () => {
|
||||
const lastPrimary = await browser.storage.local.get(BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY);
|
||||
const primaryOk = lastPrimary[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY] === true;
|
||||
if (primaryOk) {
|
||||
await registerInstall(apiBase(), true, true);
|
||||
} else {
|
||||
const res = await refreshRemoteConfig(apiBase);
|
||||
if (res.primaryOk) await registerInstall(apiBase(), true, true);
|
||||
else {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
if (typeof bsplus_token === "string" && bsplus_token) {
|
||||
void linkCloudInstall(bsplus_token, await getOrCreateInstallId());
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function createRemoteConfigHandlers(
|
||||
apiBase: () => string,
|
||||
): Record<string, (request: unknown, sendResponse: MessageSender) => boolean> {
|
||||
function handleRefresh(_req: unknown, sendResponse: MessageSender): boolean {
|
||||
void refreshRemoteConfig(apiBase)
|
||||
.then((res) => sendResponse(res))
|
||||
.catch((err) =>
|
||||
sendResponse({
|
||||
error: err instanceof Error ? err.message : "Refresh failed",
|
||||
}),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleGetSnapshot(_req: unknown, sendResponse: MessageSender): boolean {
|
||||
void browser.storage.local.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY).then((stored) => {
|
||||
sendResponse({
|
||||
snapshot: normalizeRemoteConfigSnapshot(stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]),
|
||||
});
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleSetPageContext(req: unknown, sendResponse: MessageSender): boolean {
|
||||
const { hostname: rawHostname } = req as { hostname?: unknown };
|
||||
const hostname = typeof rawHostname === "string" ? rawHostname.trim() : "";
|
||||
if (hostname) {
|
||||
void browser.storage.local
|
||||
.set({ [BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY]: hostname })
|
||||
.then(() => sendResponse({ ok: true }));
|
||||
} else {
|
||||
sendResponse({ ok: false });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchRemoteThemePackage(req: unknown, sendResponse: MessageSender): boolean {
|
||||
const { packageId: rawPackageId } = req as { packageId?: unknown };
|
||||
const packageId = typeof rawPackageId === "string" ? rawPackageId.trim() : "";
|
||||
if (!packageId) {
|
||||
sendResponse({ error: "Missing packageId" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const hostname = await readLastHostname();
|
||||
const params = await bsplusApiQueryParams();
|
||||
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: unknown, sendResponse: MessageSender): boolean {
|
||||
const { url: rawUrl } = req as { url?: unknown };
|
||||
const url = typeof rawUrl === "string" ? rawUrl.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,
|
||||
};
|
||||
}
|
||||
|
||||
export async function isRemoteCloudSyncDisabled(): Promise<boolean> {
|
||||
const stored = await browser.storage.local.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY);
|
||||
const snap = normalizeRemoteConfigSnapshot(stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]);
|
||||
return snap.global.disableCloudSync === true;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ function crossedUpgrade(previousVersion: string, boundary: string): boolean {
|
||||
return prev != null && curr != null && !semver.lt(curr, boundary) && semver.lt(prev, boundary);
|
||||
}
|
||||
|
||||
/** One-time storage patches when crossing 3.6.5 / 3.6.6 / 3.7.0 (see git history on main). */
|
||||
/** One-time storage patches when crossing 3.6.5 / 3.6.6 / 3.7.0 / 3.7.7 (see git history on main). */
|
||||
export async function runStorageMigrations(previousVersion: string): Promise<void> {
|
||||
if (crossedUpgrade(previousVersion, "3.6.5")) {
|
||||
try {
|
||||
@@ -47,4 +47,25 @@ export async function runStorageMigrations(previousVersion: string): Promise<voi
|
||||
console.warn("[BetterSEQTA+] Theme of the Month 3.7.0 dismissal migration failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (crossedUpgrade(previousVersion, "3.7.7")) {
|
||||
try {
|
||||
await browser.storage.local.remove([
|
||||
"bsplus_remote_config_snapshot",
|
||||
"bsplus_remote_config_etag",
|
||||
"bsplus_remote_config_fetched_at",
|
||||
"bsplus_remote_config_last_hostname",
|
||||
"bsplus_remote_last_primary_ok",
|
||||
"bsplus_campaign_seen",
|
||||
"bsplus_local_override_onoff",
|
||||
"bsplus_features_hidden_until_version",
|
||||
"bsplus_install_registered_at",
|
||||
"bsplus_remote_theme_before_v1",
|
||||
"bsplus_remote_theme_state_v1",
|
||||
"bsplus_remote_theme_user_off",
|
||||
]);
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] 3.7.7 storage cleanup migration failed:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export const API_BASE = "https://betterseqta.org";
|
||||
@@ -4088,23 +4088,6 @@ div.day-empty {
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.bsplus-remote-page-banner {
|
||||
width: 90%;
|
||||
margin: 0 auto 0.75rem;
|
||||
padding: 0.65rem 0.85rem;
|
||||
border-radius: 12px;
|
||||
border: 1px solid color-mix(in srgb, var(--text-primary) 14%, transparent);
|
||||
background: color-mix(in srgb, var(--text-primary) 5%, var(--background-primary));
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.5;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.bsplus-remote-page-banner__title {
|
||||
font-weight: 600;
|
||||
margin: 0 0 0.35rem;
|
||||
}
|
||||
|
||||
.whatsnewTextContainer.bsplus-founder-badge-body p {
|
||||
margin: 0 0 1rem;
|
||||
font-size: 1.2rem;
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
dismissOptionalRemoteTheme,
|
||||
getRemoteConfigSnapshot,
|
||||
isEffectiveBsplusEnabled,
|
||||
isRemoteKillActive,
|
||||
resolveEffectiveRemoteTheme,
|
||||
setLocalOverrideOnoff,
|
||||
} from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { getRemoteStatusMessage } from "@/seqta/utils/remoteConfig/apply";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { requestSettingsDestination } from "@/seqta/utils/settingsNavigation";
|
||||
import browser from "@/lib/browser";
|
||||
import { onMount } from "svelte";
|
||||
|
||||
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;
|
||||
});
|
||||
});
|
||||
|
||||
async function enableLocalRun() {
|
||||
await setLocalOverrideOnoff(true);
|
||||
localOverride = true;
|
||||
location.reload();
|
||||
}
|
||||
|
||||
function openGeneralSettings() {
|
||||
requestSettingsDestination({ page: "settings", section: "general" });
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if showStrip}
|
||||
<div
|
||||
class="shrink-0 border-b border-amber-200/80 bg-amber-50 px-4 py-3 text-sm text-amber-950 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-50"
|
||||
role="status"
|
||||
>
|
||||
<p class="leading-relaxed">
|
||||
{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"
|
||||
onclick={() => void turnOffOptionalTheme()}
|
||||
>
|
||||
Turn off school theme
|
||||
</button>
|
||||
{/if}
|
||||
{#if killActive && !isEffectiveBsplusEnabled() && allowOverride}
|
||||
<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"
|
||||
onclick={enableLocalRun}
|
||||
>
|
||||
Run locally anyway
|
||||
</button>
|
||||
{:else if killActive && localOverride && isEffectiveBsplusEnabled()}
|
||||
<span class="text-xs text-amber-800 dark:text-amber-200/90">
|
||||
Running locally (override). Reload SEQTA after the operator clears the kill switch.
|
||||
</span>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-amber-300/80 px-3 py-1.5 text-xs font-medium transition-colors duration-200 hover:bg-amber-100/80 dark:border-amber-800 dark:hover:bg-amber-900/50"
|
||||
onclick={openGeneralSettings}
|
||||
>
|
||||
General settings
|
||||
</button>
|
||||
{#if $settingsState.onoff === false}
|
||||
<span class="text-xs opacity-80">Master toggle is off in General.</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,27 @@
|
||||
<script lang="ts">
|
||||
import { choosePause, getRemoteStatus, isPaused, pauseMessage } from "@/seqta/utils/remoteStatus";
|
||||
|
||||
const status = getRemoteStatus();
|
||||
const message = status.off ? pauseMessage() : status.message;
|
||||
|
||||
async function runAnyway() {
|
||||
await choosePause(true);
|
||||
location.reload();
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if message}
|
||||
<div
|
||||
class="flex shrink-0 items-center gap-3 border-b border-amber-200/80 bg-amber-50 px-4 py-3 text-sm text-amber-950 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-50"
|
||||
role="status"
|
||||
>
|
||||
<p class="flex-1 leading-relaxed">{message}</p>
|
||||
{#if isPaused()}
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-lg px-3 py-1.5 font-semibold ring-1 ring-current"
|
||||
onclick={runAnyway}>Run Anyway</button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
getThemeApplyButtonStyles,
|
||||
resolveStoreVariantAccentColor,
|
||||
} from '@/interface/utils/themeListFilters'
|
||||
import { isRemoteThemeStoreDisabled } from '@/seqta/utils/remoteConfig/runtime'
|
||||
import { isFeatureDisabled } from '@/seqta/utils/remoteStatus'
|
||||
let {
|
||||
theme,
|
||||
currentThemes,
|
||||
@@ -59,7 +59,7 @@ adminPreviewMode?: boolean
|
||||
} = $props()
|
||||
const installActionLabel = $derived(adminPreviewMode ? 'Preview & apply' : 'Install')
|
||||
const isCommunity = $derived(variant === 'community')
|
||||
const themeStoreInstallLocked = $derived(isRemoteThemeStoreDisabled() && !adminPreviewMode)
|
||||
const themeStoreInstallLocked = $derived(isFeatureDisabled('themeStore.install') && !adminPreviewMode)
|
||||
const showFavorites = $derived(!isCommunity)
|
||||
function variantApplyStyles(variantId: string) {
|
||||
if (!theme) {
|
||||
|
||||
@@ -16,13 +16,8 @@
|
||||
import ThemePlaceholderCover from '@/interface/components/themes/ThemePlaceholderCover.svelte'
|
||||
import { isLocalCustomTheme } from '@/interface/utils/themeListFilters'
|
||||
import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors'
|
||||
import { getRemoteConfigSnapshot, resolveEffectiveRemoteTheme } from '@/seqta/utils/remoteConfig/runtime'
|
||||
|
||||
const themeManager = ThemeManager.getInstance();
|
||||
const remoteDirective = $derived(resolveEffectiveRemoteTheme(getRemoteConfigSnapshot()));
|
||||
const remoteThemeForced = $derived(
|
||||
remoteDirective?.mode === 'forced' && (remoteDirective.applicationMode ?? 'replace') === 'replace',
|
||||
);
|
||||
|
||||
let themes = $state<ThemeList | null>(null);
|
||||
let { isEditMode, showNavigation = true }: {
|
||||
@@ -47,7 +42,7 @@
|
||||
});
|
||||
|
||||
const handleThemeClick = async (theme: CustomTheme, e: MouseEvent) => {
|
||||
if (isEditMode || remoteThemeForced) return;
|
||||
if (isEditMode) return;
|
||||
if (theme.id === themes?.selectedTheme) {
|
||||
themeManager.setTransitionPoint(e.clientX, e.clientY);
|
||||
await themeManager.disableTheme();
|
||||
@@ -173,12 +168,7 @@
|
||||
role="list"
|
||||
tabindex="-1"
|
||||
>
|
||||
{#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' : ''}">
|
||||
<div class="{useTwoColumnLayout ? 'grid grid-cols-2 gap-3' : 'flex flex-col gap-2 px-2'}">
|
||||
{#if themes}
|
||||
{#each themes.themes as theme (theme.id)}
|
||||
<button
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import Settings from "./pages/settings.svelte";
|
||||
import renderSvelte from "./main";
|
||||
import { initializeSettingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { loadRemoteStatus } from "@/seqta/utils/remoteStatus";
|
||||
import { initVerboseLogging, verboseInfo } from "@/utils/verboseLog";
|
||||
|
||||
const mountPoint = document.getElementById("app");
|
||||
@@ -12,9 +13,8 @@ if (!mountPoint) {
|
||||
} else {
|
||||
void (async () => {
|
||||
await initializeSettingsState();
|
||||
await loadRemoteStatus();
|
||||
initVerboseLogging();
|
||||
const { syncApiBaseToBackground } = await import("@/seqta/utils/DevApiBase");
|
||||
syncApiBaseToBackground();
|
||||
renderSvelte(Settings, mountPoint, { standalone: true });
|
||||
})();
|
||||
}
|
||||
@@ -27,8 +27,8 @@
|
||||
import { settingsPopup } from "@/seqta/utils/settingsPopup";
|
||||
import { armDevModeUnlock } from "@/seqta/utils/devModeUnlock";
|
||||
import { consumeOpenFeedbackRequest } from "@/seqta/utils/feedback/client";
|
||||
import RemoteConfigStatusStrip from "../components/RemoteConfigStatusStrip.svelte";
|
||||
import { isRemoteSettingsSectionVisible } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import RemoteStatusStrip from "../components/RemoteStatusStrip.svelte";
|
||||
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
|
||||
import {
|
||||
consumeSettingsDestination,
|
||||
SETTINGS_NAVIGATION_EVENT,
|
||||
@@ -94,11 +94,14 @@
|
||||
const ghReleaseChannelLabel = getInstalledGhReleaseChannelLabel();
|
||||
let ghReleaseUpdate = $state<GhReleaseUpdateInfo | null>(null);
|
||||
|
||||
const isSectionVisible = (id: string) =>
|
||||
!isFeatureDisabled(id === "account" ? "settings.nav.cloud" : `settings.section.${id}`);
|
||||
|
||||
const userNav: NavItem[] = [
|
||||
{ id: "account", label: "My Account" },
|
||||
{ id: "general", label: "General" },
|
||||
{ id: "appearance", label: "Appearance" },
|
||||
].filter((item) => isRemoteSettingsSectionVisible(item.id));
|
||||
].filter((item) => isSectionVisible(item.id));
|
||||
|
||||
$effect(() => {
|
||||
if (!$settingsState.devMode && activeSection === "advanced") activeSection = "general";
|
||||
@@ -110,7 +113,7 @@
|
||||
{ id: "features", label: "Features" },
|
||||
...($settingsState.devMode ? [{ id: "advanced", label: "Advanced" }] : []),
|
||||
{ id: "shortcuts", label: "Shortcuts" },
|
||||
].filter((item) => isRemoteSettingsSectionVisible(item.id)));
|
||||
].filter((item) => isSectionVisible(item.id)));
|
||||
|
||||
const settingsNavGroups = $derived([
|
||||
{ label: "User Settings", items: userNav },
|
||||
@@ -559,7 +562,7 @@
|
||||
onToggleSize={standalone ? undefined : toggleExpanded}
|
||||
/>
|
||||
|
||||
<RemoteConfigStatusStrip />
|
||||
<RemoteStatusStrip />
|
||||
|
||||
<!-- Body: left nav + content -->
|
||||
<div class="flex flex-1 min-h-0 overflow-hidden">
|
||||
@@ -716,7 +719,7 @@
|
||||
<div
|
||||
class="flex h-full min-h-0 flex-col gap-2 overflow-hidden bg-white dark:bg-zinc-800 dark:text-white"
|
||||
>
|
||||
<RemoteConfigStatusStrip />
|
||||
<RemoteStatusStrip />
|
||||
<div
|
||||
class="grid shrink-0 items-center border-b border-zinc-200/40 dark:border-zinc-700/40 {standalone ? 'grid-cols-1' : 'grid-cols-[minmax(0,1fr)_44px] gap-2 px-2'}"
|
||||
>
|
||||
|
||||
@@ -7,37 +7,11 @@
|
||||
import { showThemeOfTheMonthPopupNow } from "@/seqta/utils/openers/OpenThemeOfTheMonthPopup";
|
||||
import { closeExtensionPopup } from "@/seqta/utils/closers/closeExtensionPopup";
|
||||
import { getSnapshotForUpload } from "@/seqta/utils/cloudSettingsSync";
|
||||
import { getStoredOverride, PRODUCTION_API_BASE, setApiBase } from "@/seqta/utils/DevApiBase";
|
||||
|
||||
const isExtensionDevBuild = import.meta.env.DEV;
|
||||
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
|
||||
|
||||
let { searchQuery = "" }: SettingsSectionSharedProps = $props();
|
||||
|
||||
let devApiBaseInput = $state<string>(getStoredOverride() ?? "");
|
||||
let devApiBaseActive = $state<string | null>(getStoredOverride());
|
||||
|
||||
function applyDevApiBase() {
|
||||
const trimmed = devApiBaseInput.trim();
|
||||
if (trimmed === "") {
|
||||
setApiBase(null);
|
||||
devApiBaseActive = null;
|
||||
return;
|
||||
}
|
||||
if (!/^https?:\/\//.test(trimmed)) {
|
||||
alert("Please enter a full URL starting with http:// or https://");
|
||||
return;
|
||||
}
|
||||
setApiBase(trimmed);
|
||||
devApiBaseActive = trimmed.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
function clearDevApiBase() {
|
||||
devApiBaseInput = "";
|
||||
setApiBase(null);
|
||||
devApiBaseActive = null;
|
||||
}
|
||||
|
||||
async function exportCloudSettingsJsonToFile() {
|
||||
const payload = await getSnapshotForUpload();
|
||||
const blob = new Blob([JSON.stringify(payload, null, 2)], {
|
||||
@@ -189,43 +163,6 @@
|
||||
<Button onClick={exportCloudSettingsJsonToFile} text="Export to file" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 px-4 py-3">
|
||||
<div class="flex justify-between items-start gap-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">API Base URL (session only)</h2>
|
||||
{#if isExtensionDevBuild}
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Extension dev builds always use production ({PRODUCTION_API_BASE}) for the theme store,
|
||||
community submit, and related APIs. Build a release package to test a staging host override.
|
||||
</p>
|
||||
{:else}
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Override the content API host for this browser session. Cleared on restart. Affects
|
||||
themes, theme of the month, and other server-driven content.
|
||||
</p>
|
||||
{#if devApiBaseActive}
|
||||
<p class="text-xs mt-1 text-amber-600 dark:text-amber-400">
|
||||
Override active: <span class="font-mono">{devApiBaseActive}</span>
|
||||
</p>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if !isExtensionDevBuild}
|
||||
<div class="flex gap-2 items-center">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="https://betterseqta.org"
|
||||
bind:value={devApiBaseInput}
|
||||
class="flex-1 px-2 py-1 text-xs rounded-sm border bg-white dark:bg-zinc-800 border-zinc-300 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100"
|
||||
/>
|
||||
<Button onClick={applyDevApiBase} text="Apply" />
|
||||
{#if devApiBaseActive}
|
||||
<Button onClick={clearDevApiBase} text="Clear" />
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 px-4 py-3">
|
||||
<div>
|
||||
<h2 class="text-sm font-bold">GitHub latest version override</h2>
|
||||
|
||||
@@ -13,14 +13,12 @@
|
||||
import browser from "@/lib/browser";
|
||||
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
|
||||
import type { SettingsList } from "@/interface/types/SettingsProps";
|
||||
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
|
||||
|
||||
let { searchQuery = "" }: SettingsSectionSharedProps = $props();
|
||||
|
||||
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 sidebarEditHidden = isFeatureDisabled("ui.sidebar.edit");
|
||||
|
||||
const generalOptions = $derived([
|
||||
{
|
||||
@@ -149,19 +147,7 @@
|
||||
{#if generalOptions.some((option) => matchesSearch(searchQuery, option.title, option.description))}
|
||||
<SettingsCard class="divide-y divide-zinc-200/60 dark:divide-zinc-700/40">
|
||||
{#each generalOptions as option (option.id)}
|
||||
{#if option.id === 12}
|
||||
<div
|
||||
class:opacity-50={onoffGreyedOut}
|
||||
class:pointer-events-none={onoffGreyedOut}
|
||||
title={onoffGreyedOut
|
||||
? (onoffGate.message?.body ?? "Disabled by site operator")
|
||||
: undefined}
|
||||
>
|
||||
<SettingRow {...option} {searchQuery} />
|
||||
</div>
|
||||
{:else}
|
||||
<SettingRow {...option} {searchQuery} />
|
||||
{/if}
|
||||
<SettingRow {...option} {searchQuery} />
|
||||
{#if option.id === 0 && $settingsState.performanceMode && matchesSearch(searchQuery, "Performance Mode", "Global Search", "Assessment Averages", "enable anyway", "paused")}
|
||||
<div class="border-none -mt-px">
|
||||
<div
|
||||
|
||||
@@ -9,7 +9,7 @@ import { processMenuItemNode } from "@/seqta/utils/sidebarMenuIcons";
|
||||
import { ChangeMenuItemPositions } from "@/seqta/utils/openers/menuOrder";
|
||||
import { isMenuOptionsOpen } from "@/seqta/utils/openers/menuOptionsState";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
|
||||
import { applyMenuItemVisibility } from "@/seqta/utils/menuItemVisibility";
|
||||
import { getNativeMenuList } from "@/seqta/ui/sidebar/parseNativeMenu";
|
||||
import { rafThrottle } from "@/seqta/utils/rafThrottle";
|
||||
@@ -30,7 +30,7 @@ export async function injectAnalyticsMenuItem(): Promise<() => void> {
|
||||
if (isSeqtaEngageExperience()) {
|
||||
return () => {};
|
||||
}
|
||||
if (checkRemoteFeature("page.analytics").hide) {
|
||||
if (isFeatureDisabled("page.analytics")) {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
|
||||
@@ -17,9 +17,6 @@ jest.mock("@/seqta/utils/listeners/SettingsState", () => ({
|
||||
jest.mock("@/seqta/utils/performanceMode", () => ({
|
||||
fullMotionEffectsEnabled: () => false,
|
||||
}));
|
||||
jest.mock("@/seqta/utils/DevApiBase", () => ({
|
||||
getApiBase: () => "https://betterseqta.org",
|
||||
}));
|
||||
jest.mock("@/seqta/ui/colors/Manager", () => ({ updateAllColors: jest.fn() }));
|
||||
jest.mock("@/seqta/ui/colors/customThemeAdaptiveBindings", () => ({}));
|
||||
jest.mock("@/seqta/utils/patchThemeImagesPageContext", () => ({}));
|
||||
@@ -48,11 +45,7 @@ describe("cloud theme restoration", () => {
|
||||
it.each(["themes", "custom-themes"])("installs a missing %s catalog theme", async (catalog) => {
|
||||
const jsonUrl = "https://betterseqta.org/storage/theme.json";
|
||||
(browser.runtime.sendMessage as jest.Mock).mockImplementation(async ({ url }) => {
|
||||
if (
|
||||
typeof url === "string" &&
|
||||
url.includes(`/api/${catalog}/catalog-id/download`) &&
|
||||
url.includes("extensionVersion=")
|
||||
) {
|
||||
if (url === `https://betterseqta.org/api/${catalog}/catalog-id/download`) {
|
||||
return {
|
||||
data: { success: true, data: { theme_json_url: jsonUrl } },
|
||||
};
|
||||
|
||||
@@ -11,8 +11,7 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode";
|
||||
import debounce from "@/seqta/utils/debounce";
|
||||
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
|
||||
import { getApiBase } from "@/seqta/utils/DevApiBase";
|
||||
import { withBsplusApiQuery } from "@/seqta/utils/bsplusClientContext";
|
||||
import { API_BASE } from "@/config/apiBase";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import { updateAllColors } from "@/seqta/ui/colors/Manager";
|
||||
import {
|
||||
@@ -545,10 +544,7 @@ export class ThemeManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** Use a getter so dev-mode session-only base URL overrides take effect immediately. */
|
||||
private get THEME_API_BASE(): string {
|
||||
return `${getApiBase()}/api`;
|
||||
}
|
||||
private readonly THEME_API_BASE = `${API_BASE}/api`;
|
||||
private readonly GITHUB_THEMES_BASE =
|
||||
"https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes";
|
||||
|
||||
@@ -642,16 +638,8 @@ export class ThemeManager {
|
||||
|
||||
let themeJsonUrl = themeContent.theme_json_url;
|
||||
if (!themeJsonUrl) {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
const auth =
|
||||
typeof bsplus_token === "string" && bsplus_token.length > 0
|
||||
? { auth: true as const }
|
||||
: undefined;
|
||||
const downloadData = (await this.fetchFromUrl(
|
||||
await withBsplusApiQuery(
|
||||
`${this.THEME_API_BASE}/custom-themes/${encodeURIComponent(themeContent.id)}/download`,
|
||||
),
|
||||
auth,
|
||||
`${this.THEME_API_BASE}/custom-themes/${encodeURIComponent(themeContent.id)}/download`,
|
||||
)) as { success?: boolean; data?: { theme_json_url: string } };
|
||||
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
|
||||
throw new Error("Failed to get community theme download URL");
|
||||
@@ -701,16 +689,8 @@ export class ThemeManager {
|
||||
let themeData: ThemeContent;
|
||||
|
||||
try {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
const auth =
|
||||
typeof bsplus_token === "string" && bsplus_token.length > 0
|
||||
? { auth: true as const }
|
||||
: undefined;
|
||||
const downloadData = (await this.fetchFromUrl(
|
||||
await withBsplusApiQuery(
|
||||
`${this.THEME_API_BASE}/themes/${encodeURIComponent(themeContent.id)}/download`,
|
||||
),
|
||||
auth,
|
||||
`${this.THEME_API_BASE}/themes/${encodeURIComponent(themeContent.id)}/download`,
|
||||
)) as { success?: boolean; data?: { theme_json_url: string } };
|
||||
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
|
||||
throw new Error("Failed to get theme download URL");
|
||||
|
||||
@@ -14,11 +14,7 @@ import { createPluginAPI } from "./createAPI";
|
||||
import browser from "@/lib/browser";
|
||||
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 { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
|
||||
import { isPluginAllowedInPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||
|
||||
interface PluginSettingsStorage {
|
||||
@@ -194,10 +190,7 @@ export class PluginManager {
|
||||
if (settingsState.onoff === false || !isPluginAllowedInPerformanceMode(plugin.id)) {
|
||||
return false;
|
||||
}
|
||||
if (!isRemotePluginStartAllowed(plugin.id)) {
|
||||
return false;
|
||||
}
|
||||
if (isRemoteRouteEnhancementsStripped() && !ROUTE_STRIP_KEEP_PLUGINS.has(plugin.id)) {
|
||||
if (isFeatureDisabled(`plugin.${plugin.id}`)) {
|
||||
return false;
|
||||
}
|
||||
if (!plugin.disableToggle) return true;
|
||||
@@ -277,13 +270,6 @@ 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);
|
||||
}
|
||||
|
||||
public getPlugin(pluginId: string): Plugin | undefined {
|
||||
return this.plugins.get(pluginId);
|
||||
}
|
||||
|
||||
+19
-19
@@ -30,6 +30,7 @@ import {
|
||||
updateEngageHomeMenuActive,
|
||||
} from "@/seqta/utils/loaders/LoadEngageHomePage";
|
||||
import { loadHomePage } from "@/seqta/utils/loaders/LoadHomePage";
|
||||
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
|
||||
import { runStartupPopupQueue } from "@/seqta/utils/openers/StartupPopupQueue";
|
||||
import { OpenCoursesAssessmentsFixPopup } from "@/seqta/utils/openers/OpenCoursesAssessmentsFixPopup";
|
||||
|
||||
@@ -196,8 +197,16 @@ function SortMessagePageItems() {
|
||||
|
||||
async function LoadPageElements(): Promise<void> {
|
||||
await AddBetterSEQTAElements();
|
||||
const { syncRouteEnhancementChrome } = await import("@/seqta/utils/remoteConfig/routeGate");
|
||||
await syncRouteEnhancementChrome();
|
||||
if (!isFeatureDisabled("ui.sidebar.styled")) {
|
||||
void import("@/seqta/ui/sidebar/applyNativeSidebar").then((mod) => {
|
||||
void mod.applyNativeSidebar();
|
||||
});
|
||||
}
|
||||
if (!isFeatureDisabled("ui.titlebar.custom")) {
|
||||
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
|
||||
void mod.mountCustomTitleBar();
|
||||
});
|
||||
}
|
||||
const sublink: string | undefined = getEngageRoutePage();
|
||||
|
||||
if (isSeqtaEngageExperience() && !engageHashListenerAttached) {
|
||||
@@ -715,17 +724,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/utils/remoteConfig/routeGate").then(async (gate) => {
|
||||
if (gate.isRemoteRouteEnhancementsStripped()) return;
|
||||
if (gate.remoteChromeGateAllowed("ui.sidebar.styled")) {
|
||||
const mod = await import("@/seqta/ui/sidebar/applyNativeSidebar");
|
||||
if (!isFeatureDisabled("ui.sidebar.styled")) {
|
||||
void import("@/seqta/ui/sidebar/applyNativeSidebar").then((mod) => {
|
||||
mod.prepareNativeSidebarEarly();
|
||||
}
|
||||
if (gate.remoteChromeGateAllowed("ui.titlebar.custom")) {
|
||||
const mod = await import("@/seqta/ui/titlebar/mountCustomTitleBar");
|
||||
});
|
||||
}
|
||||
if (!isFeatureDisabled("ui.titlebar.custom")) {
|
||||
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
|
||||
mod.prepareCustomTitleBarEarly();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
} else {
|
||||
document.documentElement.classList.remove("bsplus-custom-title-pending");
|
||||
}
|
||||
@@ -750,15 +758,7 @@ 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(
|
||||
|
||||
+12
-17
@@ -10,13 +10,13 @@ import { installSeqtaMenuColourPatch } from "@/seqta/utils/patchSeqtaMenuUpdateC
|
||||
import { installThemeImagePagePatch } from "@/seqta/utils/patchThemeImagesPageContext";
|
||||
import { initVerboseLogging, verboseInfo } from "@/utils/verboseLog";
|
||||
import {
|
||||
hydrateRemoteConfigFromStorage,
|
||||
installRemoteConfigStorageListener,
|
||||
isEffectiveBsplusEnabled,
|
||||
notifyRemoteConfigPageContext,
|
||||
ensureKilledModeSettingsAccess,
|
||||
} from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { runStartupPopupQueue } from "@/seqta/utils/openers/StartupPopupQueue";
|
||||
hasSeenPause,
|
||||
isPaused,
|
||||
loadRemoteStatus,
|
||||
refreshRemoteStatus,
|
||||
} from "@/seqta/utils/remoteStatus";
|
||||
import { showPauseNotice } from "@/seqta/utils/pauseNotice";
|
||||
import { ensureSettingsAccess } from "@/seqta/utils/ensureSettingsAccess";
|
||||
import { recoverFromStaleDevModuleGraph } from "@/seqta/devModuleGraphRecovery";
|
||||
|
||||
function registerFetchSeqtaAppLinkListener() {
|
||||
@@ -101,15 +101,10 @@ async function init() {
|
||||
await delay(5);
|
||||
}
|
||||
|
||||
await hydrateRemoteConfigFromStorage();
|
||||
notifyRemoteConfigPageContext(location.hostname);
|
||||
installRemoteConfigStorageListener(() => {
|
||||
location.reload();
|
||||
});
|
||||
await loadRemoteStatus();
|
||||
void refreshRemoteStatus();
|
||||
|
||||
const bsplusEnabled = isEffectiveBsplusEnabled();
|
||||
|
||||
if (bsplusEnabled) {
|
||||
if (settingsState.onoff !== false && !isPaused()) {
|
||||
await main();
|
||||
|
||||
const { init: Monofile } = await import("@/plugins/monofile");
|
||||
@@ -120,8 +115,8 @@ async function init() {
|
||||
await initializePlugins();
|
||||
}
|
||||
} else {
|
||||
await ensureKilledModeSettingsAccess();
|
||||
void runStartupPopupQueue();
|
||||
await ensureSettingsAccess();
|
||||
if (settingsState.onoff !== false && !hasSeenPause()) showPauseNotice();
|
||||
}
|
||||
|
||||
if (settingsState.devMode) {
|
||||
|
||||
@@ -28,8 +28,7 @@ import {
|
||||
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 { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
|
||||
import { rafThrottle } from "@/seqta/utils/rafThrottle";
|
||||
import {
|
||||
installSidebarDrillReturn,
|
||||
@@ -69,10 +68,10 @@ export async function AddBetterSEQTAElements() {
|
||||
const menu = document.getElementById("menu")!;
|
||||
const menuList = menu.firstChild as HTMLElement;
|
||||
|
||||
if (!checkRemoteFeature("page.home").hide) {
|
||||
if (!isFeatureDisabled("page.home")) {
|
||||
createHomeButton(fragment);
|
||||
}
|
||||
if (!checkRemoteFeature("page.news").hide) {
|
||||
if (!isFeatureDisabled("page.news")) {
|
||||
createNewsButton(fragment, menu);
|
||||
}
|
||||
|
||||
@@ -92,7 +91,7 @@ export async function AddBetterSEQTAElements() {
|
||||
setupEventListeners();
|
||||
await addDarkLightToggle();
|
||||
customizeMenuToggle();
|
||||
if (remoteChromeGateAllowed("ui.sidebar.styled")) {
|
||||
if (!isFeatureDisabled("ui.sidebar.styled")) {
|
||||
maybeSetupSidebarAccessibility();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type BadgeItem,
|
||||
} from "@/seqta/utils/founderBadges";
|
||||
import { openFounderBadgeModal } from "@/seqta/ui/founderBadge/openFounderBadgeModal";
|
||||
import { remoteChromeGateAllowed } from "@/seqta/utils/remoteConfig/routeGate";
|
||||
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
|
||||
|
||||
let subscribed = false;
|
||||
let refreshPending = false;
|
||||
@@ -82,7 +82,7 @@ async function syncTitlebarFounderBadge(): Promise<void> {
|
||||
if (
|
||||
settingsState.showTitlebarFounderBadge === false ||
|
||||
!cloudAuth.state.isLoggedIn ||
|
||||
!remoteChromeGateAllowed("ui.titlebar.founderBadge")
|
||||
isFeatureDisabled("ui.titlebar.founderBadge")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import { PRODUCTION_API_BASE, resolveApiBase } from "./apiBasePolicy";
|
||||
|
||||
describe("resolveApiBase", () => {
|
||||
it("uses production during extension dev builds", () => {
|
||||
expect(resolveApiBase("development", "http://localhost:3000")).toBe(PRODUCTION_API_BASE);
|
||||
expect(resolveApiBase("development", null)).toBe(PRODUCTION_API_BASE);
|
||||
});
|
||||
|
||||
it("honors session override in production builds", () => {
|
||||
expect(resolveApiBase("production", "https://staging.example.test")).toBe(
|
||||
"https://staging.example.test",
|
||||
);
|
||||
expect(resolveApiBase("production", null)).toBe(PRODUCTION_API_BASE);
|
||||
});
|
||||
});
|
||||
@@ -1,76 +0,0 @@
|
||||
import browser from "@/lib/browser";
|
||||
import { resolveApiBase } from "@/seqta/utils/apiBasePolicy";
|
||||
|
||||
export { PRODUCTION_API_BASE } from "@/seqta/utils/apiBasePolicy";
|
||||
|
||||
const KEY = "bsplus_dev_api_base";
|
||||
|
||||
function readSessionOverride(): string | null {
|
||||
try {
|
||||
if (typeof sessionStorage === "undefined") return null;
|
||||
const v = sessionStorage.getItem(KEY);
|
||||
if (v && /^https?:\/\//.test(v)) return v.replace(/\/$/, "");
|
||||
} catch {
|
||||
// sessionStorage may throw in some restricted contexts; fall back silently.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function currentBuildMode(): "development" | "production" {
|
||||
return import.meta.env.DEV ? "development" : "production";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current content-API base URL.
|
||||
*
|
||||
* In production builds, Advanced settings may set a session-only override for server testing.
|
||||
* In extension dev builds, overrides are ignored and production is always used.
|
||||
*/
|
||||
export function getApiBase(): string {
|
||||
return resolveApiBase(currentBuildMode(), readSessionOverride());
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a session-scoped override and broadcast it to the background script
|
||||
* so its `fetch` calls hit the same host.
|
||||
*
|
||||
* Pass `null` to clear the override. No-op in extension dev builds.
|
||||
*/
|
||||
export function setApiBase(url: string | null): void {
|
||||
if (import.meta.env.DEV) {
|
||||
try {
|
||||
sessionStorage.removeItem(KEY);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
void browser.runtime.sendMessage({ type: "setDevApiBase", url: null }).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!url) {
|
||||
sessionStorage.removeItem(KEY);
|
||||
} else {
|
||||
sessionStorage.setItem(KEY, url.replace(/\/$/, ""));
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
void browser.runtime.sendMessage({ type: "setDevApiBase", url: url || null }).catch(() => {});
|
||||
}
|
||||
|
||||
/** Returns the override URL if one is currently active (production builds only). */
|
||||
export function getStoredOverride(): string | null {
|
||||
if (import.meta.env.DEV) return null;
|
||||
return readSessionOverride();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the current session override to the background script.
|
||||
* Call this early in page load so the background context stays in sync after
|
||||
* service-worker restarts.
|
||||
*/
|
||||
export function syncApiBaseToBackground(): void {
|
||||
const override = import.meta.env.DEV ? null : readSessionOverride();
|
||||
void browser.runtime.sendMessage({ type: "setDevApiBase", url: override }).catch(() => {});
|
||||
}
|
||||
@@ -9,13 +9,10 @@ import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
|
||||
import { animate, stagger } from "motion";
|
||||
import { verboseInfo } from "@/utils/verboseLog";
|
||||
import { toNewsArticles, type NewsPayload } from "@/seqta/utils/newsFeed";
|
||||
import {
|
||||
applyPageFeatureGateEarly,
|
||||
injectPageFeatureBanner,
|
||||
} from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
|
||||
|
||||
export async function SendNewsPage() {
|
||||
if (applyPageFeatureGateEarly("news")) return;
|
||||
if (isFeatureDisabled("page.news")) return;
|
||||
|
||||
verboseInfo("[BetterSEQTA+] Started Loading News Page");
|
||||
document.title = "News ― SEQTA Learn";
|
||||
@@ -58,7 +55,6 @@ export async function SendNewsPage() {
|
||||
</div>`);
|
||||
|
||||
main.append(html.firstChild!);
|
||||
injectPageFeatureBanner("news", "#news-container");
|
||||
|
||||
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
|
||||
mod.setCustomTitleBarText("News");
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
export const PRODUCTION_API_BASE = "https://betterseqta.org";
|
||||
|
||||
/**
|
||||
* Resolves the content API host. Extension dev builds always use production
|
||||
* so community theme submit and the theme store work against the live API.
|
||||
*/
|
||||
export function resolveApiBase(
|
||||
buildMode: "development" | "production",
|
||||
sessionOverride: string | null,
|
||||
): string {
|
||||
if (buildMode === "development") return PRODUCTION_API_BASE;
|
||||
if (sessionOverride) return sessionOverride;
|
||||
return PRODUCTION_API_BASE;
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import browser from "@/lib/browser";
|
||||
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
|
||||
|
||||
function manifestVersion(): string {
|
||||
try {
|
||||
return browser.runtime.getManifest().version;
|
||||
} catch {
|
||||
return "0";
|
||||
}
|
||||
}
|
||||
|
||||
function updateChannel(): string {
|
||||
if (typeof __UPDATE_CHANNEL__ !== "undefined") {
|
||||
if (__UPDATE_CHANNEL__ === "nightly") return "nightly";
|
||||
if (__UPDATE_CHANNEL__ === "stable") return "stable";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function bsplusExtensionPayload(): {
|
||||
version: string;
|
||||
channel: string;
|
||||
browser: "chrome";
|
||||
} {
|
||||
return { version: manifestVersion(), channel: updateChannel(), browser: "chrome" };
|
||||
}
|
||||
|
||||
/** Shared query params for betterseqta.org theme + remote-config requests. */
|
||||
export async function bsplusApiQueryParams(): Promise<URLSearchParams> {
|
||||
const params = new URLSearchParams({
|
||||
extensionVersion: manifestVersion(),
|
||||
channel: updateChannel(),
|
||||
installId: await getOrCreateInstallId(),
|
||||
});
|
||||
const { bsplus_user } = await browser.storage.local.get("bsplus_user");
|
||||
if (bsplus_user && typeof bsplus_user === "object" && "id" in bsplus_user) {
|
||||
const id = (bsplus_user as { id: unknown }).id;
|
||||
if (typeof id === "string" && id) params.set("userId", id);
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
export async function withBsplusApiQuery(url: string): Promise<string> {
|
||||
const qs = (await bsplusApiQueryParams()).toString();
|
||||
return qs ? (url.includes("?") ? `${url}&${qs}` : `${url}?${qs}`) : url;
|
||||
}
|
||||
@@ -1,20 +1,6 @@
|
||||
import browser from "@/lib/browser";
|
||||
import isEqual from "@/seqta/utils/isEqual";
|
||||
import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY } from "@/seqta/utils/calendarSync/settings";
|
||||
import {
|
||||
BSPLUS_CAMPAIGN_SEEN_KEY,
|
||||
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
|
||||
BSPLUS_INSTALL_REGISTERED_AT_KEY,
|
||||
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY,
|
||||
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 */
|
||||
export const CLOUD_SETTINGS_SYNC_SCHEMA_VERSION = 1;
|
||||
@@ -58,18 +44,7 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [
|
||||
"bsplus_install_id",
|
||||
/** Pending feedback ids awaiting a reply notification — device-local. */
|
||||
"bsplus_pending_feedback_ids",
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
|
||||
BSPLUS_CAMPAIGN_SEEN_KEY,
|
||||
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
|
||||
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
|
||||
BSPLUS_INSTALL_REGISTERED_AT_KEY,
|
||||
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_remote_status",
|
||||
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
|
||||
] as const;
|
||||
|
||||
@@ -94,9 +69,6 @@ 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. */
|
||||
@@ -116,7 +88,6 @@ const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
|
||||
"devMode",
|
||||
"devGhReleaseVersionOverride",
|
||||
"devDelayLoadingScreen",
|
||||
"bsplus_dev_api_base",
|
||||
"bsplus_dev_accounts_base",
|
||||
"bsplus_dev_oauth_client_id",
|
||||
"bsplus_dev_oauth_client_secret",
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { icon } from "@/lib/icon";
|
||||
import { Wrench } from "lucide-static";
|
||||
import stringToHTML from "@/seqta/utils/stringToHTML";
|
||||
import { addExtensionSettings } from "@/seqta/utils/adders/AddExtensionSettings";
|
||||
import { setupSettingsButton } from "@/seqta/utils/setupSettingsButton";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||
|
||||
export async function ensureSettingsAccess(): Promise<void> {
|
||||
addExtensionSettings();
|
||||
if (document.getElementById("AddedSettings")) {
|
||||
setupSettingsButton();
|
||||
return;
|
||||
}
|
||||
|
||||
const fallback =
|
||||
document.getElementById("content") ?? document.getElementById("container") ?? document.body;
|
||||
|
||||
const mountParent = async (): Promise<Element> => {
|
||||
if (isSeqtaEngageExperience()) {
|
||||
try {
|
||||
const el = await waitForElm(
|
||||
"#content > div.connectedNotificationsWrapper > div",
|
||||
true,
|
||||
100,
|
||||
40,
|
||||
);
|
||||
return el.parentElement ?? el;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await waitForElm(
|
||||
"#content > div.connectedNotificationsWrapper",
|
||||
true,
|
||||
isPerformanceMode() ? 120 : 80,
|
||||
50,
|
||||
);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
mountParent().then((parent) => {
|
||||
if (document.getElementById("AddedSettings")) return;
|
||||
parent.append(
|
||||
stringToHTML(/* html */ `
|
||||
<button class="addedButton" id="AddedSettings" type="button" aria-label="BetterSEQTA+ settings">
|
||||
${icon(Wrench)}
|
||||
</button>
|
||||
`).firstChild!,
|
||||
);
|
||||
setupSettingsButton();
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,3 @@
|
||||
jest.mock("@/seqta/utils/DevApiBase", () => ({
|
||||
getApiBase: () => "https://example.test",
|
||||
}));
|
||||
|
||||
import browser from "@/lib/browser";
|
||||
import {
|
||||
addPendingFeedbackId,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import browser from "@/lib/browser";
|
||||
import { getApiBase } from "@/seqta/utils/DevApiBase";
|
||||
import { API_BASE } from "@/config/apiBase";
|
||||
import { isExtensionSettingsOpen } from "@/seqta/utils/settingsPopupAnimation";
|
||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
type FeedbackProduct,
|
||||
} from "./constants";
|
||||
import { getOrCreateInstallId } from "./installId";
|
||||
import { isRemoteFeedbackSubmitDisabled } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
|
||||
|
||||
export class FeedbackApiError extends Error {
|
||||
constructor(
|
||||
@@ -115,7 +115,7 @@ function channel(): FeedbackChannel {
|
||||
|
||||
async function apiFetch(path: string, init?: RequestInit): Promise<Response> {
|
||||
try {
|
||||
return await fetch(`${getApiBase()}${path}`, {
|
||||
return await fetch(`${API_BASE}${path}`, {
|
||||
...init,
|
||||
headers: { Accept: "application/json", ...init?.headers },
|
||||
});
|
||||
@@ -149,7 +149,7 @@ export async function submitFeedback(form: FeedbackFormInput): Promise<{ id: str
|
||||
const err = validateFeedbackForm(form);
|
||||
if (err) throw new FeedbackApiError(err, 422);
|
||||
|
||||
if (isRemoteFeedbackSubmitDisabled()) {
|
||||
if (isFeatureDisabled("feedback.submit")) {
|
||||
throw new FeedbackApiError(
|
||||
"Feedback submissions are temporarily disabled.",
|
||||
503,
|
||||
|
||||
@@ -54,12 +54,7 @@ const EXCLUDED_FROM_SETTINGS_SURFACE = new Set([
|
||||
"cloudUsername",
|
||||
"bsplus_install_id",
|
||||
"bsplus_pending_feedback_ids",
|
||||
"bsplus_remote_config_snapshot",
|
||||
"bsplus_remote_config_etag",
|
||||
"bsplus_campaign_seen",
|
||||
"bsplus_local_override_onoff",
|
||||
"bsplus_features_hidden_until_version",
|
||||
"bsplus_install_registered_at",
|
||||
"bsplus_remote_status",
|
||||
]);
|
||||
|
||||
function isExcludedSettingsKey(key: string): boolean {
|
||||
|
||||
@@ -23,10 +23,7 @@ import {
|
||||
import { resolveNoticeFilterTokens } from "@/seqta/utils/notices/noticeLabelFilters";
|
||||
import { setupNoticesSection } from "@/seqta/utils/notices/noticeHomeUi";
|
||||
import { lessonsSubtitleForViewDate } from "@/seqta/utils/loaders/timetableSubtitle";
|
||||
import {
|
||||
applyPageFeatureGateEarly,
|
||||
injectPageFeatureBanner,
|
||||
} from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
|
||||
import type {
|
||||
ActiveSubjectLike,
|
||||
DateSortable,
|
||||
@@ -50,7 +47,7 @@ function clearLessonInterval(): void {
|
||||
}
|
||||
|
||||
export async function loadHomePage() {
|
||||
if (applyPageFeatureGateEarly("home")) return;
|
||||
if (isFeatureDisabled("page.home")) return;
|
||||
|
||||
homeTeardown?.();
|
||||
homeTeardown = null;
|
||||
@@ -109,8 +106,6 @@ export async function loadHomePage() {
|
||||
</div>`);
|
||||
|
||||
homeContainer.appendChild(skeletonStructure.firstChild!);
|
||||
injectPageFeatureBanner("home", "#home-container");
|
||||
injectPageFeatureBanner("home", "#home-container");
|
||||
|
||||
if (settingsState.animations) {
|
||||
animate(
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
jest.mock("../DevApiBase", () => ({
|
||||
getApiBase: () => "https://betterseqta.org",
|
||||
}));
|
||||
|
||||
import {
|
||||
getFallbackTermsOfService,
|
||||
markTermsOfServiceAccepted,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import stringToHTML from "../stringToHTML";
|
||||
import { settingsState } from "../listeners/SettingsState";
|
||||
import { getApiBase } from "../DevApiBase";
|
||||
import { API_BASE } from "@/config/apiBase";
|
||||
import { closePopup, openPopup } from "./PopupManager";
|
||||
import fallbackTerms from "@/exampletermsresponse.json";
|
||||
import type { SettingsState } from "@/types/storage";
|
||||
@@ -33,7 +33,7 @@ export function getFallbackTermsOfService(): LegalDocumentPayload {
|
||||
/** Loads Terms of Service body from `GET /api/terms`. */
|
||||
export async function fetchTermsOfService(): Promise<LegalDocumentPayload> {
|
||||
try {
|
||||
const res = await fetch(`${getApiBase()}/api/terms`, {
|
||||
const res = await fetch(`${API_BASE}/api/terms`, {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(TERMS_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
@@ -2,9 +2,6 @@
|
||||
import { OpenThemeOfTheMonthPopup } from "./OpenThemeOfTheMonthPopup";
|
||||
import { settingsState } from "../listeners/SettingsState";
|
||||
|
||||
jest.mock("../DevApiBase", () => ({
|
||||
getApiBase: () => "https://example.test",
|
||||
}));
|
||||
jest.mock("./PopupManager", () => ({ closePopup: jest.fn() }));
|
||||
jest.mock("../listeners/SettingsState", () => ({
|
||||
settingsState: { animations: false },
|
||||
|
||||
@@ -4,8 +4,7 @@ import browser from "@/lib/browser";
|
||||
import stringToHTML from "../stringToHTML";
|
||||
import { settingsState } from "../listeners/SettingsState";
|
||||
import { closePopup } from "./PopupManager";
|
||||
import { getApiBase } from "../DevApiBase";
|
||||
import { withBsplusApiQuery } from "../bsplusClientContext";
|
||||
import { API_BASE } from "@/config/apiBase";
|
||||
import { openThemeStoreWithHighlight } from "../openThemeStoreWithHighlight";
|
||||
import type { Theme } from "@/interface/types/Theme";
|
||||
import { buildModalHeroSlides, normalizeStoreTheme } from "@/interface/utils/themeStoreFlavours";
|
||||
@@ -61,8 +60,7 @@ async function writeCachedThemeOfTheMonth(entry: ThemeOfTheMonthEntry): Promise<
|
||||
*/
|
||||
export async function fetchThemeOfTheMonth(): Promise<ThemeOfTheMonthEntry | null> {
|
||||
try {
|
||||
const url = await withBsplusApiQuery(`${getApiBase()}/api/theme-of-the-month/current`);
|
||||
const res = await fetch(url, {
|
||||
const res = await fetch(`${API_BASE}/api/theme-of-the-month/current`, {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(TOTM_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import semver from "semver";
|
||||
import browser from "@/lib/browser";
|
||||
import { settingsState } from "../listeners/SettingsState";
|
||||
import { OpenWhatsNewPopup } from "./OpenWhatsNewPopup";
|
||||
import {
|
||||
@@ -12,45 +10,17 @@ import {
|
||||
OpenCoursesAssessmentsFixPopup,
|
||||
shouldShowCoursesAssessmentsFixPopup,
|
||||
} from "./OpenCoursesAssessmentsFixPopup";
|
||||
import { syncApiBaseToBackground } from "../DevApiBase";
|
||||
import { cloudAuth } from "../CloudAuth";
|
||||
import {
|
||||
fetchTermsOfService,
|
||||
openTermsOfServicePopup,
|
||||
shouldShowTermsOfServicePopup,
|
||||
} from "./OpenTermsOfServicePopup";
|
||||
import { getCampaignSeen, getRemoteConfigSnapshot } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import type { RemoteCampaign } from "@/seqta/utils/remoteConfig/types";
|
||||
import { openRemoteCampaignPopup } from "./openRemoteCampaignPopup";
|
||||
|
||||
type QueueStep = (goNext: () => void) => void;
|
||||
|
||||
function remoteCampaignSteps(): QueueStep[] {
|
||||
const now = Date.now();
|
||||
const version = browser.runtime.getManifest().version;
|
||||
const seen = getCampaignSeen();
|
||||
|
||||
return [...getRemoteConfigSnapshot().campaigns]
|
||||
.filter((c) => {
|
||||
if (!c.id) return false;
|
||||
if (c.activeFrom && now < Date.parse(c.activeFrom)) return false;
|
||||
if (c.activeTo && now > Date.parse(c.activeTo)) return false;
|
||||
const hit = seen[c.id];
|
||||
if (hit && (!c.requireAcknowledge || hit.ack)) return false;
|
||||
if (c.minVersion && semver.valid(version) && semver.lt(version, c.minVersion)) return false;
|
||||
if (c.maxVersion && semver.valid(version) && semver.gt(version, c.maxVersion)) return false;
|
||||
return true;
|
||||
})
|
||||
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
|
||||
.map((campaign: RemoteCampaign) => (goNext: () => void) => {
|
||||
openRemoteCampaignPopup(campaign, goNext);
|
||||
});
|
||||
}
|
||||
|
||||
export async function runStartupPopupQueue() {
|
||||
syncApiBaseToBackground();
|
||||
|
||||
const steps: QueueStep[] = [...remoteCampaignSteps()];
|
||||
const steps: QueueStep[] = [];
|
||||
|
||||
if (settingsState.justupdated) {
|
||||
steps.push((goNext) => OpenWhatsNewPopup(goNext));
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import browser from "@/lib/browser";
|
||||
import { fetchThemeOfTheMonth } from "./OpenThemeOfTheMonthPopup";
|
||||
|
||||
jest.mock("../DevApiBase", () => ({
|
||||
getApiBase: () => "https://example.test",
|
||||
}));
|
||||
|
||||
const CACHE_KEY = "bsplus_theme_of_the_month_cache";
|
||||
|
||||
const sampleEntry = {
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
import stringToHTML from "../stringToHTML";
|
||||
import { closePopup, openPopup } from "./PopupManager";
|
||||
import { createPopupHeroVideo } from "./attachPopupMediaFullscreen";
|
||||
import { markCampaignSeen } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import type { RemoteCampaign } from "@/seqta/utils/remoteConfig/types";
|
||||
import { requestSettingsDestination } from "@/seqta/utils/settingsNavigation";
|
||||
import { openSettingsPopup } from "@/seqta/utils/setupSettingsButton";
|
||||
|
||||
export function openRemoteCampaignPopup(campaign: RemoteCampaign, onDismissed?: () => void): 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>`,
|
||||
).firstChild as HTMLElement;
|
||||
|
||||
const buttons = campaign.buttons?.length
|
||||
? campaign.buttons
|
||||
: [{ id: "dismiss", label: "Dismiss", action: "dismiss" as const }];
|
||||
|
||||
const actionsHtml = buttons
|
||||
.map(
|
||||
(btn, i) =>
|
||||
`<button type="button" id="bsplus-campaign-${campaign.id}-${btn.id}" class="bsplus-cal-btn ${i === 0 ? "bsplus-cal-btn--primary" : "bsplus-cal-btn--ghost"}">${btn.label}</button>`,
|
||||
)
|
||||
.join("");
|
||||
|
||||
const text = stringToHTML(/* html */ `
|
||||
<div class="whatsnewTextContainer bsplus-founder-badge-body" style="overflow-y: auto;">
|
||||
<div class="bsplus-campaign-body"></div>
|
||||
<div class="bsplus-founder-badge-actions">${actionsHtml}</div>
|
||||
</div>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
const bodySlot = text.querySelector(".bsplus-campaign-body");
|
||||
if (bodySlot && campaign.bodyHtml) bodySlot.innerHTML = campaign.bodyHtml;
|
||||
|
||||
const content: HTMLElement[] = [];
|
||||
const hero = campaign.hero;
|
||||
if (hero?.url) {
|
||||
if (hero.type === "video") {
|
||||
content.push(createPopupHeroVideo(hero.url, hero.alt ?? ""));
|
||||
} else {
|
||||
const wrap = stringToHTML(/* html */ `<div class="whatsnewImgContainer"></div>`)
|
||||
.firstChild as HTMLElement;
|
||||
const img = document.createElement("img");
|
||||
img.src = hero.url;
|
||||
img.alt = hero.alt ?? "";
|
||||
img.className = "whatsnewImg";
|
||||
img.loading = "lazy";
|
||||
wrap.append(img);
|
||||
content.push(wrap);
|
||||
}
|
||||
}
|
||||
content.push(text);
|
||||
|
||||
const actions = buttons.map((btn) => ({
|
||||
id: `bsplus-campaign-${campaign.id}-${btn.id}`,
|
||||
onClick: async () => {
|
||||
if (btn.action === "url" && btn.url) {
|
||||
window.open(btn.url, "_blank", "noopener,noreferrer");
|
||||
} else if (btn.action === "openSettingsSection" && btn.section) {
|
||||
requestSettingsDestination({ page: "settings", section: btn.section });
|
||||
await openSettingsPopup();
|
||||
}
|
||||
if (campaign.requireAcknowledge) acknowledged = true;
|
||||
await closePopup();
|
||||
},
|
||||
}));
|
||||
|
||||
openPopup({
|
||||
header,
|
||||
content,
|
||||
animateSelector: ".whatsnewImgContainer, .whatsnewTextContainer *",
|
||||
actions,
|
||||
afterClose: () => {
|
||||
void markCampaignSeen(campaign.id, campaign.requireAcknowledge ? acknowledged : undefined);
|
||||
onDismissed?.();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -5,20 +5,15 @@ export type WhatsNewRelease = {
|
||||
|
||||
export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [
|
||||
{
|
||||
title: "3.7.7 - Startup performance & reliability",
|
||||
items: [
|
||||
"Lazy-loads plugin code on first use for faster SEQTA startup, plus background and stability fixes from the latest maintenance release.",
|
||||
],
|
||||
title: "3.7.7 - Faster Startup",
|
||||
items: ["SEQTA now loads faster with BetterSEQTA+.", "Stability fixes."],
|
||||
},
|
||||
{
|
||||
title:
|
||||
"3.7.6 - Timetable Sharing Fixes, Better Update resilience & Community Theme Submitter Badges,",
|
||||
title: "3.7.6 - Timetable Sharing Fixes & Theme Submitter Badges",
|
||||
items: [
|
||||
"Improved releiability of opening the connection for Timetable Sharing.",
|
||||
"Added a new submitter badge for community theme submitters.",
|
||||
"Added ability for Admin's to view unreleased community themes for QA.",
|
||||
"Added ability for BetterSEQTA+ features to be dynamically configured remotly to negate compatability issues.",
|
||||
"Added ability to set BetterSEQTA Cloud Profile Picture from Extension Settings.",
|
||||
"Timetable Sharing now connects more reliably.",
|
||||
"Community theme submitters now get a badge.",
|
||||
"Set your BetterSEQTA Cloud profile picture from Settings.",
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -14,11 +14,8 @@ export type ThemePageSyncInput = {
|
||||
images?: Array<{ variableName: string; blob: Blob }>;
|
||||
customCss?: string;
|
||||
previewCss?: string;
|
||||
overlayCss?: string;
|
||||
overlayImages?: Array<{ variableName: string; blob: Blob }>;
|
||||
clear?: boolean;
|
||||
clearPreview?: boolean;
|
||||
clearOverlay?: boolean;
|
||||
};
|
||||
|
||||
export function installThemeImagePagePatch(): void {
|
||||
@@ -62,22 +59,7 @@ function preserveCustomSidebarActive(css: string): string {
|
||||
return css.replace(/\.active(?![\w-])/g, ":is(.active, .bsplus-active)");
|
||||
}
|
||||
|
||||
async function encodeImages(images?: Array<{ variableName: string; blob: Blob }>) {
|
||||
if (images === undefined) return undefined;
|
||||
return Promise.all(
|
||||
images.map(async (image) => ({
|
||||
variableName: image.variableName,
|
||||
data: await blobToBase64Data(image.blob),
|
||||
mime: image.blob.type || "image/png",
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
export async function syncThemeToPage(input: ThemePageSyncInput): Promise<void> {
|
||||
if (input.clearOverlay) {
|
||||
sendPayload({ clearOverlay: true });
|
||||
return;
|
||||
}
|
||||
if (input.clear) {
|
||||
sendPayload({ clear: true });
|
||||
return;
|
||||
@@ -91,15 +73,16 @@ export async function syncThemeToPage(input: ThemePageSyncInput): Promise<void>
|
||||
if (input.previewCss !== undefined) {
|
||||
payload.previewCss = preserveCustomSidebarActive(input.previewCss);
|
||||
}
|
||||
if (input.overlayCss !== undefined) {
|
||||
payload.overlayCss = preserveCustomSidebarActive(input.overlayCss);
|
||||
if (input.images !== undefined) {
|
||||
payload.images = await Promise.all(
|
||||
input.images.map(async (image) => ({
|
||||
variableName: image.variableName,
|
||||
data: await blobToBase64Data(image.blob),
|
||||
mime: image.blob.type || "image/png",
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const images = await encodeImages(input.images);
|
||||
if (images !== undefined) payload.images = images;
|
||||
const overlayImages = await encodeImages(input.overlayImages);
|
||||
if (overlayImages !== undefined) payload.overlayImages = overlayImages;
|
||||
|
||||
if (Object.keys(payload).length === 0) return;
|
||||
sendPayload(payload);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { choosePause, pauseMessage } from "@/seqta/utils/remoteStatus";
|
||||
|
||||
// SEQTA's page styles aren't patched while paused, so the bar carries its own inline styles.
|
||||
const BUTTON_STYLE =
|
||||
"border:0;border-radius:8px;padding:6px 12px;font:inherit;font-weight:600;cursor:pointer;";
|
||||
|
||||
export function showPauseNotice(): void {
|
||||
const bar = document.createElement("div");
|
||||
bar.setAttribute("role", "status");
|
||||
bar.style.cssText =
|
||||
"position:fixed;left:50%;bottom:16px;transform:translateX(-50%);z-index:2147483647;display:flex;align-items:center;gap:12px;max-width:min(560px,calc(100vw - 32px));padding:12px 16px;border-radius:12px;background:#1f1f1f;color:#fff;font:14px/1.4 system-ui,sans-serif;box-shadow:0 8px 24px rgba(0,0,0,.3);";
|
||||
|
||||
const text = document.createElement("span");
|
||||
text.textContent = pauseMessage();
|
||||
|
||||
const runAnyway = document.createElement("button");
|
||||
runAnyway.textContent = "Run Anyway";
|
||||
runAnyway.style.cssText = `${BUTTON_STYLE}background:transparent;color:#fff;box-shadow:inset 0 0 0 1px rgba(255,255,255,.4);`;
|
||||
runAnyway.onclick = async () => {
|
||||
await choosePause(true);
|
||||
location.reload();
|
||||
};
|
||||
|
||||
const ok = document.createElement("button");
|
||||
ok.textContent = "OK";
|
||||
ok.style.cssText = `${BUTTON_STYLE}background:#fff;color:#111;`;
|
||||
ok.onclick = async () => {
|
||||
await choosePause(false);
|
||||
bar.remove();
|
||||
};
|
||||
|
||||
bar.append(text, runAnyway, ok);
|
||||
document.body.append(bar);
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
import { computeEffectiveEnabled, isRemoteFeatureAllowed, resolveFeatureMode } from "./apply";
|
||||
import { DEFAULT_REMOTE_CONFIG } from "./normalize";
|
||||
import type { RemoteConfigSnapshot } from "./types";
|
||||
|
||||
function snapshot(partial: Partial<RemoteConfigSnapshot>): RemoteConfigSnapshot {
|
||||
return {
|
||||
...DEFAULT_REMOTE_CONFIG,
|
||||
...partial,
|
||||
global: { ...DEFAULT_REMOTE_CONFIG.global, ...partial.global },
|
||||
features: { ...DEFAULT_REMOTE_CONFIG.features, ...partial.features },
|
||||
};
|
||||
}
|
||||
|
||||
describe("computeEffectiveEnabled", () => {
|
||||
it("respects user master toggle", () => {
|
||||
expect(computeEffectiveEnabled(false, snapshot({}), false)).toBe(false);
|
||||
});
|
||||
|
||||
it("allows when remote mode is on", () => {
|
||||
expect(computeEffectiveEnabled(true, snapshot({ global: { mode: "on" } }), false)).toBe(true);
|
||||
});
|
||||
|
||||
it("blocks when remote kill without local override", () => {
|
||||
expect(
|
||||
computeEffectiveEnabled(
|
||||
true,
|
||||
snapshot({ global: { mode: "off", allowLocalOverride: true } }),
|
||||
false,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("allows local override when permitted", () => {
|
||||
expect(
|
||||
computeEffectiveEnabled(
|
||||
true,
|
||||
snapshot({ global: { mode: "off", allowLocalOverride: true } }),
|
||||
true,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores local override when server forbids it", () => {
|
||||
expect(
|
||||
computeEffectiveEnabled(
|
||||
true,
|
||||
snapshot({ global: { mode: "off", allowLocalOverride: false } }),
|
||||
true,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("blocks hostname on denylist unless local override", () => {
|
||||
const snap = snapshot({
|
||||
global: {
|
||||
mode: "on",
|
||||
hostnamePolicy: { mode: "denylist", suffixes: ["blocked.edu.au"] },
|
||||
},
|
||||
});
|
||||
expect(computeEffectiveEnabled(true, snap, false, "learn.blocked.edu.au")).toBe(false);
|
||||
expect(computeEffectiveEnabled(true, snap, true, "learn.blocked.edu.au")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveFeatureMode", () => {
|
||||
it("treats temp_hide as hide only for matching config version", () => {
|
||||
const snap = snapshot({
|
||||
configVersion: "42",
|
||||
features: { "page.news": { mode: "temp_hide" } },
|
||||
});
|
||||
expect(resolveFeatureMode("page.news", snap, { "page.news": "41" })).toBe("allow");
|
||||
expect(resolveFeatureMode("page.news", snap, { "page.news": "42" })).toBe("hide");
|
||||
});
|
||||
|
||||
it("maps banner to allowed but not hide", () => {
|
||||
const snap = snapshot({
|
||||
features: { "plugin.grade-analytics": { mode: "banner" } },
|
||||
});
|
||||
expect(isRemoteFeatureAllowed("plugin.grade-analytics", snap)).toBe(true);
|
||||
expect(resolveFeatureMode("plugin.grade-analytics", snap)).toBe("banner");
|
||||
});
|
||||
});
|
||||
|
||||
describe("SEQTA boot decision", () => {
|
||||
it("would skip monofile when effective enablement is false", () => {
|
||||
const shouldBootFull = computeEffectiveEnabled(
|
||||
true,
|
||||
snapshot({ global: { mode: "off", allowLocalOverride: true } }),
|
||||
false,
|
||||
);
|
||||
expect(shouldBootFull).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hydrateRemoteConfigFromStorage", () => {
|
||||
it("requests cached snapshot before background refresh when storage is empty", async () => {
|
||||
jest.resetModules();
|
||||
jest.doMock("@/lib/browser", () => ({
|
||||
storage: {
|
||||
local: {
|
||||
get: jest.fn(async () => ({})),
|
||||
set: jest.fn(async () => {}),
|
||||
},
|
||||
onChanged: { addListener: jest.fn() },
|
||||
},
|
||||
runtime: {
|
||||
getManifest: () => ({ version: "3.7.6" }),
|
||||
sendMessage: jest.fn(async (msg: { type?: string }) =>
|
||||
msg.type === "getRemoteConfigSnapshot"
|
||||
? {
|
||||
snapshot: {
|
||||
configVersion: "1",
|
||||
global: { mode: "on" },
|
||||
features: {},
|
||||
campaigns: [],
|
||||
},
|
||||
}
|
||||
: {},
|
||||
),
|
||||
},
|
||||
}));
|
||||
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");
|
||||
const browser = jest.requireMock("@/lib/browser");
|
||||
const types = browser.runtime.sendMessage.mock.calls.map(
|
||||
(c: [{ type?: string }]) => c[0]?.type,
|
||||
);
|
||||
expect(types).toContain("getRemoteConfigSnapshot");
|
||||
expect(types).toContain("setRemoteConfigPageContext");
|
||||
expect(types).toContain("refreshRemoteConfig");
|
||||
expect(types.indexOf("getRemoteConfigSnapshot")).toBeLessThan(
|
||||
types.indexOf("refreshRemoteConfig"),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,112 +0,0 @@
|
||||
import type { FeatureMode, RemoteConfigSnapshot, RemoteFeatureGate } from "./types";
|
||||
import { DEFAULT_REMOTE_CONFIG } from "./normalize";
|
||||
import semver from "semver";
|
||||
import browser from "@/lib/browser";
|
||||
|
||||
function normalizeHostname(hostname: string): string {
|
||||
return hostname.trim().toLowerCase().replace(/\.$/, "");
|
||||
}
|
||||
|
||||
export function isHostnameAllowedByPolicy(
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
hostname: string,
|
||||
): boolean {
|
||||
const policy = snapshot.global.hostnamePolicy;
|
||||
if (!policy?.suffixes?.length) return true;
|
||||
const host = normalizeHostname(hostname);
|
||||
const suffixes = policy.suffixes.map((s) => normalizeHostname(s));
|
||||
const matches = suffixes.some((suffix) => host === suffix || host.endsWith(`.${suffix}`));
|
||||
if (policy.mode === "denylist") return !matches;
|
||||
if (policy.mode === "allowlist") return matches;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function isExtensionVersionBelowMinimum(snapshot: RemoteConfigSnapshot): boolean {
|
||||
const min = snapshot.global.minExtensionVersion;
|
||||
if (!min || !semver.valid(min)) return false;
|
||||
const current = browser.runtime.getManifest().version;
|
||||
if (!semver.valid(current)) return false;
|
||||
return semver.lt(current, min);
|
||||
}
|
||||
|
||||
export function getMinVersionStatusMessage(snapshot: RemoteConfigSnapshot): string | null {
|
||||
if (!isExtensionVersionBelowMinimum(snapshot)) return null;
|
||||
const min = snapshot.global.minExtensionVersion;
|
||||
const url = snapshot.global.forceUpdateUrl;
|
||||
const base = `BetterSEQTA+ ${min ?? "a newer version"} or later is required for full features.`;
|
||||
return url ? `${base} Update: ${url}` : base;
|
||||
}
|
||||
|
||||
export function computeEffectiveEnabled(
|
||||
userOnoff: boolean,
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
localOverride: boolean,
|
||||
hostname = typeof location !== "undefined" ? location.hostname : "",
|
||||
): boolean {
|
||||
if (!userOnoff) return false;
|
||||
if (!isHostnameAllowedByPolicy(snapshot, hostname)) {
|
||||
if (snapshot.global.allowLocalOverride === false) return false;
|
||||
return localOverride;
|
||||
}
|
||||
if (snapshot.global.mode !== "off") return true;
|
||||
if (snapshot.global.allowLocalOverride === false) return false;
|
||||
return localOverride;
|
||||
}
|
||||
|
||||
export function getRemoteStatusMessage(snapshot: RemoteConfigSnapshot): string | null {
|
||||
const minMsg = getMinVersionStatusMessage(snapshot);
|
||||
if (minMsg) return minMsg;
|
||||
if (snapshot.global.mode === "off" && snapshot.global.statusMessage) {
|
||||
return snapshot.global.statusMessage;
|
||||
}
|
||||
const maint = snapshot.global.maintenance;
|
||||
if (maint?.body) return maint.body;
|
||||
if (maint?.title) return maint.title;
|
||||
if (
|
||||
!isHostnameAllowedByPolicy(snapshot, typeof location !== "undefined" ? location.hostname : "")
|
||||
) {
|
||||
return "BetterSEQTA+ is not enabled for this SEQTA site.";
|
||||
}
|
||||
return snapshot.global.mode === "off"
|
||||
? "BetterSEQTA+ is temporarily disabled by the site operator."
|
||||
: null;
|
||||
}
|
||||
|
||||
export function resolveFeatureMode(
|
||||
key: string,
|
||||
snapshot: RemoteConfigSnapshot = DEFAULT_REMOTE_CONFIG,
|
||||
hiddenUntilVersion: Record<string, string> = {},
|
||||
): FeatureMode {
|
||||
const gate: RemoteFeatureGate | undefined = snapshot.features[key];
|
||||
if (!gate?.mode || gate.mode === "allow") return "allow";
|
||||
if (gate.mode === "temp_hide") {
|
||||
const pinned = hiddenUntilVersion[key];
|
||||
if (pinned && pinned === snapshot.configVersion) return "hide";
|
||||
return "allow";
|
||||
}
|
||||
return gate.mode;
|
||||
}
|
||||
|
||||
export function isRemoteFeatureAllowed(
|
||||
key: string,
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
hiddenUntilVersion: Record<string, string> = {},
|
||||
): boolean {
|
||||
const mode = resolveFeatureMode(key, snapshot, hiddenUntilVersion);
|
||||
return mode === "allow" || mode === "banner";
|
||||
}
|
||||
|
||||
export function shouldHideFeature(
|
||||
key: string,
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
hiddenUntilVersion: Record<string, string> = {},
|
||||
): boolean {
|
||||
return resolveFeatureMode(key, snapshot, hiddenUntilVersion) === "hide";
|
||||
}
|
||||
|
||||
export function getFeatureMessage(
|
||||
key: string,
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
): RemoteFeatureGate["message"] | undefined {
|
||||
return snapshot.features[key]?.message;
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import {
|
||||
DEFAULT_REMOTE_CONFIG,
|
||||
mergeGithubConfigFiles,
|
||||
normalizeRemoteConfigSnapshot,
|
||||
} from "./normalize";
|
||||
|
||||
describe("normalizeRemoteConfigSnapshot", () => {
|
||||
it("returns defaults for empty input", () => {
|
||||
expect(normalizeRemoteConfigSnapshot(null)).toEqual(DEFAULT_REMOTE_CONFIG);
|
||||
});
|
||||
|
||||
it("unwraps API envelope data", () => {
|
||||
const snap = normalizeRemoteConfigSnapshot({
|
||||
success: true,
|
||||
data: {
|
||||
configVersion: "9",
|
||||
global: { mode: "off", statusMessage: "Maintenance" },
|
||||
},
|
||||
});
|
||||
expect(snap.configVersion).toBe("9");
|
||||
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();
|
||||
});
|
||||
|
||||
it("normalizes applicationMode overlay", () => {
|
||||
const snap = normalizeRemoteConfigSnapshot({
|
||||
remoteTheme: {
|
||||
packageId: "p",
|
||||
packageVersion: "1",
|
||||
mode: "optional",
|
||||
applicationMode: "overlay",
|
||||
},
|
||||
});
|
||||
expect(snap.remoteTheme?.applicationMode).toBe("overlay");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeGithubConfigFiles", () => {
|
||||
it("merges manifest file map into snapshot", () => {
|
||||
const snap = mergeGithubConfigFiles(
|
||||
{ version: "1", updatedAt: "2026-01-01" },
|
||||
{
|
||||
global: { mode: "on" },
|
||||
features: { "page.news": { mode: "hide" } },
|
||||
campaigns: [],
|
||||
},
|
||||
);
|
||||
expect(snap.source).toBe("github");
|
||||
expect(snap.features["page.news"]?.mode).toBe("hide");
|
||||
});
|
||||
});
|
||||
@@ -1,162 +0,0 @@
|
||||
import type {
|
||||
RemoteConfigSnapshot,
|
||||
RemoteFeatureGate,
|
||||
RemoteGlobalConfig,
|
||||
RemoteThemeDirective,
|
||||
} from "./types";
|
||||
|
||||
export const DEFAULT_REMOTE_CONFIG: RemoteConfigSnapshot = {
|
||||
configVersion: "0",
|
||||
source: "default",
|
||||
global: { mode: "on", allowLocalOverride: true },
|
||||
features: {},
|
||||
campaigns: [],
|
||||
remoteTheme: null,
|
||||
};
|
||||
|
||||
function normalizeGlobal(raw: unknown): RemoteGlobalConfig {
|
||||
if (!raw || typeof raw !== "object") return DEFAULT_REMOTE_CONFIG.global;
|
||||
const g = raw as Record<string, unknown>;
|
||||
return {
|
||||
mode: g.mode === "off" ? "off" : "on",
|
||||
allowLocalOverride: g.allowLocalOverride !== false,
|
||||
statusMessage: typeof g.statusMessage === "string" ? g.statusMessage : null,
|
||||
maintenance:
|
||||
g.maintenance && typeof g.maintenance === "object"
|
||||
? (g.maintenance as RemoteGlobalConfig["maintenance"])
|
||||
: null,
|
||||
minExtensionVersion: typeof g.minExtensionVersion === "string" ? g.minExtensionVersion : null,
|
||||
forceUpdateUrl: typeof g.forceUpdateUrl === "string" ? g.forceUpdateUrl : null,
|
||||
disableCloudSync: g.disableCloudSync === true,
|
||||
disableThemeStore: g.disableThemeStore === true,
|
||||
disableFeedbackSubmit: g.disableFeedbackSubmit === true,
|
||||
hostnamePolicy:
|
||||
g.hostnamePolicy && typeof g.hostnamePolicy === "object"
|
||||
? {
|
||||
mode:
|
||||
(g.hostnamePolicy as { mode?: string }).mode === "allowlist" ||
|
||||
(g.hostnamePolicy as { mode?: string }).mode === "denylist"
|
||||
? (g.hostnamePolicy as { mode: "allowlist" | "denylist" }).mode
|
||||
: undefined,
|
||||
suffixes: Array.isArray((g.hostnamePolicy as { suffixes?: unknown }).suffixes)
|
||||
? (g.hostnamePolicy as { suffixes: string[] }).suffixes.filter(
|
||||
(s) => typeof s === "string",
|
||||
)
|
||||
: undefined,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeFeatures(raw: unknown): Record<string, RemoteFeatureGate> {
|
||||
if (!raw || typeof raw !== "object") return {};
|
||||
const out: Record<string, RemoteFeatureGate> = {};
|
||||
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
|
||||
if (!value || typeof value !== "object") continue;
|
||||
const v = value as Record<string, unknown>;
|
||||
const mode = v.mode;
|
||||
if (
|
||||
mode !== "allow" &&
|
||||
mode !== "hide" &&
|
||||
mode !== "banner" &&
|
||||
mode !== "block" &&
|
||||
mode !== "greyout" &&
|
||||
mode !== "temp_hide"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const msg = v.message;
|
||||
out[key] = {
|
||||
mode,
|
||||
message:
|
||||
msg && typeof msg === "object" && typeof (msg as { body?: string }).body === "string"
|
||||
? {
|
||||
title:
|
||||
typeof (msg as { title?: string }).title === "string"
|
||||
? (msg as { title: string }).title
|
||||
: undefined,
|
||||
body: (msg as { body: string }).body,
|
||||
severity:
|
||||
(msg as { severity?: string }).severity === "warning" ||
|
||||
(msg as { severity?: string }).severity === "error" ||
|
||||
(msg as { severity?: string }).severity === "info"
|
||||
? (msg as { severity: "info" | "warning" | "error" }).severity
|
||||
: undefined,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
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,
|
||||
applicationMode: r.applicationMode === "overlay" ? "overlay" : "replace",
|
||||
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>;
|
||||
const data = r.data && typeof r.data === "object" ? (r.data as Record<string, unknown>) : r;
|
||||
return {
|
||||
configVersion: typeof data.configVersion === "string" ? data.configVersion : "0",
|
||||
etag: typeof data.etag === "string" ? data.etag : undefined,
|
||||
source:
|
||||
data.source === "api" ||
|
||||
data.source === "github" ||
|
||||
data.source === "cache" ||
|
||||
data.source === "default"
|
||||
? data.source
|
||||
: "cache",
|
||||
global: normalizeGlobal(data.global),
|
||||
features: normalizeFeatures(data.features),
|
||||
campaigns: Array.isArray(data.campaigns)
|
||||
? (data.campaigns as RemoteConfigSnapshot["campaigns"])
|
||||
: [],
|
||||
remoteTheme: normalizeRemoteTheme(data.remoteTheme),
|
||||
};
|
||||
}
|
||||
|
||||
/** Merge GitHub manifest + partial files into one snapshot. */
|
||||
export function mergeGithubConfigFiles(
|
||||
manifest: Record<string, unknown>,
|
||||
files: Record<string, unknown>,
|
||||
): RemoteConfigSnapshot {
|
||||
return normalizeRemoteConfigSnapshot({
|
||||
configVersion: manifest.configVersion ?? manifest.updatedAt ?? "0",
|
||||
source: "github",
|
||||
global: files.global ?? {},
|
||||
features: files.features ?? {},
|
||||
campaigns: files.campaigns ?? [],
|
||||
remoteTheme: files.remoteTheme ?? null,
|
||||
});
|
||||
}
|
||||
@@ -1,271 +0,0 @@
|
||||
import browser from "@/lib/browser";
|
||||
import localforage from "localforage";
|
||||
import type { CustomTheme } from "@/types/CustomThemes";
|
||||
import {
|
||||
applyLocalSettingsRecord,
|
||||
captureSyncableSettingsSnapshot,
|
||||
} from "@/seqta/utils/cloudSettingsSync";
|
||||
import { settingsState, initializeSettingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { syncThemeToPage } from "@/seqta/utils/patchThemeImagesPageContext";
|
||||
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;
|
||||
layerIds: string[];
|
||||
mode: "optional" | "forced";
|
||||
applicationMode: "replace" | "overlay";
|
||||
};
|
||||
|
||||
type RemotePackage = {
|
||||
theme?: Record<string, unknown>;
|
||||
overlayLayers?: Record<string, unknown>[];
|
||||
downloadUrl?: string;
|
||||
};
|
||||
|
||||
let reconcileChain: Promise<void> = Promise.resolve();
|
||||
|
||||
function directiveKey(snapshot: RemoteConfigSnapshot, d: RemoteThemeDirective): string {
|
||||
return `${snapshot.configVersion}|${d.packageId}|${d.packageVersion}|${d.mode}|${d.applicationMode ?? "replace"}`;
|
||||
}
|
||||
|
||||
function isWithinWindow(d: RemoteThemeDirective, now = Date.now()): boolean {
|
||||
if (d.activeFrom && !Number.isNaN(Date.parse(d.activeFrom)) && now < Date.parse(d.activeFrom)) {
|
||||
return false;
|
||||
}
|
||||
if (d.activeTo && !Number.isNaN(Date.parse(d.activeTo)) && now > Date.parse(d.activeTo)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function resolveEffectiveRemoteTheme(
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
): RemoteThemeDirective | null {
|
||||
const d = snapshot.remoteTheme;
|
||||
if (!d || d.mode === "off" || !isWithinWindow(d)) return null;
|
||||
return d;
|
||||
}
|
||||
|
||||
async function readJson<T>(key: string): Promise<T | null> {
|
||||
const stored = await browser.storage.local.get(key);
|
||||
const raw = stored[key];
|
||||
return raw && typeof raw === "object" ? (raw as T) : null;
|
||||
}
|
||||
|
||||
async function loadBeforeSnapshot(): Promise<BeforeSnapshot | null> {
|
||||
const b = await readJson<BeforeSnapshot>(BSPLUS_REMOTE_THEME_BEFORE_V1_KEY);
|
||||
if (!b?.directiveKey || !b.storage) return null;
|
||||
return b;
|
||||
}
|
||||
|
||||
async function loadActiveState(): Promise<ActiveThemeState | null> {
|
||||
return readJson<ActiveThemeState>(BSPLUS_REMOTE_THEME_STATE_V1_KEY);
|
||||
}
|
||||
|
||||
async function loadUserOffKey(): Promise<string | null> {
|
||||
const raw = await readJson<{ directiveKey?: string }>(BSPLUS_REMOTE_THEME_USER_OFF_KEY);
|
||||
return typeof raw?.directiveKey === "string" ? raw.directiveKey : null;
|
||||
}
|
||||
|
||||
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 clearRemoteThemeOverlay(state?: ActiveThemeState | null): Promise<void> {
|
||||
const active = state ?? (await loadActiveState());
|
||||
await syncThemeToPage({ clearOverlay: true });
|
||||
if (!active?.layerIds?.length) return;
|
||||
const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager");
|
||||
const tm = ThemeManager.getInstance();
|
||||
for (const id of active.layerIds) {
|
||||
await tm.deleteTheme(id).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export async function dismissOptionalRemoteTheme(snapshot: RemoteConfigSnapshot): Promise<void> {
|
||||
const d = resolveEffectiveRemoteTheme(snapshot);
|
||||
if (!d || d.mode !== "optional") return;
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_THEME_USER_OFF_KEY]: { directiveKey: directiveKey(snapshot, d) },
|
||||
});
|
||||
await restoreRemoteThemeSnapshot();
|
||||
}
|
||||
|
||||
async function restoreRemoteThemeSnapshot(): Promise<void> {
|
||||
const state = await loadActiveState();
|
||||
if (state?.applicationMode === "overlay") {
|
||||
await clearRemoteThemeOverlay(state);
|
||||
await clearRemoteThemeLocalState();
|
||||
return;
|
||||
}
|
||||
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<RemotePackage | null> {
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "fetchRemoteThemePackage",
|
||||
packageId,
|
||||
})) as { package?: RemotePackage; error?: string };
|
||||
return res?.package && !res.error ? res.package : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchDownload(url: string): Promise<Record<string, unknown> | null> {
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "fetchRemoteThemePackageUrl",
|
||||
url,
|
||||
})) as { theme?: Record<string, unknown> };
|
||||
return res?.theme && typeof res.theme === "object" ? res.theme : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveLayers(pkg: RemotePackage): Promise<Record<string, unknown>[]> {
|
||||
if (Array.isArray(pkg.overlayLayers) && pkg.overlayLayers.length) {
|
||||
return pkg.overlayLayers.filter((l) => l && typeof l === "object") as Record<string, unknown>[];
|
||||
}
|
||||
if (pkg.theme && typeof pkg.theme === "object") return [pkg.theme];
|
||||
if (!pkg.downloadUrl) return [];
|
||||
const dl = await fetchDownload(pkg.downloadUrl);
|
||||
if (!dl) return [];
|
||||
if (Array.isArray((dl as { overlayLayers?: unknown }).overlayLayers)) {
|
||||
return (dl as { overlayLayers: Record<string, unknown>[] }).overlayLayers;
|
||||
}
|
||||
return [dl];
|
||||
}
|
||||
|
||||
async function saveActiveState(state: ActiveThemeState): Promise<void> {
|
||||
await browser.storage.local.set({ [BSPLUS_REMOTE_THEME_STATE_V1_KEY]: state });
|
||||
await browser.storage.local.remove(BSPLUS_REMOTE_THEME_USER_OFF_KEY);
|
||||
}
|
||||
|
||||
async function applyRemoteTheme(
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
directive: RemoteThemeDirective,
|
||||
): Promise<void> {
|
||||
if (directive.mode === "off") return;
|
||||
const key = directiveKey(snapshot, directive);
|
||||
const prior = await loadActiveState();
|
||||
if (prior?.directiveKey === key) return;
|
||||
|
||||
const overlay = (directive.applicationMode ?? "replace") === "overlay";
|
||||
if (prior?.applicationMode === "overlay") await clearRemoteThemeOverlay(prior);
|
||||
|
||||
const pkg = await fetchPackage(directive.packageId);
|
||||
if (!pkg) return;
|
||||
|
||||
const layers = await resolveLayers(pkg);
|
||||
const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager");
|
||||
const tm = ThemeManager.getInstance();
|
||||
|
||||
if (overlay) {
|
||||
if (!layers.length) return;
|
||||
for (const layer of layers) {
|
||||
if (typeof layer.id !== "string" || !layer.name) continue;
|
||||
await tm.installTheme(layer as Parameters<typeof tm.installTheme>[0], { fromStore: false });
|
||||
}
|
||||
if (settingsState.selectedTheme) await tm.setTheme(settingsState.selectedTheme, false);
|
||||
|
||||
const css: string[] = [];
|
||||
const images = new Map<string, { variableName: string; blob: Blob }>();
|
||||
const layerIds: string[] = [];
|
||||
for (const layer of layers) {
|
||||
if (typeof layer.id === "string") layerIds.push(layer.id);
|
||||
if (typeof layer.CustomCSS === "string") css.push(layer.CustomCSS);
|
||||
const stored =
|
||||
typeof layer.id === "string"
|
||||
? ((await localforage.getItem(layer.id)) as CustomTheme | null)
|
||||
: null;
|
||||
for (const img of stored?.CustomImages ?? []) {
|
||||
if (img.variableName && img.blob) images.set(img.variableName, img);
|
||||
}
|
||||
}
|
||||
await syncThemeToPage({
|
||||
overlayCss: css.join("\n"),
|
||||
overlayImages: [...images.values()],
|
||||
});
|
||||
await saveActiveState({
|
||||
directiveKey: key,
|
||||
layerIds,
|
||||
mode: directive.mode,
|
||||
applicationMode: "overlay",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const theme = layers[0];
|
||||
if (!theme || typeof theme.id !== "string") return;
|
||||
|
||||
await captureBeforeSnapshot(key);
|
||||
await tm.installTheme(theme as Parameters<typeof tm.installTheme>[0], {
|
||||
fromStore: false,
|
||||
forceTheme: directive.mode === "forced",
|
||||
});
|
||||
await tm.setTheme(String(theme.id), false);
|
||||
await saveActiveState({
|
||||
directiveKey: key,
|
||||
layerIds: [String(theme.id)],
|
||||
mode: directive.mode,
|
||||
applicationMode: "replace",
|
||||
});
|
||||
}
|
||||
|
||||
async function captureBeforeSnapshot(directiveKey: string): Promise<void> {
|
||||
const existing = await loadBeforeSnapshot();
|
||||
if (existing?.directiveKey === directiveKey) return;
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_THEME_BEFORE_V1_KEY]: {
|
||||
capturedAt: new Date().toISOString(),
|
||||
directiveKey,
|
||||
storage: await captureSyncableSettingsSnapshot(),
|
||||
selectedTheme: settingsState.selectedTheme ?? "",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function reconcileRemoteThemeInner(snapshot: RemoteConfigSnapshot): Promise<void> {
|
||||
const d = resolveEffectiveRemoteTheme(snapshot);
|
||||
if (!d) {
|
||||
if (await loadActiveState()) await restoreRemoteThemeSnapshot();
|
||||
return;
|
||||
}
|
||||
const key = directiveKey(snapshot, d);
|
||||
if (d.mode === "optional" && (await loadUserOffKey()) === key) return;
|
||||
await applyRemoteTheme(snapshot, d);
|
||||
}
|
||||
|
||||
export function scheduleReconcileRemoteTheme(snapshot: RemoteConfigSnapshot): void {
|
||||
reconcileChain = reconcileChain
|
||||
.then(() => reconcileRemoteThemeInner(snapshot))
|
||||
.catch((e) => console.warn("[BetterSEQTA+] remote theme reconcile failed:", e));
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
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();
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
import { icon } from "@/lib/icon";
|
||||
import { Wrench } from "lucide-static";
|
||||
import browser from "@/lib/browser";
|
||||
import stringToHTML from "@/seqta/utils/stringToHTML";
|
||||
import { addExtensionSettings } from "@/seqta/utils/adders/AddExtensionSettings";
|
||||
import { setupSettingsButton } from "@/seqta/utils/setupSettingsButton";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import {
|
||||
BSPLUS_CAMPAIGN_SEEN_KEY,
|
||||
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
|
||||
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
} from "./storageKeys";
|
||||
import { normalizeRemoteConfigSnapshot } from "./normalize";
|
||||
import type { CampaignSeenRecord, RemoteConfigSnapshot } from "./types";
|
||||
import {
|
||||
computeEffectiveEnabled,
|
||||
getFeatureMessage,
|
||||
isExtensionVersionBelowMinimum,
|
||||
isRemoteFeatureAllowed,
|
||||
resolveFeatureMode,
|
||||
shouldHideFeature,
|
||||
} from "./apply";
|
||||
import { scheduleReconcileRemoteTheme } from "./remoteTheme";
|
||||
|
||||
export { dismissOptionalRemoteTheme, resolveEffectiveRemoteTheme } from "./remoteTheme";
|
||||
|
||||
let snapshot: RemoteConfigSnapshot = normalizeRemoteConfigSnapshot(null);
|
||||
let localOverride = false;
|
||||
let hiddenUntilVersion: Record<string, string> = {};
|
||||
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;
|
||||
}
|
||||
|
||||
export function getHiddenUntilVersion(): Record<string, string> {
|
||||
return hiddenUntilVersion;
|
||||
}
|
||||
|
||||
export function getCampaignSeen(): CampaignSeenRecord {
|
||||
return campaignSeen;
|
||||
}
|
||||
|
||||
export function isEffectiveBsplusEnabled(userOnoff = settingsState.onoff !== false): boolean {
|
||||
return computeEffectiveEnabled(userOnoff, snapshot, localOverride, location.hostname);
|
||||
}
|
||||
|
||||
export function isRemoteKillActive(): boolean {
|
||||
return snapshot.global.mode === "off";
|
||||
}
|
||||
|
||||
export function isRemoteThemeStoreDisabled(): boolean {
|
||||
return snapshot.global.disableThemeStore === true;
|
||||
}
|
||||
|
||||
export function isRemoteFeedbackSubmitDisabled(): boolean {
|
||||
return snapshot.global.disableFeedbackSubmit === true;
|
||||
}
|
||||
|
||||
export async function setLocalOverrideOnoff(enabled: boolean): Promise<void> {
|
||||
localOverride = enabled;
|
||||
await browser.storage.local.set({ [BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY]: enabled });
|
||||
}
|
||||
|
||||
function applyRemoteRuntime(
|
||||
next: RemoteConfigSnapshot,
|
||||
override: boolean,
|
||||
hidden: Record<string, string>,
|
||||
seen: CampaignSeenRecord,
|
||||
): void {
|
||||
snapshot = next;
|
||||
localOverride = override;
|
||||
hiddenUntilVersion = hidden;
|
||||
campaignSeen = seen;
|
||||
pinTempHideVersions(next);
|
||||
}
|
||||
|
||||
function pinTempHideVersions(next: RemoteConfigSnapshot): void {
|
||||
let changed = false;
|
||||
for (const [key, gate] of Object.entries(next.features)) {
|
||||
if (gate.mode === "temp_hide" && hiddenUntilVersion[key] !== next.configVersion) {
|
||||
hiddenUntilVersion = { ...hiddenUntilVersion, [key]: next.configVersion };
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
void browser.storage.local.set({
|
||||
[BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY]: hiddenUntilVersion,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function hydrateRemoteConfigFromStorage(): Promise<RemoteConfigSnapshot> {
|
||||
const stored = await browser.storage.local.get([
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
|
||||
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
|
||||
BSPLUS_CAMPAIGN_SEEN_KEY,
|
||||
]);
|
||||
|
||||
let raw = stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY];
|
||||
if (!raw) {
|
||||
try {
|
||||
const res = (await Promise.race([
|
||||
browser.runtime.sendMessage({ type: "getRemoteConfigSnapshot" }),
|
||||
new Promise<null>((resolve) => setTimeout(() => resolve(null), SNAPSHOT_FETCH_TIMEOUT_MS)),
|
||||
])) as { snapshot?: unknown } | null;
|
||||
if (res?.snapshot) raw = res.snapshot;
|
||||
} catch {
|
||||
// SW unavailable
|
||||
}
|
||||
}
|
||||
|
||||
applyRemoteRuntime(
|
||||
normalizeRemoteConfigSnapshot(raw),
|
||||
stored[BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY] === true,
|
||||
(stored[BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY] as Record<string, string>) ?? {},
|
||||
(stored[BSPLUS_CAMPAIGN_SEEN_KEY] as CampaignSeenRecord) ?? {},
|
||||
);
|
||||
kickRemoteSideEffects();
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export function syncRemoteConfigFromBackend(): void {
|
||||
void browser.runtime.sendMessage({ type: "refreshRemoteConfig" }).catch(() => {});
|
||||
}
|
||||
|
||||
export function notifyRemoteConfigPageContext(hostname: string): void {
|
||||
void browser.storage.local.set({ [BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY]: hostname });
|
||||
void browser.runtime
|
||||
.sendMessage({ type: "setRemoteConfigPageContext", hostname })
|
||||
.catch(() => {});
|
||||
syncRemoteConfigFromBackend();
|
||||
}
|
||||
|
||||
export async function markCampaignSeen(campaignId: string, ack?: boolean): Promise<void> {
|
||||
campaignSeen = {
|
||||
...campaignSeen,
|
||||
[campaignId]: {
|
||||
seenAt: new Date().toISOString(),
|
||||
...(ack === true ? { ack: true } : ack === false ? { ack: false } : {}),
|
||||
},
|
||||
};
|
||||
await browser.storage.local.set({ [BSPLUS_CAMPAIGN_SEEN_KEY]: campaignSeen });
|
||||
}
|
||||
|
||||
const REMOTE_STORAGE_WATCH_KEYS = new Set([
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
|
||||
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
|
||||
]);
|
||||
|
||||
export function installRemoteConfigStorageListener(onEffectiveChange: () => void): void {
|
||||
let priorEnabled = isEffectiveBsplusEnabled();
|
||||
browser.storage.onChanged.addListener((changes, area) => {
|
||||
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;
|
||||
onEffectiveChange();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function checkRemoteFeature(key: string) {
|
||||
const hidden = hiddenUntilVersion;
|
||||
return {
|
||||
mode: resolveFeatureMode(key, snapshot, hidden),
|
||||
allowed: isRemoteFeatureAllowed(key, snapshot, hidden),
|
||||
hide: shouldHideFeature(key, snapshot, hidden),
|
||||
message: getFeatureMessage(key, snapshot),
|
||||
};
|
||||
}
|
||||
|
||||
export function isRemoteSettingsSectionVisible(sectionId: string): boolean {
|
||||
const key = sectionId === "account" ? "settings.nav.cloud" : `settings.section.${sectionId}`;
|
||||
return !checkRemoteFeature(key).hide;
|
||||
}
|
||||
|
||||
export function isRemotePluginStartAllowed(pluginId: string): boolean {
|
||||
const remote = checkRemoteFeature(`plugin.${pluginId}`);
|
||||
if (remote.hide || remote.mode === "greyout" || remote.mode === "block") return false;
|
||||
if (isExtensionVersionBelowMinimum(snapshot)) return false;
|
||||
return remote.allowed;
|
||||
}
|
||||
|
||||
/** Returns true when navigation should stop (hide or block). */
|
||||
export function applyPageFeatureGateEarly(page: string): boolean {
|
||||
const gate = checkRemoteFeature(`page.${page}`);
|
||||
if (gate.hide) return true;
|
||||
if (gate.mode !== "block") return false;
|
||||
|
||||
const main = document.getElementById("main");
|
||||
if (main) {
|
||||
const title = gate.message?.title ?? "Page unavailable";
|
||||
const body = gate.message?.body ?? "This BetterSEQTA+ page is temporarily unavailable.";
|
||||
main.innerHTML = "";
|
||||
main.append(
|
||||
stringToHTML(
|
||||
/* html */ `<div class="home-root"><div class="home-container"><h1 class="bsplus-rounded">${title}</h1><p>${body}</p></div></div>`,
|
||||
).firstChild!,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function injectPageFeatureBanner(page: string, containerSelector: string): void {
|
||||
const gate = checkRemoteFeature(`page.${page}`);
|
||||
if (gate.mode !== "banner" || !gate.message?.body) return;
|
||||
const container = document.querySelector(containerSelector);
|
||||
if (!container || container.querySelector(`[data-bsplus-page-banner="${page}"]`)) return;
|
||||
|
||||
const severity = gate.message.severity ?? "info";
|
||||
container.insertBefore(
|
||||
stringToHTML(/* html */ `
|
||||
<div data-bsplus-page-banner="${page}" class="bsplus-remote-page-banner bsplus-remote-page-banner--${severity} mb-4 rounded-lg border px-4 py-3 text-sm">
|
||||
${gate.message.title ? `<p class="font-semibold mb-1">${gate.message.title}</p>` : ""}
|
||||
<p>${gate.message.body}</p>
|
||||
</div>
|
||||
`).firstChild!,
|
||||
container.firstChild,
|
||||
);
|
||||
}
|
||||
|
||||
/** Remote kill path: settings popup + toolbar cog without monofile. */
|
||||
export async function ensureKilledModeSettingsAccess(): Promise<void> {
|
||||
addExtensionSettings();
|
||||
if (document.getElementById("AddedSettings")) {
|
||||
setupSettingsButton();
|
||||
return;
|
||||
}
|
||||
|
||||
const fallback =
|
||||
document.getElementById("content") ?? document.getElementById("container") ?? document.body;
|
||||
|
||||
const mountParent = async (): Promise<Element> => {
|
||||
if (isSeqtaEngageExperience()) {
|
||||
try {
|
||||
const el = await waitForElm(
|
||||
"#content > div.connectedNotificationsWrapper > div",
|
||||
true,
|
||||
100,
|
||||
40,
|
||||
);
|
||||
return el.parentElement ?? el;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await waitForElm(
|
||||
"#content > div.connectedNotificationsWrapper",
|
||||
true,
|
||||
isPerformanceMode() ? 120 : 80,
|
||||
50,
|
||||
);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
mountParent().then((parent) => {
|
||||
if (document.getElementById("AddedSettings")) return;
|
||||
parent.append(
|
||||
stringToHTML(/* html */ `
|
||||
<button class="addedButton" id="AddedSettings" type="button" aria-label="BetterSEQTA+ settings">
|
||||
${icon(Wrench)}
|
||||
</button>
|
||||
`).firstChild!,
|
||||
);
|
||||
setupSettingsButton();
|
||||
});
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
export const BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY = "bsplus_remote_config_snapshot";
|
||||
export const BSPLUS_REMOTE_CONFIG_ETAG_KEY = "bsplus_remote_config_etag";
|
||||
export const BSPLUS_CAMPAIGN_SEEN_KEY = "bsplus_campaign_seen";
|
||||
export const BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY = "bsplus_local_override_onoff";
|
||||
export const BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY = "bsplus_features_hidden_until_version";
|
||||
export const BSPLUS_INSTALL_REGISTERED_AT_KEY = "bsplus_install_registered_at";
|
||||
export const BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY = "bsplus_remote_config_fetched_at";
|
||||
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;
|
||||
|
||||
export const BS_STATUS_MANIFEST_URL =
|
||||
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/manifest.json";
|
||||
@@ -1,70 +0,0 @@
|
||||
export type FeatureMode = "allow" | "hide" | "banner" | "block" | "greyout" | "temp_hide";
|
||||
|
||||
export type RemoteFeatureGate = {
|
||||
mode?: FeatureMode;
|
||||
message?: { title?: string; body?: string; severity?: "info" | "warning" | "error" };
|
||||
};
|
||||
|
||||
export type RemoteGlobalConfig = {
|
||||
mode?: "on" | "off";
|
||||
allowLocalOverride?: boolean;
|
||||
statusMessage?: string | null;
|
||||
maintenance?: { title?: string; body?: string } | null;
|
||||
minExtensionVersion?: string | null;
|
||||
forceUpdateUrl?: string | null;
|
||||
disableCloudSync?: boolean;
|
||||
disableThemeStore?: boolean;
|
||||
disableFeedbackSubmit?: boolean;
|
||||
hostnamePolicy?: {
|
||||
mode?: "allowlist" | "denylist";
|
||||
suffixes?: string[];
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type RemoteCampaignButton = {
|
||||
id: string;
|
||||
label: string;
|
||||
action: "dismiss" | "url" | "openSettingsSection";
|
||||
url?: string;
|
||||
section?: string;
|
||||
};
|
||||
|
||||
export type RemoteCampaign = {
|
||||
id: string;
|
||||
priority?: number;
|
||||
activeFrom?: string;
|
||||
activeTo?: string;
|
||||
header?: { title?: string; subtitle?: string };
|
||||
hero?: { type?: "image" | "video"; url?: string; alt?: string };
|
||||
bodyHtml?: string;
|
||||
buttons?: RemoteCampaignButton[];
|
||||
requireAcknowledge?: boolean;
|
||||
minVersion?: string;
|
||||
maxVersion?: string;
|
||||
};
|
||||
|
||||
export type RemoteThemeMode = "off" | "optional" | "forced";
|
||||
export type RemoteThemeApplicationMode = "replace" | "overlay";
|
||||
|
||||
export type RemoteThemeDirective = {
|
||||
packageId: string;
|
||||
packageVersion: string;
|
||||
mode: RemoteThemeMode;
|
||||
applicationMode?: RemoteThemeApplicationMode;
|
||||
activeFrom?: string;
|
||||
activeTo?: string;
|
||||
message?: { title?: string; body?: string };
|
||||
allowUserOptOut?: boolean;
|
||||
};
|
||||
|
||||
export type RemoteConfigSnapshot = {
|
||||
configVersion: string;
|
||||
etag?: string;
|
||||
source?: "api" | "github" | "default" | "cache";
|
||||
global: RemoteGlobalConfig;
|
||||
features: Record<string, RemoteFeatureGate>;
|
||||
campaigns: RemoteCampaign[];
|
||||
remoteTheme?: RemoteThemeDirective | null;
|
||||
};
|
||||
|
||||
export type CampaignSeenRecord = Record<string, { seenAt: string; ack?: boolean }>;
|
||||
@@ -0,0 +1,27 @@
|
||||
import { normalizeRemoteStatus } from "./remoteStatus";
|
||||
|
||||
describe("normalizeRemoteStatus", () => {
|
||||
it("falls back to working defaults for missing or malformed data", () => {
|
||||
const defaults = { off: false, message: null, disabledFeatures: [], sites: {} };
|
||||
expect(normalizeRemoteStatus(null)).toEqual(defaults);
|
||||
expect(
|
||||
normalizeRemoteStatus({ off: "yes", message: 4, disabledFeatures: "page.news" }),
|
||||
).toEqual(defaults);
|
||||
});
|
||||
|
||||
it("keeps valid fields and drops non-string feature keys", () => {
|
||||
expect(
|
||||
normalizeRemoteStatus({
|
||||
off: true,
|
||||
message: "Back soon",
|
||||
disabledFeatures: ["page.news", 1],
|
||||
sites: { "Learn.School.edu.au": ["plugin.timetable-classmates", 2] },
|
||||
}),
|
||||
).toEqual({
|
||||
off: true,
|
||||
message: "Back soon",
|
||||
disabledFeatures: ["page.news"],
|
||||
sites: { "learn.school.edu.au": ["plugin.timetable-classmates"] },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import browser from "@/lib/browser";
|
||||
|
||||
export type RemoteStatus = {
|
||||
off: boolean;
|
||||
message: string | null;
|
||||
disabledFeatures: string[];
|
||||
sites: Record<string, string[]>;
|
||||
};
|
||||
|
||||
const STATUS_URL =
|
||||
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/status.json";
|
||||
export const REMOTE_STATUS_KEY = "bsplus_remote_status";
|
||||
const PAUSE_CHOICE_KEY = "bsplus_pause_choice";
|
||||
|
||||
type PauseChoice = { message: string; runAnyway: boolean };
|
||||
|
||||
function stringList(value: unknown): string[] {
|
||||
return Array.isArray(value) ? value.filter((key): key is string => typeof key === "string") : [];
|
||||
}
|
||||
|
||||
export function normalizeRemoteStatus(raw: unknown): RemoteStatus {
|
||||
const r = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
|
||||
const sites = r.sites && typeof r.sites === "object" ? r.sites : {};
|
||||
return {
|
||||
off: r.off === true,
|
||||
message: typeof r.message === "string" && r.message.trim() ? r.message : null,
|
||||
disabledFeatures: stringList(r.disabledFeatures),
|
||||
sites: Object.fromEntries(
|
||||
Object.entries(sites).map(([host, keys]) => [host.toLowerCase(), stringList(keys)]),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export async function readRemoteStatus(): Promise<RemoteStatus> {
|
||||
const stored = await browser.storage.local.get(REMOTE_STATUS_KEY);
|
||||
return normalizeRemoteStatus(stored[REMOTE_STATUS_KEY]);
|
||||
}
|
||||
|
||||
let status = normalizeRemoteStatus(null);
|
||||
let pauseChoice: PauseChoice | null = null;
|
||||
|
||||
export const pauseMessage = (): string => status.message ?? "BetterSEQTA+ is paused for now.";
|
||||
|
||||
export const getRemoteStatus = (): RemoteStatus => status;
|
||||
|
||||
export const isFeatureDisabled = (key: string): boolean =>
|
||||
status.disabledFeatures.includes(key) ||
|
||||
!!status.sites[location.hostname.toLowerCase()]?.includes(key);
|
||||
|
||||
const currentPauseChoice = (): PauseChoice | null =>
|
||||
status.off && pauseChoice?.message === pauseMessage() ? pauseChoice : null;
|
||||
|
||||
export const isPaused = (): boolean => status.off && !currentPauseChoice()?.runAnyway;
|
||||
|
||||
export const hasSeenPause = (): boolean => currentPauseChoice() !== null;
|
||||
|
||||
export async function choosePause(runAnyway: boolean): Promise<void> {
|
||||
pauseChoice = { message: pauseMessage(), runAnyway };
|
||||
await browser.storage.local.set({ [PAUSE_CHOICE_KEY]: pauseChoice });
|
||||
}
|
||||
|
||||
export async function loadRemoteStatus(): Promise<void> {
|
||||
status = await readRemoteStatus();
|
||||
const stored = await browser.storage.local.get(PAUSE_CHOICE_KEY);
|
||||
pauseChoice = (stored[PAUSE_CHOICE_KEY] as PauseChoice | undefined) ?? null;
|
||||
}
|
||||
|
||||
export async function refreshRemoteStatus(): Promise<void> {
|
||||
const res = await browser.runtime
|
||||
.sendMessage({ type: "fetchFromUrl", url: STATUS_URL })
|
||||
.catch(() => null);
|
||||
if (!res?.data && res?.httpStatus !== 404) return;
|
||||
await browser.storage.local.set({ [REMOTE_STATUS_KEY]: normalizeRemoteStatus(res.data) });
|
||||
}
|
||||
@@ -5,13 +5,19 @@
|
||||
import stringToHTML from "./stringToHTML";
|
||||
|
||||
describe("stringToHTML", () => {
|
||||
it("preserves inline onclick handlers used by lesson action buttons", () => {
|
||||
it("strips inline onclick handlers and keeps data-href", () => {
|
||||
const body = stringToHTML(
|
||||
`<div class="day-button clickable" onclick="location.href='../#?page=/courses/123:456'">Go</div>`,
|
||||
`<div class="day-button clickable" data-href="../#?page=/courses/123:456" onclick="location.href='x'">Go</div>`,
|
||||
);
|
||||
|
||||
const el = body.firstElementChild as HTMLElement | null;
|
||||
expect(el).not.toBeNull();
|
||||
expect(el?.getAttribute("onclick")).toContain("location.href");
|
||||
expect(el?.hasAttribute("onclick")).toBe(false);
|
||||
expect(el?.dataset.href).toBe("../#?page=/courses/123:456");
|
||||
});
|
||||
|
||||
it("strips javascript: URLs", () => {
|
||||
const body = stringToHTML(`<a href="javascript:alert(1)">x</a>`);
|
||||
expect(body.querySelector("a")?.getAttribute("href")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,6 @@ export default function stringToHTML(str: string, styles = false) {
|
||||
const parser = new DOMParser();
|
||||
|
||||
str = DOMPurify.sanitize(str, {
|
||||
ADD_ATTR: ["onclick"],
|
||||
ALLOWED_URI_REGEXP:
|
||||
/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|chrome-extension):|\/|#|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
|
||||
});
|
||||
|
||||
@@ -6,10 +6,7 @@ const PAYLOAD_ID = "bsplus-theme-image-payload";
|
||||
const IMAGES_STYLE_ID = "bsplus-theme-images";
|
||||
const THEME_STYLE_ID = "custom-theme";
|
||||
const PREVIEW_STYLE_ID = "custom-theme-preview";
|
||||
const OVERLAY_STYLE_ID = "bsplus-remote-theme-overlay";
|
||||
const OVERLAY_IMAGES_STYLE_ID = "bsplus-remote-theme-overlay-images";
|
||||
const urlCache = new Set();
|
||||
const overlayUrlCache = new Set();
|
||||
let headObserver = null;
|
||||
|
||||
function log(event, detail) {
|
||||
@@ -32,13 +29,6 @@ function styleEl(id) {
|
||||
return el;
|
||||
}
|
||||
|
||||
function keepOverlayStylesLast() {
|
||||
for (const id of [OVERLAY_IMAGES_STYLE_ID, OVERLAY_STYLE_ID]) {
|
||||
const el = document.getElementById(id);
|
||||
if (el && document.head.contains(el)) document.head.appendChild(el);
|
||||
}
|
||||
}
|
||||
|
||||
function keepThemeStyleLast() {
|
||||
const themeStyle = document.getElementById(THEME_STYLE_ID);
|
||||
if (
|
||||
@@ -48,7 +38,6 @@ function keepThemeStyleLast() {
|
||||
) {
|
||||
document.head.appendChild(themeStyle);
|
||||
}
|
||||
keepOverlayStylesLast();
|
||||
}
|
||||
|
||||
function watchHead() {
|
||||
@@ -69,10 +58,10 @@ function setStyleText(id, text, watchThemeOrder) {
|
||||
}
|
||||
}
|
||||
|
||||
function applyRootImages(images, styleId, cache, afterApply) {
|
||||
releaseCache(cache);
|
||||
function applyThemeImages(images) {
|
||||
releaseCache(urlCache);
|
||||
if (!images?.length) {
|
||||
document.getElementById(styleId)?.remove();
|
||||
setStyleText(IMAGES_STYLE_ID, "");
|
||||
return;
|
||||
}
|
||||
const lines = [":root {"];
|
||||
@@ -80,23 +69,15 @@ function applyRootImages(images, styleId, cache, afterApply) {
|
||||
if (!img?.variableName || !img.data) continue;
|
||||
try {
|
||||
const url = URL.createObjectURL(base64ToBlob(img.data, img.mime || "image/png"));
|
||||
cache.add(url);
|
||||
urlCache.add(url);
|
||||
lines.push(` --${img.variableName}: url("${url}");`);
|
||||
} catch (e) {
|
||||
console.warn(LOG, "skip image", img.variableName, e);
|
||||
}
|
||||
}
|
||||
lines.push("}");
|
||||
styleEl(styleId).textContent = lines.join("\n");
|
||||
afterApply?.();
|
||||
log("images applied", { styleId, count: images.length });
|
||||
}
|
||||
|
||||
function clearOverlayOnly() {
|
||||
releaseCache(overlayUrlCache);
|
||||
document.getElementById(OVERLAY_STYLE_ID)?.remove();
|
||||
document.getElementById(OVERLAY_IMAGES_STYLE_ID)?.remove();
|
||||
log("overlay cleared");
|
||||
styleEl(IMAGES_STYLE_ID).textContent = lines.join("\n");
|
||||
log("images applied", { count: images.length });
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
@@ -122,31 +103,12 @@ function processPayload() {
|
||||
clearAll();
|
||||
return;
|
||||
}
|
||||
if (payload.clearOverlay) {
|
||||
clearOverlayOnly();
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.images !== undefined) {
|
||||
applyRootImages(payload.images, IMAGES_STYLE_ID, urlCache);
|
||||
}
|
||||
if (payload.images !== undefined) applyThemeImages(payload.images);
|
||||
if (payload.customCss !== undefined) {
|
||||
setStyleText(THEME_STYLE_ID, payload.customCss || "", true);
|
||||
log("custom css applied");
|
||||
}
|
||||
if (payload.overlayImages !== undefined) {
|
||||
applyRootImages(
|
||||
payload.overlayImages,
|
||||
OVERLAY_IMAGES_STYLE_ID,
|
||||
overlayUrlCache,
|
||||
keepOverlayStylesLast,
|
||||
);
|
||||
}
|
||||
if (payload.overlayCss !== undefined) {
|
||||
setStyleText(OVERLAY_STYLE_ID, payload.overlayCss || "", false);
|
||||
keepOverlayStylesLast();
|
||||
log("overlay css applied");
|
||||
}
|
||||
if (payload.previewCss !== undefined) {
|
||||
setStyleText(PREVIEW_STYLE_ID, payload.previewCss || "");
|
||||
const previewStyle = document.getElementById(PREVIEW_STYLE_ID);
|
||||
|
||||
@@ -133,6 +133,9 @@ export default defineConfig(({ command, mode: viteMode }) => {
|
||||
},
|
||||
output: {
|
||||
assetFileNames: "assets/[name]-[hash][extname]",
|
||||
// Extension packages are versioned; stable chunk names keep source rebuilds identical.
|
||||
entryFileNames: "assets/[name].js",
|
||||
chunkFileNames: "assets/[name].js",
|
||||
manualChunks(id) {
|
||||
const normalized = id.replace(/\\/g, "/");
|
||||
// Keep the Svelte mount helper out of the settings entry chunk so
|
||||
|
||||
Reference in new issue
Block a user