Files
danyang-match/scripts/lib/wxss-selectors.mjs
T
WorkBuddy b67a56479e fix(miniapp): 修 P0 请求层崩溃(一个下划线致所有请求卡死)+ 组件 WXSS 违规选择器,再补 3 项门禁
═══ 缺陷 1(P0,运行期):utils/api.js 成功回调调用不存在的方法 ═══

控制台:
  TypeError: _this._releaseIdempotencyKey is not a function

根因:类中定义的是 `releaseIdempotencyKey()`,成功回调写成了
`this._releaseIdempotencyKey(...)`(**多一个下划线**)。

**为什么一个字符的笔误是 P0**:该调用位于 `wx.request` 的 success 回调内、
且在 `resolve()` **之前**。抛错 → `resolve` 永不执行 → 该 Promise **永不 settle**
→ 所有页面永远停在 loading,同时 App.onError 刷屏。
即「一次成功请求」本应推进流程,实际把前端整成不可用。

修复不只是改名,而是纠正结构:
- **先 `resolve(body.data)`,再执行收尾动作** —— 收尾逻辑不允许挡在响应路径上;
- 释放动作自带 try/catch + console.warn:释放失败最多是"下次操作没拿到新键",
  不得升级为业务失败。
- 语义未变(勿改):成功→释放(下次同域操作是新的一次);失败→刻意不释放
  (重试复用同一把键,后端才能识别重复投递)。

═══ 缺陷 2(编译期警告):组件 wxss 用了标签选择器 ═══

  Some selectors are not allowed in component wxss ... (components/recommend-card/index.wxss:1:1092)

实测违规 1 处(23 个组件样式文件全扫):`.compact-like image` —— 组件 wxss 只允许类选择器。
改为 `.compact-like__icon` 并**同步在 WXML 补上类名**
(只改 wxss 会让样式静默落空,是另一种"假成功")。

═══ 门禁:15 → 18(既有的全是源码内容断言,抓不到上述两类)═══

- 第15 `wxml-structure-contracts`(上一提交新增,本轮 MIN_GUARDS 基线顺带对齐)
- 第16 `miniapp-self-method-contracts`:扫描 `this._x(` / `self._x(` 等私有调用,
  要求同文件有定义(方法简写 / 类字段 / `this._x = 值` / prototype 四种形态)。
  **判据先自证假阳性**:首版正则不允许 `.` 前缀,把 `this._unsub = store.bind(this)`
  形式误报为未定义(3 个页面);修正并加反向自检样例固化了该坑。
- 第17 `wxss-component-selector-contracts`:组件 wxss 禁标签/ID/属性选择器。
  **作用域刻意只限 miniapp/components/**(page 的 wxss 允许标签选择器,套上去必有误报)。
- 第18 `miniapp-api-client-behavior`:**唯一的行为断言** —— 桩掉 `wx.request` 真跑 api.js,
  验证成功 resolve / 失败 retain 键 / 成功 release 键 / 收尾抛错不影响响应路径 4 组。
  含 1s settle 超时,直接编码"永不 settle"这一失败模式。
- 新增 `scripts/lib/wxss-selectors.mjs` + `scripts/check-wxss-component-selectors.mjs`(CLI)。
- `MIN_GUARDS` 15 → 18;执行器措辞改为「源码结构与关键行为断言」。

═══ 验证 ═══

- `node scripts/run-ui-contracts.mjs` → **PASS 18 / 18**,退出 0;
- 负向注入:未定义私有方法 / 标签+ID+属性选择器 / 多余闭合标签 → 均精准变红,
  且**合法样例(`this._x = 值`、纯类选择器、属性内含 `>`)不被误报**;
  行为守卫的负向自证见下一提交/记录;`UI_GUARDS_MIN=99` 拒绝报绿。
- 文档口径同步:AGENTS.md、STATUS.md(4 处当前口径 + 新增 1.1.0-rc.18 行)、ci.yml 注释。
- **未验证**:微信开发者工具真实编译与真机渲染(本机无该环境)。
2026-09-19 11:40:38 +08:00

114 lines
3.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 组件 WXSS 选择器检查(lib):供 CLI 与 UI 契约门禁共用。
//
// 规则来源:微信小程序**自定义组件**的 wxss 只允许类选择器。使用标签选择器(`image`/`view`…)、
// ID 选择器(`#id`)、属性选择器(`[attr]`)时开发者工具警告:
// [pages/index/index] Some selectors are not allowed in component wxss,
// including tag name selectors, ID selectors, and attribute selectors.
// (./components/recommend-card/index.wxss:1:1092)
//
// ⚠️ 作用域:**page 的 wxss 不受此限制**(页面不是组件)。
// 对 `miniapp/pages/` 套用本规则会产生误报,故只管 `miniapp/components/`。
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
/** 去掉注释,并用等长空白占位以保持原始字符偏移(报错行号才准) */
export function stripComments(src) {
return src.replace(/\/\*[\s\S]*?\*\//g, (m) => ' '.repeat(m.length));
}
/** 切出所有「选择器前置文本」(`{` 之前),跳过 at-rule 与声明块内部 */
export function extractSelectorPreludes(src) {
const preludes = [];
let depth = 0;
let buf = '';
let bufStart = 0;
for (let i = 0; i < src.length; i++) {
const c = src[i];
if (c === '{') {
if (depth === 0) preludes.push({ text: buf, index: bufStart });
depth++;
buf = '';
continue;
}
if (c === '}') {
depth = Math.max(0, depth - 1);
buf = '';
continue;
}
if (depth === 0) {
if (buf === '') bufStart = i;
buf += c;
}
}
return preludes;
}
/**
* 检查一段选择器前置文本是否含违规成分。
* @returns {string[]} 违规描述(去重)
*/
export function findViolations(selector) {
const bad = [];
const s = selector.trim();
if (!s) return bad;
if (s.startsWith('@')) return bad; // @media / @keyframes / @import 不是选择器
// 去掉伪类/伪元素及其函数括号内容,避免把 `:nth-child(2)` 里的标识符当标签
const cleaned = s.replace(/:{1,2}[a-zA-Z-]+(\([^)]*\))?/g, '').replace(/\([^)]*\)/g, '');
for (const part of cleaned.split(',')) {
const token = part.trim();
if (!token) continue;
const idMatch = token.match(/#[A-Za-z_][\w-]*/);
if (idMatch) bad.push(`ID 选择器 \`${idMatch[0]}\``);
const attrMatch = token.match(/\[[^\]]*\]/);
if (attrMatch) bad.push(`属性选择器 \`${attrMatch[0]}\``);
// 标签选择器:`>`/空格/`+`/`~` 之后紧跟的裸元素名
const tagMatch = token.match(/(^|[\s>+~])([a-zA-Z][\w-]*)/);
if (tagMatch) bad.push(`标签选择器 \`${tagMatch[2]}\``);
}
return [...new Set(bad)];
}
/**
* 检查单个 wxss 文件内容。
* @returns {{line:number, message:string}[]}
*/
export function checkWxss(src) {
const clean = stripComments(src);
const out = [];
for (const { text, index } of extractSelectorPreludes(clean)) {
for (const v of findViolations(text)) {
out.push({
line: clean.slice(0, index).split('\n').length,
message: `${v}(选择器原文 \`${text.trim().slice(0, 60)}\`)`,
});
}
}
return out;
}
export function walkWxss(dir, out = []) {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return out;
}
for (const e of entries) {
const p = join(dir, e.name);
if (e.isDirectory()) {
if (!['node_modules', 'miniprogram_npm'].includes(e.name)) walkWxss(p, out);
} else if (e.name.endsWith('.wxss')) {
out.push(p);
}
}
return out;
}
export { readFileSync };