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
+2 -1
View File
@@ -1,5 +1,6 @@
dist
dist-features
node_modules
*.local
.DS_Store
temp
temp
+35 -9
View File
@@ -28,7 +28,17 @@ pnpm dev
pnpm build
```
产物目录:`dist/`。
产物:
| 目录 | 说明 |
|------|------|
| `dist/` | 扩展壳(装到浏览器) |
| `dist-features/` | 功能清单 `manifest.json` + 各功能 JS(部署到后端静态目录) |
`pnpm build` 会顺带把 `dist-features/` 同步到
`ecom-dmb-backend/src/main/resources/static/extension-features/`(本地联调)。
生产更新功能时:只拷贝 `dist-features/*` 到服务器对应静态目录并重启/热加载即可,扩展壳不必每次重装(壳内 API 未变时)。
## 安装到 Chrome / Edge
@@ -65,11 +75,29 @@ Popup 右上角「配置」:
| Base URL | 例 `http://localhost:8080/api`(不要末尾 `/`) |
| API Key | 后台创建的 Open API Key(`sk_...`),**不要**填登录 JWT |
Key 需具备:
Key 建议具备:
- `open:scope:extension_feature:read`(功能清单/脚本)
- `open:scope:pdd_shop:read`
- `open:scope:pdd_goods_ad_fee:import`
## 功能清单(静态 JSON)方案
清单与脚本放在同一静态目录,例如:
```text
static/extension-features/
manifest.json
pdd-ad-fee.js
```
- **直接读静态文件**:可以,部署简单;但无 API Key 鉴权(取决于网关是否暴露 `/static/**`)。
- **推荐(已实现)**:Open API 读同一份 JSON/脚本并鉴权:
- `GET /api/open/v1/extension/features`
- `GET /api/open/v1/extension/features/{id}/script`
扩展 Popup 拉清单 → 打开功能时下载脚本并做 sha256 校验 → 当前 UI 仍由壳内嵌入模块挂载(MV3 限制远程 `eval`);远程包用于版本对齐与后续 main-world 执行。
## 与后端字段对照
| 插件 | 后端 batch-import |
@@ -81,6 +109,8 @@ Key 需具备:
相关接口:
- `GET /open/v1/extension/features`
- `GET /open/v1/extension/features/{id}/script`
- `POST /open/v1/channel/pdd/shop/list`
- `POST /open/v1/channel/pdd/goods/adfee/batch-import`
@@ -88,13 +118,9 @@ Key 需具备:
## 当前能力说明
- **拼多多推广总览**(`yingxiao.pinduoduo.com/.../report/promotion/overView`)已接入真实 DOM 解析:
- 店铺名:`AccountNew_mallName` → 调用店铺分页接口按名匹配 `channelShopId`
- 日期:URL `beginDate`/`endDate`(或主 RangePicker);**仅 begin=end 的单日**才读取
- 商品:`OverviewTable_goodsId`;费用列:**总花费(元)**
- 范围日期报表会提示「不记录」,不写入预览/同步
- 非上述页面仍回退 `MockPlatformAdapter` 便于本地联调
- Popup 只负责配置与打开悬浮层
- Popup:配置 Base URL / API Key,拉取远程功能清单并打开/关闭功能
- **拼多多商品推广费**(`pdd-ad-fee`):页内悬浮读取/累计/同步(逻辑仍在壳内嵌入;远程 JS 同步发布)
- 非推广页仍可用 Mock Adapter 联调链路
## 权限说明
+2 -1
View File
@@ -6,7 +6,8 @@
"description": "企业内部 BI 数据同步浏览器扩展(Manifest V3)",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"build": "vue-tsc --noEmit && vite build && pnpm build:features",
"build:features": "node scripts/build-features.mjs",
"typecheck": "vue-tsc --noEmit",
"lint": "eslint . --ext .ts,.vue",
"format": "prettier --write \"src/**/*.{ts,vue,css,json}\""
@@ -0,0 +1,68 @@
import { createHash } from 'node:crypto';
import { copyFileSync, mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { build } from 'vite';
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..');
const outDir = resolve(root, 'dist-features');
const backendStatic = resolve(
root,
'../ecom-dmb-backend/src/main/resources/static/extension-features',
);
async function main() {
await build({
configFile: resolve(root, 'vite.features.config.ts'),
});
const entryFile = 'pdd-ad-fee.js';
const jsPath = resolve(outDir, entryFile);
const code = readFileSync(jsPath, 'utf8');
const sha256 = createHash('sha256').update(code).digest('hex');
const manifest = {
schemaVersion: 1,
updatedAt: new Date().toISOString(),
features: [
{
id: 'pdd-ad-fee',
name: '拼多多商品推广费同步',
version: '0.1.0',
description: '从推广总览读取单日总花费并同步到 BI(壳内嵌入执行;远程包用于版本校验)',
matchUrlPatterns: [
'*://yingxiao.pinduoduo.com/*',
'https://yingxiao.pinduoduo.com/',
],
entry: entryFile,
sha256,
executionWorld: 'extension',
},
],
};
writeFileSync(resolve(outDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
// 同步到后端 classpath 静态目录,便于本地联调;部署时也可只拷 dist-features
if (existsSync(backendStatic)) {
rmSync(backendStatic, { recursive: true, force: true });
}
mkdirSync(backendStatic, { recursive: true });
copyFileSync(jsPath, resolve(backendStatic, entryFile));
copyFileSync(resolve(outDir, 'manifest.json'), resolve(backendStatic, 'manifest.json'));
// sourcemap 可选
const mapPath = `${jsPath}.map`;
if (existsSync(mapPath)) {
copyFileSync(mapPath, resolve(backendStatic, `${entryFile}.map`));
}
console.log(`[build-features] wrote ${outDir}`);
console.log(`[build-features] synced → ${backendStatic}`);
console.log(`[build-features] pdd-ad-fee sha256=${sha256}`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
@@ -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',
]);
+33
View File
@@ -0,0 +1,33 @@
import { resolve } from 'node:path';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
/** 功能脚本独立构建 → dist-features/(部署到后端静态目录) */
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
},
},
define: {
'process.env.NODE_ENV': JSON.stringify('production'),
},
build: {
outDir: 'dist-features',
emptyOutDir: true,
lib: {
entry: resolve(__dirname, 'src/features/pdd-ad-fee/index.ts'),
name: 'EcbiFeaturePddAdFee',
formats: ['iife'],
fileName: () => 'pdd-ad-fee.js',
},
rollupOptions: {
output: {
inlineDynamicImports: true,
},
},
sourcemap: true,
minify: true,
},
});
@@ -0,0 +1,4 @@
-- 开放接口:浏览器扩展功能清单/脚本读取
INSERT INTO `sys_permission` (`parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:open' LIMIT 1), 'open:scope:extension_feature:read', '开放-浏览器扩展功能读取', 'api', 1, 'GET /open/v1/extension/features', 90
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:extension_feature:read');
@@ -17,6 +17,7 @@ public final class OpenApiScopeConstants {
public static final String META_READ = "open:scope:meta:read";
public static final String PDD_GOODS_AD_FEE_IMPORT = "open:scope:pdd_goods_ad_fee:import";
public static final String PDD_SHOP_READ = "open:scope:pdd_shop:read";
public static final String EXTENSION_FEATURE_READ = "open:scope:extension_feature:read";
public static final List<String> ALL = List.of(
ORDER_IMPORT,
@@ -26,7 +27,8 @@ public final class OpenApiScopeConstants {
IMPORT_TASK_READ,
META_READ,
PDD_GOODS_AD_FEE_IMPORT,
PDD_SHOP_READ
PDD_SHOP_READ,
EXTENSION_FEATURE_READ
);
private OpenApiScopeConstants() {
@@ -0,0 +1,42 @@
package top.xyquan.ecomdmbbackend.modules.open.api.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.open.api.constants.OpenApiScopeConstants;
import top.xyquan.ecomdmbbackend.modules.open.api.model.vo.ExtensionFeatureManifestVO;
import top.xyquan.ecomdmbbackend.modules.open.api.model.vo.ExtensionFeatureScriptVO;
import top.xyquan.ecomdmbbackend.modules.open.api.service.ExtensionFeatureService;
/**
* 浏览器扩展功能清单 / 脚本。
* 数据来自 classpath:static/extension-features/(与构建产物 dist-features 对齐)。
*/
@RestController
@RequestMapping("/api/open/v1/extension/features")
@RequiredArgsConstructor
@Tag(name = "开放接口-浏览器扩展功能", description = "API Key 认证;清单为静态 JSON,脚本同目录按需下载")
public class OpenExtensionFeatureController {
private final ExtensionFeatureService extensionFeatureService;
@GetMapping
@RequireOpenScope(value = OpenApiScopeConstants.EXTENSION_FEATURE_READ, description = "查询浏览器扩展功能清单")
@Operation(summary = "获取功能清单", description = "读取 static/extension-features/manifest.json")
public ApiResponse<ExtensionFeatureManifestVO> listFeatures() {
return ApiResponse.success("获取扩展功能清单成功", extensionFeatureService.getManifest());
}
@GetMapping("/{featureId}/script")
@RequireOpenScope(value = OpenApiScopeConstants.EXTENSION_FEATURE_READ, description = "下载浏览器扩展功能脚本")
@Operation(summary = "下载功能脚本", description = "按清单 entry 读取同目录 JS,返回 content 文本")
public ApiResponse<ExtensionFeatureScriptVO> getScript(@PathVariable String featureId) {
return ApiResponse.success("获取扩展功能脚本成功", extensionFeatureService.getScript(featureId));
}
}
@@ -0,0 +1,21 @@
package top.xyquan.ecomdmbbackend.modules.open.api.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@Schema(description = "浏览器扩展单个功能项")
public class ExtensionFeatureItemVO {
private String id;
private String name;
private String version;
private String description;
private List<String> matchUrlPatterns = new ArrayList<>();
private String entry;
private String sha256;
private String executionWorld;
}
@@ -0,0 +1,16 @@
package top.xyquan.ecomdmbbackend.modules.open.api.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@Schema(description = "浏览器扩展功能清单(对应静态目录 manifest.json)")
public class ExtensionFeatureManifestVO {
private Integer schemaVersion;
private String updatedAt;
private List<ExtensionFeatureItemVO> features = new ArrayList<>();
}
@@ -0,0 +1,18 @@
package top.xyquan.ecomdmbbackend.modules.open.api.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "浏览器扩展功能脚本内容")
public class ExtensionFeatureScriptVO {
private String featureId;
private String version;
private String sha256;
private String content;
}
@@ -0,0 +1,11 @@
package top.xyquan.ecomdmbbackend.modules.open.api.service;
import top.xyquan.ecomdmbbackend.modules.open.api.model.vo.ExtensionFeatureManifestVO;
import top.xyquan.ecomdmbbackend.modules.open.api.model.vo.ExtensionFeatureScriptVO;
public interface ExtensionFeatureService {
ExtensionFeatureManifestVO getManifest();
ExtensionFeatureScriptVO getScript(String featureId);
}
@@ -0,0 +1,81 @@
package top.xyquan.ecomdmbbackend.modules.open.api.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.open.api.model.vo.ExtensionFeatureItemVO;
import top.xyquan.ecomdmbbackend.modules.open.api.model.vo.ExtensionFeatureManifestVO;
import top.xyquan.ecomdmbbackend.modules.open.api.model.vo.ExtensionFeatureScriptVO;
import top.xyquan.ecomdmbbackend.modules.open.api.service.ExtensionFeatureService;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
@Service
@RequiredArgsConstructor
public class ExtensionFeatureServiceImpl implements ExtensionFeatureService {
private static final String MANIFEST_PATH = "static/extension-features/manifest.json";
private static final String FEATURE_DIR = "static/extension-features/";
private final ObjectMapper objectMapper;
@Override
public ExtensionFeatureManifestVO getManifest() {
Resource resource = new ClassPathResource(MANIFEST_PATH);
if (!resource.exists()) {
throw new BusinessException("扩展功能清单不存在,请先部署 dist-features 到 static/extension-features/");
}
try (InputStream in = resource.getInputStream()) {
return objectMapper.readValue(in, ExtensionFeatureManifestVO.class);
} catch (IOException e) {
throw new BusinessException("读取扩展功能清单失败: " + e.getMessage());
}
}
@Override
public ExtensionFeatureScriptVO getScript(String featureId) {
if (!StringUtils.hasText(featureId)) {
throw new BusinessException("featureId 不能为空");
}
ExtensionFeatureManifestVO manifest = getManifest();
ExtensionFeatureItemVO item = manifest.getFeatures().stream()
.filter(f -> featureId.equals(f.getId()))
.findFirst()
.orElseThrow(() -> new BusinessException("未知功能: " + featureId));
String entry = item.getEntry();
if (!StringUtils.hasText(entry)) {
throw new BusinessException("功能未配置入口脚本: " + featureId);
}
// 防止路径穿越
Path normalized = Paths.get(entry).normalize();
if (normalized.isAbsolute() || normalized.startsWith("..") || entry.contains("..")) {
throw new BusinessException("非法脚本路径");
}
Resource resource = new ClassPathResource(FEATURE_DIR + normalized);
if (!resource.exists()) {
throw new BusinessException("功能脚本文件不存在: " + entry);
}
try (InputStream in = resource.getInputStream()) {
String content = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
return new ExtensionFeatureScriptVO(
item.getId(),
item.getVersion(),
item.getSha256(),
content
);
} catch (IOException e) {
throw new BusinessException("读取功能脚本失败: " + e.getMessage());
}
}
}
@@ -177,6 +177,10 @@ INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status
SELECT 5208, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:open' LIMIT 1), 'open:scope:pdd_shop:read', '开放-拼多多渠道店铺查询', 'api', 1, 'POST /open/v1/channel/pdd/shop/list', 80
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:pdd_shop:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 5209, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:open' LIMIT 1), 'open:scope:extension_feature:read', '开放-浏览器扩展功能读取', 'api', 1, 'GET /open/v1/extension/features', 90
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:extension_feature:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 1101, (SELECT id FROM `sys_permission` WHERE `code` = 'system:menu' LIMIT 1), 'system:menu:read', '菜单查看', 'api', 1, '系统管理-菜单查看', 14
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'system:menu:read');
@@ -0,0 +1,19 @@
{
"schemaVersion": 1,
"updatedAt": "2026-08-16T10:21:40.757Z",
"features": [
{
"id": "pdd-ad-fee",
"name": "拼多多商品推广费同步",
"version": "0.1.0",
"description": "从推广总览读取单日总花费并同步到 BI(壳内嵌入执行;远程包用于版本校验)",
"matchUrlPatterns": [
"*://yingxiao.pinduoduo.com/*",
"https://yingxiao.pinduoduo.com/"
],
"entry": "pdd-ad-fee.js",
"sha256": "56dc0b6672a9cac6a7cffa8ee4139dc31a2bce37975d8a57b67f6a0e77221c6c",
"executionWorld": "extension"
}
]
}
@@ -0,0 +1,2 @@
var EcbiFeaturePddAdFee=function(){"use strict";const e="pdd-ad-fee",E={id:e,version:"0.1.0",executionWorld:"extension"},_=globalThis;return _.__ECBI_FEATURES__=_.__ECBI_FEATURES__??{},_.__ECBI_FEATURES__[e]=E,E}();
//# sourceMappingURL=pdd-ad-fee.js.map
@@ -0,0 +1 @@
{"version":3,"file":"pdd-ad-fee.js","sources":["../src/features/pdd-ad-fee/index.ts"],"sourcesContent":["/**\n * 远程功能包入口(IIFE 构建)。\n * 当前阶段导出元数据;真正 UI 仍由壳内 embedded 模块挂载。\n * 后续可将 FloatingPanel 整包打入此入口并在 main world 执行。\n */\nconst FEATURE_ID = 'pdd-ad-fee';\n\nexport interface RemoteFeatureExport {\n id: string;\n version: string;\n executionWorld: 'extension';\n}\n\nconst meta: RemoteFeatureExport = {\n id: FEATURE_ID,\n version: '0.1.0',\n executionWorld: 'extension',\n};\n\ndeclare global {\n interface Window {\n __ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;\n }\n}\n\nconst g = globalThis as typeof globalThis & {\n __ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;\n};\ng.__ECBI_FEATURES__ = g.__ECBI_FEATURES__ ?? {};\ng.__ECBI_FEATURES__[FEATURE_ID] = meta;\n\nexport default meta;\n"],"names":["FEATURE_ID","meta","g"],"mappings":"gDAKA,MAAMA,EAAa,aAQbC,EAA4B,CAChC,GAAID,EACJ,QAAS,QACT,eAAgB,WAClB,EAQME,EAAI,WAGV,OAAAA,EAAE,kBAAoBA,EAAE,mBAAqB,CAAA,EAC7CA,EAAE,kBAAkBF,CAAU,EAAIC"}