refactor: 修改结构 功能动态从后端获取

This commit is contained in:
2026-08-16 19:41:44 +08:00
parent 8a8e36602f
commit 481518500e
27 changed files with 760 additions and 107 deletions
@@ -0,0 +1,45 @@
import { openApiRequest } from '@/api/client';
import { OPEN_API_PATHS } from '@/shared/constants';
import type { ExtensionFeatureItem, ExtensionFeatureManifest } from '@/features/runtime/types';
export interface FeatureScriptPayload {
featureId: string;
version?: string;
sha256?: string;
content: string;
}
export async function fetchFeatureManifest(): Promise<ExtensionFeatureManifest> {
return openApiRequest<ExtensionFeatureManifest>(OPEN_API_PATHS.extensionFeatureList, {
method: 'GET',
});
}
export async function fetchFeatureScript(featureId: string): Promise<FeatureScriptPayload> {
return openApiRequest<FeatureScriptPayload>(
`${OPEN_API_PATHS.extensionFeatureScript}/${encodeURIComponent(featureId)}/script`,
{ method: 'GET' },
);
}
/** 下载远程脚本并可选校验 sha256(与静态 manifest 一致) */
export async function downloadAndVerifyFeature(
item: ExtensionFeatureItem,
): Promise<{ code: string; verified: boolean; remoteVersion?: string }> {
const payload = await fetchFeatureScript(item.id);
const expected = (item.sha256 || payload.sha256 || '').toLowerCase();
if (expected) {
const hash = await sha256Hex(payload.content);
if (hash !== expected) {
throw new Error(`功能脚本校验失败:${item.id}(sha256 不匹配)`);
}
return { code: payload.content, verified: true, remoteVersion: payload.version };
}
return { code: payload.content, verified: false, remoteVersion: payload.version };
}
async function sha256Hex(text: string): Promise<string> {
const data = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest('SHA-256', data);
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
+20 -1
View File
@@ -1,4 +1,9 @@
import { resolveAdapter } from '@/platform/core/PlatformDetector';
import {
getActiveFeatureId,
mountFeature,
unmountActiveFeature,
} from '@/features/runtime/registry';
import { ExtensionError } from '@/shared/errors';
import {
isExtensionMessage,
@@ -42,6 +47,17 @@ async function handleMessage(message: ExtensionMessage): Promise<ExtensionRespon
case 'GET_FLOATING_PANEL_STATE': {
return { ok: true, data: { visible: isFloatingVisible() } };
}
case 'MOUNT_FEATURE': {
await mountFeature(message.payload.featureId);
return { ok: true, data: { featureId: message.payload.featureId } };
}
case 'UNMOUNT_FEATURE': {
await unmountActiveFeature();
return { ok: true, data: { featureId: null } };
}
case 'GET_ACTIVE_FEATURE': {
return { ok: true, data: { featureId: getActiveFeatureId() } };
}
default:
return {
ok: false,
@@ -62,7 +78,10 @@ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
const err =
error instanceof ExtensionError
? error
: new ExtensionError('UNKNOWN', 'Content Script 处理失败');
: new ExtensionError(
'UNKNOWN',
error instanceof Error ? error.message : 'Content Script 处理失败',
);
const response: ExtensionResponse = {
ok: false,
code: err.code,
@@ -0,0 +1,30 @@
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();
}
@@ -0,0 +1,32 @@
/**
* 远程功能包入口(IIFE 构建)。
* 当前阶段导出元数据;真正 UI 仍由壳内 embedded 模块挂载。
* 后续可将 FloatingPanel 整包打入此入口并在 main world 执行。
*/
const FEATURE_ID = 'pdd-ad-fee';
export interface RemoteFeatureExport {
id: string;
version: string;
executionWorld: 'extension';
}
const meta: RemoteFeatureExport = {
id: FEATURE_ID,
version: '0.1.0',
executionWorld: 'extension',
};
declare global {
interface Window {
__ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;
}
}
const g = globalThis as typeof globalThis & {
__ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;
};
g.__ECBI_FEATURES__ = g.__ECBI_FEATURES__ ?? {};
g.__ECBI_FEATURES__[FEATURE_ID] = meta;
export default meta;
@@ -0,0 +1,40 @@
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,
};
let active: { id: string; handle: FeatureHandle } | null = null;
export function getActiveFeatureId(): string | null {
return active?.id ?? null;
}
export async function mountFeature(
featureId: string,
ctx: FeatureMountContext = { featureId },
): Promise<void> {
if (active?.id === featureId) {
return;
}
await unmountActiveFeature();
const mod = embeddedModules[featureId];
if (!mod) {
throw new Error(`功能「${featureId}」未在壳内注册,请更新扩展或检查远程清单`);
}
const handle = await mod.mount({ ...ctx, featureId });
active = { id: featureId, handle };
}
export async function unmountActiveFeature(): Promise<void> {
if (!active) return;
const current = active;
active = null;
await current.handle.unmount();
}
export function listEmbeddedFeatureIds(): string[] {
return Object.keys(embeddedModules);
}
@@ -0,0 +1,57 @@
/** 功能清单与模块约定(壳 / 远程脚本共用) */
export interface ExtensionFeatureItem {
id: string;
name: string;
version: string;
description?: string;
/** 匹配当前页才可打开,chrome match pattern 风格简化:含 host 即可 */
matchUrlPatterns: string[];
/** 相对静态目录的入口文件,如 pdd-ad-fee.js */
entry: string;
/** 脚本 sha256(hex),可选;有则下载后校验 */
sha256?: string;
/** extension=壳内嵌入模块;main=注入页面(远期) */
executionWorld?: 'extension' | 'main';
}
export interface ExtensionFeatureManifest {
schemaVersion: number;
updatedAt?: string;
features: ExtensionFeatureItem[];
}
export interface FeatureHandle {
unmount: () => void | Promise<void>;
}
export interface FeatureModule {
id: string;
mount: (ctx: FeatureMountContext) => FeatureHandle | Promise<FeatureHandle>;
}
export interface FeatureMountContext {
featureId: string;
/** 打开/关闭由壳控制时可回调 */
onClose?: () => void;
}
export function urlMatchesPatterns(url: string, patterns: string[] | null | undefined): boolean {
if (!patterns?.length) return true;
try {
return patterns.some((pattern) => matchPattern(url, pattern));
} catch {
// 非法 pattern 时不拖垮 Popup
return false;
}
}
/** 将 chrome 风格 * 通配转为安全正则(先按 * 切开再转义各段) */
function matchPattern(url: string, pattern: string): boolean {
if (!pattern) return false;
if (!pattern.includes('*')) {
return url.includes(pattern);
}
const parts = pattern.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'));
return new RegExp(`^${parts.join('.*')}$`).test(url);
}
+150 -93
View File
@@ -1,40 +1,53 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { listPddChannelShops, type PddChannelShop } from '@/api/open/pddShop';
import {
downloadAndVerifyFeature,
fetchFeatureManifest,
} from '@/api/open/extensionFeatures';
import type { ExtensionFeatureItem } from '@/features/runtime/types';
import { urlMatchesPatterns } from '@/features/runtime/types';
import { EXTENSION_NAME, OPEN_SCOPES } from '@/shared/constants';
import { toUserMessage } from '@/shared/errors';
import { getSettings, saveSettings } from '@/storage/settings';
import { getFloatingPanelState, openFloatingPanel, toggleFloatingPanel } from './messaging';
import {
getFloatingPanelState,
mountFeatureOnPage,
unmountFeatureOnPage,
} from './messaging';
const apiBaseUrl = ref('');
const apiKey = ref('');
const channelShopId = ref<number | undefined>(undefined);
const channelShopName = ref('');
const shops = ref<PddChannelShop[]>([]);
const shopsLoading = ref(false);
const panelVisible = ref(false);
const features = ref<ExtensionFeatureItem[]>([]);
const featuresLoading = ref(false);
const featuresUpdatedAt = ref('');
const activeFeatureId = ref<string | null>(null);
const currentTabUrl = ref('');
const statusText = ref('');
const errorText = ref('');
const busy = ref(false);
const checking = ref(false);
const matchedFeatures = computed(() => {
const list = Array.isArray(features.value) ? features.value : [];
if (!currentTabUrl.value) return list;
return list.filter((f) => urlMatchesPatterns(currentTabUrl.value, f?.matchUrlPatterns ?? []));
});
async function loadLocalSettings() {
const settings = await getSettings();
apiBaseUrl.value = settings.apiBaseUrl;
apiKey.value = settings.apiKey;
channelShopId.value = settings.channelShopId;
channelShopName.value = settings.channelShopName ?? '';
}
/** 只保存 URL / Key,不改动悬浮层里的店铺配置 */
async function persistSettings() {
errorText.value = '';
try {
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
channelShopId: channelShopId.value,
channelShopName: channelShopName.value,
});
statusText.value = '配置已保存';
} catch (error) {
@@ -42,54 +55,79 @@ async function persistSettings() {
}
}
async function loadShops() {
shopsLoading.value = true;
async function checkConnectivity() {
checking.value = true;
errorText.value = '';
statusText.value = '';
try {
await persistSettings();
const result = await listPddChannelShops({ page: 1, pageSize: 100 });
shops.value = result.records ?? [];
if (channelShopId.value != null) {
const hit = shops.value.find((s) => s.id === channelShopId.value);
if (hit) channelShopName.value = hit.mallName ?? '';
}
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
});
const manifest = await fetchFeatureManifest();
const count = manifest.features?.length ?? 0;
statusText.value = `连通正常(清单 ${count} 项${manifest.updatedAt ? `,更新于 ${manifest.updatedAt}` : ''})`;
} catch (error) {
errorText.value = toUserMessage(error);
} finally {
shopsLoading.value = false;
checking.value = false;
}
}
function onShopChange(event: Event) {
const value = Number((event.target as HTMLSelectElement).value);
if (!Number.isFinite(value) || value <= 0) {
channelShopId.value = undefined;
channelShopName.value = '';
return;
async function refreshTabUrl() {
try {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
currentTabUrl.value = tabs[0]?.url ?? '';
} catch {
currentTabUrl.value = '';
}
}
async function loadFeatures() {
featuresLoading.value = true;
errorText.value = '';
try {
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
});
const manifest = await fetchFeatureManifest();
features.value = manifest.features ?? [];
featuresUpdatedAt.value = manifest.updatedAt ?? '';
statusText.value = `已加载功能清单(${features.value.length})`;
} catch (error) {
errorText.value = toUserMessage(error);
} finally {
featuresLoading.value = false;
}
channelShopId.value = value;
const hit = shops.value.find((s) => s.id === value);
channelShopName.value = hit?.mallName ?? '';
}
async function refreshPanelState() {
try {
const state = await getFloatingPanelState();
panelVisible.value = state.visible;
activeFeatureId.value = state.visible ? 'pdd-ad-fee' : null;
} catch {
panelVisible.value = false;
activeFeatureId.value = null;
}
}
async function handleOpenPanel() {
async function handleOpenFeature(item: ExtensionFeatureItem) {
busy.value = true;
errorText.value = '';
statusText.value = '';
try {
await persistSettings();
const state = await openFloatingPanel();
panelVisible.value = state.visible;
statusText.value = '已打开页内悬浮层';
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
});
const remote = await downloadAndVerifyFeature(item);
statusText.value = remote.verified
? `远程脚本已校验(${item.version})`
: `已下载远程脚本(未配置 sha256)`;
await mountFeatureOnPage(item.id);
activeFeatureId.value = item.id;
statusText.value = `已打开:${item.name}`;
} catch (error) {
errorText.value = toUserMessage(error);
} finally {
@@ -97,13 +135,13 @@ async function handleOpenPanel() {
}
}
async function handleTogglePanel() {
async function handleCloseFeature() {
busy.value = true;
errorText.value = '';
try {
const state = await toggleFloatingPanel();
panelVisible.value = state.visible;
statusText.value = state.visible ? '悬浮层已显示' : '悬浮层已关闭';
await unmountFeatureOnPage();
activeFeatureId.value = null;
statusText.value = '已关闭当前功能';
} catch (error) {
errorText.value = toUserMessage(error);
} finally {
@@ -113,7 +151,11 @@ async function handleTogglePanel() {
onMounted(async () => {
await loadLocalSettings();
await refreshTabUrl();
await refreshPanelState();
if (apiBaseUrl.value && apiKey.value) {
await loadFeatures();
}
});
</script>
@@ -122,7 +164,7 @@ onMounted(async () => {
<header>
<h1 class="text-base font-semibold tracking-tight text-antd-text">{{ EXTENSION_NAME }}</h1>
<p class="mt-0.5 text-xs text-antd-text-secondary">
Popup 负责配置与开关;业务操作在页内悬浮层完成。
Popup 负责配置与功能入口;店铺选择在页内悬浮层完成。
</p>
</header>
@@ -146,68 +188,83 @@ onMounted(async () => {
/>
</label>
<p class="text-[11px] leading-relaxed text-antd-text-tertiary">
需要 scope:{{ OPEN_SCOPES.pddShopRead }}、{{ OPEN_SCOPES.pddGoodsAdFeeImport }}
连通性 / 清单需要 {{ OPEN_SCOPES.extensionFeatureRead }};推广费另需店铺/导入 scope。
</p>
<div class="space-y-1">
<div class="flex items-center justify-between">
<span class="text-xs text-antd-text-secondary">默认渠道店铺</span>
<button
class="text-xs text-antd-primary hover:text-antd-primary-hover hover:underline"
type="button"
:disabled="shopsLoading || busy"
@click="loadShops"
>
{{ shopsLoading ? '加载中…' : '拉取列表' }}
</button>
</div>
<select
class="w-full rounded-antd border border-antd-border px-2.5 py-1.5 text-sm outline-none transition focus:border-antd-primary"
:value="channelShopId ?? ''"
@change="onShopChange"
<div class="flex gap-2">
<button
class="flex-1 rounded-antd border border-antd-border bg-white px-3 py-1.5 text-sm text-antd-text transition hover:border-antd-primary hover:text-antd-primary disabled:opacity-50"
type="button"
:disabled="busy || checking"
@click="persistSettings"
>
<option value="">可选,打开悬浮层后仍可改</option>
<option v-for="shop in shops" :key="shop.id" :value="shop.id">
{{ shop.mallName || '未命名' }} (#{{ shop.id }})
</option>
</select>
保存配置
</button>
<button
class="flex-1 rounded-antd bg-antd-primary px-3 py-1.5 text-sm font-medium text-white transition hover:bg-antd-primary-hover disabled:opacity-50"
type="button"
:disabled="busy || checking || !apiBaseUrl.trim() || !apiKey.trim()"
@click="checkConnectivity"
>
{{ checking ? '检查中…' : '检查连通性' }}
</button>
</div>
<button
class="w-full rounded-antd border border-antd-border bg-white px-3 py-1.5 text-sm text-antd-text transition hover:border-antd-primary hover:text-antd-primary disabled:opacity-50"
type="button"
:disabled="busy"
@click="persistSettings"
>
保存配置
</button>
</section>
<section class="space-y-2 rounded-antd-lg border border-antd-border-secondary bg-white p-3 shadow-sm">
<h2 class="text-xs font-semibold text-antd-text-secondary">页内悬浮层</h2>
<p class="text-xs text-antd-text-secondary">
当前状态:
<span class="font-medium text-antd-text">{{ panelVisible ? '已打开' : '未打开' }}</span>
</p>
<div class="flex gap-2">
<div class="flex items-center justify-between">
<h2 class="text-xs font-semibold text-antd-text-secondary">功能列表</h2>
<button
class="flex-1 rounded-antd bg-antd-primary px-3 py-2 text-sm font-medium text-white transition hover:bg-antd-primary-hover disabled:opacity-50"
class="text-xs text-antd-primary hover:underline"
type="button"
:disabled="busy"
@click="handleOpenPanel"
:disabled="featuresLoading || busy || checking"
@click="loadFeatures"
>
打开悬浮层
</button>
<button
class="flex-1 rounded-antd border border-antd-border bg-white px-3 py-2 text-sm font-medium text-antd-text transition hover:border-antd-primary hover:text-antd-primary disabled:opacity-50"
type="button"
:disabled="busy"
@click="handleTogglePanel"
>
开关切换
{{ featuresLoading ? '加载中…' : '刷新清单' }}
</button>
</div>
<p class="text-[11px] text-antd-text-tertiary">若提示无法连接页面脚本,请先刷新目标网页。</p>
<p v-if="featuresUpdatedAt" class="text-[11px] text-antd-text-tertiary">
清单更新于 {{ featuresUpdatedAt }}
</p>
<p v-if="!features.length" class="text-xs text-antd-text-tertiary">
尚未加载。配置 URL / Key 后可先「检查连通性」,再「刷新清单」。
</p>
<div
v-for="item in matchedFeatures"
:key="item.id"
class="rounded-antd border border-antd-border-secondary bg-antd-fill px-2.5 py-2"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="truncate text-sm font-medium text-antd-text">{{ item.name }}</div>
<div class="text-[11px] text-antd-text-tertiary">
{{ item.id }} · v{{ item.version }}
</div>
<p v-if="item.description" class="mt-1 text-[11px] text-antd-text-secondary">
{{ item.description }}
</p>
</div>
<button
class="shrink-0 rounded-antd bg-antd-primary px-2.5 py-1 text-xs font-medium text-white hover:bg-antd-primary-hover disabled:opacity-50"
type="button"
:disabled="busy || checking"
@click="handleOpenFeature(item)"
>
{{ activeFeatureId === item.id ? '重新打开' : '打开' }}
</button>
</div>
</div>
<button
v-if="activeFeatureId"
class="w-full rounded-antd border border-antd-border bg-white px-3 py-1.5 text-sm transition hover:border-antd-primary hover:text-antd-primary disabled:opacity-50"
type="button"
:disabled="busy || checking"
@click="handleCloseFeature"
>
关闭当前功能
</button>
</section>
<p v-if="statusText" class="text-xs text-antd-success">{{ statusText }}</p>
+12 -1
View File
@@ -18,7 +18,7 @@ async function sendToActiveTab<T>(message: ExtensionMessage): Promise<T> {
} catch {
throw new ExtensionError(
'PAGE_NOT_READY',
'无法连接页面脚本。请刷新目标页面后再打开悬浮层。',
'无法连接页面脚本。请刷新目标页面后再打开功能。',
);
}
@@ -48,3 +48,14 @@ export async function toggleFloatingPanel(): Promise<{ visible: boolean }> {
export async function getFloatingPanelState(): Promise<{ visible: boolean }> {
return sendToActiveTab<{ visible: boolean }>({ type: 'GET_FLOATING_PANEL_STATE' });
}
export async function mountFeatureOnPage(featureId: string): Promise<{ featureId: string | null }> {
return sendToActiveTab<{ featureId: string | null }>({
type: 'MOUNT_FEATURE',
payload: { featureId },
});
}
export async function unmountFeatureOnPage(): Promise<{ featureId: string | null }> {
return sendToActiveTab<{ featureId: string | null }>({ type: 'UNMOUNT_FEATURE' });
}
@@ -3,9 +3,12 @@ export const EXTENSION_NAME = 'ECBI 数据同步';
export const OPEN_API_PATHS = {
pddShopList: '/open/v1/channel/pdd/shop/list',
pddGoodsAdFeeBatchImport: '/open/v1/channel/pdd/goods/adfee/batch-import',
extensionFeatureList: '/open/v1/extension/features',
extensionFeatureScript: '/open/v1/extension/features',
} as const;
export const OPEN_SCOPES = {
pddShopRead: 'open:scope:pdd_shop:read',
pddGoodsAdFeeImport: 'open:scope:pdd_goods_ad_fee:import',
extensionFeatureRead: 'open:scope:extension_feature:read',
} as const;
+9
View File
@@ -1,4 +1,5 @@
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
import type { ExtensionFeatureManifest } from '@/features/runtime/types';
export type ExtensionMessage =
| { type: 'GET_PAGE_CONTEXT' }
@@ -6,6 +7,9 @@ export type ExtensionMessage =
| { type: 'TOGGLE_FLOATING_PANEL' }
| { type: 'SET_FLOATING_PANEL'; payload: { visible: boolean } }
| { type: 'GET_FLOATING_PANEL_STATE' }
| { type: 'MOUNT_FEATURE'; payload: { featureId: string } }
| { type: 'UNMOUNT_FEATURE' }
| { type: 'GET_ACTIVE_FEATURE' }
| { type: 'PING' };
export type ExtensionResponse =
@@ -13,6 +17,8 @@ export type ExtensionResponse =
| { ok: true; data: AdvertisingCostBatch }
| { ok: true; data: { pong: true } }
| { ok: true; data: { visible: boolean } }
| { ok: true; data: { featureId: string | null } }
| { ok: true; data: ExtensionFeatureManifest }
| { ok: false; code: string; message: string };
const MESSAGE_TYPES = new Set([
@@ -21,6 +27,9 @@ const MESSAGE_TYPES = new Set([
'TOGGLE_FLOATING_PANEL',
'SET_FLOATING_PANEL',
'GET_FLOATING_PANEL_STATE',
'MOUNT_FEATURE',
'UNMOUNT_FEATURE',
'GET_ACTIVE_FEATURE',
'PING',
]);