Commit 43f6039d by liimin

fix: resolve merge conflicts and sync workspace changes

1 parent 3b9c4135
...@@ -2,29 +2,37 @@ import type { App } from "vue"; ...@@ -2,29 +2,37 @@ import type { App } from "vue";
import { import {
VButton, VButton,
VCard,
VCell, VCell,
VDropdownItem, VDropdownItem,
VDropdownMenu, VDropdownMenu,
VField, VField,
VImage,
VList, VList,
VNavBar, VNavBar,
VPicker, VPicker,
VPopup, VPopup,
VSearch, VSearch,
VSwiper,
VTabbar, VTabbar,
VTabs,
} from "@vui/mobile"; } from "@vui/mobile";
import "vant/lib/index.css"; import "vant/lib/index.css";
export function setupUI(app: App) { export function setupUI(app: App) {
app.component("VButton", VButton); app.component("VButton", VButton);
app.component("VCard", VCard);
app.component("VCell", VCell); app.component("VCell", VCell);
app.component("VDropdownItem", VDropdownItem); app.component("VDropdownItem", VDropdownItem);
app.component("VDropdownMenu", VDropdownMenu); app.component("VDropdownMenu", VDropdownMenu);
app.component("VField", VField); app.component("VField", VField);
app.component("VImage", VImage);
app.component("VList", VList); app.component("VList", VList);
app.component("VNavBar", VNavBar); app.component("VNavBar", VNavBar);
app.component("VPicker", VPicker); app.component("VPicker", VPicker);
app.component("VPopup", VPopup); app.component("VPopup", VPopup);
app.component("VSearch", VSearch); app.component("VSearch", VSearch);
app.component("VSwiper", VSwiper);
app.component("VTabbar", VTabbar); app.component("VTabbar", VTabbar);
app.component("VTabs", VTabs);
} }
# AI Anti-Pattern Registry
本文件是 AI 反模式注册表,记录 AI 在代码生成过程中犯过的错误。
AI 管线在构建 prompt 时会自动读取本文件,防止同类错误重复出现。
## 格式约定
每个条目使用 `---` 分隔的 JSON 元数据块 + Markdown 正文。
字段说明:
| 字段 | 必填 | 说明 |
|------|------|------|
| `id` | 是 | 唯一标识,格式 `AP-NNN` |
| `category` | 是 | 错误类别:`component-misuse` / `style-error` / `type-error` / `arch-drift` / `import-error` / `logic-error` / `template-error` / `other` |
| `scope` | 是 | 作用域:`vue-sfc` / `css` / `typescript` / `template` / `router` / `api` / `config` / `general` |
| `severity` | 是 | 严重级别:`high` / `medium` / `low` |
| `pattern` | 是 | 错误模式简述(一句话) |
| `correction` | 是 | 正确做法简述(一句话) |
| `capturedAt` | 是 | 捕获时间(ISO 8601) |
| `capturedBy` | 否 | 捕获方式:`auto-lint` / `auto-typecheck` / `manual` |
| `sourceFile` | 否 | 首次发现错误的文件路径 |
正文部分包含:描述、错误示例、正确示例。
## 条目列表
---
{
"id": "AP-001",
"category": "component-misuse",
"scope": "vue-sfc",
"severity": "high",
"pattern": "重复 import 已全局注册的 VUI 组件",
"correction": "全局注册的组件直接在 template 中使用,禁止在 script 中 import",
"capturedAt": "2026-06-17T00:00:00.000Z",
"capturedBy": "manual",
"sourceFile": ""
}
---
### 描述
VUI 组件(如 VButton、VCell、VSearch 等)已在 `src/ui.ts` 中通过 `app.component()` 全局注册。
AI 经常在 `<script setup>` 中再次 import 这些组件,导致 vue/no-unused-import 或重复注册警告。
### 错误示例
```vue
<script setup lang="ts">
import { VSearch } from "@vui/mobile"; // 已全局注册,不需要 import
import { ref } from "vue";
</script>
```
### 正确示例
```vue
<script setup lang="ts">
import { ref } from "vue";
// VSearch 已在 ui.ts 中全局注册,直接在 template 中使用
</script>
```
---
{
"id": "AP-002",
"category": "style-error",
"scope": "css",
"severity": "medium",
"pattern": "CSS 属性顺序不符合 recess-order 规则",
"correction": "严格按 position → display → box-model → typography → visual → animation 顺序排列",
"capturedAt": "2026-06-17T00:00:00.000Z",
"capturedBy": "manual",
"sourceFile": ""
}
---
### 描述
AI 生成的 CSS 经常不按 stylelint-config-recess-order 要求的顺序排列属性。
常见错误:`text-overflow` 放在 `line-height` 之前,`white-space` 远离 `overflow`。
### 错误示例
```css
.title {
text-overflow: ellipsis;
line-height: 1.5;
white-space: nowrap;
overflow: hidden;
font-size: 14px;
}
```
### 正确示例
```css
.title {
overflow: hidden;
font-size: 14px;
line-height: 1.5;
white-space: nowrap;
text-overflow: ellipsis;
}
```
---
{
"id": "AP-003",
"category": "type-error",
"scope": "typescript",
"severity": "medium",
"pattern": "用宽泛 string 替代联合类型",
"correction": "必须使用组件库定义的精确定义类型,不能用 string 偷懒",
"capturedAt": "2026-06-17T00:00:00.000Z",
"capturedBy": "manual",
"sourceFile": ""
}
---
### 描述
AI 在定义 VUI / Element Plus 组件的 columns、align、status 等属性时,经常用 `string` 代替精确的联合类型,导致 TypeScript 类型检查失败。
### 错误示例
```ts
interface TableColumn {
prop: string;
align: string; // 太宽泛
status: string; // 太宽泛
}
```
### 正确示例
```ts
interface TableColumn {
prop: string;
align: "left" | "center" | "right";
status: "success" | "warning" | "danger" | "info";
}
```
---
{
"id": "AP-004",
"category": "template-error",
"scope": "vue-sfc",
"severity": "high",
"pattern": "template v-for 的 :key 放在了子元素上而不是 template 标签上",
"correction": "Vue 3.4+ 要求 :key 必须放在 <template v-for> 标签上,不能放在内部子元素",
"capturedAt": "2026-06-17T00:00:00.000Z",
"capturedBy": "auto-lint",
"sourceFile": "apps/web/ai-previews/diaobo-preview/src/views/car1/index.vue"
}
---
### 描述
Vue 3.4+ 要求 `<template v-for>` 的 `:key` **必须放在 `<template>` 标签上**。
早期版本(Vue 3.3 及以前)的 `vue/no-v-for-template-key` 规则曾要求放在子元素上,但该规则在 Vue 3.4 中已被废弃,替换为 `vue/no-v-for-template-key-on-child`。
Vue 3.4+ 编译器会报:`<template v-for> key should be placed on the <template> tag.`
### 错误示例
```vue
<template v-for="item in list">
<div :key="item.id">{{ item.name }}</div>
</template>
```
### 正确示例
```vue
<template v-for="item in list" :key="item.id">
<div>{{ item.name }}</div>
</template>
```
---
{
"id": "AP-005",
"category": "template-error",
"scope": "vue-sfc",
"severity": "high",
"pattern": "Vue template 属性语法损坏:属性名含引号或属性错位拼接",
"correction": "确保每个 HTML/Vue 属性在同一行内完整书写,属性名不含引号,属性值用成对引号包裹",
"capturedAt": "2026-06-17T00:00:00.000Z",
"capturedBy": "auto-lint",
"sourceFile": "apps/web/ai-previews/testpage-preview/src/views/car/index.vue"
}
---
### 描述
AI 生成的 Vue template 中,元素的属性被拆碎并错位拼接,导致属性名包含引号字符(`"`、`'`)或属性值跨行断裂。
Vue 编译器会报 `Attribute name cannot contain U+0022 ("), U+0027 ('), and U+003C (<)` 错误。
这类错误通常发生在 AI 对复杂多属性元素(如带 `:class`、`@click`、`v-if` 的标签)生成时,属性被错误地拆分成多行碎片。
### 错误示例
```vue
<span active:
"exterior"
activeView="=="
:class="["
exterior""@click="activeView = "
toggle-item",
{
}]">
外观
</span>
```
### 正确示例
```vue
<span
:class="['toggle-item', { active: activeView === 'exterior' }]"
@click="activeView = 'exterior'"
>
外观
</span>
```
{
"$schema": "../../../../../../contracts/ai/component-manifest-item.schema.json",
"name": "card",
"exportName": "VCard",
"source": "src/components/VCard/VCard.vue",
"category": "display",
"description": "移动端商品卡片组件,基于 Vant 4 Card,支持标题、描述、缩略图、价格等展示。",
"semanticRoles": ["product-card", "list-item-card", "info-card"],
"supportedKinds": ["CARD", "PRODUCT_CARD"],
"supportedScopes": ["list", "section"],
"priority": 5,
"props": [
{ "name": "title", "type": "string", "description": "标题。" },
{ "name": "desc", "type": "string", "description": "描述。" },
{ "name": "thumb", "type": "string", "description": "左侧图片 URL。" },
{ "name": "thumbLink", "type": "string", "description": "点击缩略图的跳转链接。" },
{ "name": "price", "type": "number | string", "description": "商品价格。" },
{ "name": "num", "type": "number | string", "description": "商品数量。" },
{ "name": "originPrice", "type": "number | string", "description": "商品原价,显示为划线价。" },
{ "name": "currency", "type": "string", "description": "货币符号。", "default": "'¥'" },
{ "name": "tag", "type": "string", "description": "图片左上角标签文字。" },
{ "name": "centered", "type": "boolean", "description": "是否垂直居中布局。", "default": "false" },
{ "name": "full", "type": "boolean", "description": "是否通栏卡片(无边距圆角)。", "default": "false" }
],
"events": [
{ "name": "click", "description": "卡片点击事件。", "payload": "MouseEvent" },
{ "name": "clickThumb", "description": "缩略图点击事件。" }
],
"slots": [
{ "name": "default", "description": "卡片内容区域。" },
{ "name": "title", "description": "自定义标题。" },
{ "name": "desc", "description": "自定义描述。" },
{ "name": "price", "description": "自定义价格。" },
{ "name": "price-top", "description": "价格上方自定义内容。" },
{ "name": "bottom", "description": "价格下方自定义内容。" },
{ "name": "thumb", "description": "自定义缩略图。" },
{ "name": "tag", "description": "自定义标签。" },
{ "name": "footer", "description": "底部操作区域。" },
{ "name": "header", "description": "顶部自定义内容。" },
{ "name": "tags", "description": "描述下方标签区域。" }
],
"figmaMapping": {
"keywords": ["card", "product card", "商品卡片", "列表项卡片"],
"nodeTypes": ["FRAME", "COMPONENT", "INSTANCE"],
"variantHints": ["thumb", "price", "tag", "desc"]
},
"usageGuidance": {
"recommendedScenarios": ["商品列表项", "订单列表项", "信息展示卡片"],
"avoidScenarios": ["纯文本信息展示(用 VCell)", "复杂表单容器"],
"dependencies": ["vant"]
}
}
<template>
<van-card
class="vui-card"
:class="{
'vui-card--centered': centered,
'vui-card--full': full,
}"
:title="title"
:desc="desc"
:thumb="thumb"
:price="price"
:num="num"
:origin-price="originPrice"
:tag="tag"
:currency="currency"
:thumb-link="thumbLink"
v-bind="$attrs"
@click="handleClick"
@click-thumb="handleClickThumb"
>
<template v-if="$slots.tag || tag" #tag>
<slot name="tag">
{{ tag }}
</slot>
</template>
<template v-if="$slots.title" #title>
<slot name="title" />
</template>
<template v-if="$slots.desc" #desc>
<slot name="desc" />
</template>
<template v-if="$slots.price" #price>
<slot name="price" />
</template>
<template v-if="$slots['price-top']" #price-top>
<slot name="price-top" />
</template>
<template v-if="$slots['bottom']" #bottom>
<slot name="bottom" />
</template>
<template v-if="$slots['thumb']" #thumb>
<slot name="thumb" />
</template>
<template v-if="$slots.footer" #footer>
<slot name="footer" />
</template>
<template v-if="$slots.header" #header>
<slot name="header" />
</template>
<template v-if="$slots.tags" #tags>
<slot name="tags" />
</template>
<slot />
</van-card>
</template>
<script setup lang="ts">
import { Card as vanCard } from "vant";
defineOptions({ name: "VCard" });
defineProps<{
centered?: boolean;
currency?: string;
desc?: string;
full?: boolean;
num?: number | string;
originPrice?: number | string;
price?: number | string;
tag?: string;
thumb?: string;
thumbLink?: string;
title?: string;
}>();
const emit = defineEmits<{
(event: "click", value: MouseEvent): void;
(event: "clickThumb"): void;
}>();
function handleClick(event: MouseEvent) {
emit("click", event);
}
function handleClickThumb() {
emit("clickThumb");
}
</script>
<style scoped>
.vui-card--centered {
display: flex;
align-items: center;
}
.vui-card--full {
margin: 0;
border-radius: 0;
}
</style>
import type { DefineComponent } from "vue";
declare const VCard: DefineComponent<{
centered?: boolean;
currency?: string;
desc?: string;
full?: boolean;
num?: number | string;
originPrice?: number | string;
price?: number | string;
tag?: string;
thumb?: string;
thumbLink?: string;
title?: string;
}>;
export default VCard;
export { default } from "./VCard.vue";
{
"$schema": "../../../../../../contracts/ai/component-manifest-item.schema.json",
"name": "image",
"exportName": "VImage",
"source": "src/components/VImage/VImage.vue",
"category": "display",
"description": "移动端图片组件,基于 Vant 4 Image,支持懒加载、加载占位、错误占位、多种裁剪模式。对应 Element Plus 的 el-image。",
"semanticRoles": ["product-image", "avatar", "thumbnail", "banner-image"],
"supportedKinds": ["IMAGE", "PHOTO", "PICTURE"],
"supportedScopes": ["list", "page", "section"],
"priority": 5,
"props": [
{ "name": "src", "type": "string", "description": "图片 URL。" },
{ "name": "fit", "type": "'contain' | 'cover' | 'fill' | 'none' | 'scale-down'", "description": "图片填充模式。", "default": "'fill'" },
{ "name": "position", "type": "'center' | 'top' | 'right' | 'bottom' | 'left'", "description": "图片显示位置(类似 object-position)。", "default": "'center'" },
{ "name": "alt", "type": "string", "description": "替代文本。" },
{ "name": "width", "type": "number | string", "description": "宽度,默认单位为 px。" },
{ "name": "height", "type": "number | string", "description": "高度,默认单位为 px。" },
{ "name": "radius", "type": "'sm' | 'md' | 'lg' | 'xl' | number | string", "description": "圆角大小。sm=4px, md=8px, lg=12px, xl=16px。" },
{ "name": "round", "type": "boolean", "description": "是否显示为圆形。", "default": "false" },
{ "name": "lazyLoad", "type": "boolean", "description": "是否开启懒加载。", "default": "false" },
{ "name": "showLoading", "type": "boolean", "description": "是否展示加载中提示。", "default": "true" },
{ "name": "showError", "type": "boolean", "description": "是否展示加载失败提示。", "default": "true" },
{ "name": "errorIcon", "type": "string", "description": "加载失败图标名称。" },
{ "name": "loadingIcon", "type": "string", "description": "加载中图标名称。" }
],
"events": [
{ "name": "click", "description": "点击图片时触发。", "payload": "MouseEvent" },
{ "name": "load", "description": "图片加载成功时触发。", "payload": "Event" },
{ "name": "error", "description": "图片加载失败时触发。", "payload": "Event" }
],
"slots": [
{ "name": "loading", "description": "自定义加载中内容。" },
{ "name": "error", "description": "自定义加载失败内容。" }
],
"figmaMapping": {
"keywords": ["image", "photo", "picture", "图片", "照片", "缩略图", "avatar"],
"nodeTypes": ["RECTANGLE", "COMPONENT", "INSTANCE"],
"variantHints": ["cover", "contain", "round", "radius"]
},
"usageGuidance": {
"recommendedScenarios": ["商品图片", "用户头像", "缩略图", "Banner 图"],
"avoidScenarios": ["纯图标展示(用 van-icon)", "背景图片(用 CSS background)"],
"dependencies": ["vant"]
}
}
<template>
<van-image
class="vui-image"
:class="{
'vui-image--round': round,
[`vui-image--radius-${radius}`]: radius,
}"
:src="src"
:fit="fit"
:position="position"
:alt="alt"
:width="width"
:height="height"
:radius="computedRadius"
:round="round"
:lazy-load="lazyLoad"
:show-loading="showLoading"
:show-error="showError"
:error-icon="errorIcon"
:loading-icon="loadingIcon"
v-bind="$attrs"
@click="handleClick"
@load="handleLoad"
@error="handleError"
>
<template v-if="$slots.loading" #loading>
<slot name="loading" />
</template>
<template v-if="$slots.error" #error>
<slot name="error" />
</template>
</van-image>
</template>
<script setup lang="ts">
import { computed } from "vue";
import { Image as vanImage } from "vant";
defineOptions({ name: "VImage" });
const props = defineProps<{
alt?: string;
errorIcon?: string;
fit?: "contain" | "cover" | "fill" | "none" | "scale-down";
height?: number | string;
lazyLoad?: boolean;
loadingIcon?: string;
position?: "bottom" | "center" | "left" | "right" | "top";
radius?: "lg" | "md" | "sm" | "xl" | number | string;
round?: boolean;
showError?: boolean;
showLoading?: boolean;
src?: string;
width?: number | string;
}>();
const radiusMap: Record<string, string> = {
sm: "4px",
md: "8px",
lg: "12px",
xl: "16px",
};
const computedRadius = computed(() => {
if (typeof props.radius === "number") return `${props.radius}px`;
if (typeof props.radius === "string" && props.radius in radiusMap) return radiusMap[props.radius];
return props.radius;
});
const emit = defineEmits<{
(event: "click", value: MouseEvent): void;
(event: "load", value: Event): void;
(event: "error", value: Event): void;
}>();
function handleClick(event: MouseEvent) {
emit("click", event);
}
function handleLoad(event: Event) {
emit("load", event);
}
function handleError(event: Event) {
emit("error", event);
}
</script>
<style scoped>
.vui-image--round {
overflow: hidden;
}
</style>
import type { DefineComponent } from "vue";
declare const VImage: DefineComponent<{
alt?: string;
errorIcon?: string;
fit?: "contain" | "cover" | "fill" | "none" | "scale-down";
height?: number | string;
lazyLoad?: boolean;
loadingIcon?: string;
position?: "bottom" | "center" | "left" | "right" | "top";
radius?: "lg" | "md" | "sm" | "xl" | number | string;
round?: boolean;
showError?: boolean;
showLoading?: boolean;
src?: string;
width?: number | string;
}>;
export default VImage;
export { default } from "./VImage.vue";
{
"$schema": "../../../../../../contracts/ai/component-manifest-item.schema.json",
"name": "swiper",
"exportName": "VSwiper",
"source": "src/components/VSwiper/VSwiper.vue",
"category": "display",
"description": "移动端轮播图组件,基于 Vant 4 Swipe,支持自动播放、循环、指示器等。",
"semanticRoles": ["image-carousel", "banner", "hero-gallery"],
"supportedKinds": ["SWIPE", "CAROUSEL", "GALLERY"],
"supportedScopes": ["page", "section"],
"priority": 5,
"props": [
{ "name": "items", "type": "(string | Record<string, unknown>)[]", "description": "轮播项数据,string 为图片 URL,object 为自定义内容。" },
{ "name": "autoplay", "type": "number | string", "description": "自动播放间隔(ms),0 或不传则不自动播放。", "default": "0" },
{ "name": "duration", "type": "number | string", "description": "动画时长(ms)。", "default": "500" },
{ "name": "loop", "type": "boolean", "description": "是否循环播放。", "default": "true" },
{ "name": "vertical", "type": "boolean", "description": "是否纵向滚动。", "default": "false" },
{ "name": "showIndicators", "type": "boolean", "description": "是否显示指示器。", "default": "true" },
{ "name": "indicatorColor", "type": "string", "description": "指示器颜色。" },
{ "name": "height", "type": "number | string", "description": "轮播高度。" },
{ "name": "width", "type": "number | string", "description": "轮播宽度。" },
{ "name": "touchable", "type": "boolean", "description": "是否可手势滑动。", "default": "true" },
{ "name": "initialSwipe", "type": "number", "description": "初始位置索引。", "default": "0" },
{ "name": "lazyRender", "type": "boolean", "description": "是否延迟渲染未展示的轮播。", "default": "false" }
],
"events": [
{ "name": "change", "description": "当前轮播切换时触发。", "payload": "number" }
],
"slots": [
{ "name": "default", "description": "自定义轮播内容(van-swipe-item 列表)。" },
{ "name": "item", "description": "使用 items 数据时自定义每项渲染。", "scope": "{ item, index }" },
{ "name": "indicator", "description": "自定义指示器。", "scope": "{ active, total }" }
],
"figmaMapping": {
"keywords": ["swipe", "carousel", "slider", "banner", "轮播", "轮播图"],
"nodeTypes": ["FRAME", "COMPONENT", "INSTANCE"],
"variantHints": ["autoplay", "indicator", "loop"]
},
"usageGuidance": {
"recommendedScenarios": ["商品图片轮播", "广告 banner", "图片画廊"],
"avoidScenarios": ["静态单图", "Tab 切换"],
"dependencies": ["vant"]
}
}
<template>
<van-swipe :autoplay="autoplay"
class="vui-swiper"
:duration="duration"
:height="height"
:indicator-color="indicatorColor"
:initial-swipe="initialSwipe"
:lazy-render="lazyRender"
:loop="loop"
:show-indicators="showIndicators"
:touchable="touchable"
:vertical="vertical"
:width="width"
v-bind="$attrs"
@change="handleChange">
<slot>
<van-swipe-item v-for="(item, index) in items" :key="index">
<slot :index="index"
:item="item"
name="item">
<img v-if="typeof item === 'string'"
:alt="`slide-${index}`"
class="vui-swiper__image"
:src="item" />
<div v-else class="vui-swiper__custom">
{{ item }}
</div>
</slot>
</van-swipe-item>
</slot>
<template v-if="$slots.indicator" #indicator="{ active, total }">
<slot :active="active"
name="indicator"
:total="total" />
</template>
</van-swipe>
</template>
<script setup lang="ts">
import { Swipe as vanSwipe, SwipeItem as vanSwipeItem } from "vant";
defineOptions({ name: "VSwiper" });
defineProps<{
autoplay?: number | string;
duration?: number | string;
height?: number | string;
indicatorColor?: string;
initialSwipe?: number;
items?: SwiperItem[];
lazyRender?: boolean;
loop?: boolean;
showIndicators?: boolean;
touchable?: boolean;
vertical?: boolean;
width?: number | string;
}>();
const emit = defineEmits<{
(event: "change", index: number): void;
}>();
export type SwiperItem = Record<string, unknown> | string;
function handleChange(index: number) {
emit("change", index);
}
</script>
<style scoped>
.vui-swiper__image {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.vui-swiper__custom {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
</style>
import type { DefineComponent } from "vue";
export type SwiperItem = string | Record<string, unknown>;
declare const VSwiper: DefineComponent<{
autoplay?: number | string;
duration?: number | string;
height?: number | string;
indicatorColor?: string;
initialSwipe?: number;
items?: SwiperItem[];
lazyRender?: boolean;
loop?: boolean;
showIndicators?: boolean;
touchable?: boolean;
vertical?: boolean;
width?: number | string;
}>;
export default VSwiper;
export { default } from "./VSwiper.vue";
{
"$schema": "../../../../../../contracts/ai/component-manifest-item.schema.json",
"name": "tabs",
"exportName": "VTabs",
"source": "src/components/VTabs/VTabs.vue",
"category": "navigation",
"description": "移动端标签页组件,基于 Vant 4 Tabs,支持 line/card 样式、滑动切换、内容懒加载。对应 Element Plus 的 el-tabs/el-tab-pane。",
"semanticRoles": ["section-tabs", "content-tabs", "image-type-switcher"],
"supportedKinds": ["TABS", "TAB_BAR", "SEGMENTED_CONTROL"],
"supportedScopes": ["page", "section"],
"priority": 5,
"props": [
{ "name": "items", "type": "TabItem[]", "description": "标签页数据,每项包含 title、name、content、disabled 等。" },
{ "name": "modelValue", "type": "number | string", "description": "当前激活的标签 name 或 index。" },
{ "name": "type", "type": "'line' | 'card'", "description": "标签样式类型。", "default": "'line'" },
{ "name": "color", "type": "string", "description": "标签主题色。" },
{ "name": "sticky", "type": "boolean", "description": "是否使用粘性定位。", "default": "false" },
{ "name": "shrink", "type": "boolean", "description": "是否开启左侧收缩布局。", "default": "false" },
{ "name": "animated", "type": "boolean", "description": "是否开启切换动画。", "default": "true" },
{ "name": "swipeable", "type": "boolean", "description": "是否开启手势滑动切换。", "default": "false" },
{ "name": "ellipsis", "type": "boolean", "description": "是否省略过长的标题文字。", "default": "true" },
{ "name": "lazyRender", "type": "boolean", "description": "是否延迟渲染未展示的标签页。", "default": "true" },
{ "name": "scrollspy", "type": "boolean", "description": "是否开启滚动导航。", "default": "false" },
{ "name": "titleActiveColor", "type": "string", "description": "标题选中态颜色。" },
{ "name": "titleInactiveColor", "type": "string", "description": "标题默认态颜色。" },
{ "name": "lineWidth", "type": "number | string", "description": "底部条宽度。" },
{ "name": "lineHeight", "type": "number | string", "description": "底部条高度。" },
{ "name": "border", "type": "boolean", "description": "是否展示外边框。", "default": "true" }
],
"events": [
{ "name": "update:modelValue", "description": "激活标签变化时触发。", "payload": "number | string" },
{ "name": "change", "description": "切换标签时触发。", "payload": "number | string" },
{ "name": "clickTab", "description": "点击标签时触发。", "payload": "{ name, title }" }
],
"slots": [
{ "name": "default", "description": "自定义标签页内容(van-tab 列表)。" },
{ "name": "tab-content", "description": "使用 items 数据时自定义标签页内容。", "scope": "{ item, index }" }
],
"figmaMapping": {
"keywords": ["tabs", "tab bar", "segment", "标签", "tab", "切换"],
"nodeTypes": ["FRAME", "COMPONENT", "INSTANCE"],
"variantHints": ["active", "inactive", "line", "card"]
},
"usageGuidance": {
"recommendedScenarios": ["图片类型切换(外观/内饰)", "内容区域切换", "导航标签"],
"avoidScenarios": ["底部全局导航(用 VTabbar)", "下拉筛选(用 VDropdownMenu)"],
"dependencies": ["vant"]
}
}
<template>
<van-tabs
class="vui-tabs"
:model-value="modelValue"
:type="type"
:color="color"
:sticky="sticky"
:shrink="shrink"
:animated="animated"
:ellipsis="ellipsis"
:swipeable="swipeable"
:lazy-render="lazyRender"
:scrollspy="scrollspy"
:line-width="lineWidth"
:line-height="lineHeight"
:duration="duration"
:title-active-color="titleActiveColor"
:title-inactive-color="titleInactiveColor"
:border="border"
v-bind="$attrs"
@update:model-value="handleUpdate"
@change="handleChange"
@click-tab="handleClickTab"
>
<slot>
<van-tab v-for="(item, index) in items" :key="item.name ?? index" :name="item.name ?? index" :title="item.title" :disabled="item.disabled" :badge="item.badge" :dot="item.dot">
<slot name="tab-content" :item="item" :index="index">
{{ item.content }}
</slot>
</van-tab>
</slot>
</van-tabs>
</template>
<script setup lang="ts">
import { Tab as vanTab, Tabs as vanTabs } from "vant";
defineOptions({ name: "VTabs" });
export type TabItem = {
badge?: number | string;
content?: string;
disabled?: boolean;
dot?: boolean;
name?: number | string;
title: string;
};
defineProps<{
animated?: boolean;
border?: boolean;
color?: string;
duration?: number | string;
ellipsis?: boolean;
items?: TabItem[];
lazyRender?: boolean;
lineHeight?: number | string;
lineWidth?: number | string;
modelValue?: number | string;
scrollspy?: boolean;
shrink?: boolean;
sticky?: boolean;
swipeable?: boolean;
titleActiveColor?: string;
titleInactiveColor?: string;
type?: "card" | "line";
}>();
const emit = defineEmits<{
(event: "update:modelValue", value: number | string): void;
(event: "change", value: number | string): void;
(event: "clickTab", value: { name: number | string; title: string }): void;
}>();
function handleUpdate(value: number | string) {
emit("update:modelValue", value);
}
function handleChange(value: number | string) {
emit("change", value);
}
function handleClickTab({ name, title }: { name: number | string; title: string }) {
emit("clickTab", { name, title });
}
</script>
import type { DefineComponent } from "vue";
export type TabItem = {
badge?: number | string;
content?: string;
disabled?: boolean;
dot?: boolean;
name?: number | string;
title: string;
};
declare const VTabs: DefineComponent<{
animated?: boolean;
border?: boolean;
color?: string;
duration?: number | string;
ellipsis?: boolean;
items?: TabItem[];
lazyRender?: boolean;
lineHeight?: number | string;
lineWidth?: number | string;
modelValue?: number | string;
scrollspy?: boolean;
shrink?: boolean;
sticky?: boolean;
swipeable?: boolean;
titleActiveColor?: string;
titleInactiveColor?: string;
type?: "card" | "line";
}>;
export default VTabs;
export { default } from "./VTabs.vue";
#!/usr/bin/env node
/**
* AI Contribution Analytics
*
* 从三个数据源采集 AI 贡献数据,生成 HTML 可视化报告:
* 1. 文件头 @ai-co-author 注释扫描
* 2. Git log 历史解析
* 3. .ai-attribution.json 归因清单
*
* 用法:
* pnpm run ai:analytics
* pnpm run ai:analytics -- --output reports/
* pnpm run ai:analytics -- --since "30 days ago"
* pnpm run ai:analytics -- --scan-dir apps/web --scan-dir packages
*/
import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { requireWorkspaceRoot } from "./workspace-root.mjs";
const repoRoot = requireWorkspaceRoot();
// ── CLI ──
function parseCliArgs() {
const args = process.argv.slice(2);
const parsed = { outputDir: "", since: "", scanDirs: [] };
for (let i = 0; i < args.length; i++) {
const arg = args[i];
const next = args[i + 1];
if (arg === "--output" && next) {
parsed.outputDir = next;
i++;
} else if (arg === "--since" && next) {
parsed.since = next;
i++;
} else if (arg === "--scan-dir" && next) {
parsed.scanDirs.push(next);
i++;
}
}
return parsed;
}
// ── Data Collection: File Headers ──
const SCANNABLE_EXTENSIONS = new Set([
".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
".vue", ".uvue", ".svelte",
".uts", ".css", ".scss",
]);
const CO_AUTHOR_REGEX = /@ai-co-author\s+(\S+)\s*\|\s*(\S+)\s*\|\s*(\S+)/;
function scanFileHeaders(baseDir, scanDirs) {
const results = [];
const dirs = scanDirs.length > 0
? scanDirs.map((d) => path.resolve(baseDir, d))
: [baseDir];
for (const dir of dirs) {
walkDir(dir, baseDir, results);
}
return results;
}
function walkDir(dir, baseDir, results) {
if (!fs.existsSync(dir)) return;
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (shouldSkipDir(entry.name)) continue;
walkDir(fullPath, baseDir, results);
continue;
}
if (!entry.isFile()) continue;
const ext = path.extname(entry.name).toLowerCase();
if (!SCANNABLE_EXTENSIONS.has(ext)) continue;
const info = readCoAuthorHeader(fullPath);
if (info) {
results.push({
filePath: normalizePath(path.relative(baseDir, fullPath)),
extension: ext,
lineCount: countLines(fullPath),
...info,
});
}
}
}
function shouldSkipDir(name) {
return (
name === "node_modules" ||
name === ".git" ||
name === "dist" ||
name === ".output" ||
name === ".nuxt" ||
name === ".turbo" ||
name === "uni_modules"
);
}
function readCoAuthorHeader(filePath) {
try {
const fd = fs.openSync(filePath, "r");
const buf = Buffer.alloc(1024);
const bytesRead = fs.readSync(fd, buf, 0, 1024, 0);
fs.closeSync(fd);
const head = buf.toString("utf8", 0, bytesRead);
const lines = head.split(/\r?\n/).slice(0, 10);
for (const line of lines) {
const match = line.match(CO_AUTHOR_REGEX);
if (match) {
return {
tool: match[1],
provider: match[2].split("/")[0] || "unknown",
model: match[2].split("/").slice(1).join("/") || "unknown",
timestamp: match[3],
source: "file-header",
};
}
}
} catch { /* skip unreadable */ }
return null;
}
function countLines(filePath) {
try {
const content = fs.readFileSync(filePath, "utf8");
return content.split(/\r?\n/).length;
} catch {
return 0;
}
}
// ── Data Collection: Git Log ──
function parseGitLog(since) {
const sinceArg = since ? `--since="${since}"` : "";
const format = "%H|%ai|%s";
const cmd = `git log --all ${sinceArg} --format="${format}" --diff-filter=A -- "*.ts" "*.tsx" "*.vue" "*.js" "*.mjs" "*.uvue" "*.uts"`;
const result = childProcess.spawnSync(cmd, {
cwd: repoRoot,
shell: true,
encoding: "utf8",
});
if (result.status !== 0 || !result.stdout) return [];
const commits = [];
for (const line of result.stdout.trim().split(/\r?\n/)) {
if (!line) continue;
const parts = line.split("|");
if (parts.length < 3) continue;
commits.push({
hash: parts[0],
date: parts[1].trim(),
message: parts.slice(2).join("|").trim(),
});
}
const gitRecords = [];
for (const commit of commits) {
const filesResult = childProcess.spawnSync(
`git diff-tree --no-commit-id -r --name-only --diff-filter=A ${commit.hash}`,
{ cwd: repoRoot, shell: true, encoding: "utf8" },
);
if (filesResult.status !== 0 || !filesResult.stdout) continue;
const files = filesResult.stdout.trim().split(/\r?\n/).filter(Boolean);
for (const file of files) {
const showResult = childProcess.spawnSync(
`git show ${commit.hash}:${file}`,
{ cwd: repoRoot, shell: true, encoding: "utf8", maxBuffer: 1024 },
);
if (showResult.status !== 0 || !showResult.stdout) continue;
const headLines = showResult.stdout.split(/\r?\n/).slice(0, 10);
for (const line of headLines) {
const match = line.match(CO_AUTHOR_REGEX);
if (match) {
gitRecords.push({
filePath: normalizePath(file),
tool: match[1],
provider: match[2].split("/")[0] || "unknown",
model: match[2].split("/").slice(1).join("/") || "unknown",
timestamp: match[3],
commitHash: commit.hash.slice(0, 8),
commitDate: commit.date,
commitMessage: commit.message,
source: "git-log",
});
break;
}
}
}
}
return gitRecords;
}
// ── Data Collection: Attribution Manifests ──
function scanAttributionManifests(baseDir) {
const results = [];
walkForManifests(baseDir, baseDir, results);
return results;
}
function walkForManifests(dir, baseDir, results) {
if (!fs.existsSync(dir)) return;
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (shouldSkipDir(entry.name)) continue;
walkForManifests(fullPath, baseDir, results);
continue;
}
if (entry.name === ".ai-attribution.json") {
try {
const data = JSON.parse(fs.readFileSync(fullPath, "utf8"));
const relDir = normalizePath(path.relative(baseDir, path.dirname(fullPath)));
for (const file of Array.isArray(data.files) ? data.files : []) {
results.push({
filePath: `${relDir}/${file.path || "unknown"}`,
provider: data.provider || file.provider || "unknown",
model: data.model || file.model || "unknown",
timestamp: data.generatedAt || "unknown",
language: file.language || "",
purpose: file.purpose || "",
source: "attribution-manifest",
});
}
} catch { /* skip malformed */ }
}
}
}
// ── Merge & Dedup ──
function mergeRecords(fileHeaders, gitRecords, manifests) {
const byFile = new Map();
const priority = { "file-header": 0, "attribution-manifest": 1, "git-log": 2 };
const all = [...fileHeaders, ...manifests, ...gitRecords];
for (const record of all) {
const existing = byFile.get(record.filePath);
if (!existing || (priority[record.source] ?? 9) < (priority[existing.source] ?? 9)) {
byFile.set(record.filePath, record);
}
}
return [...byFile.values()];
}
// ── Aggregation ──
function aggregate(records) {
const stats = {
totalFiles: records.length,
totalLines: 0,
byProvider: {},
byModel: {},
byExtension: {},
byDirectory: {},
byMonth: {},
bySource: {},
timeline: [],
};
for (const r of records) {
stats.totalLines += r.lineCount || 0;
increment(stats.byProvider, r.provider || "unknown");
increment(stats.byModel, `${r.provider}/${r.model}`);
increment(stats.byExtension, r.extension || "unknown");
increment(stats.bySource, r.source || "unknown");
const dir = getTopDirs(r.filePath);
increment(stats.byDirectory, dir);
const month = parseMonth(r.timestamp || r.commitDate);
if (month) {
increment(stats.byMonth, month);
}
if (r.timestamp || r.commitDate) {
stats.timeline.push({
date: r.timestamp || r.commitDate,
file: r.filePath,
provider: r.provider,
model: r.model,
});
}
}
stats.timeline.sort((a, b) => new Date(a.date) - new Date(b.date));
return stats;
}
function increment(obj, key) {
if (!obj[key]) obj[key] = 0;
obj[key]++;
}
function getTopDirs(filePath) {
const parts = normalizePath(filePath).split("/");
if (parts.length >= 3) return `${parts[0]}/${parts[1]}/${parts[2]}`;
if (parts.length >= 2) return `${parts[0]}/${parts[1]}`;
return parts[0] || "root";
}
function parseMonth(dateStr) {
if (!dateStr || dateStr === "unknown") return null;
try {
const d = new Date(dateStr);
if (Number.isNaN(d.getTime())) return null;
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
} catch {
return null;
}
}
// ── HTML Report ──
function generateHtmlReport(stats, records) {
const generatedAt = new Date().toISOString();
const providerEntries = Object.entries(stats.byProvider).sort((a, b) => b[1] - a[1]);
const modelEntries = Object.entries(stats.byModel).sort((a, b) => b[1] - a[1]);
const extEntries = Object.entries(stats.byExtension).sort((a, b) => b[1] - a[1]);
const dirEntries = Object.entries(stats.byDirectory).sort((a, b) => b[1] - a[1]);
const monthEntries = Object.entries(stats.byMonth).sort((a, b) => a[0].localeCompare(b[0]));
const recentFiles = records
.filter((r) => r.timestamp && r.timestamp !== "unknown")
.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
.slice(0, 50);
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Venus AI Contribution Analytics</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0f172a; color: #e2e8f0; padding: 2rem; }
h1 { font-size: 1.75rem; margin-bottom: 0.5rem; color: #f8fafc; }
.subtitle { color: #94a3b8; margin-bottom: 2rem; font-size: 0.875rem; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1.5rem; margin-bottom: 2rem; }
.card { background: #1e293b; border-radius: 12px; padding: 1.5rem; border: 1px solid #334155; }
.card h2 { font-size: 0.875rem; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 1rem; }
.stat-value { font-size: 2.5rem; font-weight: 700; color: #38bdf8; }
.bar-chart { width: 100%; }
.bar-row { display: flex; align-items: center; margin-bottom: 0.5rem; gap: 0.75rem; }
.bar-label { flex: 0 0 180px; font-size: 0.8rem; color: #cbd5e1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bar-track { flex: 1; background: #334155; border-radius: 4px; height: 24px; position: relative; overflow: hidden; }
.bar-fill { height: 100%; border-radius: 4px; background: linear-gradient(90deg, #3b82f6, #38bdf8); display: flex; align-items: center; padding-left: 8px; }
.bar-count { font-size: 0.75rem; color: #f8fafc; font-weight: 600; white-space: nowrap; }
.full-width { grid-column: 1 / -1; }
table { width: 100%; border-collapse: collapse; font-size: 0.8rem; }
th { text-align: left; padding: 0.75rem; border-bottom: 2px solid #334155; color: #94a3b8; font-weight: 600; }
td { padding: 0.6rem 0.75rem; border-bottom: 1px solid #1e293b; color: #cbd5e1; }
tr:hover td { background: #1e293b; }
.tag { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; }
.tag-provider { background: #1e3a5f; color: #38bdf8; }
.tag-model { background: #1e3a3f; color: #2dd4bf; }
.tag-ext { background: #3b1e5f; color: #a78bfa; }
.timeline-bar { display: flex; align-items: flex-end; gap: 2px; height: 120px; padding-top: 1rem; }
.timeline-col { flex: 1; background: linear-gradient(180deg, #3b82f6, #1d4ed8); border-radius: 3px 3px 0 0; min-width: 8px; }
.timeline-labels { display: flex; gap: 2px; margin-top: 0.5rem; }
.timeline-label { flex: 1; font-size: 0.6rem; color: #64748b; text-align: center; min-width: 8px; }
.summary-pills { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 1.5rem; }
.pill { background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 0.5rem 1rem; font-size: 0.8rem; color: #94a3b8; }
.pill strong { color: #f8fafc; }
</style>
</head>
<body>
<h1>Venus AI Contribution Analytics</h1>
<p class="subtitle">Generated at ${generatedAt} | Data sources: file-headers, git-log, attribution-manifests</p>
<div class="summary-pills">
<div class="pill"><strong>${stats.totalFiles}</strong> AI-generated files</div>
<div class="pill"><strong>${stats.totalLines.toLocaleString()}</strong> total lines</div>
<div class="pill"><strong>${providerEntries.length}</strong> providers</div>
<div class="pill"><strong>${modelEntries.length}</strong> models</div>
</div>
<div class="grid">
<div class="card">
<h2>Provider Distribution</h2>
<div class="bar-chart">
${providerEntries.map(([name, count]) => `<div class="bar-row"><span class="bar-label">${name}</span><div class="bar-track"><div class="bar-fill" style="width: ${(count / Math.max(...providerEntries.map((p) => p[1]), 1) * 100).toFixed(1)}%"><span class="bar-count">${count}</span></div></div></div>`).join("")}
</div>
</div>
<div class="card">
<h2>Model Distribution</h2>
<div class="bar-chart">
${modelEntries.slice(0, 10).map(([name, count]) => `<div class="bar-row"><span class="bar-label" title="${name}">${name}</span><div class="bar-track"><div class="bar-fill" style="width: ${(count / Math.max(...modelEntries.map((m) => m[1]), 1) * 100).toFixed(1)}%; background: linear-gradient(90deg, #10b981, #2dd4bf);"><span class="bar-count">${count}</span></div></div></div>`).join("")}
</div>
</div>
<div class="card">
<h2>File Type</h2>
<div class="bar-chart">
${extEntries.map(([name, count]) => `<div class="bar-row"><span class="bar-label">${name}</span><div class="bar-track"><div class="bar-fill" style="width: ${(count / Math.max(...extEntries.map((e) => e[1]), 1) * 100).toFixed(1)}%; background: linear-gradient(90deg, #8b5cf6, #a78bfa);"><span class="bar-count">${count}</span></div></div></div>`).join("")}
</div>
</div>
<div class="card">
<h2>Directory</h2>
<div class="bar-chart">
${dirEntries.slice(0, 10).map(([name, count]) => `<div class="bar-row"><span class="bar-label" title="${name}">${name}</span><div class="bar-track"><div class="bar-fill" style="width: ${(count / Math.max(...dirEntries.map((d) => d[1]), 1) * 100).toFixed(1)}%; background: linear-gradient(90deg, #f59e0b, #fbbf24);"><span class="bar-count">${count}</span></div></div></div>`).join("")}
</div>
</div>
<div class="card full-width">
<h2>Monthly Trend</h2>
${monthEntries.length > 0 ? `<div class="timeline-bar">${monthEntries.map(([, count]) => `<div class="timeline-col" style="height: ${(count / Math.max(...monthEntries.map((m) => m[1]), 1) * 100).toFixed(1)}%;" title="${count} files"></div>`).join("")}</div><div class="timeline-labels">${monthEntries.map(([month]) => `<div class="timeline-label">${month}</div>`).join("")}</div>` : "<p style='color:#64748b'>No timeline data yet.</p>"}
</div>
<div class="card full-width">
<h2>Recent AI-Generated Files (Top 50)</h2>
${recentFiles.length > 0 ? `<table><thead><tr><th>File</th><th>Provider</th><th>Model</th><th>Lines</th><th>Source</th><th>Time</th></tr></thead><tbody>${recentFiles.map((r) => `<tr><td>${r.filePath}</td><td><span class="tag tag-provider">${r.provider}</span></td><td><span class="tag tag-model">${r.model}</span></td><td>${r.lineCount || "-"}</td><td><span class="tag tag-ext">${r.source}</span></td><td>${formatDate(r.timestamp)}</td></tr>`).join("")}</tbody></table>` : "<p style='color:#64748b'>No data yet.</p>"}
</div>
</div>
</body>
</html>`;
}
function formatDate(dateStr) {
if (!dateStr || dateStr === "unknown") return "-";
try {
const d = new Date(dateStr);
if (Number.isNaN(d.getTime())) return dateStr;
return d.toISOString().slice(0, 10);
} catch {
return dateStr;
}
}
// ── Helpers ──
function normalizePath(p) {
return p.replaceAll("\\", "/");
}
// ── Main ──
function main() {
const args = parseCliArgs();
const outputDir = args.outputDir || path.join(repoRoot, "docs");
const since = args.since || "";
const scanDirs = args.scanDirs;
console.log("[ai-analytics] Collecting data...");
console.log("[ai-analytics] Source 1: Scanning file headers...");
const fileHeaders = scanFileHeaders(repoRoot, scanDirs);
console.log(`[ai-analytics] Found ${fileHeaders.length} files with @ai-co-author headers`);
console.log("[ai-analytics] Source 2: Parsing git log...");
const gitRecords = parseGitLog(since);
console.log(`[ai-analytics] Found ${gitRecords.length} records from git history`);
console.log("[ai-analytics] Source 3: Scanning attribution manifests...");
const manifests = scanAttributionManifests(repoRoot);
console.log(`[ai-analytics] Found ${manifests.length} records from manifests`);
const merged = mergeRecords(fileHeaders, gitRecords, manifests);
console.log(`[ai-analytics] Merged: ${merged.length} unique files`);
const stats = aggregate(merged);
const html = generateHtmlReport(stats, merged);
const outputDirResolved = path.resolve(outputDir);
if (!fs.existsSync(outputDirResolved)) {
fs.mkdirSync(outputDirResolved, { recursive: true });
}
const outputFile = path.join(outputDirResolved, "ai-contribution-report.html");
fs.writeFileSync(outputFile, html, "utf8");
console.log(`[ai-analytics] Report generated: ${normalizePath(path.relative(repoRoot, outputFile))}`);
const jsonFile = path.join(outputDirResolved, "ai-contribution-data.json");
const jsonData = {
generatedAt: new Date().toISOString(),
stats: {
totalFiles: stats.totalFiles,
totalLines: stats.totalLines,
byProvider: stats.byProvider,
byModel: stats.byModel,
byExtension: stats.byExtension,
byDirectory: stats.byDirectory,
byMonth: stats.byMonth,
bySource: stats.bySource,
},
records: merged.map((r) => ({
file: r.filePath,
provider: r.provider,
model: r.model,
extension: r.extension,
lines: r.lineCount,
source: r.source,
timestamp: r.timestamp,
})),
};
fs.writeFileSync(jsonFile, `${JSON.stringify(jsonData, null, 2)}\n`, "utf8");
console.log(`[ai-analytics] Data exported: ${normalizePath(path.relative(repoRoot, jsonFile))}`);
}
main();
#!/usr/bin/env node
/**
* AI Direct - Figma to Design Spec 模块
*
* 从 Figma design context 中提取结构化 spec,包括:
* - section purpose (区域作用)
* - patterns (可复用 UI 模式)
* - token candidates (颜色、间距、字体等设计信号)
* - uncertainty (未明确的决策点)
*
* 这个 spec 作为 AI 代码生成的中间层输入,避免 AI 直接猜测设计意图。
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const _filename = fileURLToPath(import.meta.url);
const _dirname = path.dirname(_filename);
/**
* 从 Figma design context 中提取设计 spec
* @param {string} designContext - Figma YAML 或 HTML 格式的设计上下文
* @param {object} options - 选项
* @returns {object} design spec
*/
export function buildDesignSpec(designContext, options = {}) {
if (!designContext || typeof designContext !== "string") {
return null;
}
const spec = {
version: "1.0",
generatedAt: new Date().toISOString(),
sections: [],
uncertainty: [],
};
// 1. 提取 token candidates (颜色、间距、字体)
const tokens = extractTokenCandidates(designContext);
spec.tokens = tokens;
// 2. 识别 UI patterns (可复用模式)
const patterns = extractPatterns(designContext);
spec.patterns = patterns;
// 3. 标记 uncertainty (未明确的决策点)
const uncertainty = detectUncertainty(designContext);
spec.uncertainty = uncertainty;
// 4. 提取 section purpose (如果有多个 frame/section)
const sections = extractSections(designContext);
spec.sections = sections;
return spec;
}
/**
* 提取 token candidates:从 Figma 数据中识别设计信号
*/
function extractTokenCandidates(designContext) {
const tokens = {
colors: [],
spacing: [],
typography: [],
radius: [],
};
// 1. 提取颜色
const colorPattern = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/g;
const colorSet = new Set();
let match;
while ((match = colorPattern.exec(designContext)) !== null) {
const [r, g, b, a] = [
parseInt(match[1], 10),
parseInt(match[2], 10),
parseInt(match[3], 10),
match[4] ? parseFloat(match[4]) : 1,
];
const color = a < 1 ? `rgba(${r}, ${g}, ${b}, ${a})` : `rgb(${r}, ${g}, ${b})`;
if (!colorSet.has(color)) {
colorSet.add(color);
tokens.colors.push({
value: color,
role: inferColorRole(r, g, b, a, designContext, match.index),
});
}
}
// 2. 提取间距 (padding, margin, gap)
const spacingPattern = /(?:padding|margin|gap|w|h|width|height)[:\s]+(\d+)px/gi;
const spacingSet = new Set();
while ((match = spacingPattern.exec(designContext)) !== null) {
const value = parseInt(match[1], 10);
if (value > 0 && value <= 200 && !spacingSet.has(value)) {
spacingSet.add(value);
tokens.spacing.push({ value: `${value}px`, raw: value });
}
}
tokens.spacing.sort((a, b) => a.raw - b.raw);
// 3. 提取字体大小和行高
const fontSizePattern = /font-?size[:\s]+(\d+)px/gi;
const lineHeightPattern = /line-?height[:\s]+([\d.]+)/gi;
const typographySet = new Set();
while ((match = fontSizePattern.exec(designContext)) !== null) {
const size = parseInt(match[1], 10);
if (!typographySet.has(size)) {
typographySet.add(size);
tokens.typography.push({ fontSize: `${size}px`, raw: size });
}
}
while ((match = lineHeightPattern.exec(designContext)) !== null) {
const lh = parseFloat(match[1]);
const existing = tokens.typography.find((t) => t.lineHeight === lh);
if (!existing) {
tokens.typography.push({ lineHeight: lh, raw: lh });
}
}
tokens.typography.sort((a, b) => (a.raw || 0) - (b.raw || 0));
// 4. 提取圆角
const radiusPattern = /radius[:\s]+\[(\d+(?:,\s*\d+)*)\]/gi;
while ((match = radiusPattern.exec(designContext)) !== null) {
const values = match[1].split(",").map((v) => parseInt(v.trim(), 10));
tokens.radius.push({ value: values.map((v) => `${v}px`).join(" "), raw: values });
}
return tokens;
}
/**
* 推断颜色的语义角色
*/
function inferColorRole(r, g, b, a, context, index) {
// 高饱和度 = 主色/强调色
const saturation = Math.max(r, g, b) - Math.min(r, g, b);
// 主色 (蓝色系)
if (b > 180 && r < 100 && saturation > 150) {
return "primary";
}
// 错误/警告 (红色系)
if (r > 180 && g < 100 && saturation > 150) {
return "error";
}
// 成功 (绿色系)
if (g > 150 && r < 100 && b < 100) {
return "success";
}
// 文字色 (深灰/黑)
if (r === g && g === b && r < 100) {
return "text-primary";
}
// 次级文字 (中灰)
if (r === g && g === b && r >= 100 && r < 180) {
return "text-secondary";
}
// 背景色 (浅灰/白)
if (r === g && g === b && r >= 230) {
return "background";
}
// 边框 (中等灰度)
if (r === g && g === b && r >= 180 && r < 230) {
return "border";
}
return "unknown";
}
/**
* 识别 UI patterns (可复用模式)
*/
function extractPatterns(designContext) {
const patterns = [];
// 1. Key-Value 列表
if (/label|key|title[\s\S]{0,50}value|content|text/i.test(designContext)) {
patterns.push({
type: "key-value-list",
description: "标签-值对列表,常用于信息展示",
selector: ".label + .value 或 .key + .value",
});
}
// 2. 图片网格
if (/grid[\s\S]{0,100}image|photo|picture/i.test(designContext)) {
patterns.push({
type: "image-grid",
description: "图片网格布局",
selector: "display: grid + img",
});
}
// 3. 悬浮按钮/角标
if (/absolute[\s\S]{0,100}(top|right|bottom|left)/i.test(designContext)) {
patterns.push({
type: "floating-overlay",
description: "悬浮元素 (按钮、角标、计数器等)",
selector: "position: absolute",
});
}
// 4. 固定底栏
if (/fixed[\s\S]{0,50}bottom[:\s]+0/i.test(designContext)) {
patterns.push({
type: "fixed-bottom-bar",
description: "固定底栏 (操作按钮、导航等)",
selector: "position: fixed; bottom: 0",
});
}
// 5. 价格/倒计时区域
if (/price|countdown|timer/i.test(designContext)) {
patterns.push({
type: "price-countdown",
description: "价格或倒计时展示区域",
selector: ".price-section 或 .countdown",
});
}
return patterns;
}
/**
* 检测 uncertainty (未明确的决策点)
*/
function detectUncertainty(designContext) {
const uncertainty = [];
// 1. hover/focus 态
if (!/hover|:hover|focus|:focus/i.test(designContext)) {
uncertainty.push({
type: "interaction-state",
description: "hover/focus 态未在设计稿中明确",
impact: "需要设计师确认或参考同类组件",
});
}
// 2. 响应式/移动端
if (!/mobile|tablet|responsive|@media/i.test(designContext)) {
uncertainty.push({
type: "responsive",
description: "响应式/移动端布局未在设计稿中明确",
impact: "需要设计师确认或参考设计系统",
});
}
// 3. 暗色模式
if (!/dark|theme|mode/i.test(designContext)) {
uncertainty.push({
type: "dark-mode",
description: "暗色模式配色未在设计稿中明确",
impact: "如果项目支持暗色模式,需要设计师补充",
});
}
// 4. 空状态/加载态/错误态
if (!/empty|loading|error|skeleton/i.test(designContext)) {
uncertainty.push({
type: "edge-states",
description: "空状态/加载态/错误态未在设计稿中明确",
impact: "需要设计师补充或参考设计系统",
});
}
return uncertainty;
}
/**
* 提取多个 sections (如果 design context 包含多个 frame)
*/
function extractSections(designContext) {
const sections = [];
// 尝试识别 frame/section 边界
const framePattern = /name:\s*["']?([^"'\n]+)["']?[\s\S]{0,200}?type:\s*(?:FRAME|GROUP)/gi;
let match;
while ((match = framePattern.exec(designContext)) !== null) {
const name = match[1].trim();
sections.push({
name,
purpose: inferSectionPurpose(name),
});
}
return sections;
}
/**
* 推断 section 的作用
*/
function inferSectionPurpose(name) {
const lower = name.toLowerCase();
if (/hero|banner|header/i.test(lower)) return "页面顶部展示区";
if (/nav|menu|sidebar/i.test(lower)) return "导航/菜单";
if (/content|main|body/i.test(lower)) return "主要内容区";
if (/footer|bottom/i.test(lower)) return "页面底部";
if (/card|list|grid/i.test(lower)) return "卡片/列表展示";
if (/form|input|search/i.test(lower)) return "表单/输入";
if (/modal|dialog|popup/i.test(lower)) return "弹窗/浮层";
return "通用区域";
}
/**
* 将 spec 写入文件
*/
export function writeDesignSpec(spec, outputPath) {
const content = JSON.stringify(spec, null, 2);
fs.writeFileSync(outputPath, content, "utf-8");
console.log(`[ai-direct-spec] ✓ Design spec written to ${outputPath}`);
return outputPath;
}
/**
* 读取 spec 文件
*/
export function readDesignSpec(specPath) {
if (!fs.existsSync(specPath)) {
return null;
}
try {
const content = fs.readFileSync(specPath, "utf-8");
return JSON.parse(content);
} catch (err) {
console.warn(`[ai-direct-spec] Failed to read spec: ${err.message}`);
return null;
}
}
// CLI 入口
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const designContextPath = process.argv[2];
const outputPath = process.argv[3] || designContextPath.replace(/\.html$/, ".spec.json");
if (!designContextPath) {
console.error("Usage: node ai-direct-spec.mjs <design-context.html> [output.spec.json]");
process.exit(1);
}
if (!fs.existsSync(designContextPath)) {
console.error(`Error: File not found: ${designContextPath}`);
process.exit(1);
}
const designContext = fs.readFileSync(designContextPath, "utf-8");
const spec = buildDesignSpec(designContext);
writeDesignSpec(spec, outputPath);
}
#!/usr/bin/env node
/**
* AI Direct - Token to Theme Mapping 模块
*
* 将 design spec 中的 token candidates 映射到项目的语义主题变量。
*
* 核心原则:
* 1. 优先复用已有语义角色 (--vui-color-primary, --vui-spacing-4 等)
* 2. 只动 theme 层 (CSS variables, Tailwind config)
* 3. 保留项目已有格式 (HSL/hex/rgb)
* 4. 不发明局部变量 (--header-bg, --nav-text 等)
*
* 输出:theme-mapping.json,指导 AI 在代码生成时使用语义变量而非硬编码值。
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const _filename = fileURLToPath(import.meta.url);
const _dirname = path.dirname(_filename);
/**
* 扫描项目的语义主题变量
* @param {string} projectRoot - 项目根目录
* @returns {object} 语义变量集合
*/
export function scanProjectTheme(projectRoot) {
const theme = {
colors: {},
spacing: {},
typography: {},
radius: {},
format: "rgb", // hsl | hex | rgb
};
// 1. 扫描 VUI tokens (packages/vui/tokens/src/ 和 packages/vui/*/tokens/)
const vuiTokensDirs = [
path.join(projectRoot, "packages/vui/tokens/src"),
path.join(projectRoot, "packages/vui/mobile/tokens"),
path.join(projectRoot, "packages/vui/pc/tokens"),
path.join(projectRoot, "packages/vui/shared/tokens"),
];
for (const dir of vuiTokensDirs) {
if (fs.existsSync(dir)) {
const tokenFiles = fs.readdirSync(dir).filter((f) => f.endsWith(".json") || f.endsWith(".css") || f.endsWith(".ts") || f.endsWith(".js"));
for (const file of tokenFiles) {
const content = fs.readFileSync(path.join(dir, file), "utf8");
parseThemeVariables(content, theme);
}
}
}
// 2. 扫描项目级 CSS variables (apps/*/src/**/*.css)
const appsDir = path.join(projectRoot, "apps");
if (fs.existsSync(appsDir)) {
const apps = fs.readdirSync(appsDir);
for (const app of apps) {
const cssDir = path.join(appsDir, app, "src");
if (fs.existsSync(cssDir)) {
scanCssVariables(cssDir, theme);
}
}
}
// 3. 扫描 Tailwind config (tailwind.config.js)
const tailwindConfig = path.join(projectRoot, "tailwind.config.js");
if (fs.existsSync(tailwindConfig)) {
const content = fs.readFileSync(tailwindConfig, "utf8");
parseTailwindTheme(content, theme);
}
return theme;
}
/**
* 解析 CSS variables (--var-name: value) 和 TypeScript token exports
*/
function parseThemeVariables(content, theme) {
// 1. CSS variables
const varPattern = /--([a-z0-9-]+)\s*:\s*([^;]+);/gi;
let match;
while ((match = varPattern.exec(content)) !== null) {
const name = match[1];
const value = match[2].trim();
if (/color|primary|secondary|accent|error|warning|success|background|foreground|border/i.test(name)) {
theme.colors[name] = value;
if (/hsl/i.test(value)) theme.format = "hsl";
else if (value.startsWith("#")) theme.format = "hex";
} else if (/spacing|gap|margin|padding/i.test(name)) {
theme.spacing[name] = value;
} else if (/font|text|heading|body/i.test(name)) {
theme.typography[name] = value;
} else if (/radius|rounded/i.test(name)) {
theme.radius[name] = value;
}
}
// 2. TypeScript token exports (vuiColorTokens, vuiSpacingTokens 等)
// 匹配: export const vuiXxxTokens = { key: "value", ... } as const;
const tsExportPattern = /export\s+const\s+vui(\w+)Tokens\s*=\s*\{([\s\S]*?)\}\s*as\s+const/g;
while ((match = tsExportPattern.exec(content)) !== null) {
const tokenType = match[1].toLowerCase(); // color, spacing, etc.
const body = match[2];
// 解析 key: value 对
const entryPattern = /(\w+)\s*:\s*(?:"([^"]+)"|'([^']+)'|(\d+))/g;
let entry;
while ((entry = entryPattern.exec(body)) !== null) {
const key = entry[1];
const value = entry[2] || entry[3] || entry[4];
switch (tokenType) {
case "color": {
theme.colors[`vui-color-${key}`] = value;
if (value.startsWith("#")) theme.format = "hex";
break;
}
case "font":
case "typography": {
theme.typography[`vui-${key}`] = value;
break;
}
case "radius": {
theme.radius[`vui-radius-${key}`] = `${value}px`;
break;
}
case "spacing": {
theme.spacing[`vui-spacing-${key}`] = `${value}px`;
break;
}
default: {
// 通用 token
theme.colors[`vui-${tokenType}-${key}`] = value;
}
}
}
}
}
/**
* 递归扫描 CSS 文件中的 variables
*/
function scanCssVariables(dir, theme) {
const files = fs.readdirSync(dir);
for (const file of files) {
const fullPath = path.join(dir, file);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
scanCssVariables(fullPath, theme);
} else if (file.endsWith(".css")) {
const content = fs.readFileSync(fullPath, "utf8");
parseThemeVariables(content, theme);
}
}
}
/**
* 解析 Tailwind config 中的 theme 扩展
*/
function parseTailwindTheme(content, theme) {
// 简单匹配 colors/spacing/extend 等
if (/colors\s*:\s*\{/.test(content)) {
const colorMatch = content.match(/colors\s*:\s*\{([^}]+)\}/);
if (colorMatch) {
const colorContent = colorMatch[1];
const entryPattern = /(\w+)\s*:\s*['"]([^'"]+)['"]/g;
let match;
while ((match = entryPattern.exec(colorContent)) !== null) {
theme.colors[`tw-${match[1]}`] = match[2];
}
}
}
}
/**
* 将 token candidates 映射到语义主题变量
* @param {object} spec - design spec
* @param {object} projectTheme - 项目语义主题
* @returns {object} theme mapping
*/
export function mapTokensToTheme(spec, projectTheme) {
const mapping = {
version: "1.0",
generatedAt: new Date().toISOString(),
colors: [],
spacing: [],
typography: [],
radius: [],
};
// 1. 映射颜色
for (const token of spec.tokens.colors) {
const mapped = findMatchingThemeColor(token.value, token.role, projectTheme.colors);
mapping.colors.push({
designValue: token.value,
inferredRole: token.role,
semanticVariable: mapped.variable,
status: mapped.status, // "reused" | "missing" | "approximate"
recommendation: mapped.recommendation,
});
}
// 2. 映射间距
for (const token of spec.tokens.spacing) {
const mapped = findMatchingThemeSpacing(token.raw, projectTheme.spacing);
mapping.spacing.push({
designValue: token.value,
semanticVariable: mapped.variable,
status: mapped.status,
});
}
// 3. 映射字体
for (const token of spec.tokens.typography) {
const mapped = findMatchingThemeTypography(token.raw, projectTheme.typography);
mapping.typography.push({
designValue: token.fontSize || token.lineHeight,
semanticVariable: mapped.variable,
status: mapped.status,
});
}
// 4. 映射圆角
for (const token of spec.tokens.radius) {
const mapped = findMatchingThemeRadius(token.raw, projectTheme.radius);
mapping.radius.push({
designValue: token.value,
semanticVariable: mapped.variable,
status: mapped.status,
});
}
return mapping;
}
/**
* 查找匹配的主题颜色变量
*/
function findMatchingThemeColor(designValue, inferredRole, themeColors) {
// 1. 先按 role 匹配
const roleKeys = Object.keys(themeColors).filter((k) => k.toLowerCase().includes(inferredRole));
if (roleKeys.length > 0) {
return {
variable: `--${roleKeys[0]}`,
status: "reused",
recommendation: `使用已有语义变量 --${roleKeys[0]}`,
};
}
// 2. 按颜色值近似匹配
for (const [name, value] of Object.entries(themeColors)) {
if (colorDistance(designValue, value) < 30) {
return {
variable: `--${name}`,
status: "approximate",
recommendation: `颜色接近 --${name},建议复用`,
};
}
}
// 3. 未找到
return {
variable: null,
status: "missing",
recommendation: `项目中未找到匹配的颜色变量,建议新增 --${inferredRole}`,
};
}
/**
* 计算两个颜色的距离 (简单 RGB 欧氏距离)
*/
function colorDistance(c1, c2) {
const rgb1 = parseColor(c1);
const rgb2 = parseColor(c2);
if (!rgb1 || !rgb2) return Infinity;
return Math.hypot((rgb1.r - rgb2.r), (rgb1.g - rgb2.g), (rgb1.b - rgb2.b));
}
/**
* 解析颜色值为 RGB
*/
function parseColor(value) {
if (!value) return null;
// rgb(r, g, b) 或 rgba(r, g, b, a)
const rgbMatch = value.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
if (rgbMatch) {
return { r: +rgbMatch[1], g: +rgbMatch[2], b: +rgbMatch[3] };
}
// hex
const hexMatch = value.match(/^#([0-9a-f]{3,8})$/i);
if (hexMatch) {
const hex = hexMatch[1];
if (hex.length === 3) {
return {
r: Number.parseInt(hex[0] + hex[0], 16),
g: Number.parseInt(hex[1] + hex[1], 16),
b: Number.parseInt(hex[2] + hex[2], 16),
};
}
if (hex.length === 6) {
return {
r: Number.parseInt(hex.slice(0, 2), 16),
g: Number.parseInt(hex.slice(2, 4), 16),
b: Number.parseInt(hex.slice(4, 6), 16),
};
}
}
return null;
}
/**
* 查找匹配的主题间距变量
*/
function findMatchingThemeSpacing(rawValue, themeSpacing) {
// 优先精确匹配
for (const [name, value] of Object.entries(themeSpacing)) {
const match = value.match(/^(\d+)px$/);
if (match && Number.parseInt(match[1], 10) === rawValue) {
return { variable: `--${name}`, status: "reused" };
}
}
// 近似匹配 (±2px)
for (const [name, value] of Object.entries(themeSpacing)) {
const match = value.match(/^(\d+)px$/);
if (match && Math.abs(Number.parseInt(match[1], 10) - rawValue) <= 2) {
return { variable: `--${name}`, status: "approximate" };
}
}
return { variable: null, status: "missing" };
}
/**
* 查找匹配的主题字体变量
*/
function findMatchingThemeTypography(rawValue, themeTypography) {
// 简单匹配
for (const [name, value] of Object.entries(themeTypography)) {
if (Number.parseInt(value, 10) === rawValue) {
return { variable: `--${name}`, status: "reused" };
}
}
return { variable: null, status: "missing" };
}
/**
* 查找匹配的主题圆角变量
*/
function findMatchingThemeRadius(rawValues, themeRadius) {
const primaryRadius = rawValues[0];
for (const [name, value] of Object.entries(themeRadius)) {
const match = value.match(/^(\d+)px/);
if (match && Number.parseInt(match[1], 10) === primaryRadius) {
return { variable: `--${name}`, status: "reused" };
}
}
return { variable: null, status: "missing" };
}
/**
* 将 mapping 写入文件
*/
export function writeThemeMapping(mapping, outputPath) {
const content = JSON.stringify(mapping, null, 2);
fs.writeFileSync(outputPath, content, "utf-8");
console.log(`[ai-direct-theme] ✓ Theme mapping written to ${outputPath}`);
return outputPath;
}
/**
* 读取 mapping 文件
*/
export function readThemeMapping(mappingPath) {
if (!fs.existsSync(mappingPath)) {
return null;
}
try {
const content = fs.readFileSync(mappingPath, "utf8");
return JSON.parse(content);
} catch (error) {
console.warn(`[ai-direct-theme] Failed to read mapping: ${error.message}`);
return null;
}
}
// CLI 入口
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const specPath = process.argv[2];
const projectRoot = process.argv[3] || path.resolve(_dirname, "..");
const outputPath = process.argv[4] || specPath.replace(/\.spec\.json$/, ".theme-mapping.json");
if (!specPath) {
console.error("Usage: node ai-direct-theme.mjs <design.spec.json> [project-root] [output.theme-mapping.json]");
process.exit(1);
}
if (!fs.existsSync(specPath)) {
console.error(`Error: File not found: ${specPath}`);
process.exit(1);
}
const specContent = fs.readFileSync(specPath, "utf8");
const spec = JSON.parse(specContent);
console.log(`[ai-direct-theme] Scanning project theme from ${projectRoot}...`);
const projectTheme = scanProjectTheme(projectRoot);
console.log(`[ai-direct-theme] Mapping tokens to theme...`);
const mapping = mapTokensToTheme(spec, projectTheme);
writeThemeMapping(mapping, outputPath);
}
#!/usr/bin/env node
/**
* AI Pitfall Auto-Capture
*
* 自动检测 AI 生成代码中的 lint / typecheck 错误,
* 将错误模式提取为反模式条目,追加到 docs/ai/ai-anti-patterns.md。
*
* 工作流程:
* 1. 收集带 @ai-co-author 标记的变更文件
* 2. 对这些文件运行 ESLint / TypeScript 检查
* 3. 提取错误模式,与已有条目去重
* 4. 新条目追加到注册表
*
* 用法:
* pnpm run ai:capture-pitfalls # 扫描所有变更的 AI 文件
* pnpm run ai:capture-pitfalls -- --all # 扫描所有 AI 文件(不限变更)
* pnpm run ai:capture-pitfalls -- --dry-run # 只检测,不写入
*/
import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { requireWorkspaceRoot } from "./workspace-root.mjs";
const repoRoot = requireWorkspaceRoot();
const REGISTRY_PATH = path.join(repoRoot, "docs", "ai", "ai-anti-patterns.md");
const CO_AUTHOR_REGEX = /@ai-co-author\s+(\S+)\s*\|\s*(\S+)/;
// ── Lint Rule → Anti-Pattern Mapping ──
const RULE_CATEGORY_MAP = {
"vue/no-unused-imports": { category: "component-misuse", scope: "vue-sfc" },
"no-unused-vars": { category: "import-error", scope: "general" },
"@typescript-eslint/no-unused-vars": { category: "import-error", scope: "typescript" },
"perfectionist/sort-imports": { category: "import-error", scope: "general" },
"import/order": { category: "import-error", scope: "general" },
"stylelint/property-order": { category: "style-error", scope: "css" },
"stylelint-config-recess-order": { category: "style-error", scope: "css" },
"vue/no-v-for-template-key": { category: "template-error", scope: "vue-sfc" },
"vue/no-v-model-argument": { category: "template-error", scope: "vue-sfc" },
"vue/require-v-for-key": { category: "template-error", scope: "vue-sfc" },
"vue/valid-v-for": { category: "template-error", scope: "vue-sfc" },
"vue/no-unused-vars": { category: "template-error", scope: "vue-sfc" },
"@typescript-eslint/no-explicit-any": { category: "type-error", scope: "typescript" },
"no-unreachable": { category: "logic-error", scope: "general" },
"no-constant-condition": { category: "logic-error", scope: "general" },
};
const DEFAULT_CATEGORY = { category: "other", scope: "general" };
// ── CLI ──
function parseCliArgs() {
const args = process.argv.slice(2);
return {
all: args.includes("--all"),
dryRun: args.includes("--dry-run"),
};
}
// ── Step 1: Collect AI files ──
function getChangedFiles() {
const commands = [
"git diff --name-only",
"git diff --cached --name-only",
"git ls-files --others --exclude-standard",
];
const files = new Set();
for (const cmd of commands) {
const result = childProcess.spawnSync(cmd, {
cwd: repoRoot,
shell: true,
encoding: "utf8",
});
if (result.status === 0 && result.stdout) {
for (const line of result.stdout.trim().split(/\r?\n/)) {
if (line) files.add(line.replaceAll("\\", "/"));
}
}
}
return [...files];
}
function getAllAiFiles() {
const fileSet = new Set();
const result = childProcess.spawnSync(
'git ls-files -- "*.ts" "*.tsx" "*.vue" "*.js" "*.mjs" "*.uvue" "*.uts"',
{ cwd: repoRoot, shell: true, encoding: "utf8" },
);
if (result.status === 0 && result.stdout) {
for (const line of result.stdout.trim().split(/\r?\n/)) {
if (line) fileSet.add(line.replaceAll("\\", "/"));
}
}
const previewDir = path.join(repoRoot, "apps", "web", "ai-previews");
if (fs.existsSync(previewDir)) {
walkForAiFiles(previewDir, repoRoot, fileSet);
}
return [...fileSet];
}
function walkForAiFiles(dir, baseDir, fileSet) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "dist") continue;
walkForAiFiles(fullPath, baseDir, fileSet);
} else if (entry.isFile()) {
const ext = path.extname(entry.name).toLowerCase();
if ([".ts", ".tsx", ".vue", ".js", ".mjs", ".uvue", ".uts"].includes(ext)) {
fileSet.add(path.relative(baseDir, fullPath).replaceAll("\\", "/"));
}
}
}
}
function hasCoAuthorHeader(filePath) {
const absPath = path.join(repoRoot, filePath);
if (!fs.existsSync(absPath)) return false;
try {
const fd = fs.openSync(absPath, "r");
const buf = Buffer.alloc(512);
const bytesRead = fs.readSync(fd, buf, 0, 512, 0);
fs.closeSync(fd);
const head = buf.toString("utf8", 0, bytesRead);
return CO_AUTHOR_REGEX.test(head);
} catch {
return false;
}
}
// ── Step 2: Run lint / typecheck ──
function runEslintOnFiles(files) {
if (files.length === 0) return [];
const tsFiles = files.filter((f) => /\.(ts|tsx|vue|js|mjs)$/.test(f));
if (tsFiles.length === 0) return [];
const result = childProcess.spawnSync(
`npx eslint --format json ${tsFiles.map((f) => `"${f}"`).join(" ")}`,
{ cwd: repoRoot, shell: true, encoding: "utf8", maxBuffer: 10 * 1024 * 1024 },
);
const errors = [];
try {
const parsed = JSON.parse(result.stdout || "[]");
for (const fileResult of parsed) {
for (const msg of fileResult.messages || []) {
if (msg.severity === 2) {
errors.push({
file: fileResult.filePath.replace(repoRoot, "").replace(/^[\\/]/, "").replaceAll("\\", "/"),
rule: msg.ruleId || "unknown",
line: msg.line,
column: msg.column,
message: msg.message,
type: "lint",
});
}
}
}
} catch { /* eslint output may not be valid JSON */ }
return errors;
}
function runTypecheckOnFiles(files) {
if (files.length === 0) return [];
const tsFiles = files.filter((f) => /\.(ts|tsx)$/.test(f));
if (tsFiles.length === 0) return [];
const result = childProcess.spawnSync(
`npx tsc --noEmit --pretty false 2>&1`,
{ cwd: repoRoot, shell: true, encoding: "utf8", maxBuffer: 10 * 1024 * 1024 },
);
const errors = [];
const fileSet = new Set(files.map((f) => f.replaceAll("\\", "/")));
if (result.stdout) {
for (const line of result.stdout.split(/\r?\n/)) {
const match = line.match(/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/);
if (match) {
const file = match[1].replaceAll("\\", "/");
if (fileSet.has(file) || fileSet.size === 0) {
errors.push({
file,
rule: match[4],
line: Number.parseInt(match[2], 10),
column: Number.parseInt(match[3], 10),
message: match[5],
type: "typecheck",
});
}
}
}
}
return errors;
}
// ── Step 3: Extract patterns & deduplicate ──
function categorizeError(rule) {
for (const [pattern, mapping] of Object.entries(RULE_CATEGORY_MAP)) {
if (rule.includes(pattern) || pattern.includes(rule)) {
return mapping;
}
}
return DEFAULT_CATEGORY;
}
function extractPatternKey(error) {
const msg = error.message.slice(0, 60).toLowerCase().replace(/\s+/g, " ").trim();
return `${error.rule}|${msg}`;
}
function loadExistingPatterns() {
if (!fs.existsSync(REGISTRY_PATH)) return new Set();
const content = fs.readFileSync(REGISTRY_PATH, "utf8");
const patterns = new Set();
const patternRegex = /"pattern":\s*"([^"]+)"/g;
let match;
while ((match = patternRegex.exec(content)) !== null) {
patterns.add(match[1].toLowerCase());
}
const ruleRegex = /"sourceRule":\s*"([^"]+)"/g;
while ((match = ruleRegex.exec(content)) !== null) {
patterns.add(match[1]);
}
return patterns;
}
function getNextId() {
if (!fs.existsSync(REGISTRY_PATH)) return "AP-001";
const content = fs.readFileSync(REGISTRY_PATH, "utf8");
const idRegex = /"id":\s*"AP-(\d+)"/g;
let maxNum = 0;
let match;
while ((match = idRegex.exec(content)) !== null) {
const num = Number.parseInt(match[1], 10);
if (num > maxNum) maxNum = num;
}
return `AP-${String(maxNum + 1).padStart(3, "0")}`;
}
function buildEntry(error, existingPatterns) {
const { category, scope } = categorizeError(error.rule);
const id = getNextId();
const now = new Date().toISOString();
const entry = {
id,
category,
scope,
severity: error.type === "typecheck" ? "high" : "medium",
pattern: `${error.rule}: ${error.message.slice(0, 80)}`,
correction: `TODO: 填写正确做法`,
capturedAt: now,
capturedBy: error.type === "lint" ? "auto-lint" : "auto-typecheck",
sourceFile: error.file,
sourceRule: error.rule,
sourceLine: error.line,
};
const patternKey = error.rule.toLowerCase();
if (existingPatterns.has(patternKey)) {
return null;
}
return entry;
}
// ── Step 4: Append to registry ──
function appendEntry(entry) {
const jsonBlock = JSON.stringify(entry, null, 4);
const markdown = `
---
${jsonBlock}
---
### 描述
${entry.sourceRule} 错误出现在 \`${entry.sourceFile}\` 第 ${entry.sourceLine} 行。
错误信息:${entry.message || "N/A"}
### 错误示例
\`\`\`
// TODO: 填写触发此错误的代码片段
\`\`\`
### 正确示例
\`\`\`
// TODO: 填写修复后的代码
\`\`\`
`;
let content = "";
if (fs.existsSync(REGISTRY_PATH)) {
content = fs.readFileSync(REGISTRY_PATH, "utf8");
}
fs.writeFileSync(REGISTRY_PATH, content + markdown, "utf8");
}
// ── Main ──
function main() {
const args = parseCliArgs();
console.log("[ai-pitfalls] Starting auto-capture...");
let candidateFiles;
if (args.all) {
console.log("[ai-pitfalls] Scanning all AI-generated files...");
candidateFiles = getAllAiFiles();
} else {
console.log("[ai-pitfalls] Scanning changed files...");
candidateFiles = getChangedFiles();
}
const aiFiles = candidateFiles.filter((f) => hasCoAuthorHeader(f));
console.log(`[ai-pitfalls] Found ${aiFiles.length} AI-generated files to check`);
if (aiFiles.length === 0) {
console.log("[ai-pitfalls] No AI-generated files to check. Done.");
return;
}
console.log("[ai-pitfalls] Running ESLint...");
const lintErrors = runEslintOnFiles(aiFiles);
console.log(`[ai-pitfalls] Found ${lintErrors.length} lint errors`);
console.log("[ai-pitfalls] Running typecheck...");
const typeErrors = runTypecheckOnFiles(aiFiles);
console.log(`[ai-pitfalls] Found ${typeErrors.length} type errors`);
const allErrors = [...lintErrors, ...typeErrors];
if (allErrors.length === 0) {
console.log("[ai-pitfalls] No errors found. Registry is up to date.");
return;
}
const existingPatterns = loadExistingPatterns();
const newEntries = [];
const seen = new Set();
for (const error of allErrors) {
const key = extractPatternKey(error);
if (seen.has(key)) continue;
seen.add(key);
const entry = buildEntry(error, existingPatterns);
if (entry) {
newEntries.push({ entry, error });
}
}
console.log(`[ai-pitfalls] ${newEntries.length} new anti-patterns to register (${seen.size - newEntries.length} duplicates skipped)`);
if (newEntries.length === 0) {
console.log("[ai-pitfalls] All error patterns already registered. Done.");
return;
}
if (args.dryRun) {
console.log("[ai-pitfalls] Dry run - would add the following entries:");
for (const { entry } of newEntries) {
console.log(` [${entry.id}] ${entry.category}/${entry.scope}: ${entry.pattern}`);
}
return;
}
for (const { entry, error } of newEntries) {
entry.message = error.message;
appendEntry(entry);
console.log(`[ai-pitfalls] + ${entry.id}: ${entry.pattern}`);
}
console.log(`[ai-pitfalls] Registry updated: ${REGISTRY_PATH}`);
console.log(`[ai-pitfalls] Please review and refine the TODO entries.`);
}
main();
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!