Skip to content
7 changes: 7 additions & 0 deletions packages/chrome-extension-mock/tab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,11 @@ export default class MockTab {
this.hook.addListener("remove", callback);
},
};

// 由测试通过 hook.emit("replace", addedTabId, removedTabId) 触发
onReplaced = {
addListener: (callback: any) => {
this.hook.addListener("replace", callback);
},
};
}
41 changes: 41 additions & 0 deletions packages/message/extension_message.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { ExtensionContentMessageSend } from "./extension_message";

afterEach(() => {
vi.restoreAllMocks();
});

describe("ExtensionContentMessageSend.notify", () => {
// 回调形式下接收端不回包,Chrome 会报 lastError「The message port closed before a response was received」;
// Promise 形式则正常 resolve(Chrome 156 实测),所以单向通知不能带回调
it("不带回调发送,并把定向选项原样交给 tabs.sendMessage", async () => {
const spy = vi.spyOn(chrome.tabs, "sendMessage");
const msg = { action: "scripting/runtime/valueUpdates", data: [] };

await expect(new ExtensionContentMessageSend(7, { frameId: 0, documentId: "doc" }).notify(msg)).resolves.toBe(
undefined
);
await new ExtensionContentMessageSend(8).notify(msg);

expect(spy.mock.calls).toEqual([
[7, msg, { frameId: 0, documentId: "doc" }],
[8, msg],
]);
});

it("接收端不存在时以浏览器的错误拒绝", async () => {
const error = new Error("Could not establish connection. Receiving end does not exist.");
vi.spyOn(chrome.tabs, "sendMessage").mockImplementation((() => Promise.reject(error)) as never);

await expect(new ExtensionContentMessageSend(7).notify({ action: "a" })).rejects.toBe(error);
});

it("调用本身被拒(如消息超过 64 MiB)时与 chrome API 一样同步抛出,而不是返回被拒绝的 Promise", () => {
const error = new Error("Message exceeded maximum allowed size of 64MiB.");
vi.spyOn(chrome.tabs, "sendMessage").mockImplementation((() => {
throw error;
}) as never);

expect(() => new ExtensionContentMessageSend(7).notify({ action: "a" })).toThrow(error);
});
});
12 changes: 12 additions & 0 deletions packages/message/extension_message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,18 @@ export class ExtensionContentMessageSend implements MessageSend {
}
) {}

/**
* 单向通知,配合接收端的 Server.onNotify。不能带回调:接收端不回包时回调形式必有 lastError,
* Promise 形式则在接收端的监听执行完后 resolve。目标不存在时 reject;调用本身被拒(如消息超过 64 MiB)时
* 与 chrome API 一样同步抛出。调用方依赖这一区分判断目标是否还在,所以这里不能改成 async 函数。
*/
notify(data: TMessage): Promise<void> {
const sent = this.options
? chrome.tabs.sendMessage(this.tabId, data, this.options)
: chrome.tabs.sendMessage(this.tabId, data);
return sent.then(() => undefined);
}

sendMessage<T = any>(data: TMessage): Promise<T> {
return new Promise((resolve) => {
if (!this.options?.documentId && !this.options?.frameId) {
Expand Down
60 changes: 59 additions & 1 deletion packages/message/server.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect, it, beforeEach, vi, afterEach } from "vitest";
import { GetSenderType, SenderConnect, SenderRuntime, Server, type IGetSender } from "./server";
import { CustomEventMessage } from "./custom_event_message";
import type { MessageConnect, RuntimeMessageSender } from "./types";
import type { Message, MessageConnect, OnMessageCallback, RuntimeMessageSender } from "./types";
import { uuidv4 } from "@App/pkg/utils/uuid";

let inboundMessage: CustomEventMessage;
Expand Down Expand Up @@ -658,4 +658,62 @@ describe("Server", () => {
expect(response.data).toBeUndefined();
});
});
describe("onNotify 单向通知", () => {
// 直接拿到传输层的 onMessage 回调:要观察的正是回调的返回值与 sendResponse 是否被调用,
// 这决定了 chrome.runtime 是否为这条消息保留响应通道并回传一条回包
const setupNotifyServer = () => {
let onMessage: OnMessageCallback | undefined;
const transport = {
onMessage: (cb: OnMessageCallback) => {
onMessage = cb;
},
onConnect: () => {},
} as unknown as Message;
const notifyServer = new Server("api", transport);
const sender = { tab: { id: 3 }, frameId: 2 } as RuntimeMessageSender;
return {
notifyServer,
sender,
deliver: (msg: any, sendResponse: () => void) => onMessage!(msg, sendResponse, sender),
};
};

it("调用处理器,但不回包,也不保留响应通道", () => {
const { notifyServer, deliver, sender } = setupNotifyServer();
const handler = vi.fn();
notifyServer.onNotify("updates", handler);
const sendResponse = vi.fn();

const keepChannel = deliver({ action: "api/updates", data: [1, 2] }, sendResponse);

expect(handler).toHaveBeenCalledWith([1, 2], expect.any(SenderRuntime));
expect((handler.mock.calls[0][1] as SenderRuntime).getSender()).toBe(sender);
expect(sendResponse).not.toHaveBeenCalled();
expect(keepChannel).toBe(false);
});

it("处理器抛错或返回的 Promise 被拒绝时,同样不回包", async () => {
const { notifyServer, deliver } = setupNotifyServer();
notifyServer.onNotify("throws", () => {
throw new Error("sync failure");
});
notifyServer.onNotify("rejects", () => Promise.reject(new Error("async failure")));
const sendResponse = vi.fn();

expect(deliver({ action: "api/throws", data: {} }, sendResponse)).toBe(false);
expect(deliver({ action: "api/rejects", data: {} }, sendResponse)).toBe(false);
await nextTick();

expect(sendResponse).not.toHaveBeenCalled();
});

it("与 on 注册的处理器同名时抛错", () => {
const { notifyServer } = setupNotifyServer();
notifyServer.on("dup", vi.fn());
notifyServer.onNotify("dup2", vi.fn());

expect(() => notifyServer.onNotify("dup", vi.fn())).toThrow("duplicate message handler: api/dup");
expect(() => notifyServer.on("dup2", vi.fn())).toThrow("duplicate message handler: api/dup2");
});
});
});
36 changes: 33 additions & 3 deletions packages/message/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ export class SenderRuntime {

type ApiFunction = (params: any, con: IGetSender) => Promise<any> | any | void;
type ApiFunctionSync = (params: any, con: IGetSender) => any;
type NotifyFunction = (params: any, con: IGetSender) => void | Promise<void>;
type MiddlewareFunction = (params: any, con: IGetSender, next: () => Promise<any> | any) => Promise<any> | any;

const formatErrorToClient = (e: any) => {
Expand All @@ -128,6 +129,7 @@ const formatErrorToClient = (e: any) => {

export class Server {
private apiFunctionMap: Map<string, ApiFunction> = new Map();
private notifyFunctionMap: Map<string, NotifyFunction> = new Map();

private logger = LoggerCore.getInstance().logger({ service: "messageServer" });

Expand Down Expand Up @@ -155,7 +157,10 @@ export class Server {
if (typeof msg.action !== "string") return;
this.logger.trace("server onMessage", { msg: msg as any });
if (msg.action?.startsWith(prefix)) {
return this.messageHandle(msg.action.slice(prefix.length + 1), msg.data, sendResponse, sender);
const action = msg.action.slice(prefix.length + 1);
const notify = this.notifyFunctionMap.get(action);
if (notify) return this.notifyHandle(action, notify, msg.data, sender);
return this.messageHandle(action, msg.data, sendResponse, sender);
}
});
return false;
Expand All @@ -167,10 +172,35 @@ export class Server {
}

on(name: string, func: ApiFunction) {
if (this.apiFunctionMap.has(name)) {
this.assertNotRegistered(name);
this.apiFunctionMap.set(name, func);
}

/**
* 注册单向通知:不回包,监听回调返回 false,发送端不必为它保留响应通道。
* 回包本身就是一次进程间消息,高频的一对多推送(如值更新)不需要回执时用它。
*/
onNotify(name: string, func: NotifyFunction) {
this.assertNotRegistered(name);
this.notifyFunctionMap.set(name, func);
}

private assertNotRegistered(name: string) {
if (this.apiFunctionMap.has(name) || this.notifyFunctionMap.has(name)) {
throw new Error(`duplicate message handler: ${this.prefix}/${name}`);
}
this.apiFunctionMap.set(name, func);
}

private notifyHandle(action: string, func: NotifyFunction, params: any, sender: RuntimeMessageSender): false {
try {
const ret = func(params, new SenderRuntime(sender));
if (ret instanceof Promise) {
ret.catch((e: Error) => this.logger.error("notifyHandle error", { action }, Logger.E(e)));
}
} catch (e: any) {
this.logger.error("notifyHandle error", { action }, Logger.E(e));
}
return false;
}

private connectHandle(msg: string, params: any, con: MessageConnect) {
Expand Down
2 changes: 2 additions & 0 deletions src/app/cache_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ export const CACHE_KEY_TAB_LOADED = "tabLoaded:";
export const CACHE_KEY_SET_VALUE = "setValue:";
export const CACHE_KEY_PERMISSION = "permission:";
export const CACHE_KEY_SKILL_INSTALL = "skillInstall:"; // Skill ZIP 待安装数据缓存
// 值更新投递表:某 tab 里各 frame 运行着哪些 storageName,SW 重启后据此恢复
export const CACHE_KEY_VALUE_UPDATE_TARGETS = "valueUpdateTargets:";
40 changes: 40 additions & 0 deletions src/app/service/content/gm_api/gm_api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,46 @@ describe.concurrent("GM_value", () => {
});
});

// 不属于任何标签页的 frame(如扩展页面里内嵌的网页)无法用 tabs.sendMessage 投递,SW 把本次更新随应答带回;
// 否则 GM.setValue 的 Promise 永远等不到回执
it.concurrent.each(["GM.setValue", "GM.setValues"])(
"%s 的应答带回本次更新时,Promise 完成并触发本脚本的监听",
async (api) => {
const script = Object.assign({}, scriptRes, { value: {} }) as ScriptLoadInfo;
script.metadata = { ...script.metadata, grant: [api, "GM_addValueChangeListener"] };
const call = api === "GM.setValue" ? `GM.setValue("k", "v")` : `GM.setValues({ k: "v" })`;
script.code = `
const changes = [];
GM_addValueChangeListener("k", (name, oldValue, newValue, remote) => changes.push([name, oldValue, newValue, remote]));
await ${call};
return changes;
`;
const mockSendMessage = vi
.fn()
.mockImplementation(async (msg: { data: { params: [string]; runFlag: string } }) => ({
code: 0,
data: {
id: msg.data.params[0],
entries: [["k", encodeRValue("v"), encodeRValue(undefined)]],
uuid: script.uuid,
storageName: script.uuid,
sender: { runFlag: msg.data.runFlag, tabId: -1 },
valueUpdated: true,
},
}));
const exec = new ExecScript(script, {
envPrefix: "scripting",
message: { sendMessage: mockSendMessage } as unknown as Message,
contentMsg: undefined as any,
code: nilFn,
envInfo,
});
exec.scriptFunc = compileScript(compileScriptCode(script));

await expect(exec.exec()).resolves.toEqual([["k", undefined, "v", false]]);
}
);

it.concurrent("value引用问题 #1141", async () => {
const script = Object.assign({}, scriptRes) as ScriptLoadInfo;
script.value = {};
Expand Down
19 changes: 14 additions & 5 deletions src/app/service/content/gm_api/gm_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,12 @@ export default class GMApi extends GM_Base {
});
}

// 不属于任何标签页的 frame(如扩展页面里内嵌的网页)收不到 SW 的 tabs.sendMessage 投递,
// SW 会把本次更新随应答带回;其他 frame 的应答不带,回执仍由投递的值更新完成
static applyOwnValueUpdate(a: GMApi, update: unknown) {
if (update) a.valueUpdate(update as ValueUpdateDataEncoded);
}

static _GM_setValue(a: GMApi, promise: any, key: string, value: any) {
key = `${key}`;
if (!a.scriptRes) return;
Expand All @@ -292,9 +298,10 @@ export default class GMApi extends GM_Base {
if (promise) {
valueChangePromiseMap.set(id, promise);
}
let sent: Promise<unknown>;
if (value === undefined) {
delete a.scriptRes.value[key];
a.sendMessage("GM_setValue", [id, key]);
sent = a.sendMessage("GM_setValue", [id, key]);
} else {
// 对object的value进行一次转化
if (value && typeof value === "object") {
Expand All @@ -303,11 +310,12 @@ export default class GMApi extends GM_Base {
// customClone 可能返回 undefined
a.scriptRes.value[key] = value;
if (value === undefined) {
a.sendMessage("GM_setValue", [id, key]);
sent = a.sendMessage("GM_setValue", [id, key]);
} else {
a.sendMessage("GM_setValue", [id, key, value]);
sent = a.sendMessage("GM_setValue", [id, key, value]);
}
}
sent.then((update) => applyOwnValueUpdate(a, update));
return id;
}

Expand Down Expand Up @@ -339,7 +347,7 @@ export default class GMApi extends GM_Base {
// 避免undefined 等空值流失,先进行映射处理
keyValuePairs.push([key, encodeRValue(value_)]);
}
a.sendMessage("GM_setValues", [id, keyValuePairs]);
a.sendMessage("GM_setValues", [id, keyValuePairs]).then((update) => applyOwnValueUpdate(a, update));
return id;
}

Expand Down Expand Up @@ -1631,4 +1639,5 @@ export default class GMApi extends GM_Base {
export const { createGMBase } = GM_Base;

// 从 GMApi 对象中解构出内部函数,用于后续本地使用,不导出
const { _GM_getValue, _GM_cookie, _GM_setValue, _GM_setValues, _GM_download, _GM_notification } = GMApi;
const { _GM_getValue, _GM_cookie, _GM_setValue, _GM_setValues, _GM_download, _GM_notification, applyOwnValueUpdate } =
GMApi;
Loading
Loading