MCPcopy Index your code
hub / github.com/scriptscat/scriptcat / MessageQueue

Class MessageQueue

packages/message/message_queue.ts:40–94  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

38
39// 消息队列
40export class MessageQueue implements IMessageQueue {
41 private EE = new EventEmitter<string, any>();
42
43 constructor() {
44 chrome.runtime.onMessage.addListener((msg: TMessage) => {
45 const lastError = chrome.runtime.lastError;
46 const topic = msg.msgQueue;
47 if (typeof topic !== "string") return;
48 if (lastError) {
49 console.error("chrome.runtime.lastError in chrome.runtime.onMessage:", lastError);
50 // 消息API发生错误因此不继续执行
51 return false;
52 }
53 this.handler(topic, msg.data);
54 });
55 }
56
57 handler(topic: string, { action, message }: { action: string; message: any }) {
58 LoggerCore.getInstance()
59 .logger({ service: "messageQueue" })
60 .trace("messageQueueHandler", { action, topic, message });
61 switch (action) {
62 case "message":
63 this.EE.emit(topic, message);
64 break;
65 default:
66 throw new Error("action not found");
67 }
68 }
69
70 subscribe<T>(topic: string, handler: (msg: T) => void) {
71 this.EE.on(topic, handler);
72 return this.EE.off.bind(this.EE, topic, handler) as () => void;
73 }
74
75 publish<T>(topic: string, message: NonNullable<T>) {
76 chrome.runtime.sendMessage({
77 msgQueue: topic,
78 data: { action: "message", message },
79 });
80 this.EE.emit(topic, message);
81 //@ts-ignore
82 LoggerCore.getInstance().logger({ service: "messageQueue" }).trace("publish", { topic, message });
83 }
84
85 // 只发布给当前环境
86 emit<T>(topic: string, message: NonNullable<T>) {
87 this.EE.emit(topic, message);
88 }
89
90 // 创建分组
91 group(name: string, middleware?: MiddlewareFunction) {
92 return new MessageQueueGroup(this, name, middleware);
93 }
94}
95
96// 消息队列分组
97export class MessageQueueGroup implements IMessageQueue {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected