feat: 新增浏览器插件

This commit is contained in:
2026-08-16 16:45:24 +08:00
parent 2f32d955eb
commit f209d93733
38 changed files with 4727 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
dist
node_modules
*.local
.DS_Store
+1
View File
@@ -0,0 +1 @@
ignore-workspace=true
+6
View File
@@ -0,0 +1,6 @@
{
"singleQuote": true,
"semi": true,
"trailingComma": "all",
"printWidth": 100
}
+101
View File
@@ -0,0 +1,101 @@
# ECBI 数据同步扩展
企业内部用 Chromium 扩展(Manifest V3):在电商后台页面由用户主动读取推广费用,经统一模型通过 **Open API** 同步到 BI。
第一阶段:**工程骨架 + Mock Adapter**,不解析真实平台 DOM。
## 环境要求
- Node.js >= 18
- pnpm >= 9
## 安装依赖
```bash
cd browser-extension
pnpm install
```
## 开发
```bash
pnpm dev
```
## 构建
```bash
pnpm build
```
产物目录:`dist/`。
## 安装到 Chrome / Edge
1. 打开 `chrome://extensions/` 或 `edge://extensions/`
2. 开启「开发者模式」
3. 「加载已解压的扩展程序」→ 选择本项目的 `dist` 目录
## 项目架构
```text
Popup(配置 / 选店 / 读数 / 同步)
↓ chrome.tabs.sendMessage
Content Script(Platform Adapter)
↓ Mock / 未来真实平台
统一 AdvertisingCostBatch
↓ 映射
BI Open API(API Key)
```
| 环境 | 职责 |
|------|------|
| Popup | UI、配置、选 channelShopId、发起同步 |
| Content Script | 调 Adapter,不直接调 BI API |
| Background | 生命周期占位,业务不塞这里 |
新增平台:在 `src/platform/<name>/` 实现 `PlatformAdapter`,并注册到 `PlatformDetector`。
## 配置 BI Open API
Popup 右上角「配置」:
| 项 | 说明 |
|----|------|
| Base URL | 例 `http://localhost:8080/api`(不要末尾 `/`) |
| API Key | 后台创建的 Open API Key(`sk_...`),**不要**填登录 JWT |
Key 需具备:
- `open:scope:pdd_shop:read`
- `open:scope:pdd_goods_ad_fee:import`
## 与后端字段对照
| 插件 | 后端 batch-import |
|------|-------------------|
| `channelShopId` | `channelShopId`(`channel_pdd_shop.id`) |
| `feeDate` | `feeDate`(YYYY-MM-DD,以 Popup 所选为准) |
| `items[].goodsId` | `goodsId` |
| `items[].feeAmount` | `feeAmount`(元) |
相关接口:
- `POST /open/v1/channel/pdd/shop/list`
- `POST /open/v1/channel/pdd/goods/adfee/batch-import`
鉴权头:`X-Api-Key: <key>`(或 `Authorization: Bearer <key>`)。
## 当前 Mock 说明
- 任意页面均可由 `MockPlatformAdapter` 处理
- 「读取数据」返回 3 条样例 `goodsId` / 金额
- 同步仍会打真实 Open API;若要用 Mock 联调,请先在 BI 侧准备对应 `channel_pdd_goods` 与 Key
## 权限说明
Manifest 申请:`storage`、`activeTab`、`scripting`;Content Script 匹配 `http(s)://*/*` 以便开发期注入。接入真实平台后应收窄到具体域名。
## 设计文档
见同目录 [design.md](./design.md)。
+767
View File
@@ -0,0 +1,767 @@
可以。你这个项目适合让 Coding Agent **先只搭架构,不要急着实现具体平台的数据解析**。否则 Agent 很容易一上来就把 `content script / popup / background / API` 搞成一坨。
你可以直接把下面这段给它:
````text
你现在负责创建一个浏览器扩展项目,项目名称暂定为 `ecbi-data-sync-extension`。
## 一、项目目标
这是一个用于企业内部使用的浏览器扩展,主要作用是:
用户登录电商平台后台后,在平台页面中选择指定日期,扩展读取当前页面中用户有权限看到的业务数据,并将数据转换成统一的数据模型,通过 HTTPS Open API 同步到我自己的 BI 系统。
第一阶段主要用于“推广费用/广告费用”同步。
目标浏览器:
- Google Chrome
- Microsoft Edge
要求使用 Chromium Extension 兼容方案,基于 Manifest V3。
重要:
- 不需要发布 Chrome Web Store
- 不需要实现自动登录
- 不需要保存或上传平台 Cookie
- 不需要实现后台自动爬取
- 不需要实现定时抓取
- 必须由用户主动点击“同步”
- 第一阶段不要实现任何具体电商平台的解析逻辑
- 当前任务重点是搭建一个可长期扩展的工程架构
---
# 二、技术栈
使用:
- Vue 3
- TypeScript
- Vite
- Manifest V3
- pnpm
UI:
- 优先使用 Tailwind CSS
- 不使用 Element Plus
- 不引入重量级 UI 框架
代码要求:
- TypeScript strict
- ESLint
- Prettier
- 合理的类型定义
- 模块化设计
- 避免 any
- 避免把业务逻辑全部写进 Vue 组件
- 避免平台相关代码污染公共代码
---
# 三、先设计架构,再写代码
在开始创建文件之前,先分析并输出:
1. 项目整体架构
2. Extension 各运行环境之间的职责
3. Popup / Content Script / Background Service Worker 的通信方式
4. 平台 Adapter 的设计
5. BI API Client 的设计
6. 数据模型设计
7. Token / 配置存储方案
8. Manifest 权限设计
9. 后续增加多个电商平台时如何扩展
确认架构合理后再创建代码。
---
# 四、运行环境职责
严格区分以下三个环境:
## 1. Popup
负责:
- 显示当前平台
- 显示当前页面状态
- 获取用户配置
- 获取 BI Open API Key / Base URL
- 选择 BI 渠道店铺(channelShopId)
- 显示待同步数据
- 用户点击“同步”
- 显示同步成功/失败
- 显示错误信息
Popup 不负责直接解析平台 DOM。
---
## 2. Content Script
负责:
- 运行在目标电商平台页面
- 读取当前页面已经展示给用户的数据
- 获取当前页面 URL
- 获取页面上下文信息
- 调用对应平台 Adapter
- 将平台数据转换为统一业务模型
- 将解析结果返回给 Popup / Background
第一阶段只提供接口和 Mock Adapter,不实现真实平台解析。
---
## 3. Background Service Worker
负责:
- Extension 全局事件
- Popup / Content Script 消息转发
- Extension 生命周期相关逻辑
- 后续需要跨页面或后台处理的能力
不要把所有业务逻辑都塞进 background。
---
# 五、平台适配器架构
这是本项目最重要的架构之一。
必须设计成:
```text
platform/
├── core/
│ ├── PlatformAdapter.ts
│ ├── PlatformDetector.ts
│ └── types.ts
│
├── mock/
│ └── MockPlatformAdapter.ts
│
├── taobao/
│ └── ...
│
├── jd/
│ └── ...
│
└── pdd/
└── ...
````
暂时不要实现淘宝、京东、拼多多等真实平台。
定义统一接口,例如:
```ts
interface PlatformAdapter {
platform: PlatformType;
canHandle(url: string): boolean;
getPageContext(): Promise<PageContext>;
parseAdvertisingCost(): Promise<AdvertisingCostBatch>;
}
```
具体接口名称可以根据实际架构调整,但必须保持职责清晰。
---
# 六、统一业务数据模型
不要让 BI 后端直接接收某个平台的原始 DOM 数据。
定义**插件侧统一模型**,再由 API Client **映射**为后端 Open API 入参。
## 6.1 插件侧统一模型(平台无关)
```ts
/** 单条商品广告费(插件内统一模型) */
interface AdvertisingCostItem {
/** 平台商品 ID,如拼多多 goods_id */
goodsId: string;
/** 广告费金额(元) */
feeAmount: number;
/** 可选扩展,不同平台可塞入 metadata,不直接提交后端 */
metadata?: Record<string, unknown>;
}
/**
* 一次读取/同步的批次(插件内)
* channelShopId:BI 侧渠道店铺主键;拼多多 = channel_pdd_shop.id(不是 mallId)
* feeDate:以 Popup 用户选择的同步日期为准(YYYY-MM-DD)
*/
interface AdvertisingCostBatch {
platform: 'pdd' | 'taobao' | 'jd' | 'mock';
channelShopId: number;
feeDate: string;
items: AdvertisingCostItem[];
source: 'browser-extension';
importedAt: string; // ISO 时间,仅插件侧审计用,不必提交后端
}
```
## 6.2 与现有 BI Open API 对齐(第一阶段:拼多多商品广告费)
后端已实现(路径均带 `/api` 前缀):
| 能力 | Method / Path | Scope |
|------|---------------|--------|
| 渠道店铺列表 | `POST /api/open/v1/channel/pdd/shop/list` | `open:scope:pdd_shop:read` |
| 商品广告费批量导入 | `POST /api/open/v1/channel/pdd/goods/adfee/batch-import` | `open:scope:pdd_goods_ad_fee:import` |
### 店铺列表(取 channelShopId)
请求体与内部接口一致,分页查询:
```ts
// POST /api/open/v1/channel/pdd/shop/list
interface PageQuery<TFilters> {
page: number;
pageSize: number;
filters?: TFilters; // 可选:mallName 等
}
// 响应 records[].id 即为 channelShopId(channel_pdd_shop.id)
interface PddChannelShop {
id: number; // → AdvertisingCostBatch.channelShopId
mallId?: number; // 拼多多 mall_id,仅展示/核对,不要当 BI 店铺主键提交
mallName?: string;
// ...
}
```
### 批量导入广告费(提交形态)
后端入参**仅接受**以下字段,插件必须映射到此结构(不要把 platform / source / importedAt 塞进 body):
```ts
// POST /api/open/v1/channel/pdd/goods/adfee/batch-import
interface BatchImportPddGoodsAdFeeRequest {
items: Array<{
channelShopId: number; // channel_pdd_shop.id
feeDate: string; // YYYY-MM-DD
goodsId: string; // 拼多多 goods_id
feeAmount: number; // 元,>= 0
}>;
}
```
映射规则:
```text
AdvertisingCostBatch
→ items[] = batch.items.map(i => ({
channelShopId: batch.channelShopId,
feeDate: batch.feeDate, // 整批同一天
goodsId: i.goodsId,
feeAmount: i.feeAmount,
}))
```
后端行为:校验店铺归属 + 该店下存在该 `goods_id`;按 `(channelShopId, goodsId, feeDate)` **upsert**(同日覆盖金额)。
必须保证:
平台原始数据 → Platform Adapter → 统一模型 →(映射)→ BI Open API
而不是:平台 A → 一套 API、平台 B → 另一套 API(多平台仍走统一模型,仅 API Client 按平台选择 endpoint)。
---
# 七、BI API Client
创建独立 API 层,例如:
```text
src/api/
├── client.ts # Base URL、Header、超时、错误归一
├── open/
│ ├── pddShop.ts # POST .../channel/pdd/shop/list
│ └── pddGoodsAdFee.ts # POST .../channel/pdd/goods/adfee/batch-import
└── types.ts
```
统一处理:
* Base URL(如 `https://xxx/api` 或含网关前缀,以实际部署为准)
* 鉴权 Header(Open API Key,**不是** 系统登录 JWT)
* 请求超时
* HTTP 错误 / 业务错误(`ApiResponse.code`)/ 网络错误
鉴权头(二选一,与后端 `ApiKeyAuthenticationFilter` 一致):
```http
X-Api-Key: sk_live_xxxxxxxx
```
或:
```http
Authorization: Bearer sk_live_xxxxxxxx
```
注意:后端会拒绝以 `eyJ` 开头的 JWT 当作 Key。扩展配置里只存 **Open API Key**。
不要在 Vue 组件中直接到处写 fetch。
BI API Base URL 与 API Key 必须通过 Extension Storage 配置。
---
# 八、配置与 API Key
使用:
```ts
chrome.storage.local
```
保存:
```text
BI Open API Base URL (例:https://host/api)
BI Open API Key (创建 Key 时返回的明文,仅本地保存)
默认 channelShopId (可选,用户从店铺列表选过一次后记住)
```
设计独立配置模块:
```text
src/storage/
├── settings.ts
└── types.ts
```
不要直接在业务代码中到处:
```ts
chrome.storage.local.get(...)
```
统一封装。
注意:
* 不保存电商平台 Cookie
* 不向 BI 服务上传平台 Cookie
* 不实现获取平台 Token 的逻辑
* **只保存用户自己的 BI Open API Key**(需具备 `open:scope:pdd_shop:read` 与 `open:scope:pdd_goods_ad_fee:import`)
* 不使用系统后台登录 JWT 调 `/api/open/**`
---
# 九、权限设计
Manifest V3 遵循最小权限原则。
只申请实际需要的权限。
第一阶段优先考虑:
```text
storage
activeTab
scripting
```
不要为了方便直接申请:
```text
<all_urls>
```
如果后续确实需要指定平台域名,再针对具体平台增加 host_permissions。
Manifest 中不要提前加入一堆没有实际用途的权限。
---
# 十、Popup UI
先做一个简洁的内部工具 UI。
页面结构:
```text
┌──────────────────────────────┐
│ BI 数据同步 │
├──────────────────────────────┤
│ 当前平台 │
│ 淘宝 / 京东 / 未识别 │
│ │
│ 当前页面 │
│ xxx │
│ │
│ 同步日期 │
│ 2026-08-15 │
│ │
│ BI 渠道店铺 │
│ [下拉:从 open shop/list 选] │
│ channelShopId: 12 │
│ │
│ 数据状态 │
│ 等待读取 │
│ │
│ [读取数据] │
│ │
│ 数据预览 │
│ ─────────────────────────── │
│ 推广费用:¥0 │
│ 数据条数:0 │
│ │
│ [同步到 BI] │
└──────────────────────────────┘
```
第一阶段使用 Mock 数据。
例如点击:
```text
读取数据
```
显示:
```text
平台:Mock
BI 渠道店铺:测试店铺(channelShopId=1)
日期:2026-08-15
推广费用:¥1234.56
数据条数:10
```
然后:
```text
同步到 BI
```
调用 Open API:`POST .../channel/pdd/goods/adfee/batch-import`(开发环境可用 Mock Client 或真实 Key)。
日期约定:**以 Popup 所选「同步日期」为准**写入每条 `feeDate`;页面解析出的日期仅作校验/提示,不一致时提示用户确认后再同步。
---
# 十一、消息通信
设计统一消息协议。
例如:
```ts
type ExtensionMessage =
| {
type: 'GET_PAGE_CONTEXT';
}
| {
type: 'PARSE_ADVERTISING_COST';
payload: {
feeDate: string; // YYYY-MM-DD,与 Popup 同步日期一致
};
}
| {
type: 'SYNC_ADVERTISING_COST';
payload: AdvertisingCostBatch;
};
```
不要直接在各处使用字符串:
```ts
chrome.runtime.sendMessage({
type: 'xxx'
});
```
应该统一定义消息类型,保证 TypeScript 类型安全。
---
# 十二、错误处理
统一错误模型。
至少区分:
```text
PLATFORM_NOT_SUPPORTED
PAGE_NOT_READY
DATA_PARSE_FAILED
INVALID_DATA
AUTH_FAILED
API_REQUEST_FAILED
API_BUSINESS_ERROR
NETWORK_ERROR
CONFIG_MISSING
```
UI 给用户显示友好的错误。
例如:
```text
当前页面不是支持的推广费用页面
请先进入平台推广费用页面,然后重新点击“读取数据”。
```
不要直接把底层异常堆栈展示给用户。
---
# 十三、目录结构
最终建议类似:
```text
bi-data-sync-extension/
│
├── src/
│ ├── api/
│ │ ├── client.ts
│ │ ├── open/
│ │ │ ├── pddShop.ts
│ │ │ └── pddGoodsAdFee.ts
│ │ └── types.ts
│ │
│ ├── background/
│ │ └── index.ts
│ │
│ ├── content/
│ │ └── index.ts
│ │
│ ├── popup/
│ │ ├── App.vue
│ │ ├── main.ts
│ │ └── components/
│ │
│ ├── platform/
│ │ ├── core/
│ │ │ ├── types.ts
│ │ │ ├── PlatformAdapter.ts
│ │ │ └── PlatformDetector.ts
│ │ │
│ │ └── mock/
│ │ └── MockPlatformAdapter.ts
│ │
│ ├── storage/
│ │ ├── settings.ts
│ │ └── types.ts
│ │
│ ├── shared/
│ │ ├── messages.ts
│ │ ├── constants.ts
│ │ └── errors.ts
│ │
│ └── types/
│ └── advertisingCost.ts
│
├── public/
│ └── icons/
│
├── manifest.config.ts
├── vite.config.ts
├── tsconfig.json
├── package.json
├── .eslintrc...
├── .prettierrc...
└── README.md
```
可以根据 Vite/Extension 构建方式调整目录,但必须保持职责分离。
---
# 十四、构建要求
需要支持:
```bash
pnpm install
pnpm dev
pnpm build
```
构建后生成:
```text
dist/
```
能够直接通过:
Chrome:
chrome://extensions/
Edge:
edge://extensions/
开启开发者模式后加载 `dist` 目录运行。
README 必须写清楚:
1. 环境要求
2. 安装依赖
3. 开发
4. 构建
5. Chrome 安装方式
6. Edge 安装方式
7. 项目架构
8. 如何增加一个新的平台 Adapter
9. 如何配置 BI Open API(Base URL + API Key + 所需 scope)
10. 当前 Mock 数据说明
11. 与后端 open 接口字段对照(channelShopId / feeDate / goodsId / feeAmount)
---
# 十五、测试
至少建立基础测试结构。
重点测试:
* PlatformDetector
* MockPlatformAdapter
* AdvertisingCost 数据转换
* API Client 错误处理
* Storage 配置读写
不需要为了测试而过度设计。
---
# 十六、重要约束
不要做以下事情:
1. 不要实现任何平台爬虫
2. 不要逆向任何平台接口
3. 不要读取平台 Cookie
4. 不要上传平台 Cookie
5. 不要自动登录
6. 不要后台定时抓取
7. 不要自动模拟用户点击
8. 不要申请不必要的 Chrome 权限
9. 不要使用 `<all_urls>` 作为偷懒方案
10. 不要把平台逻辑写死在 Popup
11. 不要把 API 请求散落在 Vue 组件
12. 不要引入 Element Plus
第一阶段只需要:
“插件工程 + Manifest V3 + Vue + TypeScript + Popup + Content Script + Background + Storage + API Client + Platform Adapter + Mock 数据”。
---
# 十七、开发原则
遵循:
* KISS
* SOLID
* 单一职责
* 依赖倒置
* 类型安全
* 最小权限
* 平台适配器隔离
* 基础设施与业务逻辑分离
不要为了“以后可能用到”创建大量抽象。
如果一个抽象目前没有真实需求,优先保持简单。
---
# 十八、执行方式
不要一次性生成大量复杂代码。
按照以下步骤执行:
Step 1:
分析架构并说明关键设计。
Step 2:
创建项目基础结构和 Vite + Vue + TypeScript + Manifest V3。
Step 3:
实现 Popup / Content Script / Background 的最小通信链路。
Step 4:
实现 Storage。
Step 5:
实现 Platform Adapter 和 Mock Adapter。
Step 6:
实现 BI API Client。
Step 7:
实现 Mock 数据同步流程。
Step 8:
完善 UI。
Step 9:
添加测试。
Step 10:
完善 README。
每完成一个阶段,先检查 TypeScript、ESLint、Build 是否通过,再进入下一阶段。
如果发现架构问题,先修正架构,不要通过增加临时代码绕过去。
最终要求:
```bash
pnpm build
```
必须成功,并且 `dist` 可以直接加载到 Chrome 和 Edge 中运行。
````
### 我建议你再给 Agent 加一句
如果你用的是 **Cursor / Claude Code / Codex / OpenCode** 这类 Coding Agent,我建议第一轮**不要让它直接开发真实平台**。
先让它把:
```text
Vue
↓
Popup
↓
Content Script
↓
Mock Adapter
↓
统一 AdvertisingCostBatch
↓
映射为 batch-import items
↓
BI Open API(API Key)
````
注意:提交字段必须是 `channelShopId + feeDate + goodsId + feeAmount`;鉴权用 Open API Key,不要用登录 JWT。
然后第二轮你再告诉它:
> “现在接入 XX 平台,只允许读取用户当前页面已经展示的数据,实现 XX 平台 Adapter,先分析页面结构,不要修改公共架构。”
这样会稳很多。
+35
View File
@@ -0,0 +1,35 @@
import { defineManifest } from '@crxjs/vite-plugin';
import packageJson from './package.json';
const { version } = packageJson;
export default defineManifest({
manifest_version: 3,
name: 'ECBI 数据同步',
description: '从电商平台后台读取推广费用并同步到 BI(企业内用)',
version,
action: {
default_popup: 'src/popup/index.html',
default_title: 'ECBI 数据同步',
},
background: {
service_worker: 'src/background/index.ts',
type: 'module',
},
content_scripts: [
{
matches: ['http://*/*', 'https://*/*'],
js: ['src/content/index.ts'],
run_at: 'document_idle',
},
],
permissions: ['storage', 'activeTab', 'scripting'],
// 开发期便于任意页注入 Content Script;正式接平台后改为具体域名
host_permissions: ['http://*/*', 'https://*/*'],
icons: {
'16': 'public/icons/icon-16.png',
'48': 'public/icons/icon-48.png',
'128': 'public/icons/icon-128.png',
},
});
+38
View File
@@ -0,0 +1,38 @@
{
"name": "ecbi-data-sync-extension",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "企业内部 BI 数据同步浏览器扩展(Manifest V3)",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"typecheck": "vue-tsc --noEmit",
"lint": "eslint . --ext .ts,.vue",
"format": "prettier --write \"src/**/*.{ts,vue,css,json}\""
},
"dependencies": {
"vue": "^3.5.13"
},
"devDependencies": {
"@crxjs/vite-plugin": "^2.7.1",
"@types/chrome": "^0.0.287",
"@types/node": "^22.10.2",
"@vitejs/plugin-vue": "^5.2.1",
"@vue/eslint-config-prettier": "^10.1.0",
"@vue/eslint-config-typescript": "^14.1.4",
"autoprefixer": "^10.4.20",
"eslint": "^9.17.0",
"eslint-plugin-vue": "^9.32.0",
"postcss": "^8.4.49",
"prettier": "^3.4.2",
"tailwindcss": "^3.4.17",
"typescript": "~5.6.3",
"vite": "^5.4.11",
"vue-tsc": "^2.1.10"
},
"packageManager": "pnpm@9.15.0",
"engines": {
"node": ">=18"
}
}
+2844
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 602 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 242 B

+64
View File
@@ -0,0 +1,64 @@
import { ExtensionError } from '@/shared/errors';
import { getSettings } from '@/storage/settings';
export interface ApiResponseBody<T> {
code: number;
message: string;
data: T;
}
export async function openApiRequest<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
const settings = await getSettings();
if (!settings.apiBaseUrl) {
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Base URL');
}
if (!settings.apiKey) {
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Key');
}
const url = `${settings.apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`;
const headers = new Headers(init.headers);
headers.set('Content-Type', 'application/json');
headers.set('X-Api-Key', settings.apiKey);
let response: Response;
try {
response = await fetch(url, {
...init,
headers,
});
} catch {
throw new ExtensionError('NETWORK_ERROR', '网络异常,无法连接 BI Open API');
}
if (response.status === 401) {
throw new ExtensionError('AUTH_FAILED', 'API Key 无效、过期或 IP 不在白名单');
}
let body: ApiResponseBody<T>;
try {
body = (await response.json()) as ApiResponseBody<T>;
} catch {
throw new ExtensionError('API_REQUEST_FAILED', `请求失败(HTTP ${response.status})`);
}
if (!response.ok) {
throw new ExtensionError(
'API_REQUEST_FAILED',
body.message || `请求失败(HTTP ${response.status})`,
);
}
// 后端业务码:0 / 200 视为成功(兼容)
if (body.code !== 0 && body.code !== 200) {
throw new ExtensionError(
'API_BUSINESS_ERROR',
body.message || `业务错误(code=${body.code})`,
);
}
return body.data;
}
@@ -0,0 +1,55 @@
import type { AdvertisingCostBatch } from '@/types/advertisingCost';
import { openApiRequest } from '@/api/client';
import { OPEN_API_PATHS } from '@/shared/constants';
export interface BatchImportPddGoodsAdFeeItem {
channelShopId: number;
feeDate: string;
goodsId: string;
feeAmount: number;
}
export interface BatchImportPddGoodsAdFeeRequest {
items: BatchImportPddGoodsAdFeeItem[];
}
export interface BatchImportPddGoodsAdFeeResult {
totalCount: number;
successCount: number;
failureCount: number;
successIds?: number[];
failureRecords?: Array<{
rowNumber?: number;
channelShopId?: number;
goodsId?: string;
failureReason?: string;
}>;
}
/** 插件统一模型 → 后端 batch-import 入参 */
export function toBatchImportRequest(
batch: AdvertisingCostBatch,
): BatchImportPddGoodsAdFeeRequest {
return {
items: batch.items.map((item) => ({
channelShopId: batch.channelShopId,
feeDate: batch.feeDate,
goodsId: item.goodsId,
feeAmount: item.feeAmount,
})),
};
}
export async function batchImportPddGoodsAdFee(
batch: AdvertisingCostBatch,
): Promise<BatchImportPddGoodsAdFeeResult> {
const body = toBatchImportRequest(batch);
return openApiRequest<BatchImportPddGoodsAdFeeResult>(
OPEN_API_PATHS.pddGoodsAdFeeBatchImport,
{
method: 'POST',
body: JSON.stringify(body),
},
);
}
+35
View File
@@ -0,0 +1,35 @@
import { openApiRequest } from '@/api/client';
import { OPEN_API_PATHS } from '@/shared/constants';
export interface PageQueryDTO<TFilters> {
page: number;
pageSize: number;
filters?: TFilters;
}
export interface PageResultVO<T> {
records: T[];
total: number;
page?: number;
pageSize?: number;
}
export interface PddChannelShop {
id: number;
mallId?: number;
mallName?: string;
logo?: string;
}
export interface PddShopFilters {
mallName?: string;
}
export async function listPddChannelShops(
query: PageQueryDTO<PddShopFilters> = { page: 1, pageSize: 50 },
): Promise<PageResultVO<PddChannelShop>> {
return openApiRequest<PageResultVO<PddChannelShop>>(OPEN_API_PATHS.pddShopList, {
method: 'POST',
body: JSON.stringify(query),
});
}
+6
View File
@@ -0,0 +1,6 @@
export type {
BatchImportPddGoodsAdFeeItem,
BatchImportPddGoodsAdFeeRequest,
BatchImportPddGoodsAdFeeResult,
} from './open/pddGoodsAdFee';
export type { PddChannelShop, PageQueryDTO, PageResultVO } from './open/pddShop';
+15
View File
@@ -0,0 +1,15 @@
/**
* Background Service Worker:生命周期与消息转发占位。
* 第一阶段业务请求由 Popup 直接发起;Content 由 Manifest 注入。
*/
chrome.runtime.onInstalled.addListener(() => {
console.info('[ecbi-extension] installed');
});
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type === 'BACKGROUND_PING') {
sendResponse({ ok: true, data: { pong: true } });
return true;
}
return false;
});
+59
View File
@@ -0,0 +1,59 @@
import { resolveAdapter } from '@/platform/core/PlatformDetector';
import { ExtensionError } from '@/shared/errors';
import {
isExtensionMessage,
type ExtensionMessage,
type ExtensionResponse,
} from '@/shared/messages';
import type { AdvertisingCostBatch } from '@/types/advertisingCost';
async function handleMessage(message: ExtensionMessage): Promise<ExtensionResponse> {
const adapter = resolveAdapter(location.href);
switch (message.type) {
case 'PING':
return { ok: true, data: { pong: true } };
case 'GET_PAGE_CONTEXT': {
const data = await adapter.getPageContext();
return { ok: true, data };
}
case 'PARSE_ADVERTISING_COST': {
const parsed = await adapter.parseAdvertisingCost(message.payload.feeDate);
// channelShopId 由 Popup 选择后填入
const data: AdvertisingCostBatch = {
...parsed,
channelShopId: 0,
};
return { ok: true, data };
}
default:
return {
ok: false,
code: 'UNKNOWN',
message: '未知消息类型',
};
}
}
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (!isExtensionMessage(message)) {
return false;
}
void handleMessage(message)
.then((result) => sendResponse(result))
.catch((error: unknown) => {
const err =
error instanceof ExtensionError
? error
: new ExtensionError('UNKNOWN', 'Content Script 处理失败');
const response: ExtensionResponse = {
ok: false,
code: err.code,
message: err.message,
};
sendResponse(response);
});
return true;
});
+7
View File
@@ -0,0 +1,7 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<object, object, unknown>;
export default component;
}
@@ -0,0 +1,12 @@
import type {
AdvertisingCostBatch,
PageContext,
PlatformType,
} from '@/types/advertisingCost';
export interface PlatformAdapter {
readonly platform: PlatformType;
canHandle(url: string): boolean;
getPageContext(): Promise<PageContext>;
parseAdvertisingCost(feeDate: string): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>>;
}
@@ -0,0 +1,24 @@
import type { PlatformType } from '@/types/advertisingCost';
import type { PlatformAdapter } from './PlatformAdapter';
import { MockPlatformAdapter } from '../mock/MockPlatformAdapter';
const adapters: PlatformAdapter[] = [new MockPlatformAdapter()];
export function detectPlatform(url: string): PlatformType {
const adapter = adapters.find((item) => item.canHandle(url));
return adapter?.platform ?? 'unknown';
}
export function resolveAdapter(url: string): PlatformAdapter {
const matched = adapters.find((item) => item.canHandle(url));
if (matched) {
return matched;
}
// 第一阶段:未识别平台时回退 Mock,保证链路可跑通
return adapters[0]!;
}
export function listAdapters(): PlatformAdapter[] {
return [...adapters];
}
@@ -0,0 +1,2 @@
export type { PlatformAdapter } from './PlatformAdapter';
export { detectPlatform, listAdapters, resolveAdapter } from './PlatformDetector';
@@ -0,0 +1,42 @@
import type { PlatformAdapter } from '@/platform/core/PlatformAdapter';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
/**
* 第一阶段 Mock Adapter:不读真实 DOM,返回固定样例数据。
*/
export class MockPlatformAdapter implements PlatformAdapter {
readonly platform = 'mock' as const;
canHandle(_url: string): boolean {
// 未接入真实平台前,任意页面均可由 Mock 处理
return true;
}
async getPageContext(): Promise<PageContext> {
return {
url: typeof location !== 'undefined' ? location.href : '',
title: typeof document !== 'undefined' ? document.title : '',
platform: 'mock',
ready: true,
message: '当前为 Mock Adapter(未解析真实平台页面)',
};
}
async parseAdvertisingCost(
feeDate: string,
): Promise<Omit<AdvertisingCostBatch, 'channelShopId'>> {
const items = [
{ goodsId: 'mock-goods-1001', feeAmount: 128.5 },
{ goodsId: 'mock-goods-1002', feeAmount: 56.0 },
{ goodsId: 'mock-goods-1003', feeAmount: 1050.06 },
];
return {
platform: 'mock',
feeDate,
items,
source: 'browser-extension',
importedAt: new Date().toISOString(),
};
}
}
+317
View File
@@ -0,0 +1,317 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { batchImportPddGoodsAdFee } from '@/api/open/pddGoodsAdFee';
import { listPddChannelShops, type PddChannelShop } from '@/api/open/pddShop';
import { EXTENSION_NAME } from '@/shared/constants';
import { toUserMessage } from '@/shared/errors';
import { getSettings, saveSettings } from '@/storage/settings';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
import { fetchPageContext, parseAdvertisingCostFromPage } from './messaging';
const settingsOpen = ref(false);
const apiBaseUrl = ref('');
const apiKey = ref('');
const feeDate = ref(new Date().toISOString().slice(0, 10));
const shops = ref<PddChannelShop[]>([]);
const channelShopId = ref<number | undefined>(undefined);
const channelShopName = ref('');
const shopsLoading = ref(false);
const pageContext = ref<PageContext | null>(null);
const batch = ref<AdvertisingCostBatch | null>(null);
const statusText = ref('等待读取');
const errorText = ref('');
const syncResultText = ref('');
const busy = ref(false);
const totalFee = computed(() =>
(batch.value?.items ?? []).reduce((sum, item) => sum + Number(item.feeAmount || 0), 0),
);
const itemCount = computed(() => batch.value?.items.length ?? 0);
const selectedShopLabel = computed(() => {
if (channelShopId.value == null) return '未选择';
return channelShopName.value
? `${channelShopName.value} (#${channelShopId.value})`
: `#${channelShopId.value}`;
});
async function loadLocalSettings() {
const settings = await getSettings();
apiBaseUrl.value = settings.apiBaseUrl;
apiKey.value = settings.apiKey;
channelShopId.value = settings.channelShopId;
channelShopName.value = settings.channelShopName ?? '';
}
async function persistSettings() {
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
channelShopId: channelShopId.value,
channelShopName: channelShopName.value,
});
settingsOpen.value = false;
statusText.value = '配置已保存';
}
async function refreshPageContext() {
errorText.value = '';
try {
pageContext.value = await fetchPageContext();
} catch (error) {
pageContext.value = null;
errorText.value = toUserMessage(error);
}
}
async function loadShops() {
shopsLoading.value = true;
errorText.value = '';
try {
await persistSettingsQuiet();
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 ?? '';
}
}
} catch (error) {
errorText.value = toUserMessage(error);
} finally {
shopsLoading.value = false;
}
}
async function persistSettingsQuiet() {
await saveSettings({
apiBaseUrl: apiBaseUrl.value.trim(),
apiKey: apiKey.value.trim(),
channelShopId: channelShopId.value,
channelShopName: channelShopName.value,
});
}
function onShopChange(event: Event) {
const value = Number((event.target as HTMLSelectElement).value);
if (!Number.isFinite(value) || value <= 0) {
channelShopId.value = undefined;
channelShopName.value = '';
return;
}
channelShopId.value = value;
const hit = shops.value.find((s) => s.id === value);
channelShopName.value = hit?.mallName ?? '';
void persistSettingsQuiet();
}
async function handleRead() {
busy.value = true;
errorText.value = '';
syncResultText.value = '';
statusText.value = '正在读取…';
try {
if (channelShopId.value == null) {
throw new Error('请先选择 BI 渠道店铺(channelShopId)');
}
const parsed = await parseAdvertisingCostFromPage(feeDate.value);
batch.value = {
...parsed,
channelShopId: channelShopId.value,
feeDate: feeDate.value,
};
pageContext.value = await fetchPageContext();
statusText.value = '已读取(Mock)';
} catch (error) {
batch.value = null;
statusText.value = '读取失败';
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
async function handleSync() {
if (!batch.value) {
errorText.value = '请先读取数据';
return;
}
if (channelShopId.value == null) {
errorText.value = '请先选择 BI 渠道店铺';
return;
}
busy.value = true;
errorText.value = '';
syncResultText.value = '';
statusText.value = '正在同步…';
try {
await persistSettingsQuiet();
const payload: AdvertisingCostBatch = {
...batch.value,
channelShopId: channelShopId.value,
feeDate: feeDate.value,
};
const result = await batchImportPddGoodsAdFee(payload);
statusText.value = '同步完成';
syncResultText.value = `成功 ${result.successCount}/${result.totalCount}` +
(result.failureCount ? `,失败 ${result.failureCount}` : '');
} catch (error) {
statusText.value = '同步失败';
errorText.value = toUserMessage(error);
} finally {
busy.value = false;
}
}
onMounted(async () => {
await loadLocalSettings();
await refreshPageContext();
});
</script>
<template>
<div class="flex min-h-[480px] w-[380px] flex-col gap-3 p-4">
<header class="flex items-start justify-between gap-2">
<div>
<h1 class="text-base font-semibold tracking-tight">{{ EXTENSION_NAME }}</h1>
<p class="mt-0.5 text-xs text-slate-500">主动同步 · Open API · 第一阶段 Mock</p>
</div>
<button
class="rounded-md border border-slate-200 bg-white px-2 py-1 text-xs text-slate-700 hover:bg-slate-50"
type="button"
@click="settingsOpen = !settingsOpen"
>
{{ settingsOpen ? '收起配置' : '配置' }}
</button>
</header>
<section
v-if="settingsOpen"
class="space-y-2 rounded-lg border border-slate-200 bg-white p-3"
>
<label class="block text-xs text-slate-600">
Open API Base URL
<input
v-model="apiBaseUrl"
class="mt-1 w-full rounded-md border border-slate-200 px-2 py-1.5 text-sm outline-none focus:border-slate-400"
placeholder="https://host/api"
/>
</label>
<label class="block text-xs text-slate-600">
Open API Key
<input
v-model="apiKey"
type="password"
class="mt-1 w-full rounded-md border border-slate-200 px-2 py-1.5 text-sm outline-none focus:border-slate-400"
placeholder="sk_live_..."
/>
</label>
<button
class="w-full rounded-md bg-slate-900 px-3 py-1.5 text-sm text-white hover:bg-slate-800"
type="button"
@click="persistSettings"
>
保存配置
</button>
</section>
<section class="space-y-2 rounded-lg border border-slate-200 bg-white p-3 text-sm">
<div class="flex justify-between gap-2">
<span class="text-slate-500">当前平台</span>
<span class="font-medium">{{ pageContext?.platform ?? '未识别' }}</span>
</div>
<div class="flex justify-between gap-2">
<span class="text-slate-500">当前页面</span>
<span class="max-w-[220px] truncate text-right text-xs" :title="pageContext?.url">
{{ pageContext?.title || pageContext?.url || '—' }}
</span>
</div>
<label class="flex items-center justify-between gap-2">
<span class="text-slate-500">同步日期</span>
<input
v-model="feeDate"
type="date"
class="rounded-md border border-slate-200 px-2 py-1 text-sm"
/>
</label>
<div class="space-y-1">
<div class="flex items-center justify-between gap-2">
<span class="text-slate-500">BI 渠道店铺</span>
<button
class="text-xs text-sky-700 hover:underline"
type="button"
:disabled="shopsLoading || busy"
@click="loadShops"
>
{{ shopsLoading ? '加载中…' : '拉取列表' }}
</button>
</div>
<select
class="w-full rounded-md border border-slate-200 px-2 py-1.5 text-sm"
:value="channelShopId ?? ''"
@change="onShopChange"
>
<option value="">请选择 channelShopId</option>
<option v-for="shop in shops" :key="shop.id" :value="shop.id">
{{ shop.mallName || '未命名' }} (#{{ shop.id }}
<template v-if="shop.mallId != null"> / mall {{ shop.mallId }}</template>)
</option>
</select>
<p class="text-xs text-slate-400">当前:{{ selectedShopLabel }}</p>
</div>
<div class="flex justify-between gap-2">
<span class="text-slate-500">数据状态</span>
<span class="font-medium">{{ statusText }}</span>
</div>
</section>
<div class="flex gap-2">
<button
class="flex-1 rounded-md border border-slate-300 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50 disabled:opacity-50"
type="button"
:disabled="busy"
@click="handleRead"
>
读取数据
</button>
<button
class="flex-1 rounded-md bg-emerald-600 px-3 py-2 text-sm font-medium text-white hover:bg-emerald-500 disabled:opacity-50"
type="button"
:disabled="busy || !batch"
@click="handleSync"
>
同步到 BI
</button>
</div>
<section class="rounded-lg border border-slate-200 bg-white p-3 text-sm">
<h2 class="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-500">
数据预览
</h2>
<div class="flex justify-between">
<span class="text-slate-500">推广费用</span>
<span class="font-semibold text-rose-600">¥{{ totalFee.toFixed(2) }}</span>
</div>
<div class="mt-1 flex justify-between">
<span class="text-slate-500">数据条数</span>
<span class="font-medium">{{ itemCount }}</span>
</div>
<ul v-if="batch?.items?.length" class="mt-2 max-h-28 space-y-1 overflow-auto text-xs text-slate-600">
<li v-for="item in batch.items" :key="item.goodsId" class="flex justify-between gap-2">
<span class="truncate">{{ item.goodsId }}</span>
<span>¥{{ Number(item.feeAmount).toFixed(2) }}</span>
</li>
</ul>
</section>
<p v-if="syncResultText" class="text-xs text-emerald-700">{{ syncResultText }}</p>
<p v-if="errorText" class="text-xs text-rose-600">{{ errorText }}</p>
</div>
</template>
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ECBI 数据同步</title>
</head>
<body class="bg-slate-50 text-slate-900">
<div id="app"></div>
<script type="module" src="./main.ts"></script>
</body>
</html>
+6
View File
@@ -0,0 +1,6 @@
import { createApp } from 'vue';
import App from './App.vue';
import './styles.css';
createApp(App).mount('#app');
+49
View File
@@ -0,0 +1,49 @@
import type { ExtensionMessage, ExtensionResponse } from '@/shared/messages';
import { ExtensionError } from '@/shared/errors';
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
async function getActiveTabId(): Promise<number> {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const tabId = tabs[0]?.id;
if (tabId == null) {
throw new ExtensionError('NO_ACTIVE_TAB', '未找到当前标签页');
}
return tabId;
}
async function sendToActiveTab<T>(message: ExtensionMessage): Promise<T> {
const tabId = await getActiveTabId();
let response: ExtensionResponse | undefined;
try {
response = (await chrome.tabs.sendMessage(tabId, message)) as ExtensionResponse;
} catch {
throw new ExtensionError(
'PAGE_NOT_READY',
'无法连接页面脚本。请刷新目标页面后重试(需已注入 Content Script)。',
);
}
if (!response) {
throw new ExtensionError('PAGE_NOT_READY', '页面无响应');
}
if (!response.ok) {
throw new ExtensionError(
(response.code as never) || 'UNKNOWN',
response.message || '页面处理失败',
);
}
return response.data as T;
}
export async function fetchPageContext(): Promise<PageContext> {
return sendToActiveTab<PageContext>({ type: 'GET_PAGE_CONTEXT' });
}
export async function parseAdvertisingCostFromPage(
feeDate: string,
): Promise<AdvertisingCostBatch> {
return sendToActiveTab<AdvertisingCostBatch>({
type: 'PARSE_ADVERTISING_COST',
payload: { feeDate },
});
}
+10
View File
@@ -0,0 +1,10 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
html,
body {
margin: 0;
min-width: 360px;
min-height: 480px;
}
+11
View File
@@ -0,0 +1,11 @@
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',
} as const;
export const OPEN_SCOPES = {
pddShopRead: 'open:scope:pdd_shop:read',
pddGoodsAdFeeImport: 'open:scope:pdd_goods_ad_fee:import',
} as const;
+32
View File
@@ -0,0 +1,32 @@
export type ExtensionErrorCode =
| 'PLATFORM_NOT_SUPPORTED'
| 'PAGE_NOT_READY'
| 'DATA_PARSE_FAILED'
| 'INVALID_DATA'
| 'AUTH_FAILED'
| 'API_REQUEST_FAILED'
| 'API_BUSINESS_ERROR'
| 'NETWORK_ERROR'
| 'CONFIG_MISSING'
| 'NO_ACTIVE_TAB'
| 'UNKNOWN';
export class ExtensionError extends Error {
readonly code: ExtensionErrorCode;
constructor(code: ExtensionErrorCode, message: string) {
super(message);
this.name = 'ExtensionError';
this.code = code;
}
}
export function toUserMessage(error: unknown): string {
if (error instanceof ExtensionError) {
return error.message;
}
if (error instanceof Error && error.message) {
return error.message;
}
return '发生未知错误,请稍后重试';
}
+22
View File
@@ -0,0 +1,22 @@
import type { AdvertisingCostBatch, PageContext } from '@/types/advertisingCost';
export type ExtensionMessage =
| { type: 'GET_PAGE_CONTEXT' }
| { type: 'PARSE_ADVERTISING_COST'; payload: { feeDate: string } }
| { type: 'PING' };
export type ExtensionResponse =
| { ok: true; data: PageContext }
| { ok: true; data: AdvertisingCostBatch }
| { ok: true; data: { pong: true } }
| { ok: false; code: string; message: string };
export function isExtensionMessage(value: unknown): value is ExtensionMessage {
if (!value || typeof value !== 'object') return false;
const type = (value as { type?: unknown }).type;
return (
type === 'GET_PAGE_CONTEXT' ||
type === 'PARSE_ADVERTISING_COST' ||
type === 'PING'
);
}
+40
View File
@@ -0,0 +1,40 @@
export interface ExtensionSettings {
/** 例:https://host/api (不要末尾斜杠) */
apiBaseUrl: string;
/** Open API Key(非 JWT) */
apiKey: string;
/** 记住的渠道店铺 */
channelShopId?: number;
channelShopName?: string;
}
const STORAGE_KEY = 'ecbi.extension.settings';
const DEFAULT_SETTINGS: ExtensionSettings = {
apiBaseUrl: '',
apiKey: '',
};
export async function getSettings(): Promise<ExtensionSettings> {
const result = await chrome.storage.local.get(STORAGE_KEY);
const raw = result[STORAGE_KEY] as Partial<ExtensionSettings> | undefined;
return {
...DEFAULT_SETTINGS,
...raw,
apiBaseUrl: (raw?.apiBaseUrl ?? '').replace(/\/+$/, ''),
apiKey: raw?.apiKey ?? '',
};
}
export async function saveSettings(
patch: Partial<ExtensionSettings>,
): Promise<ExtensionSettings> {
const current = await getSettings();
const next: ExtensionSettings = {
...current,
...patch,
apiBaseUrl: (patch.apiBaseUrl ?? current.apiBaseUrl).replace(/\/+$/, ''),
};
await chrome.storage.local.set({ [STORAGE_KEY]: next });
return next;
}
+1
View File
@@ -0,0 +1 @@
export type { ExtensionSettings } from './settings';
@@ -0,0 +1,31 @@
/** 插件侧统一广告费模型(平台无关) */
export type PlatformType = 'pdd' | 'taobao' | 'jd' | 'mock' | 'unknown';
export interface AdvertisingCostItem {
goodsId: string;
feeAmount: number;
metadata?: Record<string, unknown>;
}
/**
* 一次读取/同步批次。
* channelShopId = BI channel_pdd_shop.id(不是 mallId)
* feeDate = Popup 所选日期 YYYY-MM-DD
*/
export interface AdvertisingCostBatch {
platform: PlatformType;
channelShopId: number;
feeDate: string;
items: AdvertisingCostItem[];
source: 'browser-extension';
importedAt: string;
}
export interface PageContext {
url: string;
title: string;
platform: PlatformType;
ready: boolean;
message?: string;
}
+8
View File
@@ -0,0 +1,8 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{vue,ts,html}'],
theme: {
extend: {},
},
plugins: [],
};
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"types": ["chrome", "vite/client", "node"],
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"],
"exclude": ["node_modules", "dist"]
}
+12
View File
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true,
"types": ["node"]
},
"include": ["vite.config.ts", "manifest.config.ts"]
}
+27
View File
@@ -0,0 +1,27 @@
import { crx } from '@crxjs/vite-plugin';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'node:path';
import { defineConfig } from 'vite';
import manifest from './manifest.config';
export default defineConfig({
plugins: [vue(), crx({ manifest })],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
},
},
build: {
sourcemap: true,
outDir: 'dist',
emptyOutDir: true,
},
server: {
port: 5173,
strictPort: true,
hmr: {
port: 5173,
},
},
});