mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 05:09:21 +08:00
feat: 浏览器扩展完全支持热更新
This commit is contained in:
@@ -1,30 +0,0 @@
|
||||
import type { FeatureHandle, FeatureModule, FeatureMountContext } from '@/features/runtime/types';
|
||||
import {
|
||||
isFloatingVisible,
|
||||
setFloatingVisible,
|
||||
toggleFloatingPanel,
|
||||
} from '@/content/floating/mount';
|
||||
|
||||
/**
|
||||
* 嵌入式实现:与远程发布的 pdd-ad-fee 同 id。
|
||||
* 壳内直接 mount;远程 JS 用于版本对齐与后续 main-world 执行。
|
||||
*/
|
||||
export const pddAdFeeEmbeddedFeature: FeatureModule = {
|
||||
id: 'pdd-ad-fee',
|
||||
async mount(_ctx: FeatureMountContext): Promise<FeatureHandle> {
|
||||
setFloatingVisible(true);
|
||||
return {
|
||||
unmount: () => {
|
||||
setFloatingVisible(false);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export function isPddAdFeePanelVisible(): boolean {
|
||||
return isFloatingVisible();
|
||||
}
|
||||
|
||||
export function togglePddAdFeePanel(): boolean {
|
||||
return toggleFloatingPanel();
|
||||
}
|
||||
@@ -1,20 +1,33 @@
|
||||
/**
|
||||
* 远程功能包入口(IIFE 构建)。
|
||||
* 当前阶段导出元数据;真正 UI 仍由壳内 embedded 模块挂载。
|
||||
* 后续可将 FloatingPanel 整包打入此入口并在 main world 执行。
|
||||
* 远程功能包入口(IIFE → dist-features/pdd-ad-fee.js)。
|
||||
* 在页面 MAIN world 执行;Open API / 设置走壳侧 postMessage 桥接。
|
||||
*/
|
||||
import { installMainWorldAdapters } from '@/features/runtime/mainWorldAdapters';
|
||||
import { setFloatingVisible } from '@/content/floating/mount';
|
||||
|
||||
const FEATURE_ID = 'pdd-ad-fee';
|
||||
const FEATURE_VERSION = '0.2.0';
|
||||
|
||||
export interface RemoteFeatureExport {
|
||||
id: string;
|
||||
version: string;
|
||||
executionWorld: 'extension';
|
||||
executionWorld: 'main';
|
||||
mount: () => Promise<void>;
|
||||
unmount: () => Promise<void>;
|
||||
}
|
||||
|
||||
const meta: RemoteFeatureExport = {
|
||||
installMainWorldAdapters();
|
||||
|
||||
const feature: RemoteFeatureExport = {
|
||||
id: FEATURE_ID,
|
||||
version: '0.1.0',
|
||||
executionWorld: 'extension',
|
||||
version: FEATURE_VERSION,
|
||||
executionWorld: 'main',
|
||||
async mount() {
|
||||
setFloatingVisible(true);
|
||||
},
|
||||
async unmount() {
|
||||
setFloatingVisible(false);
|
||||
},
|
||||
};
|
||||
|
||||
declare global {
|
||||
@@ -27,6 +40,6 @@ const g = globalThis as typeof globalThis & {
|
||||
__ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;
|
||||
};
|
||||
g.__ECBI_FEATURES__ = g.__ECBI_FEATURES__ ?? {};
|
||||
g.__ECBI_FEATURES__[FEATURE_ID] = meta;
|
||||
g.__ECBI_FEATURES__[FEATURE_ID] = feature;
|
||||
|
||||
export default meta;
|
||||
export default feature;
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Content Script(isolated)侧桥接主机:代发 Open API、读写 chrome.storage。
|
||||
*/
|
||||
import { openApiRequest } from '@/api/client';
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import { getSettings, saveSettings } from '@/storage/settings';
|
||||
|
||||
import {
|
||||
ECBI_SHELL_SOURCE,
|
||||
isBridgeFeatureEvent,
|
||||
isBridgeRpcRequest,
|
||||
type BridgeRpcRequest,
|
||||
type BridgeRpcResult,
|
||||
} from './bridgeProtocol';
|
||||
import { clearActiveIfFeature, notifyFeatureEvent } from './registry';
|
||||
|
||||
let started = false;
|
||||
|
||||
function reply(result: BridgeRpcResult): void {
|
||||
window.postMessage(result, '*');
|
||||
}
|
||||
|
||||
async function handleRpc(msg: BridgeRpcRequest): Promise<void> {
|
||||
try {
|
||||
let data: unknown;
|
||||
switch (msg.rpc) {
|
||||
case 'OPEN_API': {
|
||||
if (!msg.path) throw new ExtensionError('UNKNOWN', '缺少 path');
|
||||
data = await openApiRequest(msg.path, {
|
||||
method: msg.method || 'GET',
|
||||
body: msg.body,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'GET_SETTINGS':
|
||||
data = await getSettings();
|
||||
break;
|
||||
case 'SAVE_SETTINGS':
|
||||
data = await saveSettings(msg.patch ?? {});
|
||||
break;
|
||||
default:
|
||||
throw new ExtensionError('UNKNOWN', `未知 RPC:${(msg as { rpc: string }).rpc}`);
|
||||
}
|
||||
reply({
|
||||
source: ECBI_SHELL_SOURCE,
|
||||
type: 'RPC_RESULT',
|
||||
requestId: msg.requestId,
|
||||
ok: true,
|
||||
data,
|
||||
});
|
||||
} catch (error) {
|
||||
const err =
|
||||
error instanceof ExtensionError
|
||||
? error
|
||||
: new ExtensionError(
|
||||
'UNKNOWN',
|
||||
error instanceof Error ? error.message : '桥接处理失败',
|
||||
);
|
||||
reply({
|
||||
source: ECBI_SHELL_SOURCE,
|
||||
type: 'RPC_RESULT',
|
||||
requestId: msg.requestId,
|
||||
ok: false,
|
||||
error: { code: err.code, message: err.message },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function startBridgeHost(): void {
|
||||
if (started) return;
|
||||
started = true;
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
if (event.source !== window) return;
|
||||
const data = event.data;
|
||||
|
||||
if (isBridgeRpcRequest(data)) {
|
||||
void handleRpc(data);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isBridgeFeatureEvent(data)) {
|
||||
if (data.event === 'closed') {
|
||||
clearActiveIfFeature(data.featureId);
|
||||
}
|
||||
notifyFeatureEvent(data.featureId, data.event);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/** 壳(isolated)↔ 功能(main world)postMessage 协议 */
|
||||
|
||||
export const ECBI_SHELL_SOURCE = 'ecbi-shell';
|
||||
export const ECBI_FEATURE_SOURCE = 'ecbi-feature';
|
||||
|
||||
export type BridgeRpcType = 'OPEN_API' | 'GET_SETTINGS' | 'SAVE_SETTINGS';
|
||||
|
||||
export interface BridgeRpcRequest {
|
||||
source: typeof ECBI_FEATURE_SOURCE;
|
||||
type: 'RPC';
|
||||
rpc: BridgeRpcType;
|
||||
requestId: string;
|
||||
path?: string;
|
||||
method?: string;
|
||||
body?: string;
|
||||
patch?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BridgeRpcResult {
|
||||
source: typeof ECBI_SHELL_SOURCE;
|
||||
type: 'RPC_RESULT';
|
||||
requestId: string;
|
||||
ok: boolean;
|
||||
data?: unknown;
|
||||
error?: { code: string; message: string };
|
||||
}
|
||||
|
||||
export interface BridgeFeatureEvent {
|
||||
source: typeof ECBI_FEATURE_SOURCE;
|
||||
type: 'FEATURE_EVENT';
|
||||
featureId: string;
|
||||
event: 'closed' | 'minimized' | 'restored';
|
||||
}
|
||||
|
||||
export type BridgeIncoming = BridgeRpcRequest | BridgeFeatureEvent;
|
||||
|
||||
export function isBridgeRpcRequest(data: unknown): data is BridgeRpcRequest {
|
||||
if (!data || typeof data !== 'object') return false;
|
||||
const msg = data as BridgeRpcRequest;
|
||||
return msg.source === ECBI_FEATURE_SOURCE && msg.type === 'RPC' && typeof msg.requestId === 'string';
|
||||
}
|
||||
|
||||
export function isBridgeFeatureEvent(data: unknown): data is BridgeFeatureEvent {
|
||||
if (!data || typeof data !== 'object') return false;
|
||||
const msg = data as BridgeFeatureEvent;
|
||||
return (
|
||||
msg.source === ECBI_FEATURE_SOURCE &&
|
||||
msg.type === 'FEATURE_EVENT' &&
|
||||
typeof msg.featureId === 'string'
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Main world 适配:把 Open API / chrome.storage 换成 postMessage RPC。
|
||||
* 功能包 IIFE 加载时调用 installMainWorldAdapters()。
|
||||
*/
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import { setOpenApiRequestOverride } from '@/api/client';
|
||||
import { setSettingsOverride, type ExtensionSettings } from '@/storage/settings';
|
||||
|
||||
import {
|
||||
ECBI_FEATURE_SOURCE,
|
||||
ECBI_SHELL_SOURCE,
|
||||
type BridgeRpcResult,
|
||||
type BridgeRpcType,
|
||||
} from './bridgeProtocol';
|
||||
|
||||
const RPC_TIMEOUT_MS = 30_000;
|
||||
|
||||
function postRpc<T>(rpc: BridgeRpcType, payload: Record<string, unknown> = {}): Promise<T> {
|
||||
const requestId = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
window.removeEventListener('message', onMessage);
|
||||
reject(new ExtensionError('NETWORK_ERROR', `桥接超时(${rpc})`));
|
||||
}, RPC_TIMEOUT_MS);
|
||||
|
||||
function onMessage(event: MessageEvent) {
|
||||
if (event.source !== window) return;
|
||||
const data = event.data as BridgeRpcResult | undefined;
|
||||
if (!data || data.source !== ECBI_SHELL_SOURCE || data.type !== 'RPC_RESULT') return;
|
||||
if (data.requestId !== requestId) return;
|
||||
|
||||
window.clearTimeout(timer);
|
||||
window.removeEventListener('message', onMessage);
|
||||
|
||||
if (!data.ok) {
|
||||
reject(
|
||||
new ExtensionError(
|
||||
(data.error?.code as never) || 'UNKNOWN',
|
||||
data.error?.message || '桥接调用失败',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
resolve(data.data as T);
|
||||
}
|
||||
|
||||
window.addEventListener('message', onMessage);
|
||||
window.postMessage(
|
||||
{
|
||||
source: ECBI_FEATURE_SOURCE,
|
||||
type: 'RPC',
|
||||
rpc,
|
||||
requestId,
|
||||
...payload,
|
||||
},
|
||||
'*',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
|
||||
export function installMainWorldAdapters(): void {
|
||||
if (installed) return;
|
||||
installed = true;
|
||||
|
||||
setOpenApiRequestOverride(async <T,>(path: string, init: RequestInit = {}) => {
|
||||
const method = (init.method || 'GET').toUpperCase();
|
||||
const body = typeof init.body === 'string' ? init.body : undefined;
|
||||
return postRpc<T>('OPEN_API', { path, method, body });
|
||||
});
|
||||
|
||||
setSettingsOverride({
|
||||
get: () => postRpc<ExtensionSettings>('GET_SETTINGS'),
|
||||
save: (patch) =>
|
||||
postRpc<ExtensionSettings>('SAVE_SETTINGS', {
|
||||
patch: patch as Record<string, unknown>,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export function emitFeatureEvent(
|
||||
featureId: string,
|
||||
event: 'closed' | 'minimized' | 'restored',
|
||||
): void {
|
||||
window.postMessage(
|
||||
{
|
||||
source: ECBI_FEATURE_SOURCE,
|
||||
type: 'FEATURE_EVENT',
|
||||
featureId,
|
||||
event,
|
||||
},
|
||||
'*',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** 通过 Background 向页面 MAIN world 注入/调用功能脚本(绕过页面 CSP) */
|
||||
|
||||
interface BgResponse {
|
||||
ok: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
function sendToBackground(message: unknown): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
chrome.runtime.sendMessage(message, (response: BgResponse | undefined) => {
|
||||
if (chrome.runtime.lastError) {
|
||||
reject(new Error(chrome.runtime.lastError.message));
|
||||
return;
|
||||
}
|
||||
if (!response?.ok) {
|
||||
reject(new Error(response?.message || 'Background 执行失败'));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function injectMainWorldScript(code: string): Promise<void> {
|
||||
await sendToBackground({
|
||||
type: 'INJECT_MAIN_SCRIPT',
|
||||
payload: { code },
|
||||
});
|
||||
}
|
||||
|
||||
export async function callMainWorldFeature(
|
||||
featureId: string,
|
||||
action: 'mount' | 'unmount',
|
||||
): Promise<void> {
|
||||
await sendToBackground({
|
||||
type: 'CALL_MAIN_FEATURE',
|
||||
payload: { featureId, action },
|
||||
});
|
||||
}
|
||||
@@ -1,40 +1,81 @@
|
||||
import { pddAdFeeEmbeddedFeature } from '@/features/pdd-ad-fee/embedded';
|
||||
import type { FeatureHandle, FeatureModule, FeatureMountContext } from '@/features/runtime/types';
|
||||
|
||||
const embeddedModules: Record<string, FeatureModule> = {
|
||||
[pddAdFeeEmbeddedFeature.id]: pddAdFeeEmbeddedFeature,
|
||||
};
|
||||
import type { FeatureHandle } from '@/features/runtime/types';
|
||||
import {
|
||||
callMainWorldFeature,
|
||||
injectMainWorldScript,
|
||||
} from '@/features/runtime/mainWorldInject';
|
||||
|
||||
let active: { id: string; handle: FeatureHandle } | null = null;
|
||||
|
||||
type FeatureEventListener = (
|
||||
featureId: string,
|
||||
event: 'closed' | 'minimized' | 'restored',
|
||||
) => void;
|
||||
|
||||
const listeners = new Set<FeatureEventListener>();
|
||||
|
||||
export function onFeatureEvent(listener: FeatureEventListener): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
export function notifyFeatureEvent(
|
||||
featureId: string,
|
||||
event: 'closed' | 'minimized' | 'restored',
|
||||
): void {
|
||||
for (const listener of listeners) {
|
||||
try {
|
||||
listener(featureId, event);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getActiveFeatureId(): string | null {
|
||||
return active?.id ?? null;
|
||||
}
|
||||
|
||||
export async function mountFeature(
|
||||
featureId: string,
|
||||
ctx: FeatureMountContext = { featureId },
|
||||
): Promise<void> {
|
||||
export function clearActiveIfFeature(featureId: string): void {
|
||||
if (active?.id === featureId) {
|
||||
return;
|
||||
active = null;
|
||||
}
|
||||
await unmountActiveFeature();
|
||||
}
|
||||
|
||||
const mod = embeddedModules[featureId];
|
||||
if (!mod) {
|
||||
throw new Error(`功能「${featureId}」未在壳内注册,请更新扩展或检查远程清单`);
|
||||
export async function mountFeature(featureId: string, code: string): Promise<void> {
|
||||
if (!code?.trim()) {
|
||||
throw new Error('缺少远程功能脚本,无法挂载');
|
||||
}
|
||||
const handle = await mod.mount({ ...ctx, featureId });
|
||||
active = { id: featureId, handle };
|
||||
if (active?.id === featureId) {
|
||||
// 同一功能重新打开:先卸再挂,确保用最新脚本
|
||||
await unmountActiveFeature();
|
||||
} else {
|
||||
await unmountActiveFeature();
|
||||
}
|
||||
|
||||
await injectMainWorldScript(code);
|
||||
await callMainWorldFeature(featureId, 'mount');
|
||||
|
||||
active = {
|
||||
id: featureId,
|
||||
handle: {
|
||||
unmount: async () => {
|
||||
await callMainWorldFeature(featureId, 'unmount');
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function unmountActiveFeature(): Promise<void> {
|
||||
if (!active) return;
|
||||
const current = active;
|
||||
active = null;
|
||||
await current.handle.unmount();
|
||||
try {
|
||||
await current.handle.unmount();
|
||||
} catch {
|
||||
// 页面可能已刷新,忽略
|
||||
}
|
||||
}
|
||||
|
||||
export function listEmbeddedFeatureIds(): string[] {
|
||||
return Object.keys(embeddedModules);
|
||||
export function isFeatureUiVisible(): boolean {
|
||||
return active != null;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ export interface ExtensionFeatureItem {
|
||||
entry: string;
|
||||
/** 脚本 sha256(hex),可选;有则下载后校验 */
|
||||
sha256?: string;
|
||||
/** extension=壳内嵌入模块;main=注入页面(远期) */
|
||||
/** main=页面 MAIN world 执行(可热更新);extension=仅壳内(已弃用) */
|
||||
executionWorld?: 'extension' | 'main';
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user