@apexhub/apex-ui-rewrite-prefix-plugin 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +57 -2
- package/dist/audit-bundle.d.ts +67 -0
- package/dist/identity-rules.d.ts +59 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +651 -0
- package/dist/interface.d.ts +31 -0
- package/dist/postcss-plugin.d.ts +12 -0
- package/dist/transform-css.d.ts +20 -0
- package/dist/transform-html.d.ts +10 -0
- package/dist/transform-script.d.ts +18 -0
- package/dist/transform-vue.d.ts +15 -0
- package/dist/validate-prefix.d.ts +27 -0
- package/package.json +54 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Apex UI Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,58 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @apexhub/apex-ui-rewrite-prefix-plugin
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Vite 插件:把生产产物里的 `apex-` 前缀换成你自己的前缀。
|
|
4
|
+
|
|
5
|
+
## 何时使用
|
|
6
|
+
|
|
7
|
+
- 生产产物需要自有命名空间。
|
|
8
|
+
- 多个微前端需要彼此隔离的 class、Token 和浮层根。
|
|
9
|
+
- 需要检查构建产物中是否残留 Apex 标识。
|
|
10
|
+
|
|
11
|
+
当前版本支持 Vite 4–7;未经过 Vite 构建的 CDN 或远程资源不会被改写。
|
|
12
|
+
|
|
13
|
+
## 接入
|
|
14
|
+
|
|
15
|
+
没有具体前缀时先向用户询问。前缀必须是 2–32 位小写 kebab-case,不能使用 `react`、`vite`、
|
|
16
|
+
`radix` 或 `headlessui` 等保留词。
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pnpm add -D @apexhub/apex-ui-rewrite-prefix-plugin
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { rewriteApexPrefix } from '@apexhub/apex-ui-rewrite-prefix-plugin'
|
|
24
|
+
import react from '@vitejs/plugin-react'
|
|
25
|
+
import { defineConfig } from 'vite'
|
|
26
|
+
|
|
27
|
+
export default defineConfig({
|
|
28
|
+
plugins: [
|
|
29
|
+
rewriteApexPrefix({ prefix: 'YOUR_PREFIX' }),
|
|
30
|
+
react(),
|
|
31
|
+
],
|
|
32
|
+
build: { sourcemap: false },
|
|
33
|
+
esbuild: { keepNames: false },
|
|
34
|
+
})
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`YOUR_PREFIX` 必须替换成用户给出的值,不要擅自填示例前缀。业务代码继续这样写:
|
|
38
|
+
|
|
39
|
+
```tsx
|
|
40
|
+
import { ApexProvider, Button } from '@apexhub/apex-ui-react'
|
|
41
|
+
import '@apexhub/apex-ui-react/style.css'
|
|
42
|
+
|
|
43
|
+
export function App() {
|
|
44
|
+
return <ApexProvider><Button type="primary">提交</Button></ApexProvider>
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## API 与验收
|
|
49
|
+
|
|
50
|
+
`rewriteApexPrefix({ prefix, consoleBrand?, cleanBundle? })` 接受技术前缀、可选日志品牌和构建检查开关。
|
|
51
|
+
生产构建建议使用 `cleanBundle` 默认值、关闭 source map,并确认最终 JS、CSS、HTML 和 JSON 中没有
|
|
52
|
+
旧的 `apex-*` 或 `--apex-*` 标识。具体审计报告由插件写入 `.artifacts/`,该目录适合作为本地构建产物。
|
|
53
|
+
|
|
54
|
+
恢复默认命名空间时删除插件并重新构建。
|
|
55
|
+
|
|
56
|
+
## License
|
|
57
|
+
|
|
58
|
+
MIT
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { IdentityContext } from './identity-rules';
|
|
2
|
+
export declare const CLEAN_BUNDLE_DEFAULT_REPORT_FILE = ".artifacts/apex-prefix-audit.json";
|
|
3
|
+
/**
|
|
4
|
+
* 内部解析后的产物校验配置(不对外暴露细项)。
|
|
5
|
+
*/
|
|
6
|
+
export interface ResolvedCleanBundleOptions {
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
/** 仅供单测注入放行规则;插件公开 API 不提供 allow */
|
|
9
|
+
allow: Array<string | RegExp>;
|
|
10
|
+
reportFile: string | null;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* 将公开的 `cleanBundle?: boolean` 解析为内部完整配置。
|
|
14
|
+
*
|
|
15
|
+
* 默认:生产构建开启,开发模式关闭。
|
|
16
|
+
* 校验策略(source map / markers / 报告路径)全部内置,不开放配置。
|
|
17
|
+
*/
|
|
18
|
+
export declare function resolveCleanBundleOptions(input: boolean | undefined, isBuild: boolean): ResolvedCleanBundleOptions;
|
|
19
|
+
export interface BundleLikeChunk {
|
|
20
|
+
type: 'chunk';
|
|
21
|
+
fileName: string;
|
|
22
|
+
code: string;
|
|
23
|
+
}
|
|
24
|
+
export interface BundleLikeAsset {
|
|
25
|
+
type: 'asset';
|
|
26
|
+
fileName: string;
|
|
27
|
+
source: string | Uint8Array;
|
|
28
|
+
}
|
|
29
|
+
export type BundleLikeItem = BundleLikeChunk | BundleLikeAsset;
|
|
30
|
+
export type BundleLike = Record<string, BundleLikeItem>;
|
|
31
|
+
export interface AuditableAsset {
|
|
32
|
+
fileName: string;
|
|
33
|
+
content: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 从 Rollup/Vite 的 `OutputBundle` 中提取可做文本校验的产物内容。
|
|
37
|
+
* 二进制资产(图片/字体等)会被跳过。
|
|
38
|
+
*/
|
|
39
|
+
export declare function collectTextAssets(bundle: BundleLike): AuditableAsset[];
|
|
40
|
+
export type AuditFindingCategory = 'identity-marker' | 'internal-path' | 'source-map';
|
|
41
|
+
export interface AuditFinding {
|
|
42
|
+
file: string;
|
|
43
|
+
category: AuditFindingCategory;
|
|
44
|
+
ruleId: string;
|
|
45
|
+
snippet: string;
|
|
46
|
+
}
|
|
47
|
+
export interface AuditReport {
|
|
48
|
+
ok: boolean;
|
|
49
|
+
prefix: string;
|
|
50
|
+
generatedAt: string;
|
|
51
|
+
findings: AuditFinding[];
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* 扫描最终构建产物,确认前缀替换完整且没有敏感信息泄露。
|
|
55
|
+
*
|
|
56
|
+
* - identity-marker:复用 identity-rules;`prefix === 'apex'` 时跳过
|
|
57
|
+
* - internal-path / source-map:无论 prefix 都会检查
|
|
58
|
+
*/
|
|
59
|
+
export declare function runAudit(assets: AuditableAsset[], options: ResolvedCleanBundleOptions, ctx: IdentityContext): AuditReport;
|
|
60
|
+
/**
|
|
61
|
+
* 生成校验失败信息:仅输出"文件名 + 规则 id + 短片段",不打印完整产物内容。
|
|
62
|
+
*/
|
|
63
|
+
export declare function formatAuditFailure(report: AuditReport): string;
|
|
64
|
+
/**
|
|
65
|
+
* 将校验报告写入磁盘(默认 `.artifacts/apex-prefix-audit.json`)。
|
|
66
|
+
*/
|
|
67
|
+
export declare function writeAuditReport(reportFile: string, report: AuditReport, root?: string): void;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* identity-rules.ts —— 前缀/品牌标识的唯一规则集。
|
|
3
|
+
*
|
|
4
|
+
* transform-script.ts / transform-css.ts / transform-html.ts(转换器)与
|
|
5
|
+
* audit-bundle.ts(产物校验)都只依赖本文件导出的 {@link findIdentityMatches},
|
|
6
|
+
* 确保"转换会改什么"与"校验会查什么"永远是同一份规则,不会出现两边定义漂移。
|
|
7
|
+
*
|
|
8
|
+
* 匹配优先级(先处理最长/更具体的标识,避免被更宽泛的规则提前截断或误吞):
|
|
9
|
+
* 1. `__APEX_UI_NAMESPACE__` 运行时前缀哨兵常量
|
|
10
|
+
* 2. `[Apex UI]` 产品品牌标记(精确匹配,不带子名)
|
|
11
|
+
* 3. `[Apex XxxYyy]` 组件级品牌标记(保留组件名后缀)
|
|
12
|
+
* 4. `--apex-` CSS 自定义属性前缀
|
|
13
|
+
* 5. `__apex_` JS 内部标记前缀
|
|
14
|
+
* 6. `apex-` 通用类名/data 属性前缀
|
|
15
|
+
*
|
|
16
|
+
* 该优先级通过一条单一的、按上述顺序排列的交替(alternation)正则实现:
|
|
17
|
+
* JS 正则引擎在同一起始位置从左到右尝试各分支,命中即停止,天然保证"更具体/更长的
|
|
18
|
+
* 标识优先",且由于是单趟扫描 + 命中后跳过整个匹配长度,不会出现重复/交叉替换。
|
|
19
|
+
*/
|
|
20
|
+
export interface IdentityContext {
|
|
21
|
+
/** 目标技术前缀(已通过 validatePrefix 校验) */
|
|
22
|
+
prefix: string;
|
|
23
|
+
/** 控制台/警告中的展示品牌名 */
|
|
24
|
+
consoleBrand: string;
|
|
25
|
+
}
|
|
26
|
+
export type IdentityRuleId = 'namespace-sentinel' | 'brand-ui-marker' | 'brand-component-marker' | 'css-custom-property-prefix' | 'js-internal-marker' | 'class-prefix';
|
|
27
|
+
export interface IdentityMatch {
|
|
28
|
+
ruleId: IdentityRuleId;
|
|
29
|
+
/** 匹配片段在原始文本中的起始偏移 */
|
|
30
|
+
start: number;
|
|
31
|
+
/** 匹配片段在原始文本中的结束偏移(不含) */
|
|
32
|
+
end: number;
|
|
33
|
+
/** 命中的原始片段 */
|
|
34
|
+
original: string;
|
|
35
|
+
/** 替换后的片段 */
|
|
36
|
+
replacement: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* 快速判断文本中是否存在任何"可能"命中规则的子串,供转换器/校验器在正式解析
|
|
40
|
+
* (AST parse / PostCSS parse / 全量正则扫描)前做低成本短路,避免对无关文件做无谓开销。
|
|
41
|
+
*/
|
|
42
|
+
export declare function hasPotentialIdentityMarkers(text: string): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* 在给定文本中查找所有需要重写的标识片段。
|
|
45
|
+
*
|
|
46
|
+
* 已经是"无操作"的匹配(替换结果与原文完全相同,典型场景:`prefix` 恰好为
|
|
47
|
+
* `'apex'`,或 `consoleBrand` 恰好为默认值 `'Apex UI'`)会被自动过滤掉,
|
|
48
|
+
* 不会出现在返回结果中——这样转换器与校验器都无需再单独处理"要不要跳过"的判断。
|
|
49
|
+
*/
|
|
50
|
+
export declare function findIdentityMatches(text: string, ctx: IdentityContext): IdentityMatch[];
|
|
51
|
+
/**
|
|
52
|
+
* 基于 {@link findIdentityMatches} 对整段文本做一次性重写,适用于不需要保留
|
|
53
|
+
* AST/CSS 结构、可以直接做整体字符串替换的场景(如 index.html)。
|
|
54
|
+
*/
|
|
55
|
+
export declare function applyIdentityRules(text: string, ctx: IdentityContext): {
|
|
56
|
+
output: string;
|
|
57
|
+
changed: boolean;
|
|
58
|
+
matches: IdentityMatch[];
|
|
59
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
import type { RewriteApexPrefixOptions } from './interface';
|
|
3
|
+
export type { RewriteApexPrefixOptions } from './interface';
|
|
4
|
+
/**
|
|
5
|
+
* Apex UI 前缀替换 Vite 插件。
|
|
6
|
+
*
|
|
7
|
+
* 在构建期将 Apex UI 组件库产物与业务源码中的
|
|
8
|
+
* `apex-` 类名前缀、`--apex-` CSS 变量前缀、`__apex_` 内部标记前缀、
|
|
9
|
+
* `[Apex UI]`/`[Apex Button]` 品牌日志标记,统一重写为团队自有前缀/品牌名。
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* // vite.config.ts
|
|
14
|
+
* import { rewriteApexPrefix } from '@apexhub/apex-ui-rewrite-prefix-plugin'
|
|
15
|
+
*
|
|
16
|
+
* export default defineConfig({
|
|
17
|
+
* plugins: [
|
|
18
|
+
* rewriteApexPrefix({ prefix: 'falcon' }),
|
|
19
|
+
* // 或自定义日志品牌名:
|
|
20
|
+
* // rewriteApexPrefix({ prefix: 'host', consoleBrand: 'Host UI' }),
|
|
21
|
+
* ],
|
|
22
|
+
* })
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export declare function rewriteApexPrefix(options: RewriteApexPrefixOptions): Plugin;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, resolve, dirname } from "node:path";
|
|
3
|
+
import postcss from "postcss";
|
|
4
|
+
import { parse } from "@babel/parser";
|
|
5
|
+
import traverseModule from "@babel/traverse";
|
|
6
|
+
import * as t from "@babel/types";
|
|
7
|
+
import MagicString from "magic-string";
|
|
8
|
+
import { parse as parse$1 } from "@vue/compiler-sfc";
|
|
9
|
+
const IDENTITY_PATTERN_SOURCE = "(?<sentinel>__APEX_UI_NAMESPACE__)|(?<brandUi>\\[Apex UI\\])|\\[Apex (?<brandComponent>[A-Z][A-Za-z0-9]*(?: [A-Z][A-Za-z0-9]*)*)\\]|(?<cssVar>--apex-)|(?<jsInternal>__apex_)|(?<![a-z0-9])(?<classPrefix>apex-)";
|
|
10
|
+
const HINT_PATTERN = /apex[-_]|--apex-|\[Apex |__APEX_UI_NAMESPACE__/;
|
|
11
|
+
function hasPotentialIdentityMarkers(text) {
|
|
12
|
+
return HINT_PATTERN.test(text);
|
|
13
|
+
}
|
|
14
|
+
function resolveRuleId(groups) {
|
|
15
|
+
if (groups.sentinel !== void 0) return "namespace-sentinel";
|
|
16
|
+
if (groups.brandUi !== void 0) return "brand-ui-marker";
|
|
17
|
+
if (groups.brandComponent !== void 0) return "brand-component-marker";
|
|
18
|
+
if (groups.cssVar !== void 0) return "css-custom-property-prefix";
|
|
19
|
+
if (groups.jsInternal !== void 0) return "js-internal-marker";
|
|
20
|
+
if (groups.classPrefix !== void 0) return "class-prefix";
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
function buildReplacement(ruleId, groups, ctx) {
|
|
24
|
+
switch (ruleId) {
|
|
25
|
+
case "namespace-sentinel":
|
|
26
|
+
return ctx.prefix;
|
|
27
|
+
case "brand-ui-marker":
|
|
28
|
+
return `[${ctx.consoleBrand}]`;
|
|
29
|
+
case "brand-component-marker":
|
|
30
|
+
return `[${ctx.consoleBrand} ${groups.brandComponent}]`;
|
|
31
|
+
case "css-custom-property-prefix":
|
|
32
|
+
return `--${ctx.prefix}-`;
|
|
33
|
+
case "js-internal-marker":
|
|
34
|
+
return `__${ctx.prefix}_`;
|
|
35
|
+
case "class-prefix":
|
|
36
|
+
return `${ctx.prefix}-`;
|
|
37
|
+
default:
|
|
38
|
+
return "";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function findIdentityMatches(text, ctx) {
|
|
42
|
+
if (!hasPotentialIdentityMarkers(text)) return [];
|
|
43
|
+
const pattern = new RegExp(IDENTITY_PATTERN_SOURCE, "g");
|
|
44
|
+
const matches = [];
|
|
45
|
+
let execResult = pattern.exec(text);
|
|
46
|
+
while (execResult !== null) {
|
|
47
|
+
const groups = execResult.groups ?? {};
|
|
48
|
+
const ruleId = resolveRuleId(groups);
|
|
49
|
+
if (ruleId) {
|
|
50
|
+
const replacement = buildReplacement(ruleId, groups, ctx);
|
|
51
|
+
if (replacement !== execResult[0]) {
|
|
52
|
+
matches.push({
|
|
53
|
+
ruleId,
|
|
54
|
+
start: execResult.index,
|
|
55
|
+
end: execResult.index + execResult[0].length,
|
|
56
|
+
original: execResult[0],
|
|
57
|
+
replacement
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
execResult = pattern.exec(text);
|
|
62
|
+
}
|
|
63
|
+
return matches;
|
|
64
|
+
}
|
|
65
|
+
function applyIdentityRules(text, ctx) {
|
|
66
|
+
const matches = findIdentityMatches(text, ctx);
|
|
67
|
+
if (matches.length === 0) {
|
|
68
|
+
return { output: text, changed: false, matches };
|
|
69
|
+
}
|
|
70
|
+
let output = "";
|
|
71
|
+
let cursor = 0;
|
|
72
|
+
for (const match of matches) {
|
|
73
|
+
output += text.slice(cursor, match.start) + match.replacement;
|
|
74
|
+
cursor = match.end;
|
|
75
|
+
}
|
|
76
|
+
output += text.slice(cursor);
|
|
77
|
+
return { output, changed: true, matches };
|
|
78
|
+
}
|
|
79
|
+
const CLEAN_BUNDLE_DEFAULT_REPORT_FILE = ".artifacts/apex-prefix-audit.json";
|
|
80
|
+
function resolveCleanBundleOptions(input, isBuild) {
|
|
81
|
+
return {
|
|
82
|
+
enabled: input ?? isBuild,
|
|
83
|
+
allow: [],
|
|
84
|
+
reportFile: CLEAN_BUNDLE_DEFAULT_REPORT_FILE
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
const TEXT_ASSET_PATTERN = /\.(?:m?[jc]s|css|html?|json|map)$/i;
|
|
88
|
+
function collectTextAssets(bundle) {
|
|
89
|
+
const assets = [];
|
|
90
|
+
for (const item of Object.values(bundle)) {
|
|
91
|
+
if (item.type === "chunk") {
|
|
92
|
+
assets.push({ fileName: item.fileName, content: item.code });
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (!TEXT_ASSET_PATTERN.test(item.fileName)) continue;
|
|
96
|
+
const content = typeof item.source === "string" ? item.source : Buffer.from(item.source).toString("utf8");
|
|
97
|
+
assets.push({ fileName: item.fileName, content });
|
|
98
|
+
}
|
|
99
|
+
return assets;
|
|
100
|
+
}
|
|
101
|
+
const INTERNAL_PATH_RULES = [
|
|
102
|
+
{ id: "package-import-name", pattern: /@frontend\/apex-ui--(?:react|vue)/g },
|
|
103
|
+
{ id: "internal-monorepo-source-path", pattern: /packages\/(?:react|vue)\/src/g },
|
|
104
|
+
{ id: "internal-package-path", pattern: /node_modules\/@frontend\/apex-ui/g }
|
|
105
|
+
];
|
|
106
|
+
const SOURCE_MAP_COMMENT_PATTERN = /\/\/[#@]\s*sourceMappingURL=\S+/g;
|
|
107
|
+
const FILENAME_MARKER_PATTERN = /(?:^|[^a-z0-9])apex[-_]|--apex-|__apex_/i;
|
|
108
|
+
const SNIPPET_RADIUS = 24;
|
|
109
|
+
function extractSnippet(content, start, end) {
|
|
110
|
+
const from = Math.max(0, start - SNIPPET_RADIUS);
|
|
111
|
+
const to = Math.min(content.length, end + SNIPPET_RADIUS);
|
|
112
|
+
const prefix = from > 0 ? "…" : "";
|
|
113
|
+
const suffix = to < content.length ? "…" : "";
|
|
114
|
+
return `${prefix}${content.slice(from, to).replace(/\s+/g, " ")}${suffix}`;
|
|
115
|
+
}
|
|
116
|
+
function isAllowed(matchedText, fileName, allow, content, start = 0, end = matchedText.length) {
|
|
117
|
+
return allow.some((entry) => {
|
|
118
|
+
if (typeof entry === "string") {
|
|
119
|
+
if (fileName === entry || matchedText === entry) return true;
|
|
120
|
+
if (!content) return matchedText.includes(entry);
|
|
121
|
+
let idx = content.indexOf(entry);
|
|
122
|
+
while (idx !== -1) {
|
|
123
|
+
if (start >= idx && end <= idx + entry.length) return true;
|
|
124
|
+
idx = content.indexOf(entry, idx + 1);
|
|
125
|
+
}
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
return entry.test(matchedText) || entry.test(fileName);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
function runAudit(assets, options, ctx) {
|
|
132
|
+
const findings = [];
|
|
133
|
+
const skipIdentityChecks = ctx.prefix === "apex";
|
|
134
|
+
for (const asset of assets) {
|
|
135
|
+
if (!skipIdentityChecks) {
|
|
136
|
+
if (FILENAME_MARKER_PATTERN.test(asset.fileName) && !isAllowed(asset.fileName, asset.fileName, options.allow)) {
|
|
137
|
+
findings.push({
|
|
138
|
+
file: asset.fileName,
|
|
139
|
+
category: "identity-marker",
|
|
140
|
+
ruleId: "filename-apex-marker",
|
|
141
|
+
snippet: asset.fileName
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
const matches = findIdentityMatches(asset.content, ctx);
|
|
145
|
+
for (const match of matches) {
|
|
146
|
+
if (isAllowed(
|
|
147
|
+
match.original,
|
|
148
|
+
asset.fileName,
|
|
149
|
+
options.allow,
|
|
150
|
+
asset.content,
|
|
151
|
+
match.start,
|
|
152
|
+
match.end
|
|
153
|
+
)) {
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
findings.push({
|
|
157
|
+
file: asset.fileName,
|
|
158
|
+
category: "identity-marker",
|
|
159
|
+
ruleId: match.ruleId,
|
|
160
|
+
snippet: extractSnippet(asset.content, match.start, match.end)
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
for (const rule of INTERNAL_PATH_RULES) {
|
|
165
|
+
if (skipIdentityChecks && rule.id === "package-import-name") continue;
|
|
166
|
+
rule.pattern.lastIndex = 0;
|
|
167
|
+
let execResult2 = rule.pattern.exec(asset.content);
|
|
168
|
+
while (execResult2 !== null) {
|
|
169
|
+
const start = execResult2.index;
|
|
170
|
+
const end = start + execResult2[0].length;
|
|
171
|
+
if (!isAllowed(execResult2[0], asset.fileName, options.allow, asset.content, start, end)) {
|
|
172
|
+
findings.push({
|
|
173
|
+
file: asset.fileName,
|
|
174
|
+
category: "internal-path",
|
|
175
|
+
ruleId: rule.id,
|
|
176
|
+
snippet: extractSnippet(asset.content, start, end)
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
execResult2 = rule.pattern.exec(asset.content);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (/\.map$/i.test(asset.fileName) && !isAllowed(asset.fileName, asset.fileName, options.allow)) {
|
|
183
|
+
findings.push({
|
|
184
|
+
file: asset.fileName,
|
|
185
|
+
category: "source-map",
|
|
186
|
+
ruleId: "source-map-file-in-output",
|
|
187
|
+
snippet: asset.fileName
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
SOURCE_MAP_COMMENT_PATTERN.lastIndex = 0;
|
|
191
|
+
let execResult = SOURCE_MAP_COMMENT_PATTERN.exec(asset.content);
|
|
192
|
+
while (execResult !== null) {
|
|
193
|
+
const start = execResult.index;
|
|
194
|
+
const end = start + execResult[0].length;
|
|
195
|
+
if (!isAllowed(execResult[0], asset.fileName, options.allow, asset.content, start, end)) {
|
|
196
|
+
findings.push({
|
|
197
|
+
file: asset.fileName,
|
|
198
|
+
category: "source-map",
|
|
199
|
+
ruleId: "source-map-comment-in-output",
|
|
200
|
+
snippet: extractSnippet(asset.content, start, end)
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
execResult = SOURCE_MAP_COMMENT_PATTERN.exec(asset.content);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
ok: findings.length === 0,
|
|
208
|
+
prefix: ctx.prefix,
|
|
209
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
210
|
+
findings
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
const MAX_PRINTED_FINDINGS = 20;
|
|
214
|
+
function formatAuditFailure(report) {
|
|
215
|
+
const lines = [
|
|
216
|
+
`[apex-ui:rewrite-prefix] cleanBundle 失败:检测到 ${report.findings.length} 处前缀/标识残留(prefix="${report.prefix}")`
|
|
217
|
+
];
|
|
218
|
+
for (const finding of report.findings.slice(0, MAX_PRINTED_FINDINGS)) {
|
|
219
|
+
lines.push(` - ${finding.file} [${finding.category}:${finding.ruleId}] ${finding.snippet}`);
|
|
220
|
+
}
|
|
221
|
+
if (report.findings.length > MAX_PRINTED_FINDINGS) {
|
|
222
|
+
lines.push(
|
|
223
|
+
` ...以及另外 ${report.findings.length - MAX_PRINTED_FINDINGS} 处(完整结果见报告文件)`
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
return lines.join("\n");
|
|
227
|
+
}
|
|
228
|
+
function writeAuditReport(reportFile, report, root = process.cwd()) {
|
|
229
|
+
const target = isAbsolute(reportFile) ? reportFile : resolve(root, reportFile);
|
|
230
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
231
|
+
writeFileSync(target, `${JSON.stringify(report, null, 2)}
|
|
232
|
+
`, "utf8");
|
|
233
|
+
}
|
|
234
|
+
function rewrite(text, ctx) {
|
|
235
|
+
const matches = findIdentityMatches(text, ctx);
|
|
236
|
+
if (matches.length === 0) return { output: text, changed: false };
|
|
237
|
+
const protectedRanges = [];
|
|
238
|
+
const protectPattern = /url\(\s*['"]?[^'")]+['"]?\s*\)|data:[^\s;)]+/gi;
|
|
239
|
+
let protectMatch = protectPattern.exec(text);
|
|
240
|
+
while (protectMatch) {
|
|
241
|
+
protectedRanges.push({
|
|
242
|
+
start: protectMatch.index,
|
|
243
|
+
end: protectMatch.index + protectMatch[0].length
|
|
244
|
+
});
|
|
245
|
+
protectMatch = protectPattern.exec(text);
|
|
246
|
+
}
|
|
247
|
+
const isProtected = (start, end) => protectedRanges.some((range) => start < range.end && end > range.start);
|
|
248
|
+
let output = "";
|
|
249
|
+
let cursor = 0;
|
|
250
|
+
let changed = false;
|
|
251
|
+
for (const match of matches) {
|
|
252
|
+
if (isProtected(match.start, match.end)) continue;
|
|
253
|
+
output += text.slice(cursor, match.start) + match.replacement;
|
|
254
|
+
cursor = match.end;
|
|
255
|
+
changed = true;
|
|
256
|
+
}
|
|
257
|
+
output += text.slice(cursor);
|
|
258
|
+
return { output: changed ? output : text, changed };
|
|
259
|
+
}
|
|
260
|
+
function transformCss(code, pathname, ctx) {
|
|
261
|
+
if (!hasPotentialIdentityMarkers(code)) return null;
|
|
262
|
+
let root;
|
|
263
|
+
try {
|
|
264
|
+
root = postcss.parse(code, { from: pathname });
|
|
265
|
+
} catch {
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
let changed = false;
|
|
269
|
+
root.walkRules((rule) => {
|
|
270
|
+
const result2 = rewrite(rule.selector, ctx);
|
|
271
|
+
if (result2.changed) {
|
|
272
|
+
rule.selector = result2.output;
|
|
273
|
+
changed = true;
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
root.walkAtRules((atRule) => {
|
|
277
|
+
if (!atRule.params) return;
|
|
278
|
+
let params = atRule.params;
|
|
279
|
+
if (atRule.name === "layer") {
|
|
280
|
+
const layerRewritten = params.replace(/(^|[\s,])apex(?=\.|$|[\s,])/g, `$1${ctx.prefix}`);
|
|
281
|
+
if (layerRewritten !== params) {
|
|
282
|
+
params = layerRewritten;
|
|
283
|
+
changed = true;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const result2 = rewrite(params, ctx);
|
|
287
|
+
if (result2.changed) {
|
|
288
|
+
params = result2.output;
|
|
289
|
+
changed = true;
|
|
290
|
+
}
|
|
291
|
+
atRule.params = params;
|
|
292
|
+
});
|
|
293
|
+
root.walkDecls((decl) => {
|
|
294
|
+
const propResult = rewrite(decl.prop, ctx);
|
|
295
|
+
if (propResult.changed) {
|
|
296
|
+
decl.prop = propResult.output;
|
|
297
|
+
changed = true;
|
|
298
|
+
}
|
|
299
|
+
const valueResult = rewrite(decl.value, ctx);
|
|
300
|
+
if (valueResult.changed) {
|
|
301
|
+
decl.value = valueResult.output;
|
|
302
|
+
changed = true;
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
root.walkComments((comment) => {
|
|
306
|
+
if (ctx.prefix !== "apex") {
|
|
307
|
+
comment.remove();
|
|
308
|
+
changed = true;
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const result2 = rewrite(comment.text, ctx);
|
|
312
|
+
if (result2.changed) {
|
|
313
|
+
comment.text = result2.output;
|
|
314
|
+
changed = true;
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
if (!changed) return null;
|
|
318
|
+
const result = root.toResult({ to: pathname, map: { inline: false, annotation: false } });
|
|
319
|
+
return { code: result.css, map: result.map ?? null };
|
|
320
|
+
}
|
|
321
|
+
function createPrefixPostcssPlugin(ctx) {
|
|
322
|
+
return {
|
|
323
|
+
postcssPlugin: "apex-ui-rewrite-prefix",
|
|
324
|
+
Once(root, helper) {
|
|
325
|
+
const from = helper.result.opts.from ?? "virtual.css";
|
|
326
|
+
const input = root.toResult({ to: from, map: false }).css;
|
|
327
|
+
if (!hasPotentialIdentityMarkers(input)) return;
|
|
328
|
+
const transformed = transformCss(input, from, ctx);
|
|
329
|
+
if (!transformed) return;
|
|
330
|
+
const next = postcss.parse(transformed.code, { from });
|
|
331
|
+
root.removeAll();
|
|
332
|
+
next.each((node) => {
|
|
333
|
+
root.append(node);
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
createPrefixPostcssPlugin.postcss = true;
|
|
339
|
+
function transformHtml(html, ctx) {
|
|
340
|
+
if (!hasPotentialIdentityMarkers(html)) return null;
|
|
341
|
+
const { output, changed } = applyIdentityRules(html, ctx);
|
|
342
|
+
return changed ? output : null;
|
|
343
|
+
}
|
|
344
|
+
const traverse = typeof traverseModule === "function" ? traverseModule : traverseModule.default;
|
|
345
|
+
const SCRIPT_ID_PATTERN = /\.(?:[cm]?[jt]sx?)$/;
|
|
346
|
+
function isScriptId(pathname) {
|
|
347
|
+
return SCRIPT_ID_PATTERN.test(pathname);
|
|
348
|
+
}
|
|
349
|
+
function getParserPlugins(pathname) {
|
|
350
|
+
const plugins = [
|
|
351
|
+
"classProperties",
|
|
352
|
+
"classPrivateProperties",
|
|
353
|
+
"classPrivateMethods",
|
|
354
|
+
"objectRestSpread",
|
|
355
|
+
"optionalChaining",
|
|
356
|
+
"nullishCoalescingOperator",
|
|
357
|
+
"topLevelAwait",
|
|
358
|
+
"importMeta",
|
|
359
|
+
"decorators-legacy"
|
|
360
|
+
];
|
|
361
|
+
if (/\.tsx?$/.test(pathname)) plugins.push("typescript");
|
|
362
|
+
if (/\.[jt]sx$/.test(pathname)) plugins.push("jsx");
|
|
363
|
+
return plugins;
|
|
364
|
+
}
|
|
365
|
+
function isModuleSpecifierString(path) {
|
|
366
|
+
const { parent } = path;
|
|
367
|
+
if (t.isImportDeclaration(parent) && parent.source === path.node) return true;
|
|
368
|
+
if ((t.isExportNamedDeclaration(parent) || t.isExportAllDeclaration(parent)) && parent.source === path.node) {
|
|
369
|
+
return true;
|
|
370
|
+
}
|
|
371
|
+
if (t.isImportExpression(parent) && parent.source === path.node) return true;
|
|
372
|
+
if (t.isCallExpression(parent) && t.isIdentifier(parent.callee) && parent.callee.name === "require" && parent.arguments[0] === path.node) {
|
|
373
|
+
return true;
|
|
374
|
+
}
|
|
375
|
+
return false;
|
|
376
|
+
}
|
|
377
|
+
function transformScript(code, pathname, ctx) {
|
|
378
|
+
if (!hasPotentialIdentityMarkers(code)) return null;
|
|
379
|
+
let ast;
|
|
380
|
+
try {
|
|
381
|
+
ast = parse(code, {
|
|
382
|
+
sourceType: "unambiguous",
|
|
383
|
+
errorRecovery: true,
|
|
384
|
+
plugins: getParserPlugins(pathname)
|
|
385
|
+
});
|
|
386
|
+
} catch {
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
const magic = new MagicString(code);
|
|
390
|
+
let changed = false;
|
|
391
|
+
traverse(ast, {
|
|
392
|
+
StringLiteral(path) {
|
|
393
|
+
const { node } = path;
|
|
394
|
+
if (node.start == null || node.end == null) return;
|
|
395
|
+
if (isModuleSpecifierString(path)) return;
|
|
396
|
+
const raw = code.slice(node.start + 1, node.end - 1);
|
|
397
|
+
const matches = findIdentityMatches(raw, ctx);
|
|
398
|
+
for (const match of matches) {
|
|
399
|
+
magic.overwrite(node.start + 1 + match.start, node.start + 1 + match.end, match.replacement);
|
|
400
|
+
changed = true;
|
|
401
|
+
}
|
|
402
|
+
},
|
|
403
|
+
TemplateElement(path) {
|
|
404
|
+
const { node } = path;
|
|
405
|
+
if (node.start == null || node.end == null) return;
|
|
406
|
+
const raw = node.value.raw;
|
|
407
|
+
const matches = findIdentityMatches(raw, ctx);
|
|
408
|
+
for (const match of matches) {
|
|
409
|
+
magic.overwrite(node.start + match.start, node.start + match.end, match.replacement);
|
|
410
|
+
changed = true;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
if (!changed) return null;
|
|
415
|
+
return {
|
|
416
|
+
code: magic.toString(),
|
|
417
|
+
map: magic.generateMap({ hires: true, source: pathname, includeContent: false })
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function isVueId(pathname) {
|
|
421
|
+
return pathname.endsWith(".vue");
|
|
422
|
+
}
|
|
423
|
+
function scriptPathname(pathname, block) {
|
|
424
|
+
const lang = block.lang === "ts" || block.lang === "tsx" ? block.lang : "js";
|
|
425
|
+
return `${pathname}?vue&type=script&lang.${lang}`;
|
|
426
|
+
}
|
|
427
|
+
function transformBlockContent(content, pathname, ctx, kind) {
|
|
428
|
+
var _a, _b;
|
|
429
|
+
if (kind === "template") {
|
|
430
|
+
const { output, changed } = applyIdentityRules(content, ctx);
|
|
431
|
+
return changed ? output : null;
|
|
432
|
+
}
|
|
433
|
+
if (kind === "script") {
|
|
434
|
+
return ((_a = transformScript(content, pathname, ctx)) == null ? void 0 : _a.code) ?? null;
|
|
435
|
+
}
|
|
436
|
+
return ((_b = transformCss(content, pathname, ctx)) == null ? void 0 : _b.code) ?? null;
|
|
437
|
+
}
|
|
438
|
+
function overwriteBlock(magic, block, nextContent) {
|
|
439
|
+
const { start, end } = block.loc;
|
|
440
|
+
magic.overwrite(start.offset, end.offset, nextContent);
|
|
441
|
+
}
|
|
442
|
+
function transformVue(code, pathname, ctx) {
|
|
443
|
+
if (!hasPotentialIdentityMarkers(code)) return null;
|
|
444
|
+
const { descriptor, errors } = parse$1(code, { filename: pathname });
|
|
445
|
+
if (errors.length > 0) return null;
|
|
446
|
+
const magic = new MagicString(code);
|
|
447
|
+
let changed = false;
|
|
448
|
+
const template = descriptor.template;
|
|
449
|
+
if (template == null ? void 0 : template.content) {
|
|
450
|
+
const next = transformBlockContent(template.content, pathname, ctx, "template");
|
|
451
|
+
if (next) {
|
|
452
|
+
overwriteBlock(magic, template, next);
|
|
453
|
+
changed = true;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
for (const script of [descriptor.script, descriptor.scriptSetup]) {
|
|
457
|
+
if (!(script == null ? void 0 : script.content)) continue;
|
|
458
|
+
const next = transformBlockContent(
|
|
459
|
+
script.content,
|
|
460
|
+
scriptPathname(pathname, script),
|
|
461
|
+
ctx,
|
|
462
|
+
"script"
|
|
463
|
+
);
|
|
464
|
+
if (next) {
|
|
465
|
+
overwriteBlock(magic, script, next);
|
|
466
|
+
changed = true;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
for (const style of descriptor.styles) {
|
|
470
|
+
if (!style.content) continue;
|
|
471
|
+
const next = transformBlockContent(style.content, pathname, ctx, "style");
|
|
472
|
+
if (next) {
|
|
473
|
+
overwriteBlock(magic, style, next);
|
|
474
|
+
changed = true;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (!changed) return null;
|
|
478
|
+
return {
|
|
479
|
+
code: magic.toString(),
|
|
480
|
+
map: magic.generateMap({ hires: true, source: pathname, includeContent: false })
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
const PREFIX_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
484
|
+
const PREFIX_MIN_LENGTH = 2;
|
|
485
|
+
const PREFIX_MAX_LENGTH = 32;
|
|
486
|
+
const RESERVED_PREFIXES = ["radix", "headlessui", "react", "vite"];
|
|
487
|
+
class PrefixValidationError extends Error {
|
|
488
|
+
constructor(message) {
|
|
489
|
+
super(message);
|
|
490
|
+
this.name = "PrefixValidationError";
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
function defaultConsoleBrand(prefix) {
|
|
494
|
+
if (prefix.length === 0) return prefix;
|
|
495
|
+
return prefix[0].toUpperCase() + prefix.slice(1);
|
|
496
|
+
}
|
|
497
|
+
function validatePrefix(prefix) {
|
|
498
|
+
if (typeof prefix !== "string" || prefix.length === 0) {
|
|
499
|
+
throw new PrefixValidationError(
|
|
500
|
+
`[apex-ui:rewrite-prefix] prefix 必须是非空字符串,实际收到:${JSON.stringify(prefix)}`
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
if (prefix.length < PREFIX_MIN_LENGTH || prefix.length > PREFIX_MAX_LENGTH) {
|
|
504
|
+
throw new PrefixValidationError(
|
|
505
|
+
`[apex-ui:rewrite-prefix] prefix 长度必须在 ${PREFIX_MIN_LENGTH}~${PREFIX_MAX_LENGTH} 之间,"${prefix}" 长度为 ${prefix.length}`
|
|
506
|
+
);
|
|
507
|
+
}
|
|
508
|
+
if (!PREFIX_PATTERN.test(prefix)) {
|
|
509
|
+
throw new PrefixValidationError(
|
|
510
|
+
`[apex-ui:rewrite-prefix] prefix "${prefix}" 不合法,必须匹配 ${PREFIX_PATTERN.source}(小写字母开头,可含数字与连字符,不能以连字符开头/结尾,不能出现连续连字符)`
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
const reservedHit = RESERVED_PREFIXES.find(
|
|
514
|
+
(reserved) => prefix === reserved || prefix.startsWith(`${reserved}-`)
|
|
515
|
+
);
|
|
516
|
+
if (reservedHit) {
|
|
517
|
+
throw new PrefixValidationError(
|
|
518
|
+
`[apex-ui:rewrite-prefix] prefix "${prefix}" 使用了保留前缀 "${reservedHit}",请更换其他前缀`
|
|
519
|
+
);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
const CONSUMER_PACKAGES = ["@apexhub/apex-ui-react", "@apexhub/apex-ui-vue"];
|
|
523
|
+
const PLUGIN_NAME = "apex-ui:rewrite-prefix";
|
|
524
|
+
function stripQuery(id) {
|
|
525
|
+
const queryIndex = id.indexOf("?");
|
|
526
|
+
return queryIndex === -1 ? id : id.slice(0, queryIndex);
|
|
527
|
+
}
|
|
528
|
+
function mergePostcssPlugins(existing, plugin) {
|
|
529
|
+
if (!existing) return { plugins: [plugin] };
|
|
530
|
+
if (Array.isArray(existing)) return [...existing, plugin];
|
|
531
|
+
if (typeof existing === "object") {
|
|
532
|
+
const obj = existing;
|
|
533
|
+
return {
|
|
534
|
+
...obj,
|
|
535
|
+
plugins: [...obj.plugins ?? [], plugin]
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
return { plugins: [plugin] };
|
|
539
|
+
}
|
|
540
|
+
function rewriteApexPrefix(options) {
|
|
541
|
+
validatePrefix(options.prefix);
|
|
542
|
+
const ctx = {
|
|
543
|
+
prefix: options.prefix,
|
|
544
|
+
consoleBrand: options.consoleBrand ?? defaultConsoleBrand(options.prefix)
|
|
545
|
+
};
|
|
546
|
+
const isNoop = ctx.prefix === "apex";
|
|
547
|
+
let resolvedCleanBundle = resolveCleanBundleOptions(options.cleanBundle, false);
|
|
548
|
+
return {
|
|
549
|
+
name: PLUGIN_NAME,
|
|
550
|
+
enforce: "pre",
|
|
551
|
+
config(config, { command }) {
|
|
552
|
+
var _a, _b;
|
|
553
|
+
const isBuild = command === "build";
|
|
554
|
+
resolvedCleanBundle = resolveCleanBundleOptions(options.cleanBundle, isBuild);
|
|
555
|
+
if (isBuild && resolvedCleanBundle.enabled) {
|
|
556
|
+
const sourcemap = (_a = config.build) == null ? void 0 : _a.sourcemap;
|
|
557
|
+
if (sourcemap === true || sourcemap === "inline") {
|
|
558
|
+
throw new Error(
|
|
559
|
+
`[${PLUGIN_NAME}] 生产构建启用了 cleanBundle,但 build.sourcemap=${JSON.stringify(sourcemap)} 会在产物中暴露内部源码路径,请将其设为 false 或 "hidden"。`
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
const nextConfig = {};
|
|
564
|
+
if (!isNoop) {
|
|
565
|
+
nextConfig.css = {
|
|
566
|
+
...typeof config.css === "object" && config.css ? config.css : {},
|
|
567
|
+
postcss: mergePostcssPlugins(
|
|
568
|
+
typeof config.css === "object" && config.css ? config.css.postcss : void 0,
|
|
569
|
+
createPrefixPostcssPlugin(ctx)
|
|
570
|
+
)
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
if (!isBuild) {
|
|
574
|
+
const existingExclude = ((_b = config.optimizeDeps) == null ? void 0 : _b.exclude) ?? [];
|
|
575
|
+
nextConfig.optimizeDeps = {
|
|
576
|
+
exclude: Array.from(/* @__PURE__ */ new Set([...existingExclude, ...CONSUMER_PACKAGES]))
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
return Object.keys(nextConfig).length > 0 ? nextConfig : void 0;
|
|
580
|
+
},
|
|
581
|
+
transform(code, id) {
|
|
582
|
+
if (isNoop) return null;
|
|
583
|
+
const pathname = stripQuery(id);
|
|
584
|
+
if (!hasPotentialIdentityMarkers(code)) return null;
|
|
585
|
+
if (pathname.endsWith(".css")) {
|
|
586
|
+
const result = transformCss(code, pathname, ctx);
|
|
587
|
+
if (!result) return null;
|
|
588
|
+
return {
|
|
589
|
+
code: result.code,
|
|
590
|
+
map: result.map ? result.map : void 0
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
if (isScriptId(pathname)) {
|
|
594
|
+
const result = transformScript(code, pathname, ctx);
|
|
595
|
+
if (!result) return null;
|
|
596
|
+
return { code: result.code, map: result.map };
|
|
597
|
+
}
|
|
598
|
+
if (isVueId(pathname)) {
|
|
599
|
+
const result = transformVue(code, pathname, ctx);
|
|
600
|
+
if (!result) return null;
|
|
601
|
+
return { code: result.code, map: result.map };
|
|
602
|
+
}
|
|
603
|
+
return null;
|
|
604
|
+
},
|
|
605
|
+
transformIndexHtml(html) {
|
|
606
|
+
if (isNoop) return html;
|
|
607
|
+
const result = transformHtml(html, ctx);
|
|
608
|
+
return result ?? html;
|
|
609
|
+
},
|
|
610
|
+
generateBundle(_outputOptions, bundle) {
|
|
611
|
+
if (!isNoop) {
|
|
612
|
+
for (const item of Object.values(bundle)) {
|
|
613
|
+
if (item.type === "asset" && typeof item.source === "string") {
|
|
614
|
+
if (item.fileName.endsWith(".css") && hasPotentialIdentityMarkers(item.source)) {
|
|
615
|
+
const result = transformCss(item.source, item.fileName, ctx);
|
|
616
|
+
if (result) item.source = result.code;
|
|
617
|
+
} else if (/\.(?:html?|svg|json)$/i.test(item.fileName) && hasPotentialIdentityMarkers(item.source)) {
|
|
618
|
+
const { output, changed } = applyIdentityRules(item.source, ctx);
|
|
619
|
+
if (changed) item.source = output;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
if (item.type === "chunk" && hasPotentialIdentityMarkers(item.code)) {
|
|
623
|
+
const result = transformScript(
|
|
624
|
+
item.code,
|
|
625
|
+
item.fileName.endsWith(".js") ? item.fileName : `${item.fileName}.js`,
|
|
626
|
+
ctx
|
|
627
|
+
);
|
|
628
|
+
if (result) {
|
|
629
|
+
item.code = result.code;
|
|
630
|
+
} else {
|
|
631
|
+
const { output, changed } = applyIdentityRules(item.code, ctx);
|
|
632
|
+
if (changed) item.code = output;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
if (!resolvedCleanBundle.enabled) return;
|
|
638
|
+
const assets = collectTextAssets(bundle);
|
|
639
|
+
const report = runAudit(assets, resolvedCleanBundle, ctx);
|
|
640
|
+
if (resolvedCleanBundle.reportFile) {
|
|
641
|
+
writeAuditReport(resolvedCleanBundle.reportFile, report);
|
|
642
|
+
}
|
|
643
|
+
if (!report.ok) {
|
|
644
|
+
this.error(formatAuditFailure(report));
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
export {
|
|
650
|
+
rewriteApexPrefix
|
|
651
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `rewriteApexPrefix` 插件配置。
|
|
3
|
+
*
|
|
4
|
+
* 日常接入只需传 `prefix`;其余均为可选且有合理默认。
|
|
5
|
+
*/
|
|
6
|
+
export interface RewriteApexPrefixOptions {
|
|
7
|
+
/**
|
|
8
|
+
* 团队技术前缀。用于替换 Apex UI 组件库与业务源码中的 CSS 类名前缀(`apex-` → `{prefix}-`)、
|
|
9
|
+
* CSS 自定义属性前缀(`--apex-` → `--{prefix}-`)以及内部 JS 标记(`__apex_` → `__{prefix}_`)。
|
|
10
|
+
*
|
|
11
|
+
* 规则:`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$`,长度 2~32,且不能使用 radix/headlessui 等保留前缀。
|
|
12
|
+
* 非法配置会在插件创建时(而非构建/运行时)立即抛出异常。
|
|
13
|
+
*
|
|
14
|
+
* 特殊值 `'apex'` 表示不做任何前缀替换(no-op),此时产物校验不会要求品牌标识消失,
|
|
15
|
+
* 但仍会检查 source map 与内部仓库路径泄露。
|
|
16
|
+
*/
|
|
17
|
+
prefix: string;
|
|
18
|
+
/**
|
|
19
|
+
* 控制台/警告中的展示品牌名,用于替换形如 `[Apex UI]`、`[Apex Button]` 的日志前缀。
|
|
20
|
+
* @default 将 `prefix` 首字母大写(如 `falcon` → `Falcon`)
|
|
21
|
+
*/
|
|
22
|
+
consoleBrand?: string;
|
|
23
|
+
/**
|
|
24
|
+
* 是否在生产构建时校验产物无 apex 标识残留。
|
|
25
|
+
* 默认:`vite build` 开启,`vite dev` 关闭。
|
|
26
|
+
*
|
|
27
|
+
* 校验策略内置固定:检查受管标识残留、source map 注释/文件、内部仓库路径;
|
|
28
|
+
* 报告写入 `.artifacts/apex-prefix-audit.json`。
|
|
29
|
+
*/
|
|
30
|
+
cleanBundle?: boolean;
|
|
31
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Plugin as PostcssPlugin } from 'postcss';
|
|
2
|
+
import type { IdentityContext } from './identity-rules';
|
|
3
|
+
/**
|
|
4
|
+
* 注入到 Vite `css.postcss.plugins` 的 PostCSS 插件。
|
|
5
|
+
*
|
|
6
|
+
* Vite 会把同包内 CSS `@import` 从磁盘直接内联,绕过普通 `transform` hook;
|
|
7
|
+
* 因此必须在 PostCSS 管道中再跑一遍结构化转换,才能覆盖 theme/src 等入口。
|
|
8
|
+
*/
|
|
9
|
+
export declare function createPrefixPostcssPlugin(ctx: IdentityContext): PostcssPlugin;
|
|
10
|
+
export declare namespace createPrefixPostcssPlugin {
|
|
11
|
+
var postcss: boolean;
|
|
12
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { IdentityContext } from './identity-rules';
|
|
2
|
+
export interface CssSourceMap {
|
|
3
|
+
toString(): string;
|
|
4
|
+
toJSON(): unknown;
|
|
5
|
+
}
|
|
6
|
+
export interface CssTransformResult {
|
|
7
|
+
code: string;
|
|
8
|
+
map: CssSourceMap | null;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* 对单个 CSS 文件做命名空间重写。
|
|
12
|
+
*
|
|
13
|
+
* 使用 PostCSS 解析出结构化 AST 后逐节点改写,而非对整个文件做无边界字符串替换:
|
|
14
|
+
* - 选择器(含嵌套选择器,PostCSS 将其表示为普通嵌套 Rule 节点)
|
|
15
|
+
* - 声明的属性名(CSS 自定义属性定义 `--apex-xxx: ...`)与值(`var(--apex-xxx)`、
|
|
16
|
+
* `animation: apex-spin ...` 等)
|
|
17
|
+
* - `@keyframes`/`@media` 等 at-rule 的参数(如 `@keyframes apex-spin` 的动画名)
|
|
18
|
+
* - 注释
|
|
19
|
+
*/
|
|
20
|
+
export declare function transformCss(code: string, pathname: string, ctx: IdentityContext): CssTransformResult | null;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { IdentityContext } from './identity-rules';
|
|
2
|
+
/**
|
|
3
|
+
* 对 `index.html` 做命名空间重写。
|
|
4
|
+
*
|
|
5
|
+
* index.html 中通常只出现技术标识(如内联品牌日志脚本、预置的 class/data 属性),
|
|
6
|
+
* 不含任意业务文案的富文本内容,因此直接对整份 HTML 文本做规则驱动的字符串替换是安全的
|
|
7
|
+
* ——identity-rules 中的模式本身要求精确的标记格式(连字符/方括号/双下划线包裹),
|
|
8
|
+
* 不会误伤普通页面文案。
|
|
9
|
+
*/
|
|
10
|
+
export declare function transformHtml(html: string, ctx: IdentityContext): string | null;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import MagicString from 'magic-string';
|
|
2
|
+
import type { IdentityContext } from './identity-rules';
|
|
3
|
+
export interface ScriptTransformResult {
|
|
4
|
+
code: string;
|
|
5
|
+
map: ReturnType<InstanceType<typeof MagicString>['generateMap']>;
|
|
6
|
+
}
|
|
7
|
+
export declare function isScriptId(pathname: string): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* 对单个 JS/TS/JSX/TSX 源文件做命名空间重写。
|
|
10
|
+
*
|
|
11
|
+
* 只改动 StringLiteral 与 TemplateElement 的原始文本(含作为对象属性值/JSX 属性值的字符串),
|
|
12
|
+
* 不改动任何 Identifier(不会重命名 import/export 名、函数名、变量名),
|
|
13
|
+
* 也不会触碰普通业务文案(因为规则本身要求精确的标记格式,如 `apex-` 需带连字符)。
|
|
14
|
+
*
|
|
15
|
+
* 使用 magic-string 做最小范围的原地覆写(仅覆写命中片段本身,不重建整段字符串字面量),
|
|
16
|
+
* 因此不需要处理转义/引号重新编码问题,且生成的 source map 精确到字符级别。
|
|
17
|
+
*/
|
|
18
|
+
export declare function transformScript(code: string, pathname: string, ctx: IdentityContext): ScriptTransformResult | null;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import MagicString from 'magic-string';
|
|
2
|
+
import type { IdentityContext } from './identity-rules';
|
|
3
|
+
export interface VueTransformResult {
|
|
4
|
+
code: string;
|
|
5
|
+
map: ReturnType<InstanceType<typeof MagicString>['generateMap']>;
|
|
6
|
+
}
|
|
7
|
+
export declare function isVueId(pathname: string): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* 对 `.vue` SFC 做命名空间重写。
|
|
10
|
+
*
|
|
11
|
+
* - `<template>`:与 HTML 相同,对块内文本做标识规则替换(class、data 属性等)
|
|
12
|
+
* - `<script>` / `<script setup>`:复用 {@link transformScript},并跳过 import 说明符
|
|
13
|
+
* - `<style>`:复用 {@link transformCss}
|
|
14
|
+
*/
|
|
15
|
+
export declare function transformVue(code: string, pathname: string, ctx: IdentityContext): VueTransformResult | null;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 前缀合法性正则:小写字母开头,可包含数字与连字符分隔的小写字母数字段,
|
|
3
|
+
* 不允许以连字符开头/结尾,不允许连续连字符。
|
|
4
|
+
*/
|
|
5
|
+
export declare const PREFIX_PATTERN: RegExp;
|
|
6
|
+
export declare const PREFIX_MIN_LENGTH = 2;
|
|
7
|
+
export declare const PREFIX_MAX_LENGTH = 32;
|
|
8
|
+
/**
|
|
9
|
+
* 保留前缀:与业界常见无头/组件库同名或同前缀会被拒绝,避免样式与运行时标记冲突。
|
|
10
|
+
*/
|
|
11
|
+
export declare const RESERVED_PREFIXES: readonly ["radix", "headlessui", "react", "vite"];
|
|
12
|
+
export declare class PrefixValidationError extends Error {
|
|
13
|
+
constructor(message: string);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* 由技术前缀推导默认控制台品牌名:仅将首字母大写。
|
|
17
|
+
* 例如 `falcon` → `Falcon`,`team-a` → `Team-a`。
|
|
18
|
+
* 需要多词/自定义展示名时请显式传 `consoleBrand`。
|
|
19
|
+
*/
|
|
20
|
+
export declare function defaultConsoleBrand(prefix: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* 校验团队前缀配置是否合法,非法时同步抛出 {@link PrefixValidationError}。
|
|
23
|
+
*
|
|
24
|
+
* 设计为在插件工厂函数中同步调用,确保非法配置在 Vite 启动阶段即失败,
|
|
25
|
+
* 而不是等到某次 transform/build 才暴露问题。
|
|
26
|
+
*/
|
|
27
|
+
export declare function validatePrefix(prefix: string): void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@apexhub/apex-ui-rewrite-prefix-plugin",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Apex UI 前缀替换 Vite 插件 — 构建期将 apex- 类名/CSS 变量/内部标记重写为团队前缀",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"vite-plugin",
|
|
8
|
+
"vite",
|
|
9
|
+
"prefix",
|
|
10
|
+
"rewrite",
|
|
11
|
+
"white-label",
|
|
12
|
+
"apex-ui"
|
|
13
|
+
],
|
|
14
|
+
"type": "module",
|
|
15
|
+
"main": "./dist/index.js",
|
|
16
|
+
"module": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.js",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public",
|
|
30
|
+
"registry": "https://registry.npmjs.org/"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@babel/parser": "^7.28.0",
|
|
34
|
+
"@babel/traverse": "^7.28.0",
|
|
35
|
+
"@babel/types": "^7.28.0",
|
|
36
|
+
"@vue/compiler-sfc": "^3.5.41",
|
|
37
|
+
"magic-string": "^0.30.17",
|
|
38
|
+
"postcss": "^8.4.47"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"vite": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/babel__traverse": "^7.28.0",
|
|
45
|
+
"@types/node": "^20",
|
|
46
|
+
"typescript": "^5.7.3",
|
|
47
|
+
"vite": "^6.0.11",
|
|
48
|
+
"vitest": "^3.0.7"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "vite build && tsc -p tsconfig.json --emitDeclarationOnly",
|
|
52
|
+
"clean": "rm -rf dist",
|
|
53
|
+
"typecheck": "tsc --noEmit",
|
|
54
|
+
"test": "vitest run",
|
|
55
|
+
"test:watch": "vitest"
|
|
56
|
+
}
|
|
6
57
|
}
|