mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fde375ecf2 |
No files matched your search
@@ -108,6 +108,7 @@
|
|||||||
"semver": "^7.7.1",
|
"semver": "^7.7.1",
|
||||||
"sortablejs": "^1.15.6",
|
"sortablejs": "^1.15.6",
|
||||||
"svelte": "^5.46.4",
|
"svelte": "^5.46.4",
|
||||||
|
"svelte-hero-icons": "^5.2.0",
|
||||||
"webextension-polyfill": "^0.12.0"
|
"webextension-polyfill": "^0.12.0"
|
||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ import {
|
|||||||
registerGoogleCalendarMessageHandlers,
|
registerGoogleCalendarMessageHandlers,
|
||||||
registerOutlookCalendarMessageHandlers,
|
registerOutlookCalendarMessageHandlers,
|
||||||
} from "./background/calendarBackground";
|
} from "./background/calendarBackground";
|
||||||
|
import {
|
||||||
|
handleAiModCreatorMessage,
|
||||||
|
registerAiModCreatorStreaming,
|
||||||
|
} from "./background/aiModCreator";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Session-only dev-mode override of the content API base.
|
* Session-only dev-mode override of the content API base.
|
||||||
@@ -525,6 +529,13 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
|||||||
cloudFavorite: handleCloudFavorite,
|
cloudFavorite: handleCloudFavorite,
|
||||||
cloudSettingsUpload: handleCloudSettingsUpload,
|
cloudSettingsUpload: handleCloudSettingsUpload,
|
||||||
cloudSettingsDownload: handleCloudSettingsDownload,
|
cloudSettingsDownload: handleCloudSettingsDownload,
|
||||||
|
aiModCreator: (request, sendResponse, sender) =>
|
||||||
|
handleAiModCreatorMessage(
|
||||||
|
request,
|
||||||
|
sender ?? {},
|
||||||
|
sendResponse,
|
||||||
|
isTrustedSender,
|
||||||
|
),
|
||||||
cloudSettingsPoll: () => {
|
cloudSettingsPoll: () => {
|
||||||
void runCloudSettingsPoll();
|
void runCloudSettingsPoll();
|
||||||
return false;
|
return false;
|
||||||
@@ -573,6 +584,7 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
|||||||
|
|
||||||
registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
||||||
registerOutlookCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
registerOutlookCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
||||||
|
registerAiModCreatorStreaming(isTrustedSender);
|
||||||
initCalendarBackground();
|
initCalendarBackground();
|
||||||
|
|
||||||
browser.runtime.onMessage.addListener(
|
browser.runtime.onMessage.addListener(
|
||||||
|
|||||||
@@ -0,0 +1,292 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import {
|
||||||
|
AI_MOD_CREATOR_MESSAGE_TYPE,
|
||||||
|
createAiModCreatorService,
|
||||||
|
formatOpenRouterError,
|
||||||
|
handleAiModCreatorMessage,
|
||||||
|
} from "./aiModCreator";
|
||||||
|
import type { SelectedElementContext } from "@/plugins/built-in/aiModCreator/types";
|
||||||
|
|
||||||
|
const context: SelectedElementContext = {
|
||||||
|
route: "assessments",
|
||||||
|
rootSelector: "#selected",
|
||||||
|
request: "Round this card",
|
||||||
|
userContext: "Assessment summary",
|
||||||
|
selectedHtml: '<section id="selected">Assessment</section>',
|
||||||
|
domCatalog: [
|
||||||
|
{
|
||||||
|
selector: ":scope",
|
||||||
|
tag: "section",
|
||||||
|
classes: [],
|
||||||
|
parentSelector: null,
|
||||||
|
siblingIndex: 0,
|
||||||
|
siblingCount: 1,
|
||||||
|
layout: { display: "block" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
tagName: "section",
|
||||||
|
dimensions: { width: 400, height: 200 },
|
||||||
|
computedStyle: { color: "rgb(0, 0, 0)" },
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("AI mod OpenRouter background service", () => {
|
||||||
|
it("stores the key locally and reports only whether it exists", async () => {
|
||||||
|
const service = createAiModCreatorService({
|
||||||
|
fetchImpl: jest.fn(),
|
||||||
|
now: () => 1_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.saveKey(" sk-or-v1-test-key-123456 ");
|
||||||
|
await expect(service.getKeyStatus()).resolves.toEqual({ configured: true });
|
||||||
|
expect(await browser.storage.local.get("aiModCreator.openRouterApiKey")).toEqual({
|
||||||
|
"aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456",
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.clearKey();
|
||||||
|
await expect(service.getKeyStatus()).resolves.toEqual({ configured: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calls the free model with json_object output and provider fallbacks", async () => {
|
||||||
|
await browser.storage.local.set({
|
||||||
|
"aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456",
|
||||||
|
});
|
||||||
|
const fetchImpl = jest.fn(async (_url: string, init?: RequestInit) => {
|
||||||
|
const body = JSON.parse(String(init?.body));
|
||||||
|
expect(body).toMatchObject({
|
||||||
|
model: "minimax/minimax-m2.7:free",
|
||||||
|
provider: { allow_fallbacks: true },
|
||||||
|
response_format: { type: "json_object" },
|
||||||
|
});
|
||||||
|
expect(init?.headers).toMatchObject({
|
||||||
|
Authorization: "Bearer sk-or-v1-test-key-123456",
|
||||||
|
});
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
message: {
|
||||||
|
content: JSON.stringify({
|
||||||
|
name: "Rounded card",
|
||||||
|
description: "Rounds the selected card.",
|
||||||
|
operations: [
|
||||||
|
{
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope",
|
||||||
|
property: "border-radius",
|
||||||
|
value: "12px",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
{ status: 200 },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
const service = createAiModCreatorService({
|
||||||
|
fetchImpl,
|
||||||
|
now: () => 10_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(service.generate(context)).resolves.toMatchObject({
|
||||||
|
name: "Rounded card",
|
||||||
|
operations: [{ type: "setStyle", property: "border-radius" }],
|
||||||
|
});
|
||||||
|
expect(fetchImpl).toHaveBeenCalledWith(
|
||||||
|
"https://openrouter.ai/api/v1/chat/completions",
|
||||||
|
expect.objectContaining({ method: "POST" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retries without structured output when OpenRouter routing fails", async () => {
|
||||||
|
await browser.storage.local.set({
|
||||||
|
"aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456",
|
||||||
|
});
|
||||||
|
const fetchImpl = jest
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: {
|
||||||
|
message:
|
||||||
|
"No endpoints found that can handle the requested parameters.",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
{ status: 404 },
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
message: {
|
||||||
|
content: JSON.stringify({
|
||||||
|
name: "Fallback mod",
|
||||||
|
description: "Generated without structured output.",
|
||||||
|
operations: [{ type: "hide", selector: ":scope .meta" }],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
{ status: 200 },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const service = createAiModCreatorService({
|
||||||
|
fetchImpl,
|
||||||
|
now: () => 10_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(service.generate(context)).resolves.toMatchObject({
|
||||||
|
name: "Fallback mod",
|
||||||
|
});
|
||||||
|
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||||
|
const firstBody = JSON.parse(String(fetchImpl.mock.calls[0][1]?.body));
|
||||||
|
const secondBody = JSON.parse(String(fetchImpl.mock.calls[1][1]?.body));
|
||||||
|
expect(firstBody.response_format).toEqual({ type: "json_object" });
|
||||||
|
expect(secondBody.response_format).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("streams partial recipe content and token usage", async () => {
|
||||||
|
await browser.storage.local.set({
|
||||||
|
"aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456",
|
||||||
|
});
|
||||||
|
const json = JSON.stringify({
|
||||||
|
name: "Streamed mod",
|
||||||
|
description: "Generated incrementally",
|
||||||
|
operations: [{ type: "hide", selector: ":scope .metadata" }],
|
||||||
|
});
|
||||||
|
const first = json.slice(0, 35);
|
||||||
|
const second = json.slice(35);
|
||||||
|
const streamBody = [
|
||||||
|
`data: ${JSON.stringify({ choices: [{ delta: { reasoning_details: [{}] } }] })}\n\n`,
|
||||||
|
`data: ${JSON.stringify({ choices: [{ delta: { content: first } }] })}\n\n`,
|
||||||
|
`data: ${JSON.stringify({ choices: [{ delta: { content: second } }], usage: { prompt_tokens: 20, completion_tokens: 30 } })}\n\n`,
|
||||||
|
"data: [DONE]\n\n",
|
||||||
|
].join("");
|
||||||
|
const service = createAiModCreatorService({
|
||||||
|
fetchImpl: jest.fn(async () =>
|
||||||
|
new Response(streamBody, {
|
||||||
|
status: 200,
|
||||||
|
headers: { "Content-Type": "text/event-stream" },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
now: () => 20_000,
|
||||||
|
});
|
||||||
|
const progress: unknown[] = [];
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.streamGenerate(context, (update) => progress.push(update)),
|
||||||
|
).resolves.toMatchObject({ name: "Streamed mod" });
|
||||||
|
expect(progress).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
{ type: "status", text: "Connecting to MiniMax M2.7 (free)…" },
|
||||||
|
{ type: "status", text: "Model is reasoning…" },
|
||||||
|
{ type: "content", text: first },
|
||||||
|
{
|
||||||
|
type: "usage",
|
||||||
|
promptTokens: 20,
|
||||||
|
completionTokens: 30,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("surfaces stream rate-limit errors with actionable guidance", async () => {
|
||||||
|
await browser.storage.local.set({
|
||||||
|
"aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456",
|
||||||
|
});
|
||||||
|
const streamBody = [
|
||||||
|
": OPENROUTER PROCESSING\n\n",
|
||||||
|
`data: ${JSON.stringify({
|
||||||
|
error: {
|
||||||
|
code: 429,
|
||||||
|
message: "Provider returned error",
|
||||||
|
metadata: { error_type: "rate_limit_exceeded" },
|
||||||
|
},
|
||||||
|
})}\n\n`,
|
||||||
|
].join("");
|
||||||
|
const service = createAiModCreatorService({
|
||||||
|
fetchImpl: jest.fn(async () =>
|
||||||
|
new Response(streamBody, {
|
||||||
|
status: 200,
|
||||||
|
headers: { "Content-Type": "text/event-stream" },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
now: () => 20_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(service.streamGenerate(context, () => {})).rejects.toThrow(
|
||||||
|
/Rate limit reached for MiniMax M2\.7 \(free\)/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("formats free-tier rate-limit guidance", () => {
|
||||||
|
expect(
|
||||||
|
formatOpenRouterError(
|
||||||
|
{
|
||||||
|
code: 429,
|
||||||
|
message: "Provider returned error",
|
||||||
|
metadata: { error_type: "rate_limit_exceeded" },
|
||||||
|
},
|
||||||
|
"minimax/minimax-m2.7:free",
|
||||||
|
),
|
||||||
|
).toMatch(/switch model/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects missing keys, oversized input, throttling, and provider errors", async () => {
|
||||||
|
const service = createAiModCreatorService({
|
||||||
|
fetchImpl: jest.fn(),
|
||||||
|
now: () => 1_000,
|
||||||
|
});
|
||||||
|
await expect(service.generate(context)).rejects.toThrow("API key");
|
||||||
|
|
||||||
|
await service.saveKey("sk-or-v1-test-key-123456");
|
||||||
|
await expect(
|
||||||
|
service.generate({ ...context, request: "x".repeat(2_001) }),
|
||||||
|
).rejects.toThrow("too long");
|
||||||
|
|
||||||
|
const failingService = createAiModCreatorService({
|
||||||
|
fetchImpl: jest.fn(async () =>
|
||||||
|
new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: {
|
||||||
|
message: "Free model rate limit reached",
|
||||||
|
code: 429,
|
||||||
|
metadata: { error_type: "rate_limit_exceeded" },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
{ status: 429 },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
now: () => 10_000,
|
||||||
|
});
|
||||||
|
await expect(failingService.generate(context)).rejects.toThrow(
|
||||||
|
/Rate limit reached for MiniMax M2\.7 \(free\)/,
|
||||||
|
);
|
||||||
|
await expect(failingService.generate(context)).rejects.toThrow(
|
||||||
|
/Please wait \d+s/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects untrusted runtime message senders", () => {
|
||||||
|
const sendResponse = jest.fn();
|
||||||
|
const handled = handleAiModCreatorMessage(
|
||||||
|
{
|
||||||
|
type: AI_MOD_CREATOR_MESSAGE_TYPE,
|
||||||
|
action: "status",
|
||||||
|
},
|
||||||
|
{ id: "another-extension" } as browser.Runtime.MessageSender,
|
||||||
|
sendResponse,
|
||||||
|
() => false,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(handled).toBe(false);
|
||||||
|
expect(sendResponse).toHaveBeenCalledWith({
|
||||||
|
success: false,
|
||||||
|
error: "Unauthorized sender",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,738 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import {
|
||||||
|
buildAiModMessages,
|
||||||
|
} from "@/plugins/built-in/aiModCreator/prompt";
|
||||||
|
import {
|
||||||
|
formatRecipeValidationError,
|
||||||
|
parseGeneratedModDraft,
|
||||||
|
} from "@/plugins/built-in/aiModCreator/recipeSchema";
|
||||||
|
import { aiModLog } from "@/plugins/built-in/aiModCreator/logger";
|
||||||
|
import {
|
||||||
|
DEFAULT_OPENROUTER_MODEL_ID,
|
||||||
|
getModelOption,
|
||||||
|
validateModelId,
|
||||||
|
} from "@/plugins/built-in/aiModCreator/models";
|
||||||
|
import {
|
||||||
|
OPENROUTER_API_KEY_STORAGE_KEY,
|
||||||
|
OPENROUTER_MODEL_STORAGE_KEY,
|
||||||
|
} from "@/plugins/built-in/aiModCreator/storage";
|
||||||
|
import {
|
||||||
|
executeAdvancedMod,
|
||||||
|
getAdvancedScriptSupport,
|
||||||
|
stopAdvancedMod,
|
||||||
|
} from "./aiModUserScripts";
|
||||||
|
import type {
|
||||||
|
GenerationProgress,
|
||||||
|
GeneratedModDraft,
|
||||||
|
KeyStatus,
|
||||||
|
SelectedElementContext,
|
||||||
|
StoredModRecipe,
|
||||||
|
} from "@/plugins/built-in/aiModCreator/types";
|
||||||
|
|
||||||
|
export const AI_MOD_CREATOR_MESSAGE_TYPE = "aiModCreator";
|
||||||
|
export const OPENROUTER_MODEL_ID = DEFAULT_OPENROUTER_MODEL_ID;
|
||||||
|
const OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";
|
||||||
|
const MIN_GENERATION_INTERVAL_MS = 5_000;
|
||||||
|
const ROUTING_ERROR_PATTERN =
|
||||||
|
/no endpoints found|can handle the requested parameters/i;
|
||||||
|
|
||||||
|
type ResponseFormatMode = "json_object" | "none";
|
||||||
|
|
||||||
|
type StorageArea = Pick<
|
||||||
|
browser.Storage.StorageArea,
|
||||||
|
"get" | "set" | "remove"
|
||||||
|
>;
|
||||||
|
type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
||||||
|
type SendResponse = (response: unknown) => void;
|
||||||
|
type TrustCheck = (sender?: browser.Runtime.MessageSender) => boolean;
|
||||||
|
|
||||||
|
function validateApiKey(value: unknown): string {
|
||||||
|
if (typeof value !== "string") throw new Error("API key is required");
|
||||||
|
const key = value.trim();
|
||||||
|
if (key.length < 16 || key.length > 512) {
|
||||||
|
throw new Error("API key must be between 16 and 512 characters");
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateContext(value: unknown): SelectedElementContext {
|
||||||
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||||
|
throw new Error("Selected element context is required");
|
||||||
|
}
|
||||||
|
const context = value as SelectedElementContext;
|
||||||
|
const limits: Array<[keyof SelectedElementContext, number]> = [
|
||||||
|
["route", 256],
|
||||||
|
["rootSelector", 1_000],
|
||||||
|
["request", 2_000],
|
||||||
|
["userContext", 4_000],
|
||||||
|
["selectedHtml", 24_000],
|
||||||
|
["ancestorHtml", 6_000],
|
||||||
|
["tagName", 80],
|
||||||
|
];
|
||||||
|
for (const [key, limit] of limits) {
|
||||||
|
const field = context[key];
|
||||||
|
if (field === undefined) continue;
|
||||||
|
if (typeof field !== "string") throw new Error(`${key} must be text`);
|
||||||
|
if (field.length > limit) throw new Error(`${key} is too long`);
|
||||||
|
}
|
||||||
|
if (!Array.isArray(context.domCatalog)) {
|
||||||
|
throw new Error("domCatalog is required");
|
||||||
|
}
|
||||||
|
if (context.domCatalog.length > 100) {
|
||||||
|
throw new Error("domCatalog must contain at most 100 entries");
|
||||||
|
}
|
||||||
|
for (const entry of context.domCatalog) {
|
||||||
|
if (!entry || typeof entry !== "object") {
|
||||||
|
throw new Error("domCatalog entries must be objects");
|
||||||
|
}
|
||||||
|
if (typeof entry.selector !== "string" || entry.selector.length > 500) {
|
||||||
|
throw new Error("domCatalog selector is invalid");
|
||||||
|
}
|
||||||
|
if (typeof entry.tag !== "string" || entry.tag.length > 80) {
|
||||||
|
throw new Error("domCatalog tag is invalid");
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
entry.layout &&
|
||||||
|
(typeof entry.layout !== "object" ||
|
||||||
|
Array.isArray(entry.layout) ||
|
||||||
|
Object.keys(entry.layout).length > 24)
|
||||||
|
) {
|
||||||
|
throw new Error("domCatalog layout summary is invalid");
|
||||||
|
}
|
||||||
|
for (const countKey of ["rowCount", "columnCount", "itemCount"] as const) {
|
||||||
|
const count = entry[countKey];
|
||||||
|
if (count === undefined) continue;
|
||||||
|
if (!Number.isFinite(count) || count < 0 || count > 10_000) {
|
||||||
|
throw new Error(`domCatalog ${countKey} is invalid`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (context.parentChain !== undefined) {
|
||||||
|
if (!Array.isArray(context.parentChain)) {
|
||||||
|
throw new Error("parentChain must be an array");
|
||||||
|
}
|
||||||
|
if (context.parentChain.length > 3) {
|
||||||
|
throw new Error("parentChain must contain at most 3 entries");
|
||||||
|
}
|
||||||
|
for (const entry of context.parentChain) {
|
||||||
|
if (!entry || typeof entry !== "object") {
|
||||||
|
throw new Error("parentChain entries must be objects");
|
||||||
|
}
|
||||||
|
if (typeof entry.tag !== "string" || entry.tag.length > 80) {
|
||||||
|
throw new Error("parentChain tag is invalid");
|
||||||
|
}
|
||||||
|
if (!Array.isArray(entry.classes) || entry.classes.length > 8) {
|
||||||
|
throw new Error("parentChain classes are invalid");
|
||||||
|
}
|
||||||
|
for (const className of entry.classes) {
|
||||||
|
if (typeof className !== "string" || className.length > 80) {
|
||||||
|
throw new Error("parentChain class name is invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!entry.layout ||
|
||||||
|
typeof entry.layout !== "object" ||
|
||||||
|
Array.isArray(entry.layout) ||
|
||||||
|
Object.keys(entry.layout).length > 24
|
||||||
|
) {
|
||||||
|
throw new Error("parentChain layout summary is invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (context.structuralHints !== undefined) {
|
||||||
|
const hints = context.structuralHints;
|
||||||
|
if (!hints || typeof hints !== "object" || Array.isArray(hints)) {
|
||||||
|
throw new Error("structuralHints must be an object");
|
||||||
|
}
|
||||||
|
if (typeof hints.hasTable !== "boolean" || typeof hints.hasList !== "boolean") {
|
||||||
|
throw new Error("structuralHints flags are invalid");
|
||||||
|
}
|
||||||
|
if (!Array.isArray(hints.primaryClasses) || hints.primaryClasses.length > 8) {
|
||||||
|
throw new Error("structuralHints primaryClasses are invalid");
|
||||||
|
}
|
||||||
|
for (const className of hints.primaryClasses) {
|
||||||
|
if (typeof className !== "string" || className.length > 80) {
|
||||||
|
throw new Error("structuralHints class name is invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const countKey of ["rowCount", "columnCount", "itemCount"] as const) {
|
||||||
|
const count = hints[countKey];
|
||||||
|
if (count === undefined) continue;
|
||||||
|
if (!Number.isFinite(count) || count < 0 || count > 10_000) {
|
||||||
|
throw new Error(`structuralHints ${countKey} is invalid`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!context.request.trim()) throw new Error("Change request is required");
|
||||||
|
if (
|
||||||
|
!context.dimensions ||
|
||||||
|
!Number.isFinite(context.dimensions.width) ||
|
||||||
|
!Number.isFinite(context.dimensions.height)
|
||||||
|
) {
|
||||||
|
throw new Error("Element dimensions are invalid");
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!context.computedStyle ||
|
||||||
|
typeof context.computedStyle !== "object" ||
|
||||||
|
Array.isArray(context.computedStyle) ||
|
||||||
|
Object.keys(context.computedStyle).length > 20
|
||||||
|
) {
|
||||||
|
throw new Error("Computed style summary is invalid");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...context,
|
||||||
|
dimensions: { ...context.dimensions },
|
||||||
|
computedStyle: { ...context.computedStyle },
|
||||||
|
domCatalog: context.domCatalog.map((entry) => ({
|
||||||
|
...entry,
|
||||||
|
classes: [...entry.classes],
|
||||||
|
layout: { ...entry.layout },
|
||||||
|
})),
|
||||||
|
...(context.parentChain
|
||||||
|
? {
|
||||||
|
parentChain: context.parentChain.map((entry) => ({
|
||||||
|
...entry,
|
||||||
|
classes: [...entry.classes],
|
||||||
|
layout: { ...entry.layout },
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(context.structuralHints
|
||||||
|
? {
|
||||||
|
structuralHints: {
|
||||||
|
...context.structuralHints,
|
||||||
|
primaryClasses: [...context.structuralHints.primaryClasses],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function responseContent(payload: unknown): string {
|
||||||
|
if (!payload || typeof payload !== "object") {
|
||||||
|
throw new Error("OpenRouter returned an invalid response");
|
||||||
|
}
|
||||||
|
const choices = (payload as { choices?: unknown }).choices;
|
||||||
|
if (!Array.isArray(choices) || choices.length === 0) {
|
||||||
|
throw new Error("OpenRouter returned no choices");
|
||||||
|
}
|
||||||
|
const content = (
|
||||||
|
choices[0] as { message?: { content?: unknown } }
|
||||||
|
).message?.content;
|
||||||
|
if (typeof content === "string") return content;
|
||||||
|
if (Array.isArray(content)) {
|
||||||
|
const combined = content
|
||||||
|
.map((part) =>
|
||||||
|
part &&
|
||||||
|
typeof part === "object" &&
|
||||||
|
"text" in part &&
|
||||||
|
typeof part.text === "string"
|
||||||
|
? part.text
|
||||||
|
: "",
|
||||||
|
)
|
||||||
|
.join("");
|
||||||
|
if (combined) return combined;
|
||||||
|
}
|
||||||
|
throw new Error("OpenRouter returned no generated recipe");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function providerError(
|
||||||
|
response: Response,
|
||||||
|
modelId: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const fallback = `OpenRouter request failed (${response.status})`;
|
||||||
|
try {
|
||||||
|
const payload = (await response.json()) as {
|
||||||
|
error?: { message?: unknown; code?: number; metadata?: { error_type?: string } } | string;
|
||||||
|
};
|
||||||
|
if (typeof payload.error === "string") {
|
||||||
|
return formatOpenRouterError({ message: payload.error }, modelId);
|
||||||
|
}
|
||||||
|
if (payload.error && typeof payload.error === "object") {
|
||||||
|
return formatOpenRouterError(payload.error, modelId);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Use the status-only fallback without exposing response content.
|
||||||
|
}
|
||||||
|
if (response.status === 429) {
|
||||||
|
return formatOpenRouterError({ code: 429 }, modelId);
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
type OpenRouterErrorShape = {
|
||||||
|
code?: number;
|
||||||
|
message?: string;
|
||||||
|
metadata?: { error_type?: string };
|
||||||
|
};
|
||||||
|
|
||||||
|
export function formatOpenRouterError(
|
||||||
|
error: OpenRouterErrorShape | undefined,
|
||||||
|
modelId: string,
|
||||||
|
): string {
|
||||||
|
if (!error) return "OpenRouter request failed";
|
||||||
|
|
||||||
|
const errorType = error.metadata?.error_type;
|
||||||
|
const message = typeof error.message === "string" ? error.message : "";
|
||||||
|
const isRateLimit =
|
||||||
|
error.code === 429 ||
|
||||||
|
errorType === "rate_limit_exceeded" ||
|
||||||
|
/rate limit/i.test(message);
|
||||||
|
|
||||||
|
if (isRateLimit) {
|
||||||
|
const model = getModelOption(modelId);
|
||||||
|
const tierHint =
|
||||||
|
model?.tier === "free"
|
||||||
|
? "Free models share strict provider limits — wait 1–2 minutes or switch model in the creator panel."
|
||||||
|
: "Wait a minute and try again.";
|
||||||
|
return `Rate limit reached for ${model?.label ?? modelId}. ${tierHint}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return message || "OpenRouter request failed";
|
||||||
|
}
|
||||||
|
|
||||||
|
function openRouterRequestBody(
|
||||||
|
context: SelectedElementContext,
|
||||||
|
stream: boolean,
|
||||||
|
formatMode: ResponseFormatMode,
|
||||||
|
modelId: string,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const body: Record<string, unknown> = {
|
||||||
|
model: modelId,
|
||||||
|
messages: buildAiModMessages(context),
|
||||||
|
temperature: 0.2,
|
||||||
|
max_tokens: 8_000,
|
||||||
|
stream,
|
||||||
|
provider: {
|
||||||
|
allow_fallbacks: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if (formatMode === "json_object") {
|
||||||
|
body.response_format = { type: "json_object" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
|
function openRouterRequestInit(
|
||||||
|
apiKey: string,
|
||||||
|
context: SelectedElementContext,
|
||||||
|
stream: boolean,
|
||||||
|
formatMode: ResponseFormatMode,
|
||||||
|
modelId: string,
|
||||||
|
): RequestInit {
|
||||||
|
return {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${apiKey}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"HTTP-Referer": "https://betterseqta.org",
|
||||||
|
"X-Title": "BetterSEQTA+ AI Mod Creator",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(
|
||||||
|
openRouterRequestBody(context, stream, formatMode, modelId),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRoutingError(message: string): boolean {
|
||||||
|
return ROUTING_ERROR_PATTERN.test(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseValidatedDraft(
|
||||||
|
content: string | GeneratedModDraft,
|
||||||
|
): GeneratedModDraft {
|
||||||
|
try {
|
||||||
|
return parseGeneratedModDraft(content);
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(formatRecipeValidationError(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestGeneratedDraft(
|
||||||
|
fetchImpl: FetchLike,
|
||||||
|
apiKey: string,
|
||||||
|
context: SelectedElementContext,
|
||||||
|
stream: boolean,
|
||||||
|
modelId: string,
|
||||||
|
onProgress?: (progress: GenerationProgress) => void,
|
||||||
|
): Promise<GeneratedModDraft> {
|
||||||
|
const modes: ResponseFormatMode[] = ["json_object", "none"];
|
||||||
|
let lastError = "OpenRouter request failed";
|
||||||
|
const modelLabel = getModelOption(modelId)?.label ?? modelId;
|
||||||
|
|
||||||
|
for (const [index, mode] of modes.entries()) {
|
||||||
|
if (index > 0) {
|
||||||
|
aiModLog.warn("background", "Retrying OpenRouter request", { mode, lastError });
|
||||||
|
onProgress?.({
|
||||||
|
type: "status",
|
||||||
|
text: "Retrying with a simpler OpenRouter request…",
|
||||||
|
});
|
||||||
|
} else if (stream) {
|
||||||
|
onProgress?.({ type: "status", text: `Connecting to ${modelLabel}…` });
|
||||||
|
}
|
||||||
|
|
||||||
|
aiModLog.info("background", "Sending OpenRouter request", {
|
||||||
|
mode,
|
||||||
|
stream,
|
||||||
|
model: modelId,
|
||||||
|
route: context.route,
|
||||||
|
rootSelector: context.rootSelector,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await fetchImpl(
|
||||||
|
OPENROUTER_URL,
|
||||||
|
openRouterRequestInit(apiKey, context, stream, mode, modelId),
|
||||||
|
);
|
||||||
|
if (response.ok) {
|
||||||
|
aiModLog.info("background", "OpenRouter request succeeded", {
|
||||||
|
mode,
|
||||||
|
stream,
|
||||||
|
status: response.status,
|
||||||
|
});
|
||||||
|
if (stream) {
|
||||||
|
return consumeOpenRouterStream(
|
||||||
|
response,
|
||||||
|
modelId,
|
||||||
|
onProgress ?? (() => {}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const payload = await response.json();
|
||||||
|
const content = responseContent(payload);
|
||||||
|
aiModLog.debug("background", "OpenRouter non-stream content", content);
|
||||||
|
return parseValidatedDraft(content);
|
||||||
|
}
|
||||||
|
|
||||||
|
lastError = await providerError(response, modelId);
|
||||||
|
aiModLog.warn("background", "OpenRouter request failed", {
|
||||||
|
mode,
|
||||||
|
stream,
|
||||||
|
status: response.status,
|
||||||
|
error: lastError,
|
||||||
|
});
|
||||||
|
if (!isRoutingError(lastError)) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(lastError);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function consumeOpenRouterStream(
|
||||||
|
response: Response,
|
||||||
|
modelId: string,
|
||||||
|
onProgress: (progress: GenerationProgress) => void,
|
||||||
|
): Promise<GeneratedModDraft> {
|
||||||
|
if (!response.body) throw new Error("OpenRouter returned an empty stream");
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = "";
|
||||||
|
let generatedContent = "";
|
||||||
|
let reasoningStarted = false;
|
||||||
|
|
||||||
|
const processEvent = (event: string) => {
|
||||||
|
const data = event
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.filter((line) => line.startsWith("data:"))
|
||||||
|
.map((line) => line.slice(5).trim())
|
||||||
|
.join("");
|
||||||
|
if (!data || data === "[DONE]") return;
|
||||||
|
|
||||||
|
const chunk = JSON.parse(data) as {
|
||||||
|
error?: OpenRouterErrorShape;
|
||||||
|
choices?: Array<{
|
||||||
|
delta?: {
|
||||||
|
content?: string | null;
|
||||||
|
reasoning_details?: unknown[];
|
||||||
|
};
|
||||||
|
error?: OpenRouterErrorShape;
|
||||||
|
}>;
|
||||||
|
usage?: {
|
||||||
|
prompt_tokens?: number;
|
||||||
|
completion_tokens?: number;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const streamError = chunk.error ?? chunk.choices?.[0]?.error;
|
||||||
|
if (streamError) {
|
||||||
|
aiModLog.warn("background", "OpenRouter stream error chunk", streamError);
|
||||||
|
throw new Error(formatOpenRouterError(streamError, modelId));
|
||||||
|
}
|
||||||
|
|
||||||
|
const delta = chunk.choices?.[0]?.delta;
|
||||||
|
if (Array.isArray(delta?.reasoning_details) && !reasoningStarted) {
|
||||||
|
reasoningStarted = true;
|
||||||
|
onProgress({ type: "status", text: "Model is reasoning…" });
|
||||||
|
}
|
||||||
|
if (typeof delta?.content === "string" && delta.content) {
|
||||||
|
generatedContent += delta.content;
|
||||||
|
onProgress({ type: "content", text: delta.content });
|
||||||
|
}
|
||||||
|
if (chunk.usage) {
|
||||||
|
onProgress({
|
||||||
|
type: "usage",
|
||||||
|
promptTokens: chunk.usage.prompt_tokens,
|
||||||
|
completionTokens: chunk.usage.completion_tokens,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
buffer += decoder.decode(value, { stream: !done });
|
||||||
|
const events = buffer.split(/\r?\n\r?\n/);
|
||||||
|
buffer = events.pop() ?? "";
|
||||||
|
for (const event of events) processEvent(event);
|
||||||
|
if (done) break;
|
||||||
|
}
|
||||||
|
if (buffer.trim()) processEvent(buffer);
|
||||||
|
aiModLog.debug("background", "Completed OpenRouter stream", {
|
||||||
|
contentLength: generatedContent.length,
|
||||||
|
preview: generatedContent.slice(0, 500),
|
||||||
|
});
|
||||||
|
return parseValidatedDraft(generatedContent);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAiModCreatorService(
|
||||||
|
dependencies: {
|
||||||
|
storage?: StorageArea;
|
||||||
|
fetchImpl?: FetchLike;
|
||||||
|
now?: () => number;
|
||||||
|
} = {},
|
||||||
|
) {
|
||||||
|
const storage = dependencies.storage ?? browser.storage.local;
|
||||||
|
const fetchImpl = dependencies.fetchImpl ?? fetch;
|
||||||
|
const now = dependencies.now ?? Date.now;
|
||||||
|
let inFlight = false;
|
||||||
|
let lastGenerationAt = Number.NEGATIVE_INFINITY;
|
||||||
|
|
||||||
|
const getStoredKey = async (): Promise<string | null> => {
|
||||||
|
const result = await storage.get(OPENROUTER_API_KEY_STORAGE_KEY);
|
||||||
|
const value = result[OPENROUTER_API_KEY_STORAGE_KEY];
|
||||||
|
return typeof value === "string" && value.length > 0 ? value : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStoredModelId = async (): Promise<string> => {
|
||||||
|
const result = await storage.get(OPENROUTER_MODEL_STORAGE_KEY);
|
||||||
|
const value = result[OPENROUTER_MODEL_STORAGE_KEY];
|
||||||
|
if (typeof value === "string" && value.length > 0) {
|
||||||
|
try {
|
||||||
|
return validateModelId(value);
|
||||||
|
} catch {
|
||||||
|
aiModLog.warn("background", "Ignoring invalid stored model id", value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return DEFAULT_OPENROUTER_MODEL_ID;
|
||||||
|
};
|
||||||
|
|
||||||
|
const beginGeneration = () => {
|
||||||
|
const currentTime = now();
|
||||||
|
if (inFlight) {
|
||||||
|
throw new Error("A generation is already in progress");
|
||||||
|
}
|
||||||
|
if (currentTime - lastGenerationAt < MIN_GENERATION_INTERVAL_MS) {
|
||||||
|
const waitSeconds = Math.ceil(
|
||||||
|
(MIN_GENERATION_INTERVAL_MS - (currentTime - lastGenerationAt)) / 1000,
|
||||||
|
);
|
||||||
|
throw new Error(
|
||||||
|
`Please wait ${waitSeconds}s before generating another mod`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
inFlight = true;
|
||||||
|
lastGenerationAt = currentTime;
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
async saveKey(apiKey: unknown): Promise<void> {
|
||||||
|
await storage.set({
|
||||||
|
[OPENROUTER_API_KEY_STORAGE_KEY]: validateApiKey(apiKey),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
async clearKey(): Promise<void> {
|
||||||
|
await storage.remove(OPENROUTER_API_KEY_STORAGE_KEY);
|
||||||
|
},
|
||||||
|
|
||||||
|
async getKeyStatus(): Promise<KeyStatus> {
|
||||||
|
return { configured: (await getStoredKey()) !== null };
|
||||||
|
},
|
||||||
|
|
||||||
|
async getModelSettings() {
|
||||||
|
return { modelId: await getStoredModelId() };
|
||||||
|
},
|
||||||
|
|
||||||
|
async saveModel(modelId: unknown): Promise<void> {
|
||||||
|
await storage.set({
|
||||||
|
[OPENROUTER_MODEL_STORAGE_KEY]: validateModelId(modelId),
|
||||||
|
});
|
||||||
|
aiModLog.info("background", "Saved OpenRouter model", modelId);
|
||||||
|
},
|
||||||
|
|
||||||
|
async generate(input: unknown): Promise<GeneratedModDraft> {
|
||||||
|
const context = validateContext(input);
|
||||||
|
const apiKey = await getStoredKey();
|
||||||
|
if (!apiKey) throw new Error("OpenRouter API key is not configured");
|
||||||
|
const modelId = await getStoredModelId();
|
||||||
|
beginGeneration();
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await requestGeneratedDraft(
|
||||||
|
fetchImpl,
|
||||||
|
apiKey,
|
||||||
|
context,
|
||||||
|
false,
|
||||||
|
modelId,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
inFlight = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async streamGenerate(
|
||||||
|
input: unknown,
|
||||||
|
onProgress: (progress: GenerationProgress) => void,
|
||||||
|
): Promise<GeneratedModDraft> {
|
||||||
|
const context = validateContext(input);
|
||||||
|
const apiKey = await getStoredKey();
|
||||||
|
if (!apiKey) throw new Error("OpenRouter API key is not configured");
|
||||||
|
const modelId = await getStoredModelId();
|
||||||
|
beginGeneration();
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await requestGeneratedDraft(
|
||||||
|
fetchImpl,
|
||||||
|
apiKey,
|
||||||
|
context,
|
||||||
|
true,
|
||||||
|
modelId,
|
||||||
|
onProgress,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
inFlight = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultService = createAiModCreatorService();
|
||||||
|
|
||||||
|
export function handleAiModCreatorMessage(
|
||||||
|
request: {
|
||||||
|
type?: string;
|
||||||
|
action?: string;
|
||||||
|
apiKey?: unknown;
|
||||||
|
context?: unknown;
|
||||||
|
recipe?: unknown;
|
||||||
|
id?: unknown;
|
||||||
|
modelId?: unknown;
|
||||||
|
},
|
||||||
|
sender: browser.Runtime.MessageSender,
|
||||||
|
sendResponse: SendResponse,
|
||||||
|
isTrustedSender: TrustCheck,
|
||||||
|
): boolean {
|
||||||
|
if (!isTrustedSender(sender)) {
|
||||||
|
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const action = request.action;
|
||||||
|
aiModLog.debug("background", "Handling message", {
|
||||||
|
action,
|
||||||
|
tabId: sender.tab?.id,
|
||||||
|
senderId: sender.id,
|
||||||
|
});
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
let data: unknown;
|
||||||
|
if (action === "saveKey") {
|
||||||
|
await defaultService.saveKey(request.apiKey);
|
||||||
|
} else if (action === "clearKey") {
|
||||||
|
await defaultService.clearKey();
|
||||||
|
} else if (action === "status") {
|
||||||
|
data = await defaultService.getKeyStatus();
|
||||||
|
} else if (action === "getModel") {
|
||||||
|
data = await defaultService.getModelSettings();
|
||||||
|
} else if (action === "saveModel") {
|
||||||
|
await defaultService.saveModel(request.modelId);
|
||||||
|
} else if (action === "advancedSupport") {
|
||||||
|
data = getAdvancedScriptSupport();
|
||||||
|
} else if (action === "generate") {
|
||||||
|
data = await defaultService.generate(request.context);
|
||||||
|
} else if (action === "executeAdvanced") {
|
||||||
|
if (sender.tab?.id === undefined) {
|
||||||
|
throw new Error("Advanced scripts require a SEQTA browser tab");
|
||||||
|
}
|
||||||
|
const { devMode } = await browser.storage.local.get("devMode");
|
||||||
|
if (devMode !== true) {
|
||||||
|
throw new Error("Advanced scripts are available only in developer mode");
|
||||||
|
}
|
||||||
|
await executeAdvancedMod(
|
||||||
|
request.recipe as StoredModRecipe,
|
||||||
|
sender.tab.id,
|
||||||
|
);
|
||||||
|
} else if (action === "stopAdvanced") {
|
||||||
|
if (sender.tab?.id === undefined || typeof request.id !== "string") {
|
||||||
|
throw new Error("Advanced script id or tab is missing");
|
||||||
|
}
|
||||||
|
await stopAdvancedMod(request.id, sender.tab.id);
|
||||||
|
} else {
|
||||||
|
throw new Error("Unsupported AI Mod Creator action");
|
||||||
|
}
|
||||||
|
sendResponse({ success: true, data });
|
||||||
|
aiModLog.debug("background", "Message handled", { action });
|
||||||
|
} catch (error) {
|
||||||
|
const message =
|
||||||
|
error instanceof Error ? error.message : "AI request failed";
|
||||||
|
aiModLog.error("background", "Message failed", { action, error: message });
|
||||||
|
sendResponse({
|
||||||
|
success: false,
|
||||||
|
error: message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerAiModCreatorStreaming(
|
||||||
|
isTrustedSender: TrustCheck,
|
||||||
|
): void {
|
||||||
|
browser.runtime.onConnect.addListener((port) => {
|
||||||
|
if (port.name !== "aiModCreator.stream") return;
|
||||||
|
if (!isTrustedSender(port.sender)) {
|
||||||
|
port.postMessage({ type: "error", error: "Unauthorized sender" });
|
||||||
|
port.disconnect();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let started = false;
|
||||||
|
port.onMessage.addListener((message: unknown) => {
|
||||||
|
if (started) return;
|
||||||
|
started = true;
|
||||||
|
const context =
|
||||||
|
message && typeof message === "object" && "context" in message
|
||||||
|
? (message as { context?: unknown }).context
|
||||||
|
: undefined;
|
||||||
|
aiModLog.info("background", "Starting streamed generation");
|
||||||
|
void defaultService
|
||||||
|
.streamGenerate(context, (progress) => {
|
||||||
|
port.postMessage({ type: "progress", progress });
|
||||||
|
})
|
||||||
|
.then((draft) => {
|
||||||
|
aiModLog.info("background", "Streamed generation complete", {
|
||||||
|
name: draft.name,
|
||||||
|
operationCount: draft.operations.length,
|
||||||
|
});
|
||||||
|
port.postMessage({ type: "done", draft });
|
||||||
|
port.disconnect();
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
const message =
|
||||||
|
error instanceof Error ? error.message : "AI streaming failed";
|
||||||
|
aiModLog.error("background", "Streamed generation failed", message);
|
||||||
|
port.postMessage({
|
||||||
|
type: "error",
|
||||||
|
error: message,
|
||||||
|
});
|
||||||
|
port.disconnect();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { buildExecutionSource } from "./aiModUserScripts";
|
||||||
|
import type { StoredModRecipe } from "@/plugins/built-in/aiModCreator/types";
|
||||||
|
|
||||||
|
const baseRecipe: StoredModRecipe = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
id: "mod-test",
|
||||||
|
enabled: true,
|
||||||
|
route: "welcome",
|
||||||
|
rootSelector: "#titlebar",
|
||||||
|
name: "Test mod",
|
||||||
|
description: "Test",
|
||||||
|
operations: [],
|
||||||
|
advancedScript: `
|
||||||
|
const house = select('.userInfohouse');
|
||||||
|
if (!house) throw new Error('Missing .userInfohouse inside selected root');
|
||||||
|
return () => {};
|
||||||
|
`,
|
||||||
|
createdAt: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("advanced user script injection source", () => {
|
||||||
|
it("does not declare select twice in the generated runtime", () => {
|
||||||
|
const source = buildExecutionSource(baseRecipe);
|
||||||
|
expect(source.match(/\bconst select\b/g)?.length).toBe(1);
|
||||||
|
expect(source.match(/\bconst selectAll\b/g)?.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws when the selected root is missing", () => {
|
||||||
|
const source = buildExecutionSource(baseRecipe);
|
||||||
|
expect(source).toContain("AI mod root not found on this page");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
import {
|
||||||
|
SAFE_ATTRIBUTE_NAMES,
|
||||||
|
SAFE_INSERT_TAGS,
|
||||||
|
SAFE_STYLE_PROPERTIES,
|
||||||
|
validateStoredRecipes,
|
||||||
|
} from "@/plugins/built-in/aiModCreator/recipeSchema";
|
||||||
|
import { assertAdvancedScriptSafe } from "@/plugins/built-in/aiModCreator/scriptSafety";
|
||||||
|
import type { StoredModRecipe } from "@/plugins/built-in/aiModCreator/types";
|
||||||
|
|
||||||
|
interface UserScriptsApi {
|
||||||
|
configureWorld(details: {
|
||||||
|
worldId: string;
|
||||||
|
csp: string;
|
||||||
|
messaging: boolean;
|
||||||
|
}): Promise<void>;
|
||||||
|
execute(details: {
|
||||||
|
target: { tabId: number; allFrames: boolean };
|
||||||
|
worldId: string;
|
||||||
|
world: "USER_SCRIPT";
|
||||||
|
injectImmediately: boolean;
|
||||||
|
js: Array<{ code: string }>;
|
||||||
|
}): Promise<unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const USER_SCRIPT_CSP = [
|
||||||
|
"default-src 'none'",
|
||||||
|
"script-src 'self' 'unsafe-inline'",
|
||||||
|
"connect-src 'none'",
|
||||||
|
"img-src 'none'",
|
||||||
|
"media-src 'none'",
|
||||||
|
"font-src 'none'",
|
||||||
|
"object-src 'none'",
|
||||||
|
"frame-src 'none'",
|
||||||
|
"child-src 'none'",
|
||||||
|
"form-action 'none'",
|
||||||
|
"base-uri 'none'",
|
||||||
|
].join("; ");
|
||||||
|
|
||||||
|
function getUserScriptsApi(): UserScriptsApi {
|
||||||
|
const globalApis = globalThis as unknown as {
|
||||||
|
chrome?: { userScripts?: UserScriptsApi };
|
||||||
|
browser?: { userScripts?: UserScriptsApi };
|
||||||
|
};
|
||||||
|
const api =
|
||||||
|
globalApis.chrome?.userScripts ?? globalApis.browser?.userScripts;
|
||||||
|
if (!api?.execute || !api.configureWorld) {
|
||||||
|
throw new Error(
|
||||||
|
"Advanced scripts require Chrome User Scripts support.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return api;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ADVANCED_SCRIPT_SETUP_INSTRUCTIONS = [
|
||||||
|
"Open chrome://extensions",
|
||||||
|
"Find BetterSEQTA+ and open Details",
|
||||||
|
'Enable "Allow User Scripts"',
|
||||||
|
"Reload this SEQTA tab, then enable the mod again",
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
export function getAdvancedScriptSupport(): {
|
||||||
|
supported: boolean;
|
||||||
|
reason?: string;
|
||||||
|
instructions?: string;
|
||||||
|
} {
|
||||||
|
try {
|
||||||
|
getUserScriptsApi();
|
||||||
|
return { supported: true };
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
supported: false,
|
||||||
|
reason:
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Advanced scripts are unavailable in this browser",
|
||||||
|
instructions: ADVANCED_SCRIPT_SETUP_INSTRUCTIONS,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function worldId(id: string): string {
|
||||||
|
return `bsplus-${id}`.slice(0, 256);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildExecutionSource(recipe: StoredModRecipe): string {
|
||||||
|
const script = assertAdvancedScriptSafe(recipe.advancedScript);
|
||||||
|
const config = JSON.stringify({
|
||||||
|
id: recipe.id,
|
||||||
|
route: recipe.route,
|
||||||
|
rootSelector: recipe.rootSelector,
|
||||||
|
allowedAttributes: SAFE_ATTRIBUTE_NAMES,
|
||||||
|
allowedStyles: SAFE_STYLE_PROPERTIES,
|
||||||
|
allowedTags: SAFE_INSERT_TAGS,
|
||||||
|
});
|
||||||
|
|
||||||
|
return `(() => {
|
||||||
|
"use strict";
|
||||||
|
const config = ${config};
|
||||||
|
const registryKey = Symbol.for("betterseqta.aiModRuntime");
|
||||||
|
const registry = globalThis[registryKey] ?? (globalThis[registryKey] = new Map());
|
||||||
|
const previousCleanup = registry.get(config.id);
|
||||||
|
if (typeof previousCleanup === "function") previousCleanup();
|
||||||
|
|
||||||
|
const route = (location.hash.split("?page=/")[1] ?? "").split(/[/?#]/)[0];
|
||||||
|
if (config.route && route !== config.route) {
|
||||||
|
throw new Error("AI mod route mismatch: expected " + config.route + " but page is " + route);
|
||||||
|
}
|
||||||
|
const root = document.querySelector(config.rootSelector);
|
||||||
|
if (!(root instanceof HTMLElement)) {
|
||||||
|
throw new Error("AI mod root not found on this page: " + config.rootSelector);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanups = [];
|
||||||
|
const remember = (cleanup) => {
|
||||||
|
if (typeof cleanup === "function") cleanups.push(cleanup);
|
||||||
|
return cleanup;
|
||||||
|
};
|
||||||
|
const insideRoot = (element) =>
|
||||||
|
element instanceof Element && (element === root || root.contains(element));
|
||||||
|
const requireInsideRoot = (element) => {
|
||||||
|
if (!insideRoot(element)) throw new Error("AI mod attempted to leave its selected root");
|
||||||
|
return element;
|
||||||
|
};
|
||||||
|
const query = (selector = ":scope") =>
|
||||||
|
selector === ":scope" ? root : root.querySelector(selector);
|
||||||
|
const queryAll = (selector = ":scope") =>
|
||||||
|
selector === ":scope" ? [root] : Array.from(root.querySelectorAll(selector));
|
||||||
|
|
||||||
|
const bsplus = Object.freeze({
|
||||||
|
root,
|
||||||
|
select: query,
|
||||||
|
selectAll: queryAll,
|
||||||
|
onCleanup: remember,
|
||||||
|
setText(element, text) {
|
||||||
|
requireInsideRoot(element);
|
||||||
|
const previous = element.textContent;
|
||||||
|
element.textContent = String(text);
|
||||||
|
remember(() => { element.textContent = previous; });
|
||||||
|
return element;
|
||||||
|
},
|
||||||
|
setStyle(element, property, value) {
|
||||||
|
requireInsideRoot(element);
|
||||||
|
if (!config.allowedStyles.includes(property)) throw new Error("Unsupported style property");
|
||||||
|
const previous = element.style.getPropertyValue(property);
|
||||||
|
const priority = element.style.getPropertyPriority(property);
|
||||||
|
element.style.setProperty(property, String(value).replace(/\\s*!important\\s*$/i, "").trim(), "important");
|
||||||
|
remember(() => previous
|
||||||
|
? element.style.setProperty(property, previous, priority)
|
||||||
|
: element.style.removeProperty(property));
|
||||||
|
return element;
|
||||||
|
},
|
||||||
|
setAttribute(element, name, value) {
|
||||||
|
requireInsideRoot(element);
|
||||||
|
if (!config.allowedAttributes.includes(name)) throw new Error("Unsupported attribute");
|
||||||
|
const hadAttribute = element.hasAttribute(name);
|
||||||
|
const previous = element.getAttribute(name);
|
||||||
|
element.setAttribute(name, String(value));
|
||||||
|
remember(() => hadAttribute
|
||||||
|
? element.setAttribute(name, previous ?? "")
|
||||||
|
: element.removeAttribute(name));
|
||||||
|
return element;
|
||||||
|
},
|
||||||
|
create(tag, text, parent = root) {
|
||||||
|
requireInsideRoot(parent);
|
||||||
|
if (!config.allowedTags.includes(tag)) throw new Error("Unsupported element tag");
|
||||||
|
const element = document.createElement(tag);
|
||||||
|
element.textContent = String(text);
|
||||||
|
parent.append(element);
|
||||||
|
remember(() => element.remove());
|
||||||
|
return element;
|
||||||
|
},
|
||||||
|
on(element, event, handler, options) {
|
||||||
|
requireInsideRoot(element);
|
||||||
|
element.addEventListener(event, handler, options);
|
||||||
|
remember(() => element.removeEventListener(event, handler, options));
|
||||||
|
},
|
||||||
|
observe(element, callback, options = { childList: true, subtree: true }) {
|
||||||
|
requireInsideRoot(element);
|
||||||
|
const observer = new MutationObserver(callback);
|
||||||
|
observer.observe(element, options);
|
||||||
|
remember(() => observer.disconnect());
|
||||||
|
return observer;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const select = bsplus.select;
|
||||||
|
const selectAll = bsplus.selectAll;
|
||||||
|
|
||||||
|
let disposed = false;
|
||||||
|
const cleanup = () => {
|
||||||
|
if (disposed) return;
|
||||||
|
disposed = true;
|
||||||
|
for (const callback of cleanups.reverse()) {
|
||||||
|
try { callback(); } catch (error) { console.warn("[BetterSEQTA+ AI Mod] Cleanup failed", error); }
|
||||||
|
}
|
||||||
|
registry.delete(config.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const userCleanup = (() => {
|
||||||
|
${script}
|
||||||
|
})();
|
||||||
|
remember(userCleanup);
|
||||||
|
registry.set(config.id, cleanup);
|
||||||
|
return { ok: true };
|
||||||
|
} catch (error) {
|
||||||
|
cleanup();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
})();`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildStopSource(id: string): string {
|
||||||
|
return `(() => {
|
||||||
|
const registry = globalThis[Symbol.for("betterseqta.aiModRuntime")];
|
||||||
|
const cleanup = registry?.get(${JSON.stringify(id)});
|
||||||
|
if (typeof cleanup === "function") cleanup();
|
||||||
|
})();`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function configureWorld(api: UserScriptsApi, id: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
await api.configureWorld({
|
||||||
|
worldId: worldId(id),
|
||||||
|
csp: USER_SCRIPT_CSP,
|
||||||
|
messaging: false,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
`Could not configure the isolated script world: ${
|
||||||
|
error instanceof Error ? error.message : "browser rejected it"
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function executeSource(
|
||||||
|
api: UserScriptsApi,
|
||||||
|
id: string,
|
||||||
|
tabId: number,
|
||||||
|
source: string,
|
||||||
|
): Promise<void> {
|
||||||
|
await configureWorld(api, id);
|
||||||
|
const results = (await api.execute({
|
||||||
|
target: { tabId, allFrames: false },
|
||||||
|
world: "USER_SCRIPT",
|
||||||
|
worldId: worldId(id),
|
||||||
|
injectImmediately: true,
|
||||||
|
js: [{ code: source }],
|
||||||
|
})) as Array<{ result?: unknown; error?: unknown }> | undefined;
|
||||||
|
|
||||||
|
const injectionError = results?.find((entry) => entry.error)?.error;
|
||||||
|
if (injectionError) {
|
||||||
|
throw new Error(
|
||||||
|
injectionError instanceof Error
|
||||||
|
? injectionError.message
|
||||||
|
: String(injectionError),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function executeAdvancedMod(
|
||||||
|
input: StoredModRecipe,
|
||||||
|
tabId: number,
|
||||||
|
): Promise<void> {
|
||||||
|
const support = getAdvancedScriptSupport();
|
||||||
|
if (!support.supported) {
|
||||||
|
throw new Error(
|
||||||
|
`${support.reason ?? "Advanced scripts are unavailable"}\n\n${support.instructions ?? ADVANCED_SCRIPT_SETUP_INSTRUCTIONS}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const [recipe] = validateStoredRecipes([input]);
|
||||||
|
if (!recipe.advancedScript) return;
|
||||||
|
await executeSource(
|
||||||
|
getUserScriptsApi(),
|
||||||
|
recipe.id,
|
||||||
|
tabId,
|
||||||
|
buildExecutionSource(recipe),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function stopAdvancedMod(
|
||||||
|
id: string,
|
||||||
|
tabId: number,
|
||||||
|
): Promise<void> {
|
||||||
|
const support = getAdvancedScriptSupport();
|
||||||
|
if (!support.supported) return;
|
||||||
|
if (!/^[A-Za-z0-9_-]{1,160}$/.test(id)) throw new Error("Invalid mod id");
|
||||||
|
await executeSource(getUserScriptsApi(), id, tabId, buildStopSource(id));
|
||||||
|
}
|
||||||
@@ -772,6 +772,11 @@ html.bsplus-custom-title-pending #title > :not(#bsplus-title-root),
|
|||||||
background-image: none !important;
|
background-image: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
> #bsplus-sidebar-root.drilling .sub ul .bsplus-sidebar-item,
|
||||||
|
> #bsplus-sidebar-root.drilling .sub ul .bsplus-sidebar-item * {
|
||||||
|
pointer-events: auto !important;
|
||||||
|
}
|
||||||
|
|
||||||
> #bsplus-sidebar-root > li.hasChildren.bsplus-active > label,
|
> #bsplus-sidebar-root > li.hasChildren.bsplus-active > label,
|
||||||
> #bsplus-sidebar-root.drilling > li.hasChildren > label {
|
> #bsplus-sidebar-root.drilling > li.hasChildren > label {
|
||||||
pointer-events: none !important;
|
pointer-events: none !important;
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
"64": "resources/icons/icon-64.png"
|
"64": "resources/icons/icon-64.png"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"permissions": ["tabs", "notifications", "storage", "identity", "alarms"],
|
"permissions": ["tabs", "notifications", "storage", "identity", "alarms", "userScripts"],
|
||||||
"host_permissions": [
|
"host_permissions": [
|
||||||
"https://newsapi.org/",
|
"https://newsapi.org/",
|
||||||
"https://betterseqta.org/",
|
"https://betterseqta.org/",
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
type TabId = "create" | "mods" | "settings";
|
||||||
|
|
||||||
|
let {
|
||||||
|
tabs,
|
||||||
|
activeTab = $bindable("create" as TabId),
|
||||||
|
disabled = false,
|
||||||
|
}: {
|
||||||
|
tabs: { id: TabId; label: string }[];
|
||||||
|
activeTab?: TabId;
|
||||||
|
disabled?: boolean;
|
||||||
|
} = $props();
|
||||||
|
|
||||||
|
const activeIndex = $derived(
|
||||||
|
Math.max(
|
||||||
|
0,
|
||||||
|
tabs.findIndex((tab) => tab.id === activeTab),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="tab-nav" aria-label="Creator sections">
|
||||||
|
<div class="tab-track" role="tablist">
|
||||||
|
<div
|
||||||
|
class="tab-indicator"
|
||||||
|
style="width: {100 / tabs.length}%; transform: translateX({activeIndex * 100}%)"
|
||||||
|
aria-hidden="true"
|
||||||
|
></div>
|
||||||
|
{#each tabs as tab (tab.id)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="tab-button accent-ring"
|
||||||
|
role="tab"
|
||||||
|
aria-selected={activeTab === tab.id}
|
||||||
|
disabled={disabled}
|
||||||
|
onclick={() => (activeTab = tab.id)}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.tab-nav {
|
||||||
|
padding: 12px 16px 0;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-track {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-indicator {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
height: 100%;
|
||||||
|
border-radius: 9999px;
|
||||||
|
background: linear-gradient(
|
||||||
|
to top right,
|
||||||
|
rgb(56 55 61 / 0.8),
|
||||||
|
rgb(56 55 61)
|
||||||
|
);
|
||||||
|
opacity: 0.45;
|
||||||
|
pointer-events: none;
|
||||||
|
transition: transform 380ms cubic-bezier(0.34, 1.45, 0.64, 1);
|
||||||
|
will-change: transform;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-button {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
flex: 1;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 9999px;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
font-size: inherit;
|
||||||
|
font-weight: 600;
|
||||||
|
transition: opacity 180ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-button[aria-selected="true"] {
|
||||||
|
color: #f4f4f5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-button[aria-selected="false"] {
|
||||||
|
opacity: 0.72;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-button:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
opacity: 0.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.tab-indicator {
|
||||||
|
transition: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,326 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { tick } from "svelte";
|
||||||
|
import { fade, fly } from "svelte/transition";
|
||||||
|
import LoadingSpinnerMini from "./LoadingSpinnerMini.svelte";
|
||||||
|
|
||||||
|
let {
|
||||||
|
status = "",
|
||||||
|
tokenUsage = "",
|
||||||
|
streamChunks = [],
|
||||||
|
error = "",
|
||||||
|
onBack,
|
||||||
|
}: {
|
||||||
|
status?: string;
|
||||||
|
tokenUsage?: string;
|
||||||
|
streamChunks?: string[];
|
||||||
|
error?: string;
|
||||||
|
onBack: () => void;
|
||||||
|
} = $props();
|
||||||
|
|
||||||
|
let streamContainer = $state<HTMLElement | null>(null);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (streamChunks.length === 0 || !streamContainer) return;
|
||||||
|
void tick().then(() => {
|
||||||
|
streamContainer?.scrollTo({
|
||||||
|
top: streamContainer.scrollHeight,
|
||||||
|
behavior: "smooth",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="generating-view"
|
||||||
|
aria-live="polite"
|
||||||
|
aria-busy={!error}
|
||||||
|
>
|
||||||
|
{#if error}
|
||||||
|
<div
|
||||||
|
class="error-card"
|
||||||
|
role="alert"
|
||||||
|
in:fly={{ y: 10, duration: 420, easing: (t) => 1 + 0.36 * Math.pow(t - 1, 3) + 0.22 * Math.pow(t - 1, 2) }}
|
||||||
|
>
|
||||||
|
<p class="error-title">Generation failed</p>
|
||||||
|
<p class="error-message">{error}</p>
|
||||||
|
<button class="secondary-button w-full accent-ring" type="button" onclick={onBack}>
|
||||||
|
Go back and try again
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="generating-header">
|
||||||
|
<LoadingSpinnerMini />
|
||||||
|
<div class="min-w-0">
|
||||||
|
<h3 class="generating-title">Generating mod recipe</h3>
|
||||||
|
{#key status}
|
||||||
|
<p class="generating-status" in:fade={{ duration: 280 }}>
|
||||||
|
{status || "Connecting to model…"}
|
||||||
|
</p>
|
||||||
|
{/key}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="generating-meta">
|
||||||
|
<span class="pulse-dot" aria-hidden="true"></span>
|
||||||
|
<span class="meta-label">Streaming response</span>
|
||||||
|
{#if tokenUsage}
|
||||||
|
<span class="token-badge" in:fly={{ y: 6, duration: 280 }}>
|
||||||
|
{tokenUsage}
|
||||||
|
</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
bind:this={streamContainer}
|
||||||
|
class="stream-panel"
|
||||||
|
data-testid="generation-stream"
|
||||||
|
>
|
||||||
|
{#if streamChunks.length === 0}
|
||||||
|
<div class="stream-placeholder" in:fade={{ duration: 320 }}>
|
||||||
|
<span class="skeleton-line"></span>
|
||||||
|
<span class="skeleton-line skeleton-line--short"></span>
|
||||||
|
<span class="skeleton-line skeleton-line--medium"></span>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<pre class="stream-output">
|
||||||
|
{#each streamChunks as chunk, index (index)}
|
||||||
|
<span class="stream-chunk" in:fly={{ y: 8, duration: 220, delay: 16 }}>
|
||||||
|
{chunk}
|
||||||
|
</span>
|
||||||
|
{/each}
|
||||||
|
<span class="stream-cursor" aria-hidden="true"></span>
|
||||||
|
</pre>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.generating-view {
|
||||||
|
display: flex;
|
||||||
|
min-height: 320px;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.generating-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.generating-title {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.4;
|
||||||
|
color: #f4f4f5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.generating-status {
|
||||||
|
margin-top: 2px;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: rgba(244, 244, 245, 0.62);
|
||||||
|
}
|
||||||
|
|
||||||
|
.generating-meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: rgba(244, 244, 245, 0.52);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pulse-dot {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 9999px;
|
||||||
|
background: var(--better-main, #8b5cf6);
|
||||||
|
animation: pulse-dot 1.4s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token-badge {
|
||||||
|
margin-left: auto;
|
||||||
|
padding: 4px 10px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||||
|
border-radius: 9999px;
|
||||||
|
font-size: 0.6875rem;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0;
|
||||||
|
text-transform: none;
|
||||||
|
color: rgba(244, 244, 245, 0.82);
|
||||||
|
background: rgba(255, 255, 255, 0.06);
|
||||||
|
}
|
||||||
|
|
||||||
|
.stream-panel {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 220px;
|
||||||
|
max-height: 360px;
|
||||||
|
overflow: auto;
|
||||||
|
padding: 14px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
|
border-radius: 12px;
|
||||||
|
background:
|
||||||
|
linear-gradient(180deg, rgb(255 255 255 / 0.03) 0%, transparent 100%),
|
||||||
|
rgb(0 0 0 / 0.35);
|
||||||
|
box-shadow: inset 0 1px 0 rgb(255 255 255 / 0.04);
|
||||||
|
scroll-behavior: smooth;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stream-panel::-webkit-scrollbar {
|
||||||
|
width: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stream-panel::-webkit-scrollbar-thumb {
|
||||||
|
border-radius: 9999px;
|
||||||
|
background: rgb(255 255 255 / 0.14);
|
||||||
|
}
|
||||||
|
|
||||||
|
.stream-placeholder {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.skeleton-line {
|
||||||
|
display: block;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 9999px;
|
||||||
|
background: linear-gradient(
|
||||||
|
90deg,
|
||||||
|
rgb(255 255 255 / 0.06) 0%,
|
||||||
|
rgb(255 255 255 / 0.12) 50%,
|
||||||
|
rgb(255 255 255 / 0.06) 100%
|
||||||
|
);
|
||||||
|
background-size: 200% 100%;
|
||||||
|
animation: skeleton-shimmer 1.6s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.skeleton-line--short {
|
||||||
|
width: 55%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.skeleton-line--medium {
|
||||||
|
width: 78%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stream-output {
|
||||||
|
margin: 0;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
line-height: 1.55;
|
||||||
|
color: #e4e4e7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stream-chunk {
|
||||||
|
display: inline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stream-cursor {
|
||||||
|
display: inline-block;
|
||||||
|
width: 2px;
|
||||||
|
height: 1em;
|
||||||
|
margin-left: 1px;
|
||||||
|
vertical-align: text-bottom;
|
||||||
|
background: var(--better-main, #8b5cf6);
|
||||||
|
animation: cursor-blink 1s step-end infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-card {
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 20px;
|
||||||
|
border: 1px solid rgb(248 113 113 / 0.4);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: rgb(127 29 29 / 0.28);
|
||||||
|
backdrop-filter: blur(6px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-title {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: rgb(252 165 165);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-message {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
line-height: 1.6;
|
||||||
|
color: rgb(254 202 202);
|
||||||
|
}
|
||||||
|
|
||||||
|
.secondary-button {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 8px 16px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||||
|
border-radius: 10px;
|
||||||
|
font-size: 0.775rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: inherit;
|
||||||
|
background: rgb(255 255 255 / 0.05);
|
||||||
|
transition: all 220ms cubic-bezier(0.22, 1, 0.36, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.secondary-button:hover {
|
||||||
|
transform: scale(1.03);
|
||||||
|
border-color: rgb(96 165 250 / 0.28);
|
||||||
|
}
|
||||||
|
|
||||||
|
.secondary-button:active {
|
||||||
|
transform: scale(0.97);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes pulse-dot {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: scale(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
50% {
|
||||||
|
opacity: 0.45;
|
||||||
|
transform: scale(0.85);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes skeleton-shimmer {
|
||||||
|
0% {
|
||||||
|
background-position: 200% 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
100% {
|
||||||
|
background-position: -200% 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes cursor-blink {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
50% {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.pulse-dot,
|
||||||
|
.skeleton-line,
|
||||||
|
.stream-cursor {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { Snippet } from "svelte";
|
||||||
|
|
||||||
|
let { children }: { children: Snippet } = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="bk-skin">
|
||||||
|
<div class="bk-skin__vignette" aria-hidden="true"></div>
|
||||||
|
<div class="bk-skin__content">
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.bk-skin {
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
color: #f4f4f5;
|
||||||
|
background: linear-gradient(
|
||||||
|
180deg,
|
||||||
|
#010101 0%,
|
||||||
|
#040404 50%,
|
||||||
|
#080808 100%
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bk-skin__vignette {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
background: radial-gradient(
|
||||||
|
ellipse at center,
|
||||||
|
transparent 40%,
|
||||||
|
rgb(0 0 0 / 0.55) 100%
|
||||||
|
);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bk-skin__content {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import loadingSpinner from "@/seqta/ui/loading-spinner.html?raw";
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="bk-spinner-mini" aria-hidden="true">
|
||||||
|
{@html loadingSpinner}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.bk-spinner-mini {
|
||||||
|
position: relative;
|
||||||
|
width: 52px;
|
||||||
|
height: 52px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
color: var(--better-main, #8b5cf6);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bk-spinner-mini :global(.svg) {
|
||||||
|
transform-origin: center center;
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
left: 50%;
|
||||||
|
backface-visibility: hidden;
|
||||||
|
will-change: transform;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bk-spinner-mini :global(.logo) {
|
||||||
|
transform: translate3d(-50%, -50%, 0);
|
||||||
|
z-index: 2;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bk-spinner-mini :global(.big-circle) {
|
||||||
|
margin: -38px;
|
||||||
|
width: 76px;
|
||||||
|
height: 76px;
|
||||||
|
animation: bk-spin 3s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bk-spinner-mini :global(.small-circle) {
|
||||||
|
margin: -29px;
|
||||||
|
width: 58px;
|
||||||
|
height: 58px;
|
||||||
|
animation: bk-spin-reverse 3s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bk-spinner-mini :global(.outer-circle) {
|
||||||
|
margin: -46px;
|
||||||
|
width: 92px;
|
||||||
|
height: 92px;
|
||||||
|
animation: bk-spin 4.5s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes bk-spin {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes bk-spin-reverse {
|
||||||
|
to {
|
||||||
|
transform: rotate(-360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.bk-spinner-mini :global(.big-circle),
|
||||||
|
.bk-spinner-mini :global(.small-circle),
|
||||||
|
.bk-spinner-mini :global(.outer-circle) {
|
||||||
|
animation: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
let { size = 20 }: { size?: number } = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svg
|
||||||
|
width={size}
|
||||||
|
height={size}
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
aria-hidden="true"
|
||||||
|
class="mod-creator-icon"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d="M12 2L13.09 8.26L19 7L14.74 12L19 17L13.09 15.74L12 22L10.91 15.74L5 17L9.26 12L5 7L10.91 8.26L12 2Z"
|
||||||
|
fill="currentColor"
|
||||||
|
opacity="0.95"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M18 3L18.6 5.4L21 6L18.6 6.6L18 9L17.4 6.6L15 6L17.4 5.4L18 3Z"
|
||||||
|
fill="currentColor"
|
||||||
|
opacity="0.75"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.mod-creator-icon {
|
||||||
|
display: block;
|
||||||
|
flex-shrink: 0;
|
||||||
|
color: currentColor;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
/** @jest-environment jsdom */
|
||||||
|
/**
|
||||||
|
* Unit-test runtime only. Production advanced mods run through the background
|
||||||
|
* User Scripts API because page/content CSP blocks eval/new Function.
|
||||||
|
*/
|
||||||
|
import { runAdvancedMod, stopAdvancedMod } from "./advancedModRuntime";
|
||||||
|
import type { StoredModRecipe } from "./types";
|
||||||
|
|
||||||
|
describe("advanced mod runtime", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
document.body.innerHTML = "";
|
||||||
|
stopAdvancedMod("test-mod");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("runs an advanced script scoped to the selected root", () => {
|
||||||
|
document.body.innerHTML = `
|
||||||
|
<div id="root">
|
||||||
|
<p class="label">House</p>
|
||||||
|
<p class="target">ID</p>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
const root = document.getElementById("root")!;
|
||||||
|
const label = root.querySelector(".label")!;
|
||||||
|
const target = root.querySelector(".target")!;
|
||||||
|
|
||||||
|
const recipe: StoredModRecipe = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
id: "test-mod",
|
||||||
|
enabled: true,
|
||||||
|
route: "",
|
||||||
|
rootSelector: "#root",
|
||||||
|
name: "Move label",
|
||||||
|
description: "Moves label next to target",
|
||||||
|
operations: [],
|
||||||
|
advancedScript: `
|
||||||
|
const label = select('.label');
|
||||||
|
const target = select('.target');
|
||||||
|
target.parentNode.insertBefore(label, target);
|
||||||
|
return () => {
|
||||||
|
root.prepend(label);
|
||||||
|
};
|
||||||
|
`,
|
||||||
|
createdAt: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
runAdvancedMod(recipe);
|
||||||
|
expect(target.previousElementSibling).toBe(label);
|
||||||
|
|
||||||
|
stopAdvancedMod("test-mod");
|
||||||
|
expect(root.firstElementChild).toBe(label);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stops a previously started mod before restarting it", () => {
|
||||||
|
document.body.innerHTML = `<div id="root"><span class="badge">Y11HA</span></div>`;
|
||||||
|
const recipe: StoredModRecipe = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
id: "test-mod",
|
||||||
|
enabled: true,
|
||||||
|
route: "",
|
||||||
|
rootSelector: "#root",
|
||||||
|
name: "Hide badge",
|
||||||
|
description: "Hides badge",
|
||||||
|
operations: [],
|
||||||
|
advancedScript: `
|
||||||
|
const badge = select('.badge');
|
||||||
|
badge.hidden = true;
|
||||||
|
return () => { badge.hidden = false; };
|
||||||
|
`,
|
||||||
|
createdAt: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
runAdvancedMod(recipe);
|
||||||
|
expect(document.querySelector(".badge")).toHaveProperty("hidden", true);
|
||||||
|
runAdvancedMod(recipe);
|
||||||
|
expect(document.querySelector(".badge")).toHaveProperty("hidden", true);
|
||||||
|
stopAdvancedMod("test-mod");
|
||||||
|
expect(document.querySelector(".badge")).toHaveProperty("hidden", false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
import {
|
||||||
|
SAFE_ATTRIBUTE_NAMES,
|
||||||
|
SAFE_INSERT_TAGS,
|
||||||
|
SAFE_STYLE_PROPERTIES,
|
||||||
|
normalizeStyleProperty,
|
||||||
|
} from "./recipeSchema";
|
||||||
|
import { assertAdvancedScriptSafe } from "./scriptSafety";
|
||||||
|
import { applyModStyleProperty, restoreModStyleProperty } from "./modStyle";
|
||||||
|
import { aiModLog } from "./logger";
|
||||||
|
import type { StoredModRecipe } from "./types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test-only runtime. Production uses background User Scripts injection because
|
||||||
|
* SEQTA's CSP blocks eval/new Function inside content scripts.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const REGISTRY_KEY = Symbol.for("betterseqta.aiModRuntime");
|
||||||
|
type Cleanup = () => void;
|
||||||
|
|
||||||
|
function getRegistry(): Map<string, Cleanup> {
|
||||||
|
const globalScope = globalThis as typeof globalThis & {
|
||||||
|
[key: symbol]: Map<string, Cleanup> | undefined;
|
||||||
|
};
|
||||||
|
if (!globalScope[REGISTRY_KEY]) {
|
||||||
|
globalScope[REGISTRY_KEY] = new Map();
|
||||||
|
}
|
||||||
|
return globalScope[REGISTRY_KEY]!;
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentRoute(): string {
|
||||||
|
return (window.location.hash.split("?page=/")[1] ?? "").split(/[/?#]/)[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBsplus(root: HTMLElement, cleanups: Cleanup[]) {
|
||||||
|
const remember = (cleanup: unknown) => {
|
||||||
|
if (typeof cleanup === "function") cleanups.push(cleanup as Cleanup);
|
||||||
|
return cleanup;
|
||||||
|
};
|
||||||
|
const insideRoot = (element: Element) =>
|
||||||
|
element === root || root.contains(element);
|
||||||
|
const requireInsideRoot = (element: Element) => {
|
||||||
|
if (!insideRoot(element)) {
|
||||||
|
throw new Error("AI mod attempted to leave its selected root");
|
||||||
|
}
|
||||||
|
return element;
|
||||||
|
};
|
||||||
|
const select = (selector = ":scope") =>
|
||||||
|
selector === ":scope"
|
||||||
|
? root
|
||||||
|
: root.querySelector<HTMLElement>(selector);
|
||||||
|
const selectAll = (selector = ":scope") =>
|
||||||
|
selector === ":scope"
|
||||||
|
? [root]
|
||||||
|
: Array.from(root.querySelectorAll<HTMLElement>(selector));
|
||||||
|
|
||||||
|
return Object.freeze({
|
||||||
|
root,
|
||||||
|
select,
|
||||||
|
selectAll,
|
||||||
|
onCleanup: remember,
|
||||||
|
setText(element: HTMLElement, text: string) {
|
||||||
|
requireInsideRoot(element);
|
||||||
|
const previous = element.textContent;
|
||||||
|
element.textContent = String(text);
|
||||||
|
remember(() => {
|
||||||
|
element.textContent = previous;
|
||||||
|
});
|
||||||
|
return element;
|
||||||
|
},
|
||||||
|
setStyle(element: HTMLElement, property: string, value: string) {
|
||||||
|
requireInsideRoot(element);
|
||||||
|
const normalizedProperty = normalizeStyleProperty(property);
|
||||||
|
if (!SAFE_STYLE_PROPERTIES.includes(normalizedProperty as never)) {
|
||||||
|
throw new Error("Unsupported style property");
|
||||||
|
}
|
||||||
|
const snapshot = applyModStyleProperty(
|
||||||
|
element,
|
||||||
|
normalizedProperty,
|
||||||
|
String(value),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
remember(() =>
|
||||||
|
restoreModStyleProperty(element, normalizedProperty, snapshot),
|
||||||
|
);
|
||||||
|
return element;
|
||||||
|
},
|
||||||
|
setAttribute(element: HTMLElement, name: string, value: string) {
|
||||||
|
requireInsideRoot(element);
|
||||||
|
if (!SAFE_ATTRIBUTE_NAMES.includes(name as never)) {
|
||||||
|
throw new Error("Unsupported attribute");
|
||||||
|
}
|
||||||
|
const hadAttribute = element.hasAttribute(name);
|
||||||
|
const previous = element.getAttribute(name);
|
||||||
|
element.setAttribute(name, String(value));
|
||||||
|
remember(() =>
|
||||||
|
hadAttribute
|
||||||
|
? element.setAttribute(name, previous ?? "")
|
||||||
|
: element.removeAttribute(name),
|
||||||
|
);
|
||||||
|
return element;
|
||||||
|
},
|
||||||
|
create(tag: string, text: string, parent: HTMLElement = root) {
|
||||||
|
requireInsideRoot(parent);
|
||||||
|
if (!SAFE_INSERT_TAGS.includes(tag as never)) {
|
||||||
|
throw new Error("Unsupported element tag");
|
||||||
|
}
|
||||||
|
const element = document.createElement(tag);
|
||||||
|
element.textContent = String(text);
|
||||||
|
parent.append(element);
|
||||||
|
remember(() => element.remove());
|
||||||
|
return element;
|
||||||
|
},
|
||||||
|
on(
|
||||||
|
element: HTMLElement,
|
||||||
|
event: string,
|
||||||
|
handler: EventListenerOrEventListenerObject,
|
||||||
|
options?: boolean | AddEventListenerOptions,
|
||||||
|
) {
|
||||||
|
requireInsideRoot(element);
|
||||||
|
element.addEventListener(event, handler, options);
|
||||||
|
remember(() => element.removeEventListener(event, handler, options));
|
||||||
|
},
|
||||||
|
observe(
|
||||||
|
element: HTMLElement,
|
||||||
|
callback: MutationCallback,
|
||||||
|
options: MutationObserverInit = { childList: true, subtree: true },
|
||||||
|
) {
|
||||||
|
requireInsideRoot(element);
|
||||||
|
const observer = new MutationObserver(callback);
|
||||||
|
observer.observe(element, options);
|
||||||
|
remember(() => observer.disconnect());
|
||||||
|
return observer;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runAdvancedMod(recipe: StoredModRecipe): void {
|
||||||
|
if (!recipe.advancedScript) return;
|
||||||
|
|
||||||
|
stopAdvancedMod(recipe.id);
|
||||||
|
const script = assertAdvancedScriptSafe(recipe.advancedScript);
|
||||||
|
|
||||||
|
if (recipe.route && currentRoute() !== recipe.route) {
|
||||||
|
aiModLog.debug("runtime", `Skipped mod ${recipe.id} on route ${currentRoute()}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const root = document.querySelector(recipe.rootSelector);
|
||||||
|
if (!(root instanceof HTMLElement)) {
|
||||||
|
throw new Error(
|
||||||
|
`Selected root not found on this page: ${recipe.rootSelector}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanups: Cleanup[] = [];
|
||||||
|
const bsplus = createBsplus(root, cleanups);
|
||||||
|
const select = bsplus.select;
|
||||||
|
const selectAll = bsplus.selectAll;
|
||||||
|
let disposed = false;
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
if (disposed) return;
|
||||||
|
disposed = true;
|
||||||
|
for (const callback of cleanups.reverse()) {
|
||||||
|
try {
|
||||||
|
callback();
|
||||||
|
} catch (error) {
|
||||||
|
aiModLog.warn("runtime", `Cleanup failed for mod ${recipe.id}`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
getRegistry().delete(recipe.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const runner = new Function(
|
||||||
|
"root",
|
||||||
|
"bsplus",
|
||||||
|
"select",
|
||||||
|
"selectAll",
|
||||||
|
`"use strict"; return (() => { ${script} })();`,
|
||||||
|
) as (
|
||||||
|
root: HTMLElement,
|
||||||
|
bsplus: ReturnType<typeof createBsplus>,
|
||||||
|
select: typeof bsplus.select,
|
||||||
|
selectAll: typeof bsplus.selectAll,
|
||||||
|
) => unknown;
|
||||||
|
|
||||||
|
const userCleanup = runner(root, bsplus, select, selectAll);
|
||||||
|
if (typeof userCleanup === "function") {
|
||||||
|
cleanups.push(userCleanup as Cleanup);
|
||||||
|
}
|
||||||
|
getRegistry().set(recipe.id, cleanup);
|
||||||
|
aiModLog.info("runtime", `Started advanced mod ${recipe.id}`, recipe.name);
|
||||||
|
} catch (error) {
|
||||||
|
cleanup();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stopAdvancedMod(id: string): void {
|
||||||
|
const cleanup = getRegistry().get(id);
|
||||||
|
if (typeof cleanup === "function") {
|
||||||
|
cleanup();
|
||||||
|
aiModLog.info("runtime", `Stopped advanced mod ${id}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isAdvancedModRuntimeAvailable(): boolean {
|
||||||
|
return typeof document !== "undefined" && typeof Function !== "undefined";
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import { unmount } from "svelte";
|
||||||
|
import type { Plugin } from "@/plugins/core/types";
|
||||||
|
import renderSvelte from "@/interface/main";
|
||||||
|
import { syncPageThemeToElement } from "@/interface/utils/syncPageTheme";
|
||||||
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
|
import FloatingModCreator from "./FloatingModCreator.svelte";
|
||||||
|
import { ModRuntime } from "./modRuntime";
|
||||||
|
import { createCreatorServices } from "./services";
|
||||||
|
import { AI_MODS_STORAGE_KEY, loadStoredMods } from "./storage";
|
||||||
|
import { aiModLog } from "./logger";
|
||||||
|
|
||||||
|
const HOST_ATTRIBUTE = "data-bsplus-ai-mod-creator-host";
|
||||||
|
|
||||||
|
async function mountCreator(): Promise<() => void> {
|
||||||
|
document.querySelector(`[${HOST_ATTRIBUTE}]`)?.remove();
|
||||||
|
|
||||||
|
const host = document.createElement("div");
|
||||||
|
host.setAttribute(HOST_ATTRIBUTE, "");
|
||||||
|
Object.assign(host.style, {
|
||||||
|
position: "fixed",
|
||||||
|
right: "0",
|
||||||
|
bottom: "0",
|
||||||
|
width: "0",
|
||||||
|
height: "0",
|
||||||
|
zIndex: "2147483647",
|
||||||
|
});
|
||||||
|
document.body.appendChild(host);
|
||||||
|
syncPageThemeToElement(host);
|
||||||
|
|
||||||
|
const shadow = host.attachShadow({ mode: "open" });
|
||||||
|
const services = createCreatorServices();
|
||||||
|
const app = renderSvelte(
|
||||||
|
FloatingModCreator,
|
||||||
|
shadow,
|
||||||
|
{ services },
|
||||||
|
"content",
|
||||||
|
);
|
||||||
|
|
||||||
|
const runtime = new ModRuntime();
|
||||||
|
runtime.start();
|
||||||
|
let activeAdvancedScripts = new Map<string, number>();
|
||||||
|
|
||||||
|
const currentRoute = () => {
|
||||||
|
const path = window.location.hash.split("?page=/")[1] ?? "";
|
||||||
|
return path.split(/[/?#]/)[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
const syncMods = async () => {
|
||||||
|
const mods = await loadStoredMods();
|
||||||
|
aiModLog.debug("plugin", "Syncing stored mods", {
|
||||||
|
count: mods.length,
|
||||||
|
route: currentRoute(),
|
||||||
|
});
|
||||||
|
runtime.setRecipes(mods);
|
||||||
|
const route = currentRoute();
|
||||||
|
const nextAdvanced = mods.filter(
|
||||||
|
(mod) =>
|
||||||
|
mod.enabled &&
|
||||||
|
Boolean(mod.advancedScript) &&
|
||||||
|
(!mod.route || mod.route === route),
|
||||||
|
);
|
||||||
|
const nextIds = new Set(nextAdvanced.map((mod) => mod.id));
|
||||||
|
|
||||||
|
await Promise.all(
|
||||||
|
[...activeAdvancedScripts.keys()]
|
||||||
|
.filter((id) => !nextIds.has(id))
|
||||||
|
.map((id) =>
|
||||||
|
services.stopAdvancedScript(id).catch((error) => {
|
||||||
|
aiModLog.warn("plugin", `Failed to stop AI mod ${id}`, error);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const mod of nextAdvanced) {
|
||||||
|
if (activeAdvancedScripts.get(mod.id) === mod.updatedAt) continue;
|
||||||
|
try {
|
||||||
|
await services.executeAdvancedScript(mod);
|
||||||
|
aiModLog.info("plugin", `Started advanced mod ${mod.id}`);
|
||||||
|
} catch (error) {
|
||||||
|
aiModLog.warn("plugin", `Failed to execute advanced AI mod ${mod.id}`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
activeAdvancedScripts = new Map(
|
||||||
|
nextAdvanced.map((mod) => [mod.id, mod.updatedAt]),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
await syncMods();
|
||||||
|
|
||||||
|
const onStorageChanged = (
|
||||||
|
changes: Record<string, browser.Storage.StorageChange>,
|
||||||
|
areaName: string,
|
||||||
|
) => {
|
||||||
|
if (areaName !== "local" || !changes[AI_MODS_STORAGE_KEY]) return;
|
||||||
|
void syncMods();
|
||||||
|
};
|
||||||
|
browser.storage.onChanged.addListener(onStorageChanged);
|
||||||
|
window.addEventListener("hashchange", syncMods);
|
||||||
|
|
||||||
|
const themeObserver = new MutationObserver(() => syncPageThemeToElement(host));
|
||||||
|
themeObserver.observe(document.documentElement, {
|
||||||
|
attributes: true,
|
||||||
|
attributeFilter: ["class", "style"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const syncTheme = () => syncPageThemeToElement(host);
|
||||||
|
settingsState.register("DarkMode", syncTheme);
|
||||||
|
settingsState.register("selectedColor", syncTheme);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
settingsState.unregister("DarkMode", syncTheme);
|
||||||
|
settingsState.unregister("selectedColor", syncTheme);
|
||||||
|
themeObserver.disconnect();
|
||||||
|
browser.storage.onChanged.removeListener(onStorageChanged);
|
||||||
|
window.removeEventListener("hashchange", syncMods);
|
||||||
|
for (const id of activeAdvancedScripts.keys()) {
|
||||||
|
void services.stopAdvancedScript(id).catch((error) => {
|
||||||
|
console.warn(`[BetterSEQTA+] Failed to stop AI mod ${id}:`, error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
activeAdvancedScripts = new Map();
|
||||||
|
runtime.stop();
|
||||||
|
unmount(app);
|
||||||
|
host.remove();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const aiModCreatorPlugin: Plugin = {
|
||||||
|
id: "ai-mod-creator",
|
||||||
|
name: "AI Mod Creator",
|
||||||
|
description:
|
||||||
|
"Developer-only local creator for safe, declarative BetterSEQTA+ page mods.",
|
||||||
|
version: "0.1.0",
|
||||||
|
settings: {},
|
||||||
|
beta: true,
|
||||||
|
run: async () => {
|
||||||
|
let cleanup: (() => void) | null = null;
|
||||||
|
let generation = 0;
|
||||||
|
|
||||||
|
const syncEnabledState = async () => {
|
||||||
|
const currentGeneration = ++generation;
|
||||||
|
if (!settingsState.devMode) {
|
||||||
|
cleanup?.();
|
||||||
|
cleanup = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (cleanup) return;
|
||||||
|
const nextCleanup = await mountCreator();
|
||||||
|
if (
|
||||||
|
currentGeneration !== generation ||
|
||||||
|
!settingsState.devMode
|
||||||
|
) {
|
||||||
|
nextCleanup();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cleanup = nextCleanup;
|
||||||
|
};
|
||||||
|
|
||||||
|
const onDevModeChanged = () => void syncEnabledState();
|
||||||
|
settingsState.register("devMode", onDevModeChanged);
|
||||||
|
await syncEnabledState();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
generation += 1;
|
||||||
|
settingsState.unregister("devMode", onDevModeChanged);
|
||||||
|
cleanup?.();
|
||||||
|
cleanup = null;
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default aiModCreatorPlugin;
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
const PREFIX = "[BetterSEQTA+ AI Mod Creator]";
|
||||||
|
|
||||||
|
function serialize(value: unknown): unknown {
|
||||||
|
if (value instanceof Error) {
|
||||||
|
return { name: value.name, message: value.message, stack: value.stack };
|
||||||
|
}
|
||||||
|
if (typeof value === "string" && value.length > 4_000) {
|
||||||
|
return `${value.slice(0, 4_000)}… (${value.length} chars)`;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const aiModLog = {
|
||||||
|
debug(scope: string, ...details: unknown[]) {
|
||||||
|
console.debug(PREFIX, scope, ...details.map(serialize));
|
||||||
|
},
|
||||||
|
info(scope: string, ...details: unknown[]) {
|
||||||
|
console.info(PREFIX, scope, ...details.map(serialize));
|
||||||
|
},
|
||||||
|
warn(scope: string, ...details: unknown[]) {
|
||||||
|
console.warn(PREFIX, scope, ...details.map(serialize));
|
||||||
|
},
|
||||||
|
error(scope: string, ...details: unknown[]) {
|
||||||
|
console.error(PREFIX, scope, ...details.map(serialize));
|
||||||
|
},
|
||||||
|
group(scope: string, label: string, fn: () => void) {
|
||||||
|
console.groupCollapsed(`${PREFIX} ${scope} · ${label}`);
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} finally {
|
||||||
|
console.groupEnd();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
/** @jest-environment jsdom */
|
||||||
|
|
||||||
|
import { applyModRecipe, ModRuntime } from "./modRuntime";
|
||||||
|
import type { StoredModRecipe } from "./types";
|
||||||
|
|
||||||
|
function recipe(
|
||||||
|
operations: StoredModRecipe["operations"],
|
||||||
|
overrides: Partial<StoredModRecipe> = {},
|
||||||
|
): StoredModRecipe {
|
||||||
|
return {
|
||||||
|
schemaVersion: 1,
|
||||||
|
id: "mod-1",
|
||||||
|
name: "Test mod",
|
||||||
|
description: "Test",
|
||||||
|
enabled: true,
|
||||||
|
route: "assessments",
|
||||||
|
rootSelector: "#selected",
|
||||||
|
operations,
|
||||||
|
createdAt: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("safe AI mod runtime", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
window.location.hash = "#?page=/assessments";
|
||||||
|
document.body.innerHTML = `
|
||||||
|
<section id="selected" aria-label="Old label">
|
||||||
|
<h2 class="title">Old title</h2>
|
||||||
|
<p class="description">One old old</p>
|
||||||
|
</section>
|
||||||
|
<p id="outside">Outside</p>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
|
||||||
|
it("applies the supported standard-library operations", () => {
|
||||||
|
const cleanup = applyModRecipe(
|
||||||
|
recipe([
|
||||||
|
{
|
||||||
|
type: "setText",
|
||||||
|
selector: ":scope .title",
|
||||||
|
text: "New title",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "replaceText",
|
||||||
|
selector: ":scope .description",
|
||||||
|
search: "old",
|
||||||
|
replacement: "new",
|
||||||
|
all: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "setAttribute",
|
||||||
|
selector: ":scope",
|
||||||
|
name: "aria-label",
|
||||||
|
value: "New label",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope",
|
||||||
|
property: "border-radius",
|
||||||
|
value: "12px",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "addClass",
|
||||||
|
selector: ":scope",
|
||||||
|
className: "custom-card",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "hide",
|
||||||
|
selector: ":scope .description",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "insertText",
|
||||||
|
selector: ":scope",
|
||||||
|
position: "append",
|
||||||
|
tag: "span",
|
||||||
|
text: "Generated note",
|
||||||
|
className: "note",
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
document,
|
||||||
|
);
|
||||||
|
|
||||||
|
const selected = document.querySelector<HTMLElement>("#selected")!;
|
||||||
|
expect(selected.querySelector(".title")?.textContent).toBe("New title");
|
||||||
|
expect(selected.querySelector(".description")?.textContent).toBe(
|
||||||
|
"One new new",
|
||||||
|
);
|
||||||
|
expect(selected.querySelector<HTMLElement>(".description")?.style.display).toBe(
|
||||||
|
"none",
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
selected.querySelector<HTMLElement>(".description")?.style.getPropertyPriority(
|
||||||
|
"display",
|
||||||
|
),
|
||||||
|
).toBe("important");
|
||||||
|
expect(selected.getAttribute("aria-label")).toBe("New label");
|
||||||
|
expect(selected.style.borderRadius).toBe("12px");
|
||||||
|
expect(selected.style.getPropertyPriority("border-radius")).toBe("important");
|
||||||
|
expect(selected.classList.contains("custom-card")).toBe(true);
|
||||||
|
expect(selected.querySelector(".note")?.textContent).toBe("Generated note");
|
||||||
|
|
||||||
|
cleanup();
|
||||||
|
expect(selected.querySelector(".title")?.textContent).toBe("Old title");
|
||||||
|
expect(selected.querySelector(".description")?.textContent).toBe(
|
||||||
|
"One old old",
|
||||||
|
);
|
||||||
|
expect(selected.querySelector<HTMLElement>(".description")?.style.display).toBe(
|
||||||
|
"",
|
||||||
|
);
|
||||||
|
expect(selected.getAttribute("aria-label")).toBe("Old label");
|
||||||
|
expect(selected.style.borderRadius).toBe("");
|
||||||
|
expect(selected.classList.contains("custom-card")).toBe(false);
|
||||||
|
expect(selected.querySelector(".note")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never changes nodes outside the captured root", () => {
|
||||||
|
const cleanup = applyModRecipe(
|
||||||
|
recipe([{ type: "setText", selector: ":scope #outside", text: "Changed" }]),
|
||||||
|
document,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(document.querySelector("#outside")?.textContent).toBe("Outside");
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("applies setStyle with important priority to beat page CSS caps", () => {
|
||||||
|
window.location.hash = "#?page=/news";
|
||||||
|
document.body.innerHTML = `
|
||||||
|
<div class="home-root" id="selected">
|
||||||
|
<div class="home-container">News</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
const cleanup = applyModRecipe(
|
||||||
|
recipe(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope > div.home-container",
|
||||||
|
property: "max-width",
|
||||||
|
value: "100%",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope > div.home-container",
|
||||||
|
property: "width",
|
||||||
|
value: "100%",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ route: "news" },
|
||||||
|
),
|
||||||
|
document,
|
||||||
|
);
|
||||||
|
|
||||||
|
const container = document.querySelector<HTMLElement>(".home-container")!;
|
||||||
|
expect(container.style.getPropertyValue("max-width")).toBe("100%");
|
||||||
|
expect(container.style.getPropertyPriority("max-width")).toBe("important");
|
||||||
|
expect(container.style.getPropertyValue("width")).toBe("100%");
|
||||||
|
expect(container.style.getPropertyPriority("width")).toBe("important");
|
||||||
|
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reconciles enabled recipes after a SPA remount and restores on stop", async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
const runtime = new ModRuntime(document, () => "assessments");
|
||||||
|
runtime.start();
|
||||||
|
runtime.setRecipes(
|
||||||
|
recipe([{ type: "setText", selector: ":scope .title", text: "Changed" }]),
|
||||||
|
);
|
||||||
|
expect(document.querySelector(".title")?.textContent).toBe("Changed");
|
||||||
|
|
||||||
|
document.querySelector("#selected")!.outerHTML =
|
||||||
|
'<section id="selected"><h2 class="title">Remounted</h2></section>';
|
||||||
|
await Promise.resolve();
|
||||||
|
jest.runOnlyPendingTimers();
|
||||||
|
expect(document.querySelector(".title")?.textContent).toBe("Changed");
|
||||||
|
|
||||||
|
runtime.stop();
|
||||||
|
expect(document.querySelector(".title")?.textContent).toBe("Remounted");
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("applies only enabled recipes matching the current route", () => {
|
||||||
|
const runtime = new ModRuntime(document, () => "courses");
|
||||||
|
runtime.start();
|
||||||
|
runtime.setRecipes([
|
||||||
|
recipe([{ type: "setText", selector: ":scope .title", text: "Wrong" }]),
|
||||||
|
recipe(
|
||||||
|
[{ type: "setText", selector: ":scope .title", text: "Disabled" }],
|
||||||
|
{ id: "mod-2", route: "courses", enabled: false },
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(document.querySelector(".title")?.textContent).toBe("Old title");
|
||||||
|
runtime.stop();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
import { validateStoredRecipes } from "./recipeSchema";
|
||||||
|
import {
|
||||||
|
applyModStyleProperty,
|
||||||
|
restoreModStyleProperty,
|
||||||
|
} from "./modStyle";
|
||||||
|
import type { ModOperation, StoredModRecipe } from "./types";
|
||||||
|
type Cleanup = () => void;
|
||||||
|
|
||||||
|
function targetsFor(
|
||||||
|
root: HTMLElement,
|
||||||
|
selector: string,
|
||||||
|
): HTMLElement[] {
|
||||||
|
if (selector === ":scope") return [root];
|
||||||
|
try {
|
||||||
|
return [...root.querySelectorAll<HTMLElement>(selector)];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyOperation(
|
||||||
|
root: HTMLElement,
|
||||||
|
operation: ModOperation,
|
||||||
|
modId: string,
|
||||||
|
): Cleanup[] {
|
||||||
|
const cleanups: Cleanup[] = [];
|
||||||
|
for (const element of targetsFor(root, operation.selector)) {
|
||||||
|
switch (operation.type) {
|
||||||
|
case "setText":
|
||||||
|
case "replaceText": {
|
||||||
|
const previous = element.textContent;
|
||||||
|
if (operation.type === "setText") {
|
||||||
|
element.textContent = operation.text;
|
||||||
|
} else if (operation.all) {
|
||||||
|
element.textContent = (previous ?? "").split(operation.search).join(
|
||||||
|
operation.replacement,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
element.textContent = (previous ?? "").replace(
|
||||||
|
operation.search,
|
||||||
|
operation.replacement,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
cleanups.push(() => {
|
||||||
|
element.textContent = previous;
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "setAttribute": {
|
||||||
|
const hadAttribute = element.hasAttribute(operation.name);
|
||||||
|
const previous = element.getAttribute(operation.name);
|
||||||
|
element.setAttribute(operation.name, operation.value);
|
||||||
|
cleanups.push(() => {
|
||||||
|
if (hadAttribute && previous !== null) {
|
||||||
|
element.setAttribute(operation.name, previous);
|
||||||
|
} else {
|
||||||
|
element.removeAttribute(operation.name);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "setStyle": {
|
||||||
|
const important = operation.important !== false;
|
||||||
|
const snapshot = applyModStyleProperty(
|
||||||
|
element,
|
||||||
|
operation.property,
|
||||||
|
operation.value,
|
||||||
|
important,
|
||||||
|
);
|
||||||
|
cleanups.push(() => {
|
||||||
|
restoreModStyleProperty(element, operation.property, snapshot);
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "addClass":
|
||||||
|
case "removeClass": {
|
||||||
|
const hadClass = element.classList.contains(operation.className);
|
||||||
|
element.classList.toggle(
|
||||||
|
operation.className,
|
||||||
|
operation.type === "addClass",
|
||||||
|
);
|
||||||
|
cleanups.push(() => {
|
||||||
|
element.classList.toggle(operation.className, hadClass);
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "hide":
|
||||||
|
case "show": {
|
||||||
|
const previous = element.style.getPropertyValue("display");
|
||||||
|
const priority = element.style.getPropertyPriority("display");
|
||||||
|
if (operation.type === "hide") {
|
||||||
|
element.style.setProperty("display", "none", "important");
|
||||||
|
} else {
|
||||||
|
element.style.removeProperty("display");
|
||||||
|
}
|
||||||
|
cleanups.push(() => {
|
||||||
|
if (previous) {
|
||||||
|
element.style.setProperty("display", previous, priority);
|
||||||
|
} else {
|
||||||
|
element.style.removeProperty("display");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "insertText": {
|
||||||
|
if (
|
||||||
|
element === root &&
|
||||||
|
(operation.position === "before" || operation.position === "after")
|
||||||
|
) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const inserted = document.createElement(operation.tag);
|
||||||
|
inserted.textContent = operation.text;
|
||||||
|
inserted.dataset.bsplusAiMod = modId;
|
||||||
|
if (operation.className) inserted.classList.add(operation.className);
|
||||||
|
if (operation.position === "before") {
|
||||||
|
element.before(inserted);
|
||||||
|
} else if (operation.position === "after") {
|
||||||
|
element.after(inserted);
|
||||||
|
} else if (operation.position === "prepend") {
|
||||||
|
element.prepend(inserted);
|
||||||
|
} else {
|
||||||
|
element.append(inserted);
|
||||||
|
}
|
||||||
|
cleanups.push(() => inserted.remove());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cleanups;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyModRecipe(
|
||||||
|
input: StoredModRecipe,
|
||||||
|
documentRef: Document = document,
|
||||||
|
): Cleanup {
|
||||||
|
const [recipe] = validateStoredRecipes([input]);
|
||||||
|
let root: HTMLElement | null = null;
|
||||||
|
try {
|
||||||
|
root = documentRef.querySelector<HTMLElement>(recipe.rootSelector);
|
||||||
|
} catch {
|
||||||
|
return () => {};
|
||||||
|
}
|
||||||
|
if (!root) return () => {};
|
||||||
|
|
||||||
|
const cleanups = recipe.operations.flatMap((operation) =>
|
||||||
|
applyOperation(root!, operation, recipe.id),
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
for (const cleanup of [...cleanups].reverse()) cleanup();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ModRuntime {
|
||||||
|
private recipes: StoredModRecipe[] = [];
|
||||||
|
private cleanups: Cleanup[] = [];
|
||||||
|
private observer: MutationObserver | null = null;
|
||||||
|
private reconcileTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private running = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly documentRef: Document = document,
|
||||||
|
private readonly getRoute: () => string = () => {
|
||||||
|
const route = window.location.hash.split("?page=/")[1] ?? "";
|
||||||
|
return route.split(/[/?#]/)[0];
|
||||||
|
},
|
||||||
|
) {}
|
||||||
|
|
||||||
|
start(): void {
|
||||||
|
if (this.running) return;
|
||||||
|
this.running = true;
|
||||||
|
this.observer = new MutationObserver(() => this.scheduleReconcile());
|
||||||
|
this.observe();
|
||||||
|
window.addEventListener("hashchange", this.handleRouteChange);
|
||||||
|
this.reconcile();
|
||||||
|
}
|
||||||
|
|
||||||
|
setRecipes(input: StoredModRecipe | StoredModRecipe[]): void {
|
||||||
|
this.recipes = validateStoredRecipes(
|
||||||
|
Array.isArray(input) ? input : [input],
|
||||||
|
);
|
||||||
|
if (this.running) this.reconcile();
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
this.running = false;
|
||||||
|
if (this.reconcileTimer) clearTimeout(this.reconcileTimer);
|
||||||
|
this.reconcileTimer = null;
|
||||||
|
this.observer?.disconnect();
|
||||||
|
this.observer = null;
|
||||||
|
window.removeEventListener("hashchange", this.handleRouteChange);
|
||||||
|
this.clearAppliedMods();
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly handleRouteChange = () => this.scheduleReconcile();
|
||||||
|
|
||||||
|
private observe(): void {
|
||||||
|
if (!this.observer || !this.documentRef.body) return;
|
||||||
|
this.observer.observe(this.documentRef.body, {
|
||||||
|
childList: true,
|
||||||
|
subtree: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleReconcile(): void {
|
||||||
|
if (!this.running || this.reconcileTimer) return;
|
||||||
|
this.reconcileTimer = setTimeout(() => {
|
||||||
|
this.reconcileTimer = null;
|
||||||
|
this.reconcile();
|
||||||
|
}, 40);
|
||||||
|
}
|
||||||
|
|
||||||
|
private clearAppliedMods(): void {
|
||||||
|
for (const cleanup of [...this.cleanups].reverse()) cleanup();
|
||||||
|
this.cleanups = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
private reconcile(): void {
|
||||||
|
if (!this.running) return;
|
||||||
|
this.observer?.disconnect();
|
||||||
|
this.clearAppliedMods();
|
||||||
|
const route = this.getRoute();
|
||||||
|
this.cleanups = this.recipes
|
||||||
|
.filter((recipe) => recipe.enabled && recipe.route === route)
|
||||||
|
.map((recipe) => applyModRecipe(recipe, this.documentRef));
|
||||||
|
this.observe();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
/** @jest-environment jsdom */
|
||||||
|
|
||||||
|
import {
|
||||||
|
applyModStyleProperty,
|
||||||
|
restoreModStyleProperty,
|
||||||
|
stripStyleImportantSuffix,
|
||||||
|
} from "./modStyle";
|
||||||
|
|
||||||
|
describe("modStyle", () => {
|
||||||
|
it("strips trailing !important from values", () => {
|
||||||
|
expect(stripStyleImportantSuffix("100% !important")).toBe("100%");
|
||||||
|
expect(stripStyleImportantSuffix("100% !IMPORTANT")).toBe("100%");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("applies styles with important priority by default", () => {
|
||||||
|
const element = document.createElement("div");
|
||||||
|
const snapshot = applyModStyleProperty(element, "max-width", "100%");
|
||||||
|
expect(element.style.getPropertyValue("max-width")).toBe("100%");
|
||||||
|
expect(element.style.getPropertyPriority("max-width")).toBe("important");
|
||||||
|
restoreModStyleProperty(element, "max-width", snapshot);
|
||||||
|
expect(element.style.getPropertyValue("max-width")).toBe("");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/** Apply mod styles with priority over BetterSEQTA page CSS. */
|
||||||
|
export function stripStyleImportantSuffix(value: string): string {
|
||||||
|
return value.replace(/\s*!important\s*$/i, "").trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ModStyleSnapshot {
|
||||||
|
previous: string;
|
||||||
|
priority: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyModStyleProperty(
|
||||||
|
element: HTMLElement,
|
||||||
|
property: string,
|
||||||
|
value: string,
|
||||||
|
important = true,
|
||||||
|
): ModStyleSnapshot {
|
||||||
|
const previous = element.style.getPropertyValue(property);
|
||||||
|
const priority = element.style.getPropertyPriority(property);
|
||||||
|
element.style.setProperty(
|
||||||
|
property,
|
||||||
|
stripStyleImportantSuffix(value),
|
||||||
|
important ? "important" : "",
|
||||||
|
);
|
||||||
|
return { previous, priority };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function restoreModStyleProperty(
|
||||||
|
element: HTMLElement,
|
||||||
|
property: string,
|
||||||
|
snapshot: ModStyleSnapshot,
|
||||||
|
): void {
|
||||||
|
if (snapshot.previous) {
|
||||||
|
element.style.setProperty(property, snapshot.previous, snapshot.priority);
|
||||||
|
} else {
|
||||||
|
element.style.removeProperty(property);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
export const DEFAULT_OPENROUTER_MODEL_ID = "minimax/minimax-m2.7:free";
|
||||||
|
|
||||||
|
export interface AiModModelOption {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
description: string;
|
||||||
|
tier: "free" | "paid";
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AI_MOD_MODEL_OPTIONS: readonly AiModModelOption[] = [
|
||||||
|
{
|
||||||
|
id: "minimax/minimax-m2.7:free",
|
||||||
|
label: "MiniMax M2.7 (free)",
|
||||||
|
description:
|
||||||
|
"Best free option for agentic DOM mods. Separate provider rate limits apply.",
|
||||||
|
tier: "free",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "minimax/minimax-m3:free",
|
||||||
|
label: "MiniMax M3 (free)",
|
||||||
|
description: "Alternate free MiniMax with GMICloud rate limits.",
|
||||||
|
tier: "free",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "google/gemma-3-27b-it:free",
|
||||||
|
label: "Gemma 3 27B (free)",
|
||||||
|
description: "Free Google model; useful when MiniMax free tiers are busy.",
|
||||||
|
tier: "free",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "meta-llama/llama-3.3-70b-instruct:free",
|
||||||
|
label: "Llama 3.3 70B (free)",
|
||||||
|
description: "Free Meta model with broader availability.",
|
||||||
|
tier: "free",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "minimax/minimax-m3",
|
||||||
|
label: "MiniMax M3 (paid)",
|
||||||
|
description: "Paid tier with much higher rate limits.",
|
||||||
|
tier: "paid",
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const ALLOWED_OPENROUTER_MODEL_IDS = new Set(
|
||||||
|
AI_MOD_MODEL_OPTIONS.map((option) => option.id),
|
||||||
|
);
|
||||||
|
|
||||||
|
export function validateModelId(value: unknown): string {
|
||||||
|
if (typeof value !== "string") {
|
||||||
|
throw new Error("Model id is required");
|
||||||
|
}
|
||||||
|
const modelId = value.trim();
|
||||||
|
if (!ALLOWED_OPENROUTER_MODEL_IDS.has(modelId)) {
|
||||||
|
throw new Error("Unsupported OpenRouter model");
|
||||||
|
}
|
||||||
|
return modelId;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getModelOption(modelId: string): AiModModelOption | undefined {
|
||||||
|
return AI_MOD_MODEL_OPTIONS.find((option) => option.id === modelId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
/** @jest-environment jsdom */
|
||||||
|
|
||||||
|
import { buildSelectedElementContext } from "./pageContext";
|
||||||
|
|
||||||
|
describe("selected element context", () => {
|
||||||
|
it("sends only the selected subtree and redacts active content and values", () => {
|
||||||
|
document.body.innerHTML = `
|
||||||
|
<div id="outside">Never include me</div>
|
||||||
|
<section id="selected" onclick="steal()" data-session="secret">
|
||||||
|
<input value="student@example.test" placeholder="Email">
|
||||||
|
<a href="https://example.test/token?secret=1">Assessment details</a>
|
||||||
|
<script>window.secret = "bad"</script>
|
||||||
|
<p>Selected text</p>
|
||||||
|
</section>
|
||||||
|
`;
|
||||||
|
const selected = document.querySelector<HTMLElement>("#selected")!;
|
||||||
|
|
||||||
|
const context = buildSelectedElementContext(selected, {
|
||||||
|
route: "assessments",
|
||||||
|
rootSelector: "#selected",
|
||||||
|
request: "Make this clearer",
|
||||||
|
userContext: "This is an assessment card.",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(context.selectedHtml).toContain("Selected text");
|
||||||
|
expect(context.selectedHtml).not.toContain("Never include me");
|
||||||
|
expect(context.selectedHtml).not.toContain("student@example.test");
|
||||||
|
expect(context.selectedHtml).not.toContain("onclick");
|
||||||
|
expect(context.selectedHtml).not.toContain("data-session");
|
||||||
|
expect(context.selectedHtml).not.toContain("<script");
|
||||||
|
expect(context.selectedHtml).not.toContain("secret=1");
|
||||||
|
expect(context.domCatalog.length).toBeGreaterThan(0);
|
||||||
|
expect(context.domCatalog[0]).toMatchObject({
|
||||||
|
selector: ":scope",
|
||||||
|
tag: "section",
|
||||||
|
});
|
||||||
|
expect(context).toMatchObject({
|
||||||
|
route: "assessments",
|
||||||
|
rootSelector: "#selected",
|
||||||
|
request: "Make this clearer",
|
||||||
|
userContext: "This is an assessment card.",
|
||||||
|
tagName: "section",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("includes parent context and a layout catalog for nested structures", () => {
|
||||||
|
document.body.innerHTML = `
|
||||||
|
<div class="titlebar">
|
||||||
|
<div class="userInfo">
|
||||||
|
<div class="userInfoText" style="display: flex; flex-direction: column; align-items: flex-end;">
|
||||||
|
<div style="display: flex; align-items: center;">
|
||||||
|
<p class="userInfohouse userInfoCode">Y11HA</p>
|
||||||
|
<p class="userInfoName">Jaxon Lewis-Wilson</p>
|
||||||
|
</div>
|
||||||
|
<p class="userInfoCode">15845 // 33804833</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
const selected = document.querySelector<HTMLElement>(".userInfoText")!;
|
||||||
|
|
||||||
|
const context = buildSelectedElementContext(selected, {
|
||||||
|
route: "welcome",
|
||||||
|
rootSelector: ".userInfoText",
|
||||||
|
request: "Move house next to ID",
|
||||||
|
userContext: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(context.ancestorHtml).toContain("userInfo");
|
||||||
|
expect(context.selectedHtml).toContain('display: flex');
|
||||||
|
expect(context.domCatalog).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
tag: "p",
|
||||||
|
classes: ["userInfoCode"],
|
||||||
|
directText: "15845 // 33804833",
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
tag: "p",
|
||||||
|
classes: expect.arrayContaining(["userInfohouse", "userInfoCode"]),
|
||||||
|
directText: "Y11HA",
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
context.domCatalog.find((entry) => entry.selector === ":scope")?.layout,
|
||||||
|
).toMatchObject({
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
alignItems: "flex-end",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("caps all user-controlled fields", () => {
|
||||||
|
const selected = document.createElement("div");
|
||||||
|
selected.textContent = "x".repeat(30_000);
|
||||||
|
document.body.appendChild(selected);
|
||||||
|
|
||||||
|
const context = buildSelectedElementContext(selected, {
|
||||||
|
route: "r".repeat(2_000),
|
||||||
|
rootSelector: "#selected",
|
||||||
|
request: "q".repeat(5_000),
|
||||||
|
userContext: "c".repeat(8_000),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(context.selectedHtml.length).toBeLessThanOrEqual(24_000);
|
||||||
|
expect(context.route.length).toBeLessThanOrEqual(256);
|
||||||
|
expect(context.request.length).toBeLessThanOrEqual(2_000);
|
||||||
|
expect(context.userContext.length).toBeLessThanOrEqual(4_000);
|
||||||
|
expect(context.domCatalog.length).toBeLessThanOrEqual(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("captures only a small allowlisted computed-style summary", () => {
|
||||||
|
const selected = document.createElement("div");
|
||||||
|
selected.style.color = "rgb(1, 2, 3)";
|
||||||
|
selected.style.backgroundColor = "rgb(4, 5, 6)";
|
||||||
|
selected.style.backgroundImage = "url(https://example.test/pixel)";
|
||||||
|
document.body.appendChild(selected);
|
||||||
|
|
||||||
|
const context = buildSelectedElementContext(selected, {
|
||||||
|
route: "",
|
||||||
|
rootSelector: "div",
|
||||||
|
request: "Restyle",
|
||||||
|
userContext: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(context.computedStyle).toMatchObject({
|
||||||
|
color: "rgb(1, 2, 3)",
|
||||||
|
backgroundColor: "rgb(4, 5, 6)",
|
||||||
|
});
|
||||||
|
expect(context.computedStyle).not.toHaveProperty("backgroundImage");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("includes parent chain summaries for placement context", () => {
|
||||||
|
document.body.innerHTML = `
|
||||||
|
<div class="titlebar" style="display: flex; align-items: center;">
|
||||||
|
<div class="userInfo" style="display: flex;">
|
||||||
|
<div class="userInfoText" style="display: flex; flex-direction: column;">
|
||||||
|
<p class="userInfoCode">15845</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
const selected = document.querySelector<HTMLElement>(".userInfoText")!;
|
||||||
|
|
||||||
|
const context = buildSelectedElementContext(selected, {
|
||||||
|
route: "welcome",
|
||||||
|
rootSelector: ".userInfoText",
|
||||||
|
request: "Reorder items",
|
||||||
|
userContext: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(context.parentChain).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
tag: "div",
|
||||||
|
classes: ["userInfo"],
|
||||||
|
layout: expect.objectContaining({ display: "flex" }),
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
tag: "div",
|
||||||
|
classes: ["titlebar"],
|
||||||
|
layout: expect.objectContaining({
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
expect(context.structuralHints).toMatchObject({
|
||||||
|
hasTable: false,
|
||||||
|
hasList: false,
|
||||||
|
primaryClasses: ["userInfoText"],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("includes table and list structure counts in root catalog and hints", () => {
|
||||||
|
document.body.innerHTML = `
|
||||||
|
<table class="assessmentTable">
|
||||||
|
<tr><th>Name</th><th>Grade</th><th>Due</th></tr>
|
||||||
|
<tr><td>Essay</td><td>A</td><td>Mon</td></tr>
|
||||||
|
<tr><td>Quiz</td><td>B</td><td>Tue</td></tr>
|
||||||
|
</table>
|
||||||
|
`;
|
||||||
|
const table = document.querySelector<HTMLElement>(".assessmentTable")!;
|
||||||
|
|
||||||
|
const tableContext = buildSelectedElementContext(table, {
|
||||||
|
route: "assessments",
|
||||||
|
rootSelector: ".assessmentTable",
|
||||||
|
request: "Highlight header row",
|
||||||
|
userContext: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
tableContext.domCatalog.find((entry) => entry.selector === ":scope"),
|
||||||
|
).toMatchObject({
|
||||||
|
rowCount: 3,
|
||||||
|
columnCount: 3,
|
||||||
|
});
|
||||||
|
expect(tableContext.structuralHints).toMatchObject({
|
||||||
|
hasTable: true,
|
||||||
|
hasList: false,
|
||||||
|
rowCount: 3,
|
||||||
|
columnCount: 3,
|
||||||
|
primaryClasses: ["assessmentTable"],
|
||||||
|
});
|
||||||
|
|
||||||
|
document.body.innerHTML = `
|
||||||
|
<ul class="taskList">
|
||||||
|
<li>Task one</li>
|
||||||
|
<li>Task two</li>
|
||||||
|
<li>Task three</li>
|
||||||
|
</ul>
|
||||||
|
`;
|
||||||
|
const list = document.querySelector<HTMLElement>(".taskList")!;
|
||||||
|
|
||||||
|
const listContext = buildSelectedElementContext(list, {
|
||||||
|
route: "tasks",
|
||||||
|
rootSelector: ".taskList",
|
||||||
|
request: "Bold first item",
|
||||||
|
userContext: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
listContext.domCatalog.find((entry) => entry.selector === ":scope"),
|
||||||
|
).toMatchObject({
|
||||||
|
itemCount: 3,
|
||||||
|
});
|
||||||
|
expect(listContext.structuralHints).toMatchObject({
|
||||||
|
hasTable: false,
|
||||||
|
hasList: true,
|
||||||
|
itemCount: 3,
|
||||||
|
primaryClasses: ["taskList"],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
import { buildScopeRelativeSelector } from "./selection";
|
||||||
|
import type {
|
||||||
|
DomElementSummary,
|
||||||
|
ParentChainSummary,
|
||||||
|
SelectedElementContext,
|
||||||
|
StructuralHints,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
|
const HTML_LIMIT = 24_000;
|
||||||
|
const ANCESTOR_HTML_LIMIT = 6_000;
|
||||||
|
const REQUEST_LIMIT = 2_000;
|
||||||
|
const USER_CONTEXT_LIMIT = 4_000;
|
||||||
|
const ROUTE_LIMIT = 256;
|
||||||
|
const DOM_CATALOG_LIMIT = 100;
|
||||||
|
const DIRECT_TEXT_LIMIT = 120;
|
||||||
|
const PARENT_CHAIN_LIMIT = 3;
|
||||||
|
const CLASS_LIMIT = 8;
|
||||||
|
|
||||||
|
const COMPUTED_STYLE_PROPERTIES = [
|
||||||
|
["color", "color"],
|
||||||
|
["backgroundColor", "background-color"],
|
||||||
|
["display", "display"],
|
||||||
|
["flexDirection", "flex-direction"],
|
||||||
|
["alignItems", "align-items"],
|
||||||
|
["justifyContent", "justify-content"],
|
||||||
|
["gap", "gap"],
|
||||||
|
["flexWrap", "flex-wrap"],
|
||||||
|
["fontSize", "font-size"],
|
||||||
|
["fontWeight", "font-weight"],
|
||||||
|
["padding", "padding"],
|
||||||
|
["margin", "margin"],
|
||||||
|
["border", "border"],
|
||||||
|
["borderRadius", "border-radius"],
|
||||||
|
["width", "width"],
|
||||||
|
["height", "height"],
|
||||||
|
["textAlign", "text-align"],
|
||||||
|
["opacity", "opacity"],
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const ALLOWED_INLINE_STYLE =
|
||||||
|
/^(display|flex|align-items|justify-content|gap|flex-direction|flex-wrap|text-align|padding|margin|border-radius|opacity|font-size|font-weight|width|height|background-color|color)$/i;
|
||||||
|
|
||||||
|
function cap(value: string, maxLength: number): string {
|
||||||
|
return value.trim().slice(0, maxLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeInlineStyle(value: string): string {
|
||||||
|
return value
|
||||||
|
.split(";")
|
||||||
|
.map((part) => part.trim())
|
||||||
|
.filter((part) => {
|
||||||
|
if (!part.includes(":")) return false;
|
||||||
|
const name = part.split(":")[0]?.trim() ?? "";
|
||||||
|
return (
|
||||||
|
ALLOWED_INLINE_STYLE.test(name) &&
|
||||||
|
!/url\s*\(|expression\s*\(|javascript\s*:/i.test(part)
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.join("; ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeClone(element: HTMLElement): HTMLElement {
|
||||||
|
const clone = element.cloneNode(true) as HTMLElement;
|
||||||
|
clone
|
||||||
|
.querySelectorAll(
|
||||||
|
"script,style,noscript,iframe,object,embed,link,meta,template",
|
||||||
|
)
|
||||||
|
.forEach((node) => node.remove());
|
||||||
|
|
||||||
|
const nodes = [clone, ...clone.querySelectorAll<HTMLElement>("*")];
|
||||||
|
for (const node of nodes) {
|
||||||
|
for (const attribute of [...node.attributes]) {
|
||||||
|
const name = attribute.name.toLowerCase();
|
||||||
|
if (
|
||||||
|
name.startsWith("on") ||
|
||||||
|
name.startsWith("data-") ||
|
||||||
|
[
|
||||||
|
"action",
|
||||||
|
"checked",
|
||||||
|
"formaction",
|
||||||
|
"href",
|
||||||
|
"selected",
|
||||||
|
"src",
|
||||||
|
"srcset",
|
||||||
|
"value",
|
||||||
|
].includes(name)
|
||||||
|
) {
|
||||||
|
node.removeAttribute(attribute.name);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (name === "style") {
|
||||||
|
const sanitizedStyle = sanitizeInlineStyle(attribute.value);
|
||||||
|
if (sanitizedStyle) node.setAttribute("style", sanitizedStyle);
|
||||||
|
else node.removeAttribute("style");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return clone;
|
||||||
|
}
|
||||||
|
|
||||||
|
function computedStyleSummary(element: HTMLElement): Record<string, string> {
|
||||||
|
const style = getComputedStyle(element);
|
||||||
|
return Object.fromEntries(
|
||||||
|
COMPUTED_STYLE_PROPERTIES.map(([outputName, cssName]) => [
|
||||||
|
outputName,
|
||||||
|
style.getPropertyValue(cssName) ||
|
||||||
|
(style as unknown as Record<string, string>)[outputName] ||
|
||||||
|
"",
|
||||||
|
]).filter(([, value]) => value.length > 0),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function directText(element: HTMLElement): string | undefined {
|
||||||
|
const chunks: string[] = [];
|
||||||
|
for (const node of element.childNodes) {
|
||||||
|
if (node.nodeType === Node.TEXT_NODE) {
|
||||||
|
const text = node.textContent?.replace(/\s+/g, " ").trim() ?? "";
|
||||||
|
if (text) chunks.push(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (chunks.length === 0) return undefined;
|
||||||
|
return cap(chunks.join(" "), DIRECT_TEXT_LIMIT);
|
||||||
|
}
|
||||||
|
|
||||||
|
function classSummary(element: HTMLElement): string[] {
|
||||||
|
return [...element.classList].slice(0, CLASS_LIMIT);
|
||||||
|
}
|
||||||
|
|
||||||
|
function findTable(element: HTMLElement): HTMLTableElement | null {
|
||||||
|
if (element instanceof HTMLTableElement) return element;
|
||||||
|
return element.querySelector("table");
|
||||||
|
}
|
||||||
|
|
||||||
|
function findList(element: HTMLElement): HTMLUListElement | HTMLOListElement | null {
|
||||||
|
if (element instanceof HTMLUListElement || element instanceof HTMLOListElement) {
|
||||||
|
return element;
|
||||||
|
}
|
||||||
|
return element.querySelector("ul, ol");
|
||||||
|
}
|
||||||
|
|
||||||
|
function tableMetrics(
|
||||||
|
element: HTMLElement,
|
||||||
|
): { rowCount: number; columnCount: number } | null {
|
||||||
|
const table = findTable(element);
|
||||||
|
if (!table) return null;
|
||||||
|
|
||||||
|
const rows = [...table.querySelectorAll("tr")];
|
||||||
|
const columnCount = rows.reduce((max, row) => {
|
||||||
|
const cells = row.querySelectorAll("td, th").length;
|
||||||
|
return Math.max(max, cells);
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
return { rowCount: rows.length, columnCount };
|
||||||
|
}
|
||||||
|
|
||||||
|
function listMetrics(element: HTMLElement): { itemCount: number } | null {
|
||||||
|
const list = findList(element);
|
||||||
|
if (!list) return null;
|
||||||
|
return { itemCount: list.querySelectorAll(":scope > li").length };
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildStructuralHints(element: HTMLElement): StructuralHints {
|
||||||
|
const table = tableMetrics(element);
|
||||||
|
const list = listMetrics(element);
|
||||||
|
|
||||||
|
return {
|
||||||
|
hasTable: table !== null,
|
||||||
|
hasList: list !== null,
|
||||||
|
...(table ? table : {}),
|
||||||
|
...(list ? list : {}),
|
||||||
|
primaryClasses: classSummary(element),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildParentChain(element: HTMLElement): ParentChainSummary[] {
|
||||||
|
const chain: ParentChainSummary[] = [];
|
||||||
|
let current = element.parentElement;
|
||||||
|
|
||||||
|
while (
|
||||||
|
current &&
|
||||||
|
current !== document.body &&
|
||||||
|
current !== document.documentElement &&
|
||||||
|
chain.length < PARENT_CHAIN_LIMIT
|
||||||
|
) {
|
||||||
|
chain.push({
|
||||||
|
tag: current.tagName.toLowerCase(),
|
||||||
|
classes: classSummary(current),
|
||||||
|
layout: computedStyleSummary(current),
|
||||||
|
});
|
||||||
|
current = current.parentElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
return chain;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rootStructureSummary(
|
||||||
|
root: HTMLElement,
|
||||||
|
): Pick<DomElementSummary, "rowCount" | "columnCount" | "itemCount"> {
|
||||||
|
const table = tableMetrics(root);
|
||||||
|
const list = listMetrics(root);
|
||||||
|
return {
|
||||||
|
...(table ?? {}),
|
||||||
|
...(list ?? {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildDomCatalog(root: HTMLElement): DomElementSummary[] {
|
||||||
|
const nodes = [root, ...root.querySelectorAll<HTMLElement>("*")].slice(
|
||||||
|
0,
|
||||||
|
DOM_CATALOG_LIMIT,
|
||||||
|
);
|
||||||
|
|
||||||
|
return nodes.map((node) => {
|
||||||
|
const parent = node.parentElement;
|
||||||
|
const parentSelector =
|
||||||
|
parent && root.contains(parent)
|
||||||
|
? buildScopeRelativeSelector(root, parent)
|
||||||
|
: node === root
|
||||||
|
? null
|
||||||
|
: ":scope";
|
||||||
|
const siblings = parent
|
||||||
|
? [...parent.children].filter((child) => child instanceof HTMLElement)
|
||||||
|
: [root];
|
||||||
|
|
||||||
|
const summary: DomElementSummary = {
|
||||||
|
selector: buildScopeRelativeSelector(root, node),
|
||||||
|
tag: node.tagName.toLowerCase(),
|
||||||
|
classes: classSummary(node),
|
||||||
|
...(directText(node) ? { directText: directText(node) } : {}),
|
||||||
|
parentSelector,
|
||||||
|
siblingIndex: siblings.indexOf(node),
|
||||||
|
siblingCount: siblings.length,
|
||||||
|
layout: computedStyleSummary(node),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (node === root) {
|
||||||
|
Object.assign(summary, rootStructureSummary(root));
|
||||||
|
}
|
||||||
|
|
||||||
|
return summary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildAncestorContext(root: HTMLElement): { ancestorHtml?: string } {
|
||||||
|
const parent = root.parentElement;
|
||||||
|
if (
|
||||||
|
!parent ||
|
||||||
|
parent === document.body ||
|
||||||
|
parent === document.documentElement
|
||||||
|
) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ancestorHtml: sanitizeClone(parent).outerHTML.slice(0, ANCESTOR_HTML_LIMIT),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildSelectedElementContext(
|
||||||
|
element: HTMLElement,
|
||||||
|
input: {
|
||||||
|
route: string;
|
||||||
|
rootSelector: string;
|
||||||
|
request: string;
|
||||||
|
userContext: string;
|
||||||
|
},
|
||||||
|
): SelectedElementContext {
|
||||||
|
const rect = element.getBoundingClientRect();
|
||||||
|
const sanitized = sanitizeClone(element);
|
||||||
|
const ancestor = buildAncestorContext(element);
|
||||||
|
const parentChain = buildParentChain(element);
|
||||||
|
const structuralHints = buildStructuralHints(element);
|
||||||
|
|
||||||
|
return {
|
||||||
|
route: cap(input.route, ROUTE_LIMIT),
|
||||||
|
rootSelector: cap(input.rootSelector, 1_000),
|
||||||
|
request: cap(input.request, REQUEST_LIMIT),
|
||||||
|
userContext: cap(input.userContext, USER_CONTEXT_LIMIT),
|
||||||
|
selectedHtml: sanitized.outerHTML.slice(0, HTML_LIMIT),
|
||||||
|
domCatalog: buildDomCatalog(element),
|
||||||
|
...(ancestor.ancestorHtml ? { ancestorHtml: ancestor.ancestorHtml } : {}),
|
||||||
|
...(parentChain.length > 0 ? { parentChain } : {}),
|
||||||
|
structuralHints,
|
||||||
|
tagName: element.tagName.toLowerCase(),
|
||||||
|
dimensions: {
|
||||||
|
width: Math.round(rect.width),
|
||||||
|
height: Math.round(rect.height),
|
||||||
|
},
|
||||||
|
computedStyle: computedStyleSummary(element),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import {
|
||||||
|
SAFE_ATTRIBUTE_NAMES,
|
||||||
|
SAFE_INSERT_POSITIONS,
|
||||||
|
SAFE_INSERT_TAGS,
|
||||||
|
SAFE_STYLE_PROPERTIES,
|
||||||
|
} from "./recipeSchema";
|
||||||
|
import type { SelectedElementContext } from "./types";
|
||||||
|
|
||||||
|
const operationSchemas = [
|
||||||
|
{
|
||||||
|
type: "object",
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ["type", "selector", "text"],
|
||||||
|
properties: {
|
||||||
|
type: { const: "setText" },
|
||||||
|
selector: { type: "string" },
|
||||||
|
text: { type: "string" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "object",
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ["type", "selector", "search", "replacement"],
|
||||||
|
properties: {
|
||||||
|
type: { const: "replaceText" },
|
||||||
|
selector: { type: "string" },
|
||||||
|
search: { type: "string" },
|
||||||
|
replacement: { type: "string" },
|
||||||
|
all: { type: "boolean" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "object",
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ["type", "selector", "name", "value"],
|
||||||
|
properties: {
|
||||||
|
type: { const: "setAttribute" },
|
||||||
|
selector: { type: "string" },
|
||||||
|
name: { type: "string", enum: SAFE_ATTRIBUTE_NAMES },
|
||||||
|
value: { type: "string" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "object",
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ["type", "selector", "property", "value"],
|
||||||
|
properties: {
|
||||||
|
type: { const: "setStyle" },
|
||||||
|
selector: { type: "string" },
|
||||||
|
property: { type: "string", enum: SAFE_STYLE_PROPERTIES },
|
||||||
|
value: { type: "string" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
...(["addClass", "removeClass"] as const).map((type) => ({
|
||||||
|
type: "object",
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ["type", "selector", "className"],
|
||||||
|
properties: {
|
||||||
|
type: { const: type },
|
||||||
|
selector: { type: "string" },
|
||||||
|
className: { type: "string" },
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
...(["hide", "show"] as const).map((type) => ({
|
||||||
|
type: "object",
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ["type", "selector"],
|
||||||
|
properties: {
|
||||||
|
type: { const: type },
|
||||||
|
selector: { type: "string" },
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
{
|
||||||
|
type: "object",
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ["type", "selector", "position", "tag", "text"],
|
||||||
|
properties: {
|
||||||
|
type: { const: "insertText" },
|
||||||
|
selector: { type: "string" },
|
||||||
|
position: { type: "string", enum: SAFE_INSERT_POSITIONS },
|
||||||
|
tag: { type: "string", enum: SAFE_INSERT_TAGS },
|
||||||
|
text: { type: "string" },
|
||||||
|
className: { type: "string" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export const AI_MOD_RESPONSE_JSON_SCHEMA = {
|
||||||
|
type: "object",
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ["name", "description", "operations"],
|
||||||
|
properties: {
|
||||||
|
name: { type: "string", minLength: 1, maxLength: 120 },
|
||||||
|
description: { type: "string", maxLength: 500 },
|
||||||
|
operations: {
|
||||||
|
type: "array",
|
||||||
|
minItems: 0,
|
||||||
|
maxItems: 30,
|
||||||
|
items: { oneOf: operationSchemas },
|
||||||
|
},
|
||||||
|
advancedScript: {
|
||||||
|
type: "string",
|
||||||
|
minLength: 1,
|
||||||
|
maxLength: 20_000,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function buildAiModMessages(context: SelectedElementContext) {
|
||||||
|
const allowedStyleProperties = SAFE_STYLE_PROPERTIES.join(", ");
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
role: "system",
|
||||||
|
content: `You create advanced BetterSEQTA+ DOM mods.
|
||||||
|
Return only a valid JSON object with keys: name, description, operations, and optionally advancedScript.
|
||||||
|
Each operation must be an object with a string "type" field and a "selector" field.
|
||||||
|
Supported type values: setText, replaceText, setAttribute, setStyle, addClass, removeClass, hide, show, insertText.
|
||||||
|
operations may be an empty array when advancedScript alone implements the requested change.
|
||||||
|
|
||||||
|
setStyle rules:
|
||||||
|
- Use kebab-case property names only (e.g. "flex-wrap", not "flexWrap").
|
||||||
|
- Allowed properties: ${allowedStyleProperties}
|
||||||
|
- Do not use background-image, transform, animation, or any property not in the allowed list.
|
||||||
|
- setStyle operations automatically override BetterSEQTA page CSS (including rules with !important). Target constraining ancestors, not only leaf nodes — e.g. for full-width news cards set max-width, width, margin, and padding on :scope > div.home-container (BS+ caps it at 1050px), not only on .NewsArticle children.
|
||||||
|
|
||||||
|
Example (full-width layout — override BS+ container cap):
|
||||||
|
{"name":"Full-width news","description":"Expands home container to viewport width","operations":[{"type":"setStyle","selector":":scope > div.home-container","property":"max-width","value":"100%"},{"type":"setStyle","selector":":scope > div.home-container","property":"width","value":"100%"},{"type":"setStyle","selector":":scope > div.home-container","property":"margin-left","value":"0"},{"type":"setStyle","selector":":scope > div.home-container","property":"margin-right","value":"0"}]}
|
||||||
|
|
||||||
|
Example (simple style):
|
||||||
|
{"name":"Rounded card","description":"Adds rounded corners","operations":[{"type":"setStyle","selector":":scope","property":"border-radius","value":"12px"}]}
|
||||||
|
|
||||||
|
Example (flex row layout):
|
||||||
|
{"name":"Flex toolbar","description":"Lays out children in a horizontal row","operations":[{"type":"setStyle","selector":":scope","property":"display","value":"flex"},{"type":"setStyle","selector":":scope","property":"align-items","value":"center"},{"type":"setStyle","selector":":scope","property":"gap","value":"8px"},{"type":"setStyle","selector":":scope","property":"flex-wrap","value":"wrap"}]}
|
||||||
|
|
||||||
|
Example (CSS grid layout):
|
||||||
|
{"name":"Grid cards","description":"Displays children in a responsive grid","operations":[{"type":"setStyle","selector":":scope","property":"display","value":"grid"},{"type":"setStyle","selector":":scope","property":"grid-template-columns","value":"repeat(auto-fill, minmax(200px, 1fr))"},{"type":"setStyle","selector":":scope","property":"gap","value":"12px"}]}
|
||||||
|
|
||||||
|
Example (table to grid — convert a table container to grid while keeping child cells):
|
||||||
|
{"name":"Table as grid","description":"Replaces table layout with CSS grid on the wrapper","operations":[{"type":"setStyle","selector":":scope","property":"display","value":"grid"},{"type":"setStyle","selector":":scope","property":"grid-template-columns","value":"repeat(3, 1fr)"},{"type":"setStyle","selector":":scope","property":"gap","value":"8px"},{"type":"setStyle","selector":":scope tr","property":"display","value":"contents"},{"type":"setStyle","selector":":scope td, :scope th","property":"display","value":"block"}]}
|
||||||
|
For table-to-grid mods, target the table or tbody with display:grid and use display:contents on tr rows so td/th become direct grid items. Use advancedScript when row/column reordering or cell merging is required.
|
||||||
|
|
||||||
|
Advanced-only example:
|
||||||
|
{"name":"Reorder header","description":"Moves child nodes","operations":[],"advancedScript":"return () => {};"}
|
||||||
|
Every selector must be ":scope" or begin with ":scope " / ":scope>" so it stays inside the user's selected root.
|
||||||
|
Use domCatalog for exact relative selectors, sibling order, and computed layout on each node.
|
||||||
|
Use parentChain to understand how the selected root is nested inside parent containers.
|
||||||
|
Use structuralHints (hasTable, rowCount, columnCount, hasList, itemCount, primaryClasses) for table/list/grid transforms.
|
||||||
|
Use ancestorHtml to see how the selected root sits inside its parent container.
|
||||||
|
Use selectedHtml for full subtree markup including preserved inline layout styles.
|
||||||
|
Select the smallest page area that actually contains the elements you need to change. Do not select BetterSEQTA+ overlay UI; select the underlying SEQTA content instead.
|
||||||
|
When moving elements, preserve BetterSEQTA+ styling: prefer flex rows with align-items:center, gap, inline-block badges, var(--text-primary), var(--auto-background), and transparent/theme borders over solid black boxes.
|
||||||
|
If required elements are missing inside root, throw an Error explaining which selector failed.
|
||||||
|
Use operations for simple reversible changes and advancedScript for richer JavaScript behavior.
|
||||||
|
advancedScript runs with root, bsplus, and shorthand helpers select(selector) / selectAll(selector) in scope.
|
||||||
|
The helper library provides select(selector), selectAll(selector), setText(element,text), setStyle(element,property,value), setAttribute(element,name,value), create(tag,text,parent), on(element,event,handler), observe(element,callback,options), and onCleanup(callback).
|
||||||
|
You may call select() directly or use bsplus.select().
|
||||||
|
The advancedScript body must return a cleanup function and should use bsplus helpers so disabling the mod restores the page.
|
||||||
|
Never use network APIs, extension APIs, browser storage, cookies, navigation, raw HTML markup, eval, dynamic imports, workers, programmatic clicks/submits, src/href assignments, or unbounded loops.
|
||||||
|
You may clear a container with element.innerHTML = '' before moving existing nodes, but never assign HTML strings or use outerHTML/insertAdjacentHTML.
|
||||||
|
Prefer appendChild, insertBefore, replaceChildren, cloneNode, remove, and textContent for DOM changes.
|
||||||
|
Direct DOM APIs are allowed for advanced layout and interaction work, but keep every change within root and register cleanup.
|
||||||
|
Prefer the smallest set of reversible operations. Do not invent page content that is not requested.
|
||||||
|
For insertText, "before" and "after" may only target descendants, not :scope itself.`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
role: "user",
|
||||||
|
content: `Create a mod for this explicitly selected page area:\n${JSON.stringify(
|
||||||
|
context,
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
)}`,
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
import {
|
||||||
|
createStoredRecipe,
|
||||||
|
extractJsonFromModelText,
|
||||||
|
normalizeStyleProperty,
|
||||||
|
parseGeneratedModDraft,
|
||||||
|
parseStoredRecipes,
|
||||||
|
} from "./recipeSchema";
|
||||||
|
|
||||||
|
describe("AI mod recipe validation", () => {
|
||||||
|
const validDraft = {
|
||||||
|
name: "Calmer assessment card",
|
||||||
|
description: "Makes the selected card easier to scan.",
|
||||||
|
operations: [
|
||||||
|
{
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope",
|
||||||
|
property: "border-radius",
|
||||||
|
value: "16px",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "setText",
|
||||||
|
selector: ":scope .title",
|
||||||
|
text: "Upcoming assessment",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
it("accepts a safe generated draft and creates a stored recipe", () => {
|
||||||
|
const draft = parseGeneratedModDraft(JSON.stringify(validDraft));
|
||||||
|
const recipe = createStoredRecipe(draft, {
|
||||||
|
rootSelector: "#assessment-42",
|
||||||
|
route: "assessments",
|
||||||
|
now: 1_700_000_000_000,
|
||||||
|
id: "mod-1",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(recipe).toMatchObject({
|
||||||
|
schemaVersion: 1,
|
||||||
|
id: "mod-1",
|
||||||
|
enabled: false,
|
||||||
|
rootSelector: "#assessment-42",
|
||||||
|
route: "assessments",
|
||||||
|
name: validDraft.name,
|
||||||
|
createdAt: 1_700_000_000_000,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{
|
||||||
|
label: "script-like attribute",
|
||||||
|
operation: {
|
||||||
|
type: "setAttribute",
|
||||||
|
selector: ":scope",
|
||||||
|
name: "onclick",
|
||||||
|
value: "alert(1)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "network-capable CSS",
|
||||||
|
operation: {
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope",
|
||||||
|
property: "background-image",
|
||||||
|
value: "url(https://attacker.invalid/pixel)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "selector escaping the selected root",
|
||||||
|
operation: {
|
||||||
|
type: "hide",
|
||||||
|
selector: "body",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "raw executable operation",
|
||||||
|
operation: {
|
||||||
|
type: "javascript",
|
||||||
|
code: "document.cookie",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])("rejects $label", ({ operation }) => {
|
||||||
|
expect(() =>
|
||||||
|
parseGeneratedModDraft(
|
||||||
|
JSON.stringify({
|
||||||
|
...validDraft,
|
||||||
|
operations: [operation],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("extracts JSON from fenced model output", () => {
|
||||||
|
const json = JSON.stringify(validDraft);
|
||||||
|
expect(parseGeneratedModDraft(`\`\`\`json\n${json}\n\`\`\``)).toMatchObject({
|
||||||
|
name: validDraft.name,
|
||||||
|
});
|
||||||
|
expect(extractJsonFromModelText(`Here is the mod:\n${json}`)).toBe(json);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("normalizes common model operation shapes", () => {
|
||||||
|
expect(
|
||||||
|
parseGeneratedModDraft(
|
||||||
|
JSON.stringify({
|
||||||
|
name: "Aliased mod",
|
||||||
|
description: "Uses alternate field names",
|
||||||
|
operations: [
|
||||||
|
{
|
||||||
|
setStyle: {
|
||||||
|
target: ":scope",
|
||||||
|
styleProperty: "border-radius",
|
||||||
|
styleValue: "12px",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
action: "hide",
|
||||||
|
element: ":scope .meta",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).toMatchObject({
|
||||||
|
name: "Aliased mod",
|
||||||
|
operations: [
|
||||||
|
{
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope",
|
||||||
|
property: "border-radius",
|
||||||
|
value: "12px",
|
||||||
|
},
|
||||||
|
{ type: "hide", selector: ":scope .meta" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
["flexWrap", "flex-wrap"],
|
||||||
|
["alignItems", "align-items"],
|
||||||
|
["gridTemplateColumns", "grid-template-columns"],
|
||||||
|
["flexDirection", "flex-direction"],
|
||||||
|
["overflowX", "overflow-x"],
|
||||||
|
["zIndex", "z-index"],
|
||||||
|
["whiteSpace", "white-space"],
|
||||||
|
["border-radius", "border-radius"],
|
||||||
|
])("normalizes style property %s to %s", (input, expected) => {
|
||||||
|
expect(normalizeStyleProperty(input)).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accepts camelCase style properties from the model", () => {
|
||||||
|
expect(
|
||||||
|
parseGeneratedModDraft(
|
||||||
|
JSON.stringify({
|
||||||
|
name: "Flex layout",
|
||||||
|
description: "Uses camelCase property names",
|
||||||
|
operations: [
|
||||||
|
{
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope",
|
||||||
|
property: "flexWrap",
|
||||||
|
value: "wrap",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope",
|
||||||
|
property: "alignItems",
|
||||||
|
value: "center",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).toMatchObject({
|
||||||
|
operations: [
|
||||||
|
{ type: "setStyle", property: "flex-wrap", value: "wrap" },
|
||||||
|
{ type: "setStyle", property: "align-items", value: "center" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accepts newly allowed layout style properties", () => {
|
||||||
|
expect(
|
||||||
|
parseGeneratedModDraft(
|
||||||
|
JSON.stringify({
|
||||||
|
name: "Grid layout",
|
||||||
|
description: "CSS grid on selected root",
|
||||||
|
operations: [
|
||||||
|
{
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope",
|
||||||
|
property: "display",
|
||||||
|
value: "grid",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "setStyle",
|
||||||
|
selector: ":scope",
|
||||||
|
property: "grid-template-columns",
|
||||||
|
value: "repeat(3, 1fr)",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
).operations,
|
||||||
|
).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accepts advancedScript-only mods with no declarative operations", () => {
|
||||||
|
const draft = parseGeneratedModDraft(
|
||||||
|
JSON.stringify({
|
||||||
|
name: "House next to ID",
|
||||||
|
description: "Moves house info beside the user ID",
|
||||||
|
operations: [],
|
||||||
|
advancedScript:
|
||||||
|
"const house = bsplus.select(':scope .userInfohouse'); return () => {};",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(draft.operations).toEqual([]);
|
||||||
|
expect(draft.advancedScript).toContain("bsplus.select");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects mods with neither operations nor advancedScript", () => {
|
||||||
|
expect(() =>
|
||||||
|
parseGeneratedModDraft(
|
||||||
|
JSON.stringify({
|
||||||
|
name: "Empty mod",
|
||||||
|
description: "Does nothing",
|
||||||
|
operations: [],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).toThrow("at least one operation or an advancedScript");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects oversized or non-JSON model output", () => {
|
||||||
|
expect(() => parseGeneratedModDraft("not json")).toThrow();
|
||||||
|
expect(() =>
|
||||||
|
parseGeneratedModDraft(
|
||||||
|
JSON.stringify({
|
||||||
|
...validDraft,
|
||||||
|
name: "x".repeat(121),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("validates every imported recipe before returning any", () => {
|
||||||
|
const recipe = createStoredRecipe(
|
||||||
|
parseGeneratedModDraft(JSON.stringify(validDraft)),
|
||||||
|
{
|
||||||
|
rootSelector: "#assessment-42",
|
||||||
|
route: "assessments",
|
||||||
|
now: 1,
|
||||||
|
id: "mod-1",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(parseStoredRecipes(JSON.stringify([recipe]))).toEqual([recipe]);
|
||||||
|
expect(() =>
|
||||||
|
parseStoredRecipes(
|
||||||
|
JSON.stringify([
|
||||||
|
recipe,
|
||||||
|
{
|
||||||
|
...recipe,
|
||||||
|
id: "bad",
|
||||||
|
operations: [{ type: "hide", selector: "html" }],
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,666 @@
|
|||||||
|
import {
|
||||||
|
AI_MOD_SCHEMA_VERSION,
|
||||||
|
type GeneratedModDraft,
|
||||||
|
type ModOperation,
|
||||||
|
type SafeAttributeName,
|
||||||
|
type SafeStyleProperty,
|
||||||
|
type StoredModRecipe,
|
||||||
|
} from "./types";
|
||||||
|
import { assertAdvancedScriptSafe } from "./scriptSafety";
|
||||||
|
import { aiModLog } from "./logger";
|
||||||
|
import { stripStyleImportantSuffix } from "./modStyle";
|
||||||
|
|
||||||
|
export const SAFE_STYLE_PROPERTIES: readonly SafeStyleProperty[] = [
|
||||||
|
"align-items",
|
||||||
|
"align-self",
|
||||||
|
"aspect-ratio",
|
||||||
|
"background",
|
||||||
|
"background-color",
|
||||||
|
"border",
|
||||||
|
"border-color",
|
||||||
|
"border-radius",
|
||||||
|
"border-style",
|
||||||
|
"border-width",
|
||||||
|
"bottom",
|
||||||
|
"box-shadow",
|
||||||
|
"color",
|
||||||
|
"cursor",
|
||||||
|
"display",
|
||||||
|
"flex",
|
||||||
|
"flex-direction",
|
||||||
|
"flex-grow",
|
||||||
|
"flex-shrink",
|
||||||
|
"flex-wrap",
|
||||||
|
"font-size",
|
||||||
|
"font-weight",
|
||||||
|
"gap",
|
||||||
|
"grid-template-columns",
|
||||||
|
"height",
|
||||||
|
"justify-content",
|
||||||
|
"left",
|
||||||
|
"letter-spacing",
|
||||||
|
"line-height",
|
||||||
|
"margin",
|
||||||
|
"margin-bottom",
|
||||||
|
"margin-left",
|
||||||
|
"margin-right",
|
||||||
|
"margin-top",
|
||||||
|
"max-height",
|
||||||
|
"max-width",
|
||||||
|
"min-height",
|
||||||
|
"min-width",
|
||||||
|
"object-fit",
|
||||||
|
"opacity",
|
||||||
|
"order",
|
||||||
|
"overflow",
|
||||||
|
"overflow-x",
|
||||||
|
"overflow-y",
|
||||||
|
"padding",
|
||||||
|
"padding-bottom",
|
||||||
|
"padding-left",
|
||||||
|
"padding-right",
|
||||||
|
"padding-top",
|
||||||
|
"position",
|
||||||
|
"right",
|
||||||
|
"text-align",
|
||||||
|
"text-decoration",
|
||||||
|
"top",
|
||||||
|
"vertical-align",
|
||||||
|
"white-space",
|
||||||
|
"width",
|
||||||
|
"z-index",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const SAFE_STYLE_PROPERTY_SET = new Set<string>(SAFE_STYLE_PROPERTIES);
|
||||||
|
|
||||||
|
/** Converts camelCase CSS property names to kebab-case (e.g. flexWrap -> flex-wrap). */
|
||||||
|
export function normalizeStyleProperty(value: string): string {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (!trimmed.includes("-") && /[A-Z]/.test(trimmed)) {
|
||||||
|
return trimmed
|
||||||
|
.replace(/([a-z0-9])([A-Z])/g, "$1-$2")
|
||||||
|
.replace(/([A-Z])([A-Z][a-z])/g, "$1-$2")
|
||||||
|
.toLowerCase();
|
||||||
|
}
|
||||||
|
return trimmed.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const SAFE_ATTRIBUTE_NAMES: readonly SafeAttributeName[] = [
|
||||||
|
"aria-label",
|
||||||
|
"aria-description",
|
||||||
|
"aria-hidden",
|
||||||
|
"placeholder",
|
||||||
|
"role",
|
||||||
|
"title",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const SAFE_INSERT_TAGS = [
|
||||||
|
"div",
|
||||||
|
"span",
|
||||||
|
"p",
|
||||||
|
"button",
|
||||||
|
"label",
|
||||||
|
] as const;
|
||||||
|
export const SAFE_INSERT_POSITIONS = [
|
||||||
|
"before",
|
||||||
|
"after",
|
||||||
|
"prepend",
|
||||||
|
"append",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const OPERATION_TYPES = new Set([
|
||||||
|
"setText",
|
||||||
|
"replaceText",
|
||||||
|
"setAttribute",
|
||||||
|
"setStyle",
|
||||||
|
"addClass",
|
||||||
|
"removeClass",
|
||||||
|
"hide",
|
||||||
|
"show",
|
||||||
|
"insertText",
|
||||||
|
]);
|
||||||
|
const CLASS_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
|
||||||
|
const UNSAFE_STYLE_VALUE =
|
||||||
|
/(?:url\s*\(|expression\s*\(|javascript\s*:|@import|[{};]|<\/?style)/i;
|
||||||
|
|
||||||
|
const TYPE_ALIASES: Record<string, string> = {
|
||||||
|
settext: "setText",
|
||||||
|
set_text: "setText",
|
||||||
|
replacetext: "replaceText",
|
||||||
|
replace_text: "replaceText",
|
||||||
|
setattribute: "setAttribute",
|
||||||
|
set_attribute: "setAttribute",
|
||||||
|
setstyle: "setStyle",
|
||||||
|
set_style: "setStyle",
|
||||||
|
style: "setStyle",
|
||||||
|
addclass: "addClass",
|
||||||
|
add_class: "addClass",
|
||||||
|
removeclass: "removeClass",
|
||||||
|
remove_class: "removeClass",
|
||||||
|
inserttext: "insertText",
|
||||||
|
insert_text: "insertText",
|
||||||
|
hidden: "hide",
|
||||||
|
visible: "show",
|
||||||
|
};
|
||||||
|
|
||||||
|
function describeValue(value: unknown): string {
|
||||||
|
if (value === null) return "null";
|
||||||
|
if (value === undefined) return "undefined";
|
||||||
|
if (Array.isArray(value)) return `array(${value.length})`;
|
||||||
|
if (typeof value === "object") {
|
||||||
|
const preview = JSON.stringify(value);
|
||||||
|
return `object ${preview.length > 160 ? `${preview.slice(0, 160)}…` : preview}`;
|
||||||
|
}
|
||||||
|
return `${typeof value}: ${String(value).slice(0, 120)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function coerceString(value: unknown): string | null {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
return trimmed.length > 0 ? trimmed : null;
|
||||||
|
}
|
||||||
|
if (typeof value === "number" || typeof value === "boolean") {
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeOperationType(value: unknown): string | null {
|
||||||
|
const direct = coerceString(value);
|
||||||
|
if (direct) {
|
||||||
|
if (OPERATION_TYPES.has(direct)) return direct;
|
||||||
|
const compact = direct.replace(/[\s_-]+/g, "").toLowerCase();
|
||||||
|
const alias = TYPE_ALIASES[compact] ?? TYPE_ALIASES[direct.toLowerCase()];
|
||||||
|
if (alias) return alias;
|
||||||
|
}
|
||||||
|
if (value && typeof value === "object" && !Array.isArray(value)) {
|
||||||
|
const record = value as Record<string, unknown>;
|
||||||
|
return normalizeOperationType(
|
||||||
|
record.type ?? record.name ?? record.action ?? record.op,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function unwrapKeyedOperation(
|
||||||
|
operation: Record<string, unknown>,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
if (operation.type || operation.action || operation.op) return operation;
|
||||||
|
|
||||||
|
const keys = Object.keys(operation).filter((key) => {
|
||||||
|
const normalized = normalizeOperationType(key);
|
||||||
|
return normalized !== null;
|
||||||
|
});
|
||||||
|
if (keys.length !== 1) return operation;
|
||||||
|
|
||||||
|
const type = normalizeOperationType(keys[0]);
|
||||||
|
const payload = operation[keys[0]];
|
||||||
|
if (!type || !payload || typeof payload !== "object" || Array.isArray(payload)) {
|
||||||
|
return operation;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
...(payload as Record<string, unknown>),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeOperationRecord(
|
||||||
|
value: unknown,
|
||||||
|
index: number,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
throw new Error(
|
||||||
|
`Operation #${index + 1} must be an object, received string: ${value.slice(0, 120)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const operation = asRecord(value, `Operation #${index + 1}`);
|
||||||
|
const unwrapped = unwrapKeyedOperation(operation);
|
||||||
|
const type = normalizeOperationType(
|
||||||
|
unwrapped.type ?? unwrapped.action ?? unwrapped.op ?? unwrapped.operation,
|
||||||
|
);
|
||||||
|
if (!type) {
|
||||||
|
throw new Error(
|
||||||
|
`Operation #${index + 1} has an invalid type (received ${describeValue(
|
||||||
|
unwrapped.type ?? unwrapped.action ?? unwrapped.op,
|
||||||
|
)}). Expected one of: ${[...OPERATION_TYPES].join(", ")}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const selector =
|
||||||
|
unwrapped.selector ??
|
||||||
|
unwrapped.target ??
|
||||||
|
unwrapped.element ??
|
||||||
|
unwrapped.query ??
|
||||||
|
":scope";
|
||||||
|
|
||||||
|
return {
|
||||||
|
...unwrapped,
|
||||||
|
type,
|
||||||
|
selector,
|
||||||
|
...(unwrapped.className === undefined && unwrapped.class !== undefined
|
||||||
|
? { className: unwrapped.class }
|
||||||
|
: {}),
|
||||||
|
...(unwrapped.property === undefined &&
|
||||||
|
(unwrapped.styleProperty !== undefined || unwrapped.cssProperty !== undefined)
|
||||||
|
? {
|
||||||
|
property: unwrapped.styleProperty ?? unwrapped.cssProperty,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(unwrapped.text === undefined && unwrapped.content !== undefined
|
||||||
|
? { text: unwrapped.content }
|
||||||
|
: {}),
|
||||||
|
...(unwrapped.value === undefined && unwrapped.styleValue !== undefined
|
||||||
|
? { value: unwrapped.styleValue }
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeDraftShape(value: unknown): unknown {
|
||||||
|
const draft = asRecord(value, "Generated mod");
|
||||||
|
let operations = draft.operations;
|
||||||
|
|
||||||
|
if (operations && typeof operations === "object" && !Array.isArray(operations)) {
|
||||||
|
operations = Object.values(operations as Record<string, unknown>);
|
||||||
|
aiModLog.warn(
|
||||||
|
"recipeSchema",
|
||||||
|
"Normalized operations object into an array",
|
||||||
|
operations,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(operations)) {
|
||||||
|
throw new Error("Generated mod operations must be a list");
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...draft,
|
||||||
|
operations: operations.map(normalizeOperationRecord),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function asRecord(value: unknown, label: string): Record<string, unknown> {
|
||||||
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||||
|
throw new Error(`${label} must be an object`);
|
||||||
|
}
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function boundedString(
|
||||||
|
value: unknown,
|
||||||
|
label: string,
|
||||||
|
maxLength: number,
|
||||||
|
allowEmpty = false,
|
||||||
|
): string {
|
||||||
|
if (typeof value !== "string") {
|
||||||
|
throw new Error(`${label} must be text (received ${describeValue(value)})`);
|
||||||
|
}
|
||||||
|
const result = value.trim();
|
||||||
|
if (!allowEmpty && result.length === 0) throw new Error(`${label} is required`);
|
||||||
|
if (result.length > maxLength) {
|
||||||
|
throw new Error(`${label} is too long (maximum ${maxLength} characters)`);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateRelativeSelector(value: unknown): string {
|
||||||
|
const selector = boundedString(value, "Operation selector", 500);
|
||||||
|
if (
|
||||||
|
selector !== ":scope" &&
|
||||||
|
!selector.startsWith(":scope ") &&
|
||||||
|
!selector.startsWith(":scope>")
|
||||||
|
) {
|
||||||
|
throw new Error("Operation selectors must stay inside :scope");
|
||||||
|
}
|
||||||
|
if (selector.includes(",") || /(?:^|\s)(?:html|body|:root)(?:\s|$)/i.test(selector)) {
|
||||||
|
throw new Error("Operation selector may not escape the selected root");
|
||||||
|
}
|
||||||
|
return selector;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateClassName(value: unknown): string {
|
||||||
|
const className = boundedString(value, "Class name", 64);
|
||||||
|
if (!CLASS_NAME_PATTERN.test(className)) {
|
||||||
|
throw new Error("Class name contains unsupported characters");
|
||||||
|
}
|
||||||
|
return className;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateOperation(value: unknown): ModOperation {
|
||||||
|
const operation = asRecord(value, "Operation");
|
||||||
|
const type = boundedString(operation.type, "Operation type", 40);
|
||||||
|
if (!OPERATION_TYPES.has(type)) {
|
||||||
|
throw new Error(`Unsupported operation type: ${type}`);
|
||||||
|
}
|
||||||
|
const selector = validateRelativeSelector(operation.selector);
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case "setText":
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
selector,
|
||||||
|
text: boundedString(operation.text, "Text", 2_000, true),
|
||||||
|
};
|
||||||
|
case "replaceText":
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
selector,
|
||||||
|
search: boundedString(operation.search, "Search text", 500),
|
||||||
|
replacement: boundedString(
|
||||||
|
operation.replacement,
|
||||||
|
"Replacement text",
|
||||||
|
2_000,
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
...(operation.all === true ? { all: true } : {}),
|
||||||
|
};
|
||||||
|
case "setAttribute": {
|
||||||
|
const name = boundedString(operation.name, "Attribute name", 40);
|
||||||
|
if (!SAFE_ATTRIBUTE_NAMES.includes(name as SafeAttributeName)) {
|
||||||
|
throw new Error(`Unsafe attribute: ${name}`);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
selector,
|
||||||
|
name: name as SafeAttributeName,
|
||||||
|
value: boundedString(operation.value, "Attribute value", 1_000, true),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case "setStyle": {
|
||||||
|
const rawProperty = boundedString(operation.property, "Style property", 60);
|
||||||
|
const property = normalizeStyleProperty(rawProperty);
|
||||||
|
if (!SAFE_STYLE_PROPERTY_SET.has(property)) {
|
||||||
|
throw new Error(`Unsafe style property: ${rawProperty}`);
|
||||||
|
}
|
||||||
|
const styleValue = stripStyleImportantSuffix(
|
||||||
|
boundedString(operation.value, "Style value", 200, true),
|
||||||
|
);
|
||||||
|
if (UNSAFE_STYLE_VALUE.test(styleValue)) {
|
||||||
|
throw new Error("Style value contains unsafe content");
|
||||||
|
}
|
||||||
|
const important =
|
||||||
|
operation.important === undefined
|
||||||
|
? undefined
|
||||||
|
: operation.important === true;
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
selector,
|
||||||
|
property: property as SafeStyleProperty,
|
||||||
|
value: styleValue,
|
||||||
|
...(important === undefined ? {} : { important }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case "addClass":
|
||||||
|
case "removeClass":
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
selector,
|
||||||
|
className: validateClassName(operation.className),
|
||||||
|
};
|
||||||
|
case "hide":
|
||||||
|
case "show":
|
||||||
|
return { type, selector };
|
||||||
|
case "insertText": {
|
||||||
|
const position = boundedString(operation.position, "Insert position", 20);
|
||||||
|
const tag = boundedString(operation.tag, "Insert tag", 20);
|
||||||
|
if (!SAFE_INSERT_POSITIONS.includes(position as never)) {
|
||||||
|
throw new Error(`Unsafe insert position: ${position}`);
|
||||||
|
}
|
||||||
|
if (!SAFE_INSERT_TAGS.includes(tag as never)) {
|
||||||
|
throw new Error(`Unsafe insert tag: ${tag}`);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
selector,
|
||||||
|
position: position as "before" | "after" | "prepend" | "append",
|
||||||
|
tag: tag as "div" | "span" | "p" | "button" | "label",
|
||||||
|
text: boundedString(operation.text, "Inserted text", 2_000, true),
|
||||||
|
...(operation.className === undefined
|
||||||
|
? {}
|
||||||
|
: { className: validateClassName(operation.className) }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error("Unsupported operation");
|
||||||
|
}
|
||||||
|
|
||||||
|
function describeOperationPreview(value: unknown): string {
|
||||||
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||||
|
return "unknown operation";
|
||||||
|
}
|
||||||
|
const operation = value as Record<string, unknown>;
|
||||||
|
const type =
|
||||||
|
operation.type ??
|
||||||
|
operation.action ??
|
||||||
|
operation.op ??
|
||||||
|
Object.keys(operation).find((key) => normalizeOperationType(key) !== null) ??
|
||||||
|
"unknown";
|
||||||
|
const selector =
|
||||||
|
operation.selector ??
|
||||||
|
operation.target ??
|
||||||
|
operation.element ??
|
||||||
|
operation.query ??
|
||||||
|
":scope";
|
||||||
|
return `${String(type)} → ${String(selector).slice(0, 80)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatRecipeValidationError(error: unknown): string {
|
||||||
|
const base =
|
||||||
|
error instanceof Error ? error.message : "Recipe validation failed";
|
||||||
|
if (base.startsWith("Recipe validation failed:")) {
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
const suggestions: string[] = [];
|
||||||
|
const unsafeStyle = base.match(/Unsafe style property:\s*(.+)/i);
|
||||||
|
if (unsafeStyle) {
|
||||||
|
const property = unsafeStyle[1].trim();
|
||||||
|
suggestions.push(
|
||||||
|
`"${property}" is not allowed. Supported style properties include ${SAFE_STYLE_PROPERTIES.slice(0, 10).join(", ")}, and more.`,
|
||||||
|
);
|
||||||
|
suggestions.push(
|
||||||
|
"For layout changes, try display, flex-wrap, align-items, justify-content, gap, or grid-template-columns.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (/Unsafe attribute:/i.test(base)) {
|
||||||
|
suggestions.push(
|
||||||
|
`Allowed attributes: ${SAFE_ATTRIBUTE_NAMES.join(", ")}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (/selectors must stay inside :scope/i.test(base)) {
|
||||||
|
suggestions.push(
|
||||||
|
'Selectors must start with :scope (for example ":scope" or ":scope .child").',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (/invalid JSON/i.test(base)) {
|
||||||
|
suggestions.push("Try regenerating the mod or switching to a different model.");
|
||||||
|
}
|
||||||
|
if (/at least one operation/i.test(base)) {
|
||||||
|
suggestions.push(
|
||||||
|
"Describe a concrete DOM change such as hiding an element, changing color, or rounding corners.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (/Unsupported operation type:/i.test(base)) {
|
||||||
|
suggestions.push(
|
||||||
|
"Supported operations: setText, replaceText, setAttribute, setStyle, addClass, removeClass, hide, show, insertText.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (suggestions.length === 0) {
|
||||||
|
return `Recipe validation failed: ${base}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `Recipe validation failed: ${base} — ${suggestions.join(" ")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateDraft(value: unknown): GeneratedModDraft {
|
||||||
|
const normalized = normalizeDraftShape(value);
|
||||||
|
const draft = asRecord(normalized, "Generated mod");
|
||||||
|
if (!Array.isArray(draft.operations)) {
|
||||||
|
throw new Error("Generated mod operations must be a list");
|
||||||
|
}
|
||||||
|
if (draft.operations.length > 30) {
|
||||||
|
throw new Error("Generated mod may contain at most 30 operations");
|
||||||
|
}
|
||||||
|
|
||||||
|
const operations = draft.operations.map((operation, index) => {
|
||||||
|
try {
|
||||||
|
return validateOperation(operation);
|
||||||
|
} catch (cause) {
|
||||||
|
const detail =
|
||||||
|
cause instanceof Error ? cause.message : "Invalid operation";
|
||||||
|
throw new Error(
|
||||||
|
`Operation #${index + 1} (${describeOperationPreview(operation)}): ${detail}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const advancedScript =
|
||||||
|
draft.advancedScript === undefined ||
|
||||||
|
(typeof draft.advancedScript === "string" &&
|
||||||
|
draft.advancedScript.trim().length === 0)
|
||||||
|
? undefined
|
||||||
|
: assertAdvancedScriptSafe(draft.advancedScript);
|
||||||
|
|
||||||
|
if (operations.length === 0 && !advancedScript) {
|
||||||
|
throw new Error(
|
||||||
|
"Generated mod must include at least one operation or an advancedScript",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: boundedString(draft.name, "Mod name", 120),
|
||||||
|
description: boundedString(
|
||||||
|
draft.description,
|
||||||
|
"Mod description",
|
||||||
|
500,
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
operations,
|
||||||
|
...(advancedScript === undefined ? {} : { advancedScript }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function extractJsonFromModelText(text: string): string {
|
||||||
|
const trimmed = text.trim();
|
||||||
|
if (trimmed.startsWith("{")) return trimmed;
|
||||||
|
const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
||||||
|
if (fenced?.[1]) return fenced[1].trim();
|
||||||
|
const start = trimmed.indexOf("{");
|
||||||
|
const end = trimmed.lastIndexOf("}");
|
||||||
|
if (start >= 0 && end > start) return trimmed.slice(start, end + 1);
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseGeneratedModDraft(
|
||||||
|
input: string | GeneratedModDraft,
|
||||||
|
): GeneratedModDraft {
|
||||||
|
let parsed: unknown;
|
||||||
|
if (typeof input === "string") {
|
||||||
|
const normalized = extractJsonFromModelText(input);
|
||||||
|
if (normalized.length > 50_000) {
|
||||||
|
throw new Error("Generated response is too large");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(normalized);
|
||||||
|
} catch {
|
||||||
|
aiModLog.error("recipeSchema", "Model returned invalid JSON", normalized);
|
||||||
|
throw new Error("The model returned invalid JSON");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
parsed = input;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const draft = validateDraft(parsed);
|
||||||
|
aiModLog.info("recipeSchema", "Validated generated mod draft", {
|
||||||
|
name: draft.name,
|
||||||
|
operationCount: draft.operations.length,
|
||||||
|
hasAdvancedScript: Boolean(draft.advancedScript),
|
||||||
|
});
|
||||||
|
return draft;
|
||||||
|
} catch (error) {
|
||||||
|
aiModLog.error("recipeSchema", "Recipe validation failed", {
|
||||||
|
parsed,
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createStoredRecipe(
|
||||||
|
draft: GeneratedModDraft,
|
||||||
|
input: {
|
||||||
|
rootSelector: string;
|
||||||
|
route: string;
|
||||||
|
now?: number;
|
||||||
|
id?: string;
|
||||||
|
},
|
||||||
|
): StoredModRecipe {
|
||||||
|
const validated = validateDraft(draft);
|
||||||
|
const now = input.now ?? Date.now();
|
||||||
|
const generatedId =
|
||||||
|
input.id ??
|
||||||
|
globalThis.crypto?.randomUUID?.() ??
|
||||||
|
`mod-${now}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
|
||||||
|
return validateStoredRecipe({
|
||||||
|
...validated,
|
||||||
|
schemaVersion: AI_MOD_SCHEMA_VERSION,
|
||||||
|
id: generatedId,
|
||||||
|
enabled: false,
|
||||||
|
route: input.route,
|
||||||
|
rootSelector: input.rootSelector,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateStoredRecipe(value: unknown): StoredModRecipe {
|
||||||
|
const recipe = asRecord(value, "Stored mod");
|
||||||
|
if (recipe.schemaVersion !== AI_MOD_SCHEMA_VERSION) {
|
||||||
|
throw new Error("Unsupported mod schema version");
|
||||||
|
}
|
||||||
|
const draft = validateDraft(recipe);
|
||||||
|
const id = boundedString(recipe.id, "Mod id", 160);
|
||||||
|
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
||||||
|
throw new Error("Mod id contains unsupported characters");
|
||||||
|
}
|
||||||
|
const rootSelector = boundedString(recipe.rootSelector, "Root selector", 1_000);
|
||||||
|
if (/^(?:html|body|:root|\*)$/i.test(rootSelector)) {
|
||||||
|
throw new Error("Root selector is too broad");
|
||||||
|
}
|
||||||
|
const createdAt = Number(recipe.createdAt);
|
||||||
|
const updatedAt = Number(recipe.updatedAt);
|
||||||
|
if (!Number.isFinite(createdAt) || !Number.isFinite(updatedAt)) {
|
||||||
|
throw new Error("Mod timestamps are invalid");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...draft,
|
||||||
|
schemaVersion: AI_MOD_SCHEMA_VERSION,
|
||||||
|
id,
|
||||||
|
enabled: recipe.enabled === true,
|
||||||
|
route: boundedString(recipe.route, "Route", 256, true),
|
||||||
|
rootSelector,
|
||||||
|
createdAt,
|
||||||
|
updatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseStoredRecipes(json: string): StoredModRecipe[] {
|
||||||
|
if (json.length > 500_000) throw new Error("Import file is too large");
|
||||||
|
let parsed: unknown;
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(json);
|
||||||
|
} catch {
|
||||||
|
throw new Error("Import file is not valid JSON");
|
||||||
|
}
|
||||||
|
if (!Array.isArray(parsed)) throw new Error("Import must contain a mod list");
|
||||||
|
if (parsed.length > 100) throw new Error("At most 100 mods can be imported");
|
||||||
|
return parsed.map(validateStoredRecipe);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateStoredRecipes(value: unknown): StoredModRecipe[] {
|
||||||
|
return parseStoredRecipes(JSON.stringify(value));
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { assertAdvancedScriptSafe } from "./scriptSafety";
|
||||||
|
|
||||||
|
describe("advanced AI mod script safeguards", () => {
|
||||||
|
it("allows advanced DOM code with cleanup", () => {
|
||||||
|
expect(() =>
|
||||||
|
assertAdvancedScriptSafe(`
|
||||||
|
const cards = bsplus.selectAll(":scope .card");
|
||||||
|
for (const card of cards) {
|
||||||
|
bsplus.setStyle(card, "border-radius", "16px");
|
||||||
|
bsplus.on(card, "click", () => card.classList.toggle("expanded"));
|
||||||
|
}
|
||||||
|
const observer = bsplus.observe(root, () => console.info("changed"));
|
||||||
|
return () => observer.disconnect();
|
||||||
|
`),
|
||||||
|
).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows clearing containers with empty innerHTML during DOM moves", () => {
|
||||||
|
expect(() =>
|
||||||
|
assertAdvancedScriptSafe(`
|
||||||
|
const wrapper = bsplus.select(".search-trigger-wrapper");
|
||||||
|
wrapper.innerHTML = '';
|
||||||
|
wrapper.appendChild(anchor);
|
||||||
|
return () => {};
|
||||||
|
`),
|
||||||
|
).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
["network requests", `fetch("https://attacker.invalid")`],
|
||||||
|
["extension APIs", `chrome.storage.local.get(null)`],
|
||||||
|
["page storage", `localStorage.getItem("token")`],
|
||||||
|
["cookies", `document.cookie`],
|
||||||
|
["dynamic evaluation", `eval("alert(1)")`],
|
||||||
|
["script injection", `element.innerHTML = "<script>alert(1)</script>"`],
|
||||||
|
["non-empty innerHTML", `wrapper.innerHTML = "<div></div>"`],
|
||||||
|
["innerHTML append", `wrapper.innerHTML += "<span></span>"`],
|
||||||
|
["navigation", `location.href = "https://attacker.invalid"`],
|
||||||
|
["unbounded loops", `while (true) {}`],
|
||||||
|
])("rejects %s", (_label, script) => {
|
||||||
|
expect(() => assertAdvancedScriptSafe(script)).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
const MAX_SCRIPT_LENGTH = 20_000;
|
||||||
|
|
||||||
|
const BLOCKED_PATTERNS: ReadonlyArray<{
|
||||||
|
pattern: RegExp;
|
||||||
|
reason: string;
|
||||||
|
}> = [
|
||||||
|
{
|
||||||
|
pattern:
|
||||||
|
/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|RTCPeerConnection|sendBeacon)\b/i,
|
||||||
|
reason: "network access",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern: /\b(?:chrome|browser)\s*\./i,
|
||||||
|
reason: "extension API access",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern:
|
||||||
|
/\b(?:localStorage|sessionStorage|indexedDB|caches|cookieStore)\b/i,
|
||||||
|
reason: "browser storage access",
|
||||||
|
},
|
||||||
|
{ pattern: /\bdocument\s*\.\s*cookie\b/i, reason: "cookie access" },
|
||||||
|
{
|
||||||
|
pattern:
|
||||||
|
/\b(?:eval|Function|AsyncFunction|GeneratorFunction|importScripts|Worker|SharedWorker)\s*\(/i,
|
||||||
|
reason: "dynamic code execution",
|
||||||
|
},
|
||||||
|
{ pattern: /\bimport\s*\(/i, reason: "dynamic imports" },
|
||||||
|
{
|
||||||
|
pattern: /\b(?:globalThis|top|parent|opener)\b/i,
|
||||||
|
reason: "cross-world access",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern: /\b(?:location|history)\s*(?:\.|\[|=)/i,
|
||||||
|
reason: "navigation",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern: /\bwindow\s*\.\s*(?:open|postMessage)\s*\(/i,
|
||||||
|
reason: "cross-window messaging",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern: /\.(?:src|srcset|href|action|formAction)\s*=/i,
|
||||||
|
reason: "network-capable DOM properties",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern:
|
||||||
|
/\.setAttribute\s*\(\s*["'`](?:src|srcset|href|action|formaction|style|on[^"'`]*)["'`]/i,
|
||||||
|
reason: "unsafe DOM attributes",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern: /\.(?:outerHTML|insertAdjacentHTML)\b/i,
|
||||||
|
reason: "raw HTML injection",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern: /<\s*(?:script|iframe|object|embed|link|meta|form)\b/i,
|
||||||
|
reason: "active HTML",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern: /\.(?:submit|requestSubmit|click)\s*\(/i,
|
||||||
|
reason: "programmatic page actions",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern: /\b(?:while\s*\(\s*true\s*\)|for\s*\(\s*;\s*;\s*\))/i,
|
||||||
|
reason: "unbounded loops",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern: /(?:__proto__|prototype\s*\[|constructor\s*\.\s*constructor)/i,
|
||||||
|
reason: "prototype escape",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const EMPTY_STRING_LITERAL = /^['"`]\s*['"`]$/;
|
||||||
|
|
||||||
|
function assertNoUnsafeInnerHtml(script: string): void {
|
||||||
|
for (const match of script.matchAll(/\.innerHTML\s*=\s*([^;\n]+)/g)) {
|
||||||
|
if (!EMPTY_STRING_LITERAL.test(match[1].trim())) {
|
||||||
|
throw new Error("Advanced script blocked: raw HTML injection");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (/\.innerHTML\s*\+=/.test(script)) {
|
||||||
|
throw new Error("Advanced script blocked: raw HTML injection");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertAdvancedScriptSafe(value: unknown): string {
|
||||||
|
if (typeof value !== "string") throw new Error("Advanced script must be text");
|
||||||
|
const script = value.trim();
|
||||||
|
if (!script) throw new Error("Advanced script is empty");
|
||||||
|
if (script.length > MAX_SCRIPT_LENGTH) {
|
||||||
|
throw new Error(
|
||||||
|
`Advanced script is too long (maximum ${MAX_SCRIPT_LENGTH} characters)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assertNoUnsafeInnerHtml(script);
|
||||||
|
for (const { pattern, reason } of BLOCKED_PATTERNS) {
|
||||||
|
if (pattern.test(script)) {
|
||||||
|
throw new Error(`Advanced script blocked: ${reason}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return script;
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/** @jest-environment jsdom */
|
||||||
|
|
||||||
|
import {
|
||||||
|
createStableSelector,
|
||||||
|
startElementSelection,
|
||||||
|
} from "./selection";
|
||||||
|
|
||||||
|
describe("AI mod element selection", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
document.body.innerHTML = `
|
||||||
|
<main>
|
||||||
|
<section class="cards">
|
||||||
|
<article class="assessment card"><h2>First</h2></article>
|
||||||
|
<article class="assessment card" data-testid="target"><h2>Second</h2></article>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prefers a unique id or test attribute", () => {
|
||||||
|
const target = document.querySelector<HTMLElement>("[data-testid=target]")!;
|
||||||
|
expect(createStableSelector(target)).toBe('[data-testid="target"]');
|
||||||
|
|
||||||
|
target.id = "assessment:42";
|
||||||
|
expect(createStableSelector(target)).toBe("#assessment\\:42");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to a unique structural selector", () => {
|
||||||
|
const target = document.querySelectorAll<HTMLElement>("article")[1];
|
||||||
|
target.removeAttribute("data-testid");
|
||||||
|
|
||||||
|
const selector = createStableSelector(target);
|
||||||
|
expect(document.querySelector(selector)).toBe(target);
|
||||||
|
expect(document.querySelectorAll(selector)).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("captures a clicked page element without activating it", () => {
|
||||||
|
const onSelect = jest.fn();
|
||||||
|
const onCancel = jest.fn();
|
||||||
|
const target = document.querySelector<HTMLElement>("[data-testid=target]")!;
|
||||||
|
const clickSpy = jest.fn();
|
||||||
|
target.addEventListener("click", clickSpy);
|
||||||
|
|
||||||
|
const stop = startElementSelection({ onSelect, onCancel });
|
||||||
|
target.dispatchEvent(
|
||||||
|
new MouseEvent("click", { bubbles: true, cancelable: true }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(onSelect).toHaveBeenCalledWith(target);
|
||||||
|
expect(clickSpy).not.toHaveBeenCalled();
|
||||||
|
expect(onCancel).not.toHaveBeenCalled();
|
||||||
|
expect(document.querySelector("[data-bsplus-ai-selection-overlay]")).toBeNull();
|
||||||
|
stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("cancels with Escape and removes the overlay", () => {
|
||||||
|
const onCancel = jest.fn();
|
||||||
|
const stop = startElementSelection({
|
||||||
|
onSelect: jest.fn(),
|
||||||
|
onCancel,
|
||||||
|
});
|
||||||
|
|
||||||
|
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
|
||||||
|
|
||||||
|
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||||
|
expect(document.querySelector("[data-bsplus-ai-selection-overlay]")).toBeNull();
|
||||||
|
stop();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
const PREFERRED_ATTRIBUTES = ["data-testid", "data-id", "name"] as const;
|
||||||
|
|
||||||
|
function isUnique(selector: string, documentRef: Document): boolean {
|
||||||
|
try {
|
||||||
|
return documentRef.querySelectorAll(selector).length === 1;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeCss(value: string): string {
|
||||||
|
const escaped = value.replace(/([^\w-])/g, "\\$1");
|
||||||
|
if (/^-?\d/.test(escaped)) {
|
||||||
|
const firstDigit = escaped.startsWith("-") ? escaped[1] : escaped[0];
|
||||||
|
const prefixLength = escaped.startsWith("-") ? 2 : 1;
|
||||||
|
return `${escaped.startsWith("-") ? "-" : ""}\\3${firstDigit} ${escaped.slice(prefixLength)}`;
|
||||||
|
}
|
||||||
|
return escaped;
|
||||||
|
}
|
||||||
|
|
||||||
|
function elementSegment(element: Element): string {
|
||||||
|
const tag = element.tagName.toLowerCase();
|
||||||
|
const stableClasses = [...element.classList]
|
||||||
|
.filter((className) => /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/.test(className))
|
||||||
|
.slice(0, 2);
|
||||||
|
let segment = `${tag}${stableClasses
|
||||||
|
.map((className) => `.${escapeCss(className)}`)
|
||||||
|
.join("")}`;
|
||||||
|
|
||||||
|
const parent = element.parentElement;
|
||||||
|
if (parent) {
|
||||||
|
const sameTag = [...parent.children].filter(
|
||||||
|
(sibling) => sibling.tagName === element.tagName,
|
||||||
|
);
|
||||||
|
if (sameTag.length > 1) {
|
||||||
|
segment += `:nth-of-type(${sameTag.indexOf(element) + 1})`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return segment;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createStableSelector(
|
||||||
|
element: Element,
|
||||||
|
documentRef: Document = document,
|
||||||
|
): string {
|
||||||
|
if (element.id) {
|
||||||
|
const byId = `#${escapeCss(element.id)}`;
|
||||||
|
if (isUnique(byId, documentRef)) return byId;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const attribute of PREFERRED_ATTRIBUTES) {
|
||||||
|
const value = element.getAttribute(attribute);
|
||||||
|
if (!value || value.length > 160) continue;
|
||||||
|
const selector = `[${attribute}="${escapeCss(value)}"]`;
|
||||||
|
if (isUnique(selector, documentRef)) return selector;
|
||||||
|
}
|
||||||
|
|
||||||
|
const segments: string[] = [];
|
||||||
|
let current: Element | null = element;
|
||||||
|
while (current && current !== documentRef.documentElement) {
|
||||||
|
segments.unshift(elementSegment(current));
|
||||||
|
const selector = segments.join(" > ");
|
||||||
|
if (isUnique(selector, documentRef)) return selector;
|
||||||
|
current = current.parentElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
const selector = segments.join(" > ");
|
||||||
|
if (!selector || !isUnique(selector, documentRef)) {
|
||||||
|
throw new Error("Could not create a stable selector for this element");
|
||||||
|
}
|
||||||
|
return selector;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildScopeRelativeSelector(
|
||||||
|
root: HTMLElement,
|
||||||
|
target: Element,
|
||||||
|
): string {
|
||||||
|
if (target === root) return ":scope";
|
||||||
|
if (!root.contains(target)) {
|
||||||
|
throw new Error("Cannot build a selector outside the selected root");
|
||||||
|
}
|
||||||
|
const segments: string[] = [];
|
||||||
|
let current: Element | null = target;
|
||||||
|
while (current && current !== root) {
|
||||||
|
segments.unshift(elementSegment(current));
|
||||||
|
current = current.parentElement;
|
||||||
|
}
|
||||||
|
return segments.length > 0 ? `:scope > ${segments.join(" > ")}` : ":scope";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ElementSelectionOptions {
|
||||||
|
onSelect: (element: HTMLElement) => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
ignoredRoot?: Node | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function eventElement(event: Event): HTMLElement | null {
|
||||||
|
for (const item of event.composedPath()) {
|
||||||
|
if (item instanceof HTMLElement) return item;
|
||||||
|
}
|
||||||
|
return event.target instanceof HTMLElement ? event.target : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startElementSelection({
|
||||||
|
onSelect,
|
||||||
|
onCancel,
|
||||||
|
ignoredRoot,
|
||||||
|
}: ElementSelectionOptions): () => void {
|
||||||
|
const overlay = document.createElement("div");
|
||||||
|
overlay.dataset.bsplusAiSelectionOverlay = "";
|
||||||
|
Object.assign(overlay.style, {
|
||||||
|
position: "fixed",
|
||||||
|
pointerEvents: "none",
|
||||||
|
zIndex: "2147483647",
|
||||||
|
border: "2px solid var(--better-main, #8b5cf6)",
|
||||||
|
borderRadius: "6px",
|
||||||
|
background: "color-mix(in srgb, var(--better-main, #8b5cf6) 14%, transparent)",
|
||||||
|
boxShadow: "0 0 0 1px rgba(255,255,255,.7)",
|
||||||
|
display: "none",
|
||||||
|
transition: "left 60ms, top 60ms, width 60ms, height 60ms",
|
||||||
|
});
|
||||||
|
document.body.appendChild(overlay);
|
||||||
|
|
||||||
|
let active = true;
|
||||||
|
const isIgnored = (element: HTMLElement) =>
|
||||||
|
element === overlay ||
|
||||||
|
ignoredRoot === element ||
|
||||||
|
Boolean(ignoredRoot?.contains(element)) ||
|
||||||
|
Boolean(
|
||||||
|
ignoredRoot instanceof HTMLElement &&
|
||||||
|
ignoredRoot.shadowRoot?.contains(element),
|
||||||
|
);
|
||||||
|
|
||||||
|
const updateOverlay = (element: HTMLElement) => {
|
||||||
|
const rect = element.getBoundingClientRect();
|
||||||
|
Object.assign(overlay.style, {
|
||||||
|
display: "block",
|
||||||
|
left: `${rect.left}px`,
|
||||||
|
top: `${rect.top}px`,
|
||||||
|
width: `${rect.width}px`,
|
||||||
|
height: `${rect.height}px`,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
if (!active) return;
|
||||||
|
active = false;
|
||||||
|
document.removeEventListener("pointermove", onPointerMove, true);
|
||||||
|
document.removeEventListener("click", onClick, true);
|
||||||
|
document.removeEventListener("keydown", onKeyDown, true);
|
||||||
|
overlay.remove();
|
||||||
|
};
|
||||||
|
|
||||||
|
const onPointerMove = (event: PointerEvent) => {
|
||||||
|
const element = eventElement(event);
|
||||||
|
if (!element || isIgnored(element)) {
|
||||||
|
overlay.style.display = "none";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
updateOverlay(element);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onClick = (event: MouseEvent) => {
|
||||||
|
const element = eventElement(event);
|
||||||
|
if (!element || isIgnored(element)) return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
cleanup();
|
||||||
|
onSelect(element);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key !== "Escape") return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
cleanup();
|
||||||
|
onCancel();
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener("pointermove", onPointerMove, true);
|
||||||
|
document.addEventListener("click", onClick, true);
|
||||||
|
document.addEventListener("keydown", onKeyDown, true);
|
||||||
|
return cleanup;
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import {
|
||||||
|
formatRecipeValidationError,
|
||||||
|
parseGeneratedModDraft,
|
||||||
|
} from "./recipeSchema";
|
||||||
|
import { aiModLog } from "./logger";
|
||||||
|
import {
|
||||||
|
deleteStoredMod,
|
||||||
|
exportStoredMods,
|
||||||
|
importStoredMods,
|
||||||
|
loadStoredMods,
|
||||||
|
setStoredModEnabled,
|
||||||
|
upsertStoredMod,
|
||||||
|
} from "./storage";
|
||||||
|
import type {
|
||||||
|
AdvancedScriptSupport,
|
||||||
|
CreatorServices,
|
||||||
|
GeneratedModDraft,
|
||||||
|
GenerationProgress,
|
||||||
|
KeyStatus,
|
||||||
|
ModelSettings,
|
||||||
|
SelectedElementContext,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
|
const AI_MOD_CREATOR_MESSAGE_TYPE = "aiModCreator";
|
||||||
|
|
||||||
|
interface MessageResponse {
|
||||||
|
success?: boolean;
|
||||||
|
data?: unknown;
|
||||||
|
error?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendBackgroundMessage(
|
||||||
|
action: string,
|
||||||
|
payload: Record<string, unknown> = {},
|
||||||
|
): Promise<unknown> {
|
||||||
|
aiModLog.debug("services", `Sending background message: ${action}`, payload);
|
||||||
|
const response = (await browser.runtime.sendMessage({
|
||||||
|
type: AI_MOD_CREATOR_MESSAGE_TYPE,
|
||||||
|
action,
|
||||||
|
...payload,
|
||||||
|
})) as MessageResponse | undefined;
|
||||||
|
if (!response?.success) {
|
||||||
|
const error =
|
||||||
|
typeof response?.error === "string"
|
||||||
|
? response.error
|
||||||
|
: "AI Mod Creator background service is unavailable";
|
||||||
|
aiModLog.error("services", `Background message failed: ${action}`, error);
|
||||||
|
throw new Error(error);
|
||||||
|
}
|
||||||
|
aiModLog.debug("services", `Background message succeeded: ${action}`, response.data);
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function streamGeneration(
|
||||||
|
context: SelectedElementContext,
|
||||||
|
onProgress?: (progress: GenerationProgress) => void,
|
||||||
|
) {
|
||||||
|
return new Promise<ReturnType<typeof parseGeneratedModDraft>>(
|
||||||
|
(resolve, reject) => {
|
||||||
|
aiModLog.info("services", "Opening streaming generation port", {
|
||||||
|
route: context.route,
|
||||||
|
rootSelector: context.rootSelector,
|
||||||
|
request: context.request,
|
||||||
|
});
|
||||||
|
const port = browser.runtime.connect({ name: "aiModCreator.stream" });
|
||||||
|
let settled = false;
|
||||||
|
port.onMessage.addListener(
|
||||||
|
(message: {
|
||||||
|
type?: string;
|
||||||
|
progress?: GenerationProgress;
|
||||||
|
draft?: unknown;
|
||||||
|
error?: unknown;
|
||||||
|
}) => {
|
||||||
|
if (message.type === "progress" && message.progress) {
|
||||||
|
aiModLog.debug("services", "Stream progress", message.progress);
|
||||||
|
onProgress?.(message.progress);
|
||||||
|
} else if (message.type === "done") {
|
||||||
|
settled = true;
|
||||||
|
aiModLog.info("services", "Stream completed", message.draft);
|
||||||
|
try {
|
||||||
|
resolve(parseGeneratedModDraft(message.draft as GeneratedModDraft));
|
||||||
|
} catch (error) {
|
||||||
|
const formatted = formatRecipeValidationError(error);
|
||||||
|
aiModLog.error("services", "Failed to validate streamed draft", {
|
||||||
|
draft: message.draft,
|
||||||
|
error: formatted,
|
||||||
|
});
|
||||||
|
reject(new Error(formatted));
|
||||||
|
}
|
||||||
|
} else if (message.type === "error") {
|
||||||
|
settled = true;
|
||||||
|
const errorMessage =
|
||||||
|
typeof message.error === "string"
|
||||||
|
? message.error
|
||||||
|
: "AI streaming failed";
|
||||||
|
aiModLog.error("services", "Stream error from background", errorMessage);
|
||||||
|
reject(new Error(errorMessage));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
port.onDisconnect.addListener(() => {
|
||||||
|
if (!settled) {
|
||||||
|
aiModLog.error("services", "Streaming port disconnected early");
|
||||||
|
reject(new Error("AI streaming connection closed"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
port.postMessage({ context });
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createCreatorServices(): CreatorServices {
|
||||||
|
return {
|
||||||
|
async getKeyStatus() {
|
||||||
|
const data = await sendBackgroundMessage("status");
|
||||||
|
if (
|
||||||
|
!data ||
|
||||||
|
typeof data !== "object" ||
|
||||||
|
typeof (data as KeyStatus).configured !== "boolean"
|
||||||
|
) {
|
||||||
|
throw new Error("Invalid API key status response");
|
||||||
|
}
|
||||||
|
return { configured: (data as KeyStatus).configured };
|
||||||
|
},
|
||||||
|
async getModelSettings() {
|
||||||
|
const data = await sendBackgroundMessage("getModel");
|
||||||
|
if (
|
||||||
|
!data ||
|
||||||
|
typeof data !== "object" ||
|
||||||
|
typeof (data as ModelSettings).modelId !== "string"
|
||||||
|
) {
|
||||||
|
throw new Error("Invalid model settings response");
|
||||||
|
}
|
||||||
|
return { modelId: (data as ModelSettings).modelId };
|
||||||
|
},
|
||||||
|
async saveModel(modelId) {
|
||||||
|
await sendBackgroundMessage("saveModel", { modelId });
|
||||||
|
},
|
||||||
|
async getAdvancedScriptSupport() {
|
||||||
|
const data = await sendBackgroundMessage("advancedSupport");
|
||||||
|
if (
|
||||||
|
!data ||
|
||||||
|
typeof data !== "object" ||
|
||||||
|
typeof (data as AdvancedScriptSupport).supported !== "boolean"
|
||||||
|
) {
|
||||||
|
throw new Error("Invalid advanced script support response");
|
||||||
|
}
|
||||||
|
return data as AdvancedScriptSupport;
|
||||||
|
},
|
||||||
|
async openExtensionSettings() {
|
||||||
|
const extensionId = browser.runtime.id;
|
||||||
|
await browser.tabs.create({
|
||||||
|
url: `chrome://extensions/?id=${extensionId}`,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
async saveKey(apiKey) {
|
||||||
|
await sendBackgroundMessage("saveKey", { apiKey });
|
||||||
|
},
|
||||||
|
async clearKey() {
|
||||||
|
await sendBackgroundMessage("clearKey");
|
||||||
|
},
|
||||||
|
async generate(context, onProgress) {
|
||||||
|
return streamGeneration(context, onProgress);
|
||||||
|
},
|
||||||
|
loadMods: loadStoredMods,
|
||||||
|
saveMod: upsertStoredMod,
|
||||||
|
setModEnabled: setStoredModEnabled,
|
||||||
|
deleteMod: deleteStoredMod,
|
||||||
|
importMods: importStoredMods,
|
||||||
|
exportMods: exportStoredMods,
|
||||||
|
async executeAdvancedScript(recipe) {
|
||||||
|
aiModLog.info("services", "Requesting advanced mod via background", recipe.id);
|
||||||
|
await sendBackgroundMessage("executeAdvanced", { recipe });
|
||||||
|
},
|
||||||
|
async stopAdvancedScript(id) {
|
||||||
|
aiModLog.info("services", "Stopping advanced mod via background", id);
|
||||||
|
await sendBackgroundMessage("stopAdvanced", { id });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import {
|
||||||
|
deleteStoredMod,
|
||||||
|
exportStoredMods,
|
||||||
|
importStoredMods,
|
||||||
|
loadStoredMods,
|
||||||
|
setStoredModEnabled,
|
||||||
|
upsertStoredMod,
|
||||||
|
} from "./storage";
|
||||||
|
import type { StoredModRecipe } from "./types";
|
||||||
|
|
||||||
|
const storedRecipe: StoredModRecipe = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
id: "mod-1",
|
||||||
|
name: "Test",
|
||||||
|
description: "Test mod",
|
||||||
|
enabled: false,
|
||||||
|
route: "assessments",
|
||||||
|
rootSelector: "#selected",
|
||||||
|
operations: [{ type: "hide", selector: ":scope" }],
|
||||||
|
createdAt: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("AI mod local storage", () => {
|
||||||
|
it("immutably inserts, updates, toggles, and deletes recipes", async () => {
|
||||||
|
await upsertStoredMod(storedRecipe);
|
||||||
|
expect(await loadStoredMods()).toEqual([storedRecipe]);
|
||||||
|
|
||||||
|
await setStoredModEnabled("mod-1", true);
|
||||||
|
expect((await loadStoredMods())[0]).toMatchObject({
|
||||||
|
id: "mod-1",
|
||||||
|
enabled: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await upsertStoredMod({ ...storedRecipe, name: "Updated" });
|
||||||
|
expect((await loadStoredMods())[0].name).toBe("Updated");
|
||||||
|
|
||||||
|
await deleteStoredMod("mod-1");
|
||||||
|
expect(await loadStoredMods()).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("round-trips validated import/export JSON", async () => {
|
||||||
|
await upsertStoredMod(storedRecipe);
|
||||||
|
const exported = await exportStoredMods();
|
||||||
|
|
||||||
|
await browser.storage.local.clear?.();
|
||||||
|
const imported = await importStoredMods(exported);
|
||||||
|
|
||||||
|
expect(imported).toEqual([storedRecipe]);
|
||||||
|
expect(await loadStoredMods()).toEqual([storedRecipe]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not overwrite storage when an import is invalid", async () => {
|
||||||
|
await upsertStoredMod(storedRecipe);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
importStoredMods(
|
||||||
|
JSON.stringify([
|
||||||
|
{
|
||||||
|
...storedRecipe,
|
||||||
|
operations: [{ type: "javascript", code: "alert(1)" }],
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
).rejects.toThrow();
|
||||||
|
expect(await loadStoredMods()).toEqual([storedRecipe]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import browser from "webextension-polyfill";
|
||||||
|
import { parseStoredRecipes, validateStoredRecipes } from "./recipeSchema";
|
||||||
|
import type { StoredModRecipe } from "./types";
|
||||||
|
|
||||||
|
export const AI_MODS_STORAGE_KEY = "aiModCreator.mods";
|
||||||
|
export const OPENROUTER_API_KEY_STORAGE_KEY =
|
||||||
|
"aiModCreator.openRouterApiKey";
|
||||||
|
export const OPENROUTER_MODEL_STORAGE_KEY = "aiModCreator.openRouterModelId";
|
||||||
|
|
||||||
|
async function writeStoredMods(
|
||||||
|
recipes: StoredModRecipe[],
|
||||||
|
): Promise<StoredModRecipe[]> {
|
||||||
|
const validated = validateStoredRecipes(recipes);
|
||||||
|
await browser.storage.local.set({ [AI_MODS_STORAGE_KEY]: validated });
|
||||||
|
return validated;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadStoredMods(): Promise<StoredModRecipe[]> {
|
||||||
|
const result = await browser.storage.local.get(AI_MODS_STORAGE_KEY);
|
||||||
|
const stored = result[AI_MODS_STORAGE_KEY];
|
||||||
|
if (stored === undefined) return [];
|
||||||
|
try {
|
||||||
|
return validateStoredRecipes(stored);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[BetterSEQTA+] Ignoring invalid locally stored AI mods:", error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function upsertStoredMod(
|
||||||
|
recipe: StoredModRecipe,
|
||||||
|
): Promise<StoredModRecipe[]> {
|
||||||
|
const [validated] = validateStoredRecipes([recipe]);
|
||||||
|
const existing = await loadStoredMods();
|
||||||
|
const next = existing.some((item) => item.id === validated.id)
|
||||||
|
? existing.map((item) => (item.id === validated.id ? validated : item))
|
||||||
|
: [...existing, validated];
|
||||||
|
return writeStoredMods(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setStoredModEnabled(
|
||||||
|
id: string,
|
||||||
|
enabled: boolean,
|
||||||
|
): Promise<StoredModRecipe[]> {
|
||||||
|
const existing = await loadStoredMods();
|
||||||
|
const next = existing.map((item) =>
|
||||||
|
item.id === id ? { ...item, enabled, updatedAt: Date.now() } : item,
|
||||||
|
);
|
||||||
|
return writeStoredMods(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteStoredMod(
|
||||||
|
id: string,
|
||||||
|
): Promise<StoredModRecipe[]> {
|
||||||
|
const existing = await loadStoredMods();
|
||||||
|
return writeStoredMods(existing.filter((item) => item.id !== id));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function exportStoredMods(): Promise<string> {
|
||||||
|
return JSON.stringify(await loadStoredMods(), null, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function importStoredMods(
|
||||||
|
json: string,
|
||||||
|
): Promise<StoredModRecipe[]> {
|
||||||
|
const imported = parseStoredRecipes(json);
|
||||||
|
return writeStoredMods(imported);
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
export const AI_MOD_SCHEMA_VERSION = 1 as const;
|
||||||
|
|
||||||
|
export type SafeStyleProperty =
|
||||||
|
| "align-items"
|
||||||
|
| "align-self"
|
||||||
|
| "aspect-ratio"
|
||||||
|
| "background"
|
||||||
|
| "background-color"
|
||||||
|
| "border"
|
||||||
|
| "border-color"
|
||||||
|
| "border-radius"
|
||||||
|
| "border-style"
|
||||||
|
| "border-width"
|
||||||
|
| "bottom"
|
||||||
|
| "box-shadow"
|
||||||
|
| "color"
|
||||||
|
| "cursor"
|
||||||
|
| "display"
|
||||||
|
| "flex"
|
||||||
|
| "flex-direction"
|
||||||
|
| "flex-grow"
|
||||||
|
| "flex-shrink"
|
||||||
|
| "flex-wrap"
|
||||||
|
| "font-size"
|
||||||
|
| "font-weight"
|
||||||
|
| "gap"
|
||||||
|
| "grid-template-columns"
|
||||||
|
| "height"
|
||||||
|
| "justify-content"
|
||||||
|
| "left"
|
||||||
|
| "letter-spacing"
|
||||||
|
| "line-height"
|
||||||
|
| "margin"
|
||||||
|
| "margin-bottom"
|
||||||
|
| "margin-left"
|
||||||
|
| "margin-right"
|
||||||
|
| "margin-top"
|
||||||
|
| "max-height"
|
||||||
|
| "max-width"
|
||||||
|
| "min-height"
|
||||||
|
| "min-width"
|
||||||
|
| "object-fit"
|
||||||
|
| "opacity"
|
||||||
|
| "order"
|
||||||
|
| "overflow"
|
||||||
|
| "overflow-x"
|
||||||
|
| "overflow-y"
|
||||||
|
| "padding"
|
||||||
|
| "padding-bottom"
|
||||||
|
| "padding-left"
|
||||||
|
| "padding-right"
|
||||||
|
| "padding-top"
|
||||||
|
| "position"
|
||||||
|
| "right"
|
||||||
|
| "text-align"
|
||||||
|
| "text-decoration"
|
||||||
|
| "top"
|
||||||
|
| "vertical-align"
|
||||||
|
| "white-space"
|
||||||
|
| "width"
|
||||||
|
| "z-index";
|
||||||
|
|
||||||
|
export type SafeAttributeName =
|
||||||
|
| "aria-label"
|
||||||
|
| "aria-description"
|
||||||
|
| "aria-hidden"
|
||||||
|
| "placeholder"
|
||||||
|
| "role"
|
||||||
|
| "title";
|
||||||
|
|
||||||
|
interface OperationBase {
|
||||||
|
selector: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SetTextOperation extends OperationBase {
|
||||||
|
type: "setText";
|
||||||
|
text: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReplaceTextOperation extends OperationBase {
|
||||||
|
type: "replaceText";
|
||||||
|
search: string;
|
||||||
|
replacement: string;
|
||||||
|
all?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SetAttributeOperation extends OperationBase {
|
||||||
|
type: "setAttribute";
|
||||||
|
name: SafeAttributeName;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SetStyleOperation extends OperationBase {
|
||||||
|
type: "setStyle";
|
||||||
|
property: SafeStyleProperty;
|
||||||
|
value: string;
|
||||||
|
/** When true (default), beats BetterSEQTA stylesheet rules including !important. */
|
||||||
|
important?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AddClassOperation extends OperationBase {
|
||||||
|
type: "addClass";
|
||||||
|
className: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RemoveClassOperation extends OperationBase {
|
||||||
|
type: "removeClass";
|
||||||
|
className: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HideOperation extends OperationBase {
|
||||||
|
type: "hide";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShowOperation extends OperationBase {
|
||||||
|
type: "show";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InsertTextOperation extends OperationBase {
|
||||||
|
type: "insertText";
|
||||||
|
position: "before" | "after" | "prepend" | "append";
|
||||||
|
tag: "div" | "span" | "p" | "button" | "label";
|
||||||
|
text: string;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ModOperation =
|
||||||
|
| SetTextOperation
|
||||||
|
| ReplaceTextOperation
|
||||||
|
| SetAttributeOperation
|
||||||
|
| SetStyleOperation
|
||||||
|
| AddClassOperation
|
||||||
|
| RemoveClassOperation
|
||||||
|
| HideOperation
|
||||||
|
| ShowOperation
|
||||||
|
| InsertTextOperation;
|
||||||
|
|
||||||
|
export interface GeneratedModDraft {
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
operations: ModOperation[];
|
||||||
|
advancedScript?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StoredModRecipe extends GeneratedModDraft {
|
||||||
|
schemaVersion: typeof AI_MOD_SCHEMA_VERSION;
|
||||||
|
id: string;
|
||||||
|
enabled: boolean;
|
||||||
|
route: string;
|
||||||
|
rootSelector: string;
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DomElementSummary {
|
||||||
|
selector: string;
|
||||||
|
tag: string;
|
||||||
|
classes: string[];
|
||||||
|
directText?: string;
|
||||||
|
parentSelector: string | null;
|
||||||
|
siblingIndex: number;
|
||||||
|
siblingCount: number;
|
||||||
|
layout: Record<string, string>;
|
||||||
|
rowCount?: number;
|
||||||
|
columnCount?: number;
|
||||||
|
itemCount?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ParentChainSummary {
|
||||||
|
tag: string;
|
||||||
|
classes: string[];
|
||||||
|
layout: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StructuralHints {
|
||||||
|
hasTable: boolean;
|
||||||
|
hasList: boolean;
|
||||||
|
rowCount?: number;
|
||||||
|
columnCount?: number;
|
||||||
|
itemCount?: number;
|
||||||
|
primaryClasses: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SelectedElementContext {
|
||||||
|
route: string;
|
||||||
|
rootSelector: string;
|
||||||
|
request: string;
|
||||||
|
userContext: string;
|
||||||
|
selectedHtml: string;
|
||||||
|
domCatalog: DomElementSummary[];
|
||||||
|
ancestorHtml?: string;
|
||||||
|
parentChain?: ParentChainSummary[];
|
||||||
|
structuralHints?: StructuralHints;
|
||||||
|
tagName: string;
|
||||||
|
dimensions: {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
};
|
||||||
|
computedStyle: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface KeyStatus {
|
||||||
|
configured: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ModelSettings {
|
||||||
|
modelId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedScriptSupport {
|
||||||
|
supported: boolean;
|
||||||
|
reason?: string;
|
||||||
|
instructions?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GenerationProgress {
|
||||||
|
type: "status" | "content" | "usage";
|
||||||
|
text?: string;
|
||||||
|
promptTokens?: number;
|
||||||
|
completionTokens?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreatorServices {
|
||||||
|
getKeyStatus: () => Promise<KeyStatus>;
|
||||||
|
getModelSettings: () => Promise<ModelSettings>;
|
||||||
|
saveModel: (modelId: string) => Promise<void>;
|
||||||
|
getAdvancedScriptSupport: () => Promise<AdvancedScriptSupport>;
|
||||||
|
openExtensionSettings: () => Promise<void>;
|
||||||
|
saveKey: (apiKey: string) => Promise<void>;
|
||||||
|
clearKey: () => Promise<void>;
|
||||||
|
generate: (
|
||||||
|
context: SelectedElementContext,
|
||||||
|
onProgress?: (progress: GenerationProgress) => void,
|
||||||
|
) => Promise<GeneratedModDraft>;
|
||||||
|
loadMods: () => Promise<StoredModRecipe[]>;
|
||||||
|
saveMod: (recipe: StoredModRecipe) => Promise<StoredModRecipe[]>;
|
||||||
|
setModEnabled: (
|
||||||
|
id: string,
|
||||||
|
enabled: boolean,
|
||||||
|
) => Promise<StoredModRecipe[]>;
|
||||||
|
deleteMod: (id: string) => Promise<StoredModRecipe[]>;
|
||||||
|
importMods: (json: string) => Promise<StoredModRecipe[]>;
|
||||||
|
exportMods: () => Promise<string>;
|
||||||
|
executeAdvancedScript: (recipe: StoredModRecipe) => Promise<void>;
|
||||||
|
stopAdvancedScript: (id: string) => Promise<void>;
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@ import enhancedNavigationPluginLazy from "./built-in/enhancedNavigation/lazy";
|
|||||||
import globalSearchPluginLazy from "./built-in/globalSearch/lazy";
|
import globalSearchPluginLazy from "./built-in/globalSearch/lazy";
|
||||||
import gradeAnalyticsPluginLazy from "./built-in/gradeAnalytics/lazy";
|
import gradeAnalyticsPluginLazy from "./built-in/gradeAnalytics/lazy";
|
||||||
import errorPageKittenPlugin from "./built-in/errorPageKitten";
|
import errorPageKittenPlugin from "./built-in/errorPageKitten";
|
||||||
|
import aiModCreatorPlugin from "./built-in/aiModCreator";
|
||||||
|
|
||||||
// Initialize plugin manager
|
// Initialize plugin manager
|
||||||
const pluginManager = PluginManager.getInstance();
|
const pluginManager = PluginManager.getInstance();
|
||||||
@@ -38,6 +39,7 @@ pluginManager.registerPlugin(enhancedNavigationPluginLazy);
|
|||||||
pluginManager.registerPlugin(globalSearchPluginLazy);
|
pluginManager.registerPlugin(globalSearchPluginLazy);
|
||||||
pluginManager.registerPlugin(gradeAnalyticsPluginLazy);
|
pluginManager.registerPlugin(gradeAnalyticsPluginLazy);
|
||||||
pluginManager.registerPlugin(errorPageKittenPlugin);
|
pluginManager.registerPlugin(errorPageKittenPlugin);
|
||||||
|
pluginManager.registerPlugin(aiModCreatorPlugin);
|
||||||
|
|
||||||
export async function initializePlugins(): Promise<void> {
|
export async function initializePlugins(): Promise<void> {
|
||||||
await pluginManager.startAllPlugins();
|
await pluginManager.startAllPlugins();
|
||||||
|
|||||||
@@ -120,10 +120,11 @@ function onCustomSidebarCaptureClick(event: MouseEvent) {
|
|||||||
const li = target.closest("li.item[data-key]");
|
const li = target.closest("li.item[data-key]");
|
||||||
if (!(li instanceof HTMLElement) || !root.contains(li)) return;
|
if (!(li instanceof HTMLElement) || !root.contains(li)) return;
|
||||||
|
|
||||||
// Already-open folder chrome (renders its own `.sub`) — ignore; use Back.
|
// Open folder header row only — leaf clicks inside `.sub` must still navigate.
|
||||||
if (
|
if (
|
||||||
li.classList.contains("hasChildren") &&
|
li.classList.contains("hasChildren") &&
|
||||||
li.querySelector(":scope > .sub")
|
li.querySelector(":scope > .sub") &&
|
||||||
|
!target.closest(".sub")
|
||||||
) {
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -326,12 +326,22 @@ class SidebarState {
|
|||||||
// SEQTA rewrites `.active` on the route change.
|
// SEQTA rewrites `.active` on the route change.
|
||||||
if (this.isDrilling) {
|
if (this.isDrilling) {
|
||||||
this.enterFrameKey = null;
|
this.enterFrameKey = null;
|
||||||
restoreCustomMenuActive();
|
clearNativeDrillActive(menu);
|
||||||
}
|
}
|
||||||
|
|
||||||
const native = findNativeMenuEntry(menu, item);
|
const native = findNativeMenuEntry(menu, item);
|
||||||
if (native) {
|
if (native) {
|
||||||
native.click();
|
native.click();
|
||||||
|
// Inside a drill panel, SEQTA native rows may no-op if their folder is not
|
||||||
|
// `.active` — fall back to hash routing for standard (non-BS+) pages only.
|
||||||
|
if (
|
||||||
|
this.isDrilling &&
|
||||||
|
item.path &&
|
||||||
|
!item.betterseqta &&
|
||||||
|
getPagePathFromHash() !== item.path
|
||||||
|
) {
|
||||||
|
location.hash = `?page=${item.path}`;
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user