soma-core 1.4.0 → 1.4.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/README.md +1 -1
- package/core/build/blocks/block-compile.ts +31 -2
- package/core/build/blocks/block-container.ts +2 -11
- package/core/build/compiler/page-declaration-compiler.ts +30 -2
- package/core/build/compiler/soma-precompile.js +2041 -19
- package/core/build/component/component-graph.ts +208 -0
- package/core/build/eject/component-eject.ts +473 -0
- package/core/build/eject/component-upgrade.ts +359 -0
- package/core/build/layout/constraint-solver.ts +235 -0
- package/core/build/layout/css-emitter.ts +116 -0
- package/core/build/layout/page-layout.ts +85 -0
- package/core/build/pack/pack-init.ts +265 -0
- package/core/client/base/SomaPageRootBase.ts +61 -0
- package/core/client/component/ai-catalog.ts +79 -4
- package/core/client/component/component-defaults.ts +100 -0
- package/core/client/component/component-definition.types.ts +39 -0
- package/core/client/component/component-manager.ts +79 -4
- package/core/client/component/component-pack.ts +126 -2
- package/core/client/component/keyboard-matrix.ts +144 -0
- package/core/client/component/pack-styles.ts +59 -1
- package/core/client/component/style-features.ts +131 -0
- package/core/client/component/theme-component-tokens.ts +83 -0
- package/core/client/data/data-object-resolver.ts +407 -4
- package/core/client/data/reaction-engine.ts +176 -0
- package/core/client/data/window-engine.ts +477 -0
- package/core/client/engine/event-engine.ts +98 -0
- package/core/client/engine/soma-bootstrap.ts +265 -5
- package/core/client/engine/step-runner.ts +134 -0
- package/core/client/parser/blocks/page-parser.ts +15 -1
- package/core/client/parser/blocks/use-parser.ts +5 -12
- package/core/client/parser/data-config-parser.ts +316 -8
- package/core/client/parser/duration.ts +16 -0
- package/core/client/parser/layout-parser.ts +157 -0
- package/core/client/parser/page-state-parser.ts +166 -0
- package/core/client/parser/pipeline-parser.ts +76 -1
- package/core/client/parser/reaction-parser.ts +459 -0
- package/core/client/parser/reaction-sugar.ts +47 -0
- package/core/client/parser/step-parser.ts +359 -0
- package/core/client/parser/ui-config-parser.ts +59 -0
- package/core/client/parser/window-parser.ts +294 -0
- package/core/client/theme/theme-engine.ts +102 -2
- package/core/index.ts +163 -0
- package/core/shared/block-errors.ts +11 -0
- package/core/shared/calc/coerce.ts +29 -0
- package/core/shared/calc/errors.ts +43 -0
- package/core/shared/calc/evaluator.ts +101 -0
- package/core/shared/calc/index.ts +12 -0
- package/core/shared/calc/lexer.ts +194 -0
- package/core/shared/calc/parser.ts +204 -0
- package/core/shared/calc/typer.ts +184 -0
- package/core/shared/path-algebra.ts +169 -0
- package/core/shared/predicates/index.ts +527 -0
- package/core/shared/types/component-contract.types.ts +128 -2
- package/core/shared/types/data-config.types.ts +120 -1
- package/core/shared/types/domain.types.ts +13 -0
- package/core/shared/types/event.types.ts +22 -2
- package/core/shared/types/layout-constraint.types.ts +73 -0
- package/core/shared/types/page-state.types.ts +60 -0
- package/core/shared/types/reaction.types.ts +144 -0
- package/core/shared/types/step.types.ts +91 -0
- package/core/shared/types/ui-config.types.ts +18 -0
- package/core/shared/types/window.types.ts +177 -0
- package/dist/cli/soma.js +13 -1
- package/dist/core/index.cjs +4684 -349
- package/dist/types/build/blocks/block-container.d.ts +1 -6
- package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
- package/dist/types/build/component/component-graph.d.ts +85 -0
- package/dist/types/build/eject/component-eject.d.ts +121 -0
- package/dist/types/build/eject/component-upgrade.d.ts +43 -0
- package/dist/types/build/layout/constraint-solver.d.ts +36 -0
- package/dist/types/build/layout/css-emitter.d.ts +18 -0
- package/dist/types/build/layout/page-layout.d.ts +24 -0
- package/dist/types/build/pack/pack-init.d.ts +8 -0
- package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
- package/dist/types/client/component/ai-catalog.d.ts +24 -1
- package/dist/types/client/component/component-defaults.d.ts +15 -0
- package/dist/types/client/component/component-definition.types.d.ts +38 -0
- package/dist/types/client/component/component-manager.d.ts +36 -0
- package/dist/types/client/component/component-pack.d.ts +32 -2
- package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
- package/dist/types/client/component/pack-styles.d.ts +21 -0
- package/dist/types/client/component/style-features.d.ts +26 -0
- package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
- package/dist/types/client/data/data-object-resolver.d.ts +106 -1
- package/dist/types/client/data/reaction-engine.d.ts +21 -0
- package/dist/types/client/data/window-engine.d.ts +27 -0
- package/dist/types/client/engine/event-engine.d.ts +15 -0
- package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
- package/dist/types/client/engine/step-runner.d.ts +24 -0
- package/dist/types/client/parser/blocks/use-parser.d.ts +2 -2
- package/dist/types/client/parser/duration.d.ts +1 -0
- package/dist/types/client/parser/layout-parser.d.ts +9 -0
- package/dist/types/client/parser/page-state-parser.d.ts +32 -0
- package/dist/types/client/parser/reaction-parser.d.ts +16 -0
- package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
- package/dist/types/client/parser/step-parser.d.ts +23 -0
- package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
- package/dist/types/client/parser/window-parser.d.ts +25 -0
- package/dist/types/client/theme/theme-engine.d.ts +26 -0
- package/dist/types/index.d.ts +32 -2
- package/dist/types/shared/block-errors.d.ts +5 -0
- package/dist/types/shared/calc/coerce.d.ts +4 -0
- package/dist/types/shared/calc/errors.d.ts +14 -0
- package/dist/types/shared/calc/evaluator.d.ts +2 -0
- package/dist/types/shared/calc/index.d.ts +6 -0
- package/dist/types/shared/calc/lexer.d.ts +20 -0
- package/dist/types/shared/calc/parser.d.ts +49 -0
- package/dist/types/shared/calc/typer.d.ts +16 -0
- package/dist/types/shared/path-algebra.d.ts +56 -0
- package/dist/types/shared/predicates/index.d.ts +79 -0
- package/dist/types/shared/types/component-contract.types.d.ts +112 -0
- package/dist/types/shared/types/data-config.types.d.ts +115 -1
- package/dist/types/shared/types/domain.types.d.ts +12 -0
- package/dist/types/shared/types/event.types.d.ts +8 -2
- package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
- package/dist/types/shared/types/page-state.types.d.ts +49 -0
- package/dist/types/shared/types/reaction.types.d.ts +115 -0
- package/dist/types/shared/types/step.types.d.ts +76 -0
- package/dist/types/shared/types/ui-config.types.d.ts +18 -0
- package/dist/types/shared/types/window.types.d.ts +171 -0
- package/package.json +2 -1
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// 组件依赖图与可寻址目录(REQ-010 F-46)。
|
|
2
|
+
//
|
|
3
|
+
// ── 两个具体的坏结果 ──────────────────────────────────────────────────
|
|
4
|
+
// ① **少拉一个依赖**。TreeSelect 的面板模板用了 Tree 分片里的类,但这条依赖
|
|
5
|
+
// 只登记在 soma-ui 的一张手工表里、且曾经漏登记过——只用 TreeSelect 不用 Tree 的
|
|
6
|
+
// 页面上,展开箭头与节点文字是无样式的。它不报错,只是长得不对。
|
|
7
|
+
// ② **说不出这份副本从哪来**。shadcn 的 registry 里没有版本、没有哈希、没有依赖,
|
|
8
|
+
// 所以"我这份 Select 是从哪一版复制的、它还需要谁"这两个问题都答不出来。
|
|
9
|
+
//
|
|
10
|
+
// 把依赖写进契约(`uses`),这两件事都有了答案:拉组件时按图拉齐,
|
|
11
|
+
// 发目录时每一项带版本、哈希与依赖。
|
|
12
|
+
|
|
13
|
+
import type { SomaComponentDefinition } from '../../client/component/component-definition.types';
|
|
14
|
+
|
|
15
|
+
export interface ComponentGraphNode {
|
|
16
|
+
name: string;
|
|
17
|
+
layer: string;
|
|
18
|
+
version: string;
|
|
19
|
+
/** 直接依赖(契约 `uses`) */
|
|
20
|
+
uses: string[];
|
|
21
|
+
/** 传递闭包(不含自身) */
|
|
22
|
+
closure: string[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ComponentGraph {
|
|
26
|
+
nodes: Record<string, ComponentGraphNode>;
|
|
27
|
+
/** 声明了却不存在的依赖:`组件名 → 缺失的依赖名[]` */
|
|
28
|
+
missing: Record<string, string[]>;
|
|
29
|
+
/** 依赖环:每条是一个完整回路 */
|
|
30
|
+
cycles: string[][];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 建图。
|
|
35
|
+
*
|
|
36
|
+
* 缺失依赖与环**不抛**,而是收进产物:这个函数同时服务于闸门与 CLI,
|
|
37
|
+
* 闸门要拿到全部问题一次报完(抛的话作者修一条跑一次,修十条跑十次),
|
|
38
|
+
* CLI 则要在有问题时也能给出一份"能拉的先拉上"的清单。判定归调用方。
|
|
39
|
+
*/
|
|
40
|
+
export function buildComponentGraph(
|
|
41
|
+
definitions: Record<string, SomaComponentDefinition>,
|
|
42
|
+
): ComponentGraph {
|
|
43
|
+
const names = Object.keys(definitions);
|
|
44
|
+
const known = new Set(names);
|
|
45
|
+
const nodes: Record<string, ComponentGraphNode> = {};
|
|
46
|
+
const missing: Record<string, string[]> = {};
|
|
47
|
+
|
|
48
|
+
for (const name of names) {
|
|
49
|
+
const contract = definitions[name].contract;
|
|
50
|
+
const uses = [...new Set(contract.uses ?? [])];
|
|
51
|
+
const absent = uses.filter((dep) => !known.has(dep));
|
|
52
|
+
if (absent.length > 0) missing[name] = absent;
|
|
53
|
+
nodes[name] = {
|
|
54
|
+
name,
|
|
55
|
+
layer: String(contract.layer),
|
|
56
|
+
version: String(contract.version),
|
|
57
|
+
uses: uses.filter((dep) => known.has(dep)),
|
|
58
|
+
closure: [],
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 传递闭包 + 检环。深度优先,回边即环——报出整条回路而不只是"成环了":
|
|
63
|
+
// 只说成环的话,作者得自己把链条走一遍才知道该断哪一条。
|
|
64
|
+
const cycles: string[][] = [];
|
|
65
|
+
const state: Record<string, 'visiting' | 'done'> = {};
|
|
66
|
+
const stack: string[] = [];
|
|
67
|
+
|
|
68
|
+
const visit = (name: string): Set<string> => {
|
|
69
|
+
if (state[name] === 'done') return new Set(nodes[name].closure);
|
|
70
|
+
if (state[name] === 'visiting') {
|
|
71
|
+
const from = stack.indexOf(name);
|
|
72
|
+
if (from !== -1) cycles.push([...stack.slice(from), name]);
|
|
73
|
+
return new Set();
|
|
74
|
+
}
|
|
75
|
+
state[name] = 'visiting';
|
|
76
|
+
stack.push(name);
|
|
77
|
+
const out = new Set<string>();
|
|
78
|
+
for (const dep of nodes[name].uses) {
|
|
79
|
+
out.add(dep);
|
|
80
|
+
for (const deeper of visit(dep)) out.add(deeper);
|
|
81
|
+
}
|
|
82
|
+
stack.pop();
|
|
83
|
+
state[name] = 'done';
|
|
84
|
+
// 自己不进自己的闭包:成环时上面会把自己加进来,这里摘掉
|
|
85
|
+
out.delete(name);
|
|
86
|
+
nodes[name].closure = [...out].sort();
|
|
87
|
+
return out;
|
|
88
|
+
};
|
|
89
|
+
for (const name of names) visit(name);
|
|
90
|
+
|
|
91
|
+
return { nodes, missing, cycles };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 按图拉齐:给一组组件名,返回它们加上全部传递依赖的名单(拓扑序)。
|
|
96
|
+
*
|
|
97
|
+
* 拓扑序而不是字母序:注册组件时被依赖的要先在册,否则合成期查注册表会落空。
|
|
98
|
+
*/
|
|
99
|
+
export function resolveWithDependencies(
|
|
100
|
+
graph: ComponentGraph,
|
|
101
|
+
wanted: readonly string[],
|
|
102
|
+
): string[] {
|
|
103
|
+
const out: string[] = [];
|
|
104
|
+
const seen = new Set<string>();
|
|
105
|
+
const visit = (name: string): void => {
|
|
106
|
+
if (seen.has(name)) return;
|
|
107
|
+
seen.add(name);
|
|
108
|
+
const node = graph.nodes[name];
|
|
109
|
+
if (!node) return; // 未知名字由调用方另行报错,这里不吞也不猜
|
|
110
|
+
for (const dep of node.uses) visit(dep);
|
|
111
|
+
out.push(name);
|
|
112
|
+
};
|
|
113
|
+
for (const name of wanted) visit(name);
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** `registry.json` 的一项 */
|
|
118
|
+
export interface ComponentRegistryEntry {
|
|
119
|
+
name: string;
|
|
120
|
+
layer: string;
|
|
121
|
+
/** 契约版本(破坏性变更升 major) */
|
|
122
|
+
version: string;
|
|
123
|
+
/** 源码内容哈希:回答"我这份是不是官方那一份" */
|
|
124
|
+
sha256: string;
|
|
125
|
+
/** 直接依赖 */
|
|
126
|
+
uses: string[];
|
|
127
|
+
/** 传递依赖(拉齐时按它一次拉全) */
|
|
128
|
+
requires: string[];
|
|
129
|
+
/** 源文件相对路径(eject / upgrade 的取源位置) */
|
|
130
|
+
source: string;
|
|
131
|
+
description: string;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface ComponentRegistryManifest {
|
|
135
|
+
/** 目录格式版本:读的人据此判断自己认不认得这份文件 */
|
|
136
|
+
schema: 1;
|
|
137
|
+
/** 产出这份目录的包与版本 */
|
|
138
|
+
pack: { name: string; version: string };
|
|
139
|
+
generatedFrom: string;
|
|
140
|
+
components: ComponentRegistryEntry[];
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 产出可寻址目录。
|
|
145
|
+
*
|
|
146
|
+
* 与 shadcn registry 的差别就是这三列:`version` / `sha256` / `requires`。
|
|
147
|
+
* 少了它们,一份被复制出去的组件就永久脱离了升级链路——
|
|
148
|
+
* 而"脱离了"这件事本身也是看不出来的。
|
|
149
|
+
*/
|
|
150
|
+
export function buildRegistryManifest(
|
|
151
|
+
definitions: Record<string, SomaComponentDefinition>,
|
|
152
|
+
options: {
|
|
153
|
+
packName: string;
|
|
154
|
+
packVersion: string;
|
|
155
|
+
/** 组件名 → 源码相对路径 */
|
|
156
|
+
sourceOf(name: string): string;
|
|
157
|
+
/** 组件名 → 源码内容哈希 */
|
|
158
|
+
hashOf(name: string): string;
|
|
159
|
+
},
|
|
160
|
+
): ComponentRegistryManifest {
|
|
161
|
+
const graph = buildComponentGraph(definitions);
|
|
162
|
+
const components = Object.keys(definitions)
|
|
163
|
+
.sort()
|
|
164
|
+
.map((name) => {
|
|
165
|
+
const contract = definitions[name].contract;
|
|
166
|
+
return {
|
|
167
|
+
name,
|
|
168
|
+
layer: String(contract.layer),
|
|
169
|
+
version: String(contract.version),
|
|
170
|
+
sha256: options.hashOf(name),
|
|
171
|
+
uses: graph.nodes[name].uses,
|
|
172
|
+
requires: graph.nodes[name].closure,
|
|
173
|
+
source: options.sourceOf(name),
|
|
174
|
+
description: String(contract.description ?? ''),
|
|
175
|
+
};
|
|
176
|
+
});
|
|
177
|
+
return {
|
|
178
|
+
schema: 1,
|
|
179
|
+
pack: { name: options.packName, version: options.packVersion },
|
|
180
|
+
generatedFrom: `${options.packName}@${options.packVersion}`,
|
|
181
|
+
components,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* 契约 `uses` 与 CSS 依赖表的对账。
|
|
187
|
+
*
|
|
188
|
+
* 两张表都在描述"这个组件还需要谁",所以它们必须一致。不对账的话,
|
|
189
|
+
* 一条只写在 CSS 表里的依赖会让 eject 少拉一个文件,而一条只写在契约里的依赖
|
|
190
|
+
* 会让页面少注一段样式——两种坏法都不报错,都只是长得不对。
|
|
191
|
+
*/
|
|
192
|
+
export function reconcileCssDeps(
|
|
193
|
+
graph: ComponentGraph,
|
|
194
|
+
cssDeps: Record<string, readonly string[]>,
|
|
195
|
+
): Array<{ component: string; onlyInCss: string[]; onlyInContract: string[] }> {
|
|
196
|
+
const issues: Array<{ component: string; onlyInCss: string[]; onlyInContract: string[] }> = [];
|
|
197
|
+
const names = new Set([...Object.keys(graph.nodes), ...Object.keys(cssDeps)]);
|
|
198
|
+
for (const name of names) {
|
|
199
|
+
const fromContract = new Set(graph.nodes[name]?.uses ?? []);
|
|
200
|
+
const fromCss = new Set(cssDeps[name] ?? []);
|
|
201
|
+
const onlyInCss = [...fromCss].filter((dep) => !fromContract.has(dep) && graph.nodes[dep] !== undefined);
|
|
202
|
+
const onlyInContract = [...fromContract].filter((dep) => !fromCss.has(dep));
|
|
203
|
+
if (onlyInCss.length > 0 || onlyInContract.length > 0) {
|
|
204
|
+
issues.push({ component: name, onlyInCss, onlyInContract });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return issues;
|
|
208
|
+
}
|
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
// `soma component eject <Name>` —— 把一个官方组件的源码交给宿主(REQ-009 EC-1)。
|
|
2
|
+
//
|
|
3
|
+
// 这是 shadcn 那套「你拥有它」在 SOMA 的合法形态。已有的 `soma eject` 只固化**页面**;
|
|
4
|
+
// 组件此前没有这条路,于是「官方组件 90% 合适、剩下 10% 要改行为」只能整包覆盖,
|
|
5
|
+
// 而整包覆盖要求宿主从零重写一个组件。
|
|
6
|
+
//
|
|
7
|
+
// 与 shadcn 的两个关键差别,都是 SOMA 已有纪律的延伸:
|
|
8
|
+
// ① **不复制共享资产**。导入被改写成 `soma-ui/shared/*` 公开子路径——
|
|
9
|
+
// 焦点作用域、键盘漫游、四态这些行为底座仍由官方维护并随 soma-ui 升级。
|
|
10
|
+
// shadcn 把一切都拷给你,于是每个项目的 Dialog 焦点逻辑各自漂移。
|
|
11
|
+
// ② **产物仍过闸门**。契约自动加 `overrides: 'soma-ui'`,装配时走契约兼容检查
|
|
12
|
+
// (props 超集 + emit 全保留),所以「弹出去改一改」不会静默破坏存量页面。
|
|
13
|
+
//
|
|
14
|
+
// provenance 头记下源版本与 sha256,`soma component diff` 据此告诉宿主上游改了什么。
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import crypto from 'node:crypto';
|
|
19
|
+
|
|
20
|
+
export class ComponentEjectError extends Error {
|
|
21
|
+
constructor(message: string) {
|
|
22
|
+
super(`[soma component eject] ${message}`);
|
|
23
|
+
this.name = 'ComponentEjectError';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ComponentEjectFile {
|
|
28
|
+
/** 相对目标目录的路径 */
|
|
29
|
+
path: string;
|
|
30
|
+
content: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ComponentProvenance {
|
|
34
|
+
/** 来源包名 */
|
|
35
|
+
from: string;
|
|
36
|
+
/** 来源包版本 */
|
|
37
|
+
version: string;
|
|
38
|
+
/** 来源文件(相对 soma-ui 包根) */
|
|
39
|
+
source: string;
|
|
40
|
+
/** 来源文件内容的 sha256(diff 的比对基准) */
|
|
41
|
+
sha256: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ComponentEjectPlan {
|
|
45
|
+
componentName: string;
|
|
46
|
+
files: ComponentEjectFile[];
|
|
47
|
+
provenance: ComponentProvenance;
|
|
48
|
+
/** 被改写的导入:内部相对路径 → 公开子路径 */
|
|
49
|
+
rewrittenImports: Array<{ from: string; to: string }>;
|
|
50
|
+
/** 用到的 soma-ui 公开子路径(不复制,运行期从包里取) */
|
|
51
|
+
requiredShared: string[];
|
|
52
|
+
/**
|
|
53
|
+
* 契约声明的组件级依赖(REQ-010 F-46)。
|
|
54
|
+
*
|
|
55
|
+
* eject 只拉这一个组件的源码;依赖仍从 soma-ui 取。列出来是为了让作者知道
|
|
56
|
+
* **这份副本还牵着谁**——把 TreeSelect 拉走却不知道它要 Tree 的话,
|
|
57
|
+
* 页面上是一排无样式的折叠箭头,而且不报错。
|
|
58
|
+
*/
|
|
59
|
+
requiredComponents: string[];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface ComponentEjectOptions {
|
|
63
|
+
/** 组件契约名(PascalCase) */
|
|
64
|
+
name: string;
|
|
65
|
+
/** 目标目录(宿主的组件包目录) */
|
|
66
|
+
to: string;
|
|
67
|
+
/** soma-ui 包根(含 package.json 与 src/) */
|
|
68
|
+
uiRoot: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** PascalCase → kebab-case 文件名(DataTable → data-table) */
|
|
72
|
+
export function componentFileNameOf(name: string): string {
|
|
73
|
+
return name
|
|
74
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
75
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
|
|
76
|
+
.toLowerCase();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const PROVENANCE_MARK = '@soma-ejected-from';
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 内部导入 → 公开子路径的改写表。
|
|
83
|
+
*
|
|
84
|
+
* 表之外的内部路径一律拒绝并点名,而不是「猜一个」——猜错的下场是宿主拿到一个
|
|
85
|
+
* 编译不过的文件,或者更糟:编译得过但绑到了另一份实现上。
|
|
86
|
+
*/
|
|
87
|
+
const IMPORT_REWRITES: Array<{ test: RegExp; to: (match: RegExpMatchArray) => string }> = [
|
|
88
|
+
{ test: /^\.\.\/shared\/(.+)$/, to: (m) => `soma-ui/shared/${m[1]}` },
|
|
89
|
+
{ test: /^\.\.\/i18n$/, to: () => 'soma-ui' },
|
|
90
|
+
{ test: /^\.\.\/adaptive\/(.+)$/, to: (m) => `soma-ui/adaptive/${m[1]}` },
|
|
91
|
+
{ test: /^\.\.\/catalog\/(.+)$/, to: (m) => `soma-ui/catalog/${m[1]}` },
|
|
92
|
+
{ test: /^\.\.\/(styles|style-base|theme-recipes|style-presets)$/, to: () => 'soma-ui' },
|
|
93
|
+
];
|
|
94
|
+
|
|
95
|
+
/** 组件之间的相互导入:eject 一个就得连带 eject 它依赖的,这里明确拒绝而不是悄悄断链 */
|
|
96
|
+
const SIBLING_COMPONENT_IMPORT = /^\.\/(.+)$/;
|
|
97
|
+
|
|
98
|
+
function rewriteImport(specifier: string): { to: string } | { error: string } {
|
|
99
|
+
if (!specifier.startsWith('.')) return { to: specifier };
|
|
100
|
+
for (const rule of IMPORT_REWRITES) {
|
|
101
|
+
const match = specifier.match(rule.test);
|
|
102
|
+
if (match) return { to: rule.to(match) };
|
|
103
|
+
}
|
|
104
|
+
const sibling = specifier.match(SIBLING_COMPONENT_IMPORT);
|
|
105
|
+
if (sibling) {
|
|
106
|
+
return {
|
|
107
|
+
error: `它导入了同目录的另一个组件 "${sibling[1]}"——`
|
|
108
|
+
+ '请连同那个组件一起 eject,或先把共用逻辑提到 shared 再重试',
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
return { error: `无法把内部导入 "${specifier}" 改写成公开子路径` };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function sha256Of(text: string): string {
|
|
115
|
+
return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function readPackageVersion(uiRoot: string): string {
|
|
119
|
+
const manifestPath = path.join(uiRoot, 'package.json');
|
|
120
|
+
if (!fs.existsSync(manifestPath)) {
|
|
121
|
+
throw new ComponentEjectError(`在 "${uiRoot}" 下找不到 package.json,它不像 soma-ui 包根`);
|
|
122
|
+
}
|
|
123
|
+
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as { version?: string };
|
|
124
|
+
return manifest.version ?? '0.0.0';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 规划一次组件固化:读源、改写导入、盖 provenance、加 overrides 声明。
|
|
129
|
+
* 纯计算 + 只读文件,不落盘——落盘是 applyComponentEject 的事(与页面 eject 同形)。
|
|
130
|
+
*/
|
|
131
|
+
export function planComponentEject(options: ComponentEjectOptions): ComponentEjectPlan {
|
|
132
|
+
const { name, uiRoot } = options;
|
|
133
|
+
if (!/^[A-Z][A-Za-z0-9]*$/.test(name)) {
|
|
134
|
+
throw new ComponentEjectError(`组件名 "${name}" 必须是 PascalCase 契约名`);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const fileName = componentFileNameOf(name);
|
|
138
|
+
const relativeSource = path.join('src', 'components', `${fileName}.ts`);
|
|
139
|
+
const sourcePath = path.join(uiRoot, relativeSource);
|
|
140
|
+
if (!fs.existsSync(sourcePath)) {
|
|
141
|
+
throw new ComponentEjectError(
|
|
142
|
+
`找不到组件源文件 ${relativeSource}。`
|
|
143
|
+
+ `\n 组件名与文件名的映射是 PascalCase → kebab-case(DataTable → data-table.ts);`
|
|
144
|
+
+ '\n 请确认组件名拼写,或该组件是否来自别的包',
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const original = fs.readFileSync(sourcePath, 'utf8');
|
|
149
|
+
const version = readPackageVersion(uiRoot);
|
|
150
|
+
|
|
151
|
+
const rewrittenImports: Array<{ from: string; to: string }> = [];
|
|
152
|
+
const requiredShared = new Set<string>();
|
|
153
|
+
const problems: string[] = [];
|
|
154
|
+
|
|
155
|
+
// from '…' / import('…') 两种形态都要改;正则只认引号内的模块说明符,不动别的字符串
|
|
156
|
+
const rewritten = original.replace(
|
|
157
|
+
/(from\s+|import\s*\(\s*)(['"])([^'"]+)\2/g,
|
|
158
|
+
(whole, prefix: string, quote: string, specifier: string) => {
|
|
159
|
+
const result = rewriteImport(specifier);
|
|
160
|
+
if ('error' in result) {
|
|
161
|
+
problems.push(`${specifier}:${result.error}`);
|
|
162
|
+
return whole;
|
|
163
|
+
}
|
|
164
|
+
if (result.to !== specifier) {
|
|
165
|
+
rewrittenImports.push({ from: specifier, to: result.to });
|
|
166
|
+
if (result.to.startsWith('soma-ui/')) requiredShared.add(result.to);
|
|
167
|
+
}
|
|
168
|
+
return `${prefix}${quote}${result.to}${quote}`;
|
|
169
|
+
},
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
if (problems.length > 0) {
|
|
173
|
+
throw new ComponentEjectError(
|
|
174
|
+
`"${name}" 有 ${problems.length} 处导入无法改写成公开路径:`
|
|
175
|
+
+ `\n${problems.map((item) => ` · ${item}`).join('\n')}`
|
|
176
|
+
+ '\n eject 刻意不复制共享资产——那样每个项目的焦点/键盘实现都会各自漂移。',
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const provenance: ComponentProvenance = {
|
|
181
|
+
from: 'soma-ui',
|
|
182
|
+
version,
|
|
183
|
+
source: relativeSource.split(path.sep).join('/'),
|
|
184
|
+
sha256: sha256Of(original),
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const withOverrides = injectOverridesDeclaration(rewritten, name);
|
|
188
|
+
const content = `${renderProvenanceHeader(provenance)}\n${withOverrides}`;
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
componentName: name,
|
|
192
|
+
files: [
|
|
193
|
+
{ path: `${fileName}.ts`, content },
|
|
194
|
+
// 基线快照:eject 那一刻的上游**原文**,逐字节。
|
|
195
|
+
//
|
|
196
|
+
// 没有它,diff 只能拿 sha256 判定"上游动没动",却拿不出"动了哪几行"——
|
|
197
|
+
// 第一版正是这样:把空串当旧文本,输出是整文件全加,不是 diff。
|
|
198
|
+
// 有了它,diff 是真正的「上游旧 vs 上游新」;将来的升级合并也有了 base
|
|
199
|
+
// (base = 这份 / ours = 宿主当前 / theirs = 上游当前)——
|
|
200
|
+
// shadcn 的协议无版本无基线,做不到这一步;SOMA 只差存一份原文。
|
|
201
|
+
{ path: `${BASE_DIR}/${fileName}.ts`, content: original },
|
|
202
|
+
],
|
|
203
|
+
provenance,
|
|
204
|
+
rewrittenImports,
|
|
205
|
+
requiredShared: [...requiredShared].sort(),
|
|
206
|
+
requiredComponents: readContractUses(original),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* 从源码里读契约的 `uses`(REQ-010 F-46)。
|
|
212
|
+
*
|
|
213
|
+
* 用正则而不是把文件 import 进来求值:eject 是构建期工具,它面对的可能是一份
|
|
214
|
+
* **改坏了的**源码(宿主正在编辑),import 会直接抛在一个与 eject 无关的地方。
|
|
215
|
+
* 正则读不出来就当没有依赖——比整条命令挂掉好:拉少了作者看得见(页面缺一块),
|
|
216
|
+
* 而命令挂掉他连拉都拉不成。
|
|
217
|
+
*/
|
|
218
|
+
export function readContractUses(source: string): string[] {
|
|
219
|
+
const match = /\buses:\s*\[([^\]]*)\]/.exec(source);
|
|
220
|
+
if (!match) return [];
|
|
221
|
+
return [...match[1].matchAll(/['"]([A-Z][A-Za-z0-9]*)['"]/g)].map((item) => item[1]);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** 基线快照目录(相对目标包目录):与产物同级、单独一层,不会被当成组件源码注册 */
|
|
225
|
+
export const BASE_DIR = '.soma-eject-base';
|
|
226
|
+
|
|
227
|
+
function renderProvenanceHeader(provenance: ComponentProvenance): string {
|
|
228
|
+
return [
|
|
229
|
+
'// 本文件由 `soma component eject` 生成——它现在归你维护。',
|
|
230
|
+
'//',
|
|
231
|
+
`// ${PROVENANCE_MARK} ${provenance.from}@${provenance.version} ${provenance.source}`,
|
|
232
|
+
`// @soma-ejected-sha256 ${provenance.sha256}`,
|
|
233
|
+
'//',
|
|
234
|
+
'// 上游改了什么:`soma component diff <组件名>`。',
|
|
235
|
+
'// 契约里的 overrides 声明让它在合成时替掉官方同名组件,并强制过契约兼容闸门',
|
|
236
|
+
'// (props 超集 + emit 全保留)——所以改归改,存量页面不会静默失守。',
|
|
237
|
+
].join('\n');
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* 在契约里插入 `overrides: 'soma-ui'`。
|
|
242
|
+
*
|
|
243
|
+
* 找的是 `name: '<组件名>',` 那一行——契约的第一个字段,位置最稳定。
|
|
244
|
+
* 找不到就抛:静默产出一个不带 overrides 的组件,会在合成时以「组件名冲突」
|
|
245
|
+
* 报错,而那时的错误信息完全指不到这里。
|
|
246
|
+
*/
|
|
247
|
+
function injectOverridesDeclaration(source: string, name: string): string {
|
|
248
|
+
if (/\boverrides\s*:\s*['"]/.test(source)) return source;
|
|
249
|
+
const anchor = new RegExp(`(\\n(\\s*)name:\\s*['"]${name}['"],)`);
|
|
250
|
+
const match = source.match(anchor);
|
|
251
|
+
if (!match) {
|
|
252
|
+
throw new ComponentEjectError(
|
|
253
|
+
`在源码里找不到契约的 name: '${name}' 行,无法插入 overrides 声明。`
|
|
254
|
+
+ '\n 没有 overrides 的产物会在合成时以"组件名冲突"报错,且错误信息指不回这里,所以这里直接拒绝',
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
return source.replace(anchor, `$1\n$2overrides: 'soma-ui',`);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export interface ApplyComponentEjectOptions {
|
|
261
|
+
/** 目标目录(宿主组件包目录) */
|
|
262
|
+
to: string;
|
|
263
|
+
force?: boolean;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export interface ComponentEjectResult {
|
|
267
|
+
written: string[];
|
|
268
|
+
skipped: string[];
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** 落盘。默认撞名即中止——宿主目录里的东西是人写的(与页面 eject 同一条默认值)。 */
|
|
272
|
+
export function applyComponentEject(
|
|
273
|
+
plan: ComponentEjectPlan,
|
|
274
|
+
options: ApplyComponentEjectOptions,
|
|
275
|
+
): ComponentEjectResult {
|
|
276
|
+
const written: string[] = [];
|
|
277
|
+
|
|
278
|
+
// 先查一遍再写:撞名要**在动手之前**中止。
|
|
279
|
+
//
|
|
280
|
+
// 原先是边查边写、最后拿 `written.length === 0` 当判据——那在一次 eject 只落一个文件时
|
|
281
|
+
// 恰好成立。加上基线快照(`.soma-eject-base/<name>.ts`)之后就不成立了:组件文件撞名被跳过,
|
|
282
|
+
// 基线文件照写,`written` 非空于是闸门不响。结果是宿主看着命令成功返回,
|
|
283
|
+
// 他手写的那个文件没被动(还好),但目录里多了一份与之不对应的基线——
|
|
284
|
+
// 下一次 `diff` 会拿这份错基线去比,报出一堆不存在的改动。
|
|
285
|
+
const collisions = plan.files
|
|
286
|
+
.map((file) => path.join(options.to, file.path))
|
|
287
|
+
.filter((target) => fs.existsSync(target));
|
|
288
|
+
if (collisions.length > 0 && !options.force) {
|
|
289
|
+
throw new ComponentEjectError(
|
|
290
|
+
`目标文件已存在:${collisions.join('、')}\n 要覆盖请加 --force(默认不动宿主目录里的东西)`,
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
for (const file of plan.files) {
|
|
295
|
+
const target = path.join(options.to, file.path);
|
|
296
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
297
|
+
fs.writeFileSync(target, file.content, 'utf8');
|
|
298
|
+
written.push(target);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return { written, skipped: [] };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// ─── diff(EC-2)────────────────────────────────────────────────────────────
|
|
305
|
+
|
|
306
|
+
export interface ComponentDiffResult {
|
|
307
|
+
componentName: string;
|
|
308
|
+
changed: boolean;
|
|
309
|
+
/** 记在产物里的来源版本 */
|
|
310
|
+
ejectedFrom: ComponentProvenance;
|
|
311
|
+
/** 上游当前版本 */
|
|
312
|
+
currentVersion: string;
|
|
313
|
+
/** 上游当前内容的 sha256 */
|
|
314
|
+
currentSha256: string;
|
|
315
|
+
/** 是否找到了 eject 时落盘的基线;没有基线就出不了 diff,只能报"变了" */
|
|
316
|
+
hasBaseline?: boolean;
|
|
317
|
+
/** 统一 diff(changed 且有基线时给出) */
|
|
318
|
+
unified?: string;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** 从 eject 产物的头部读回 provenance;读不到说明它不是 eject 产物 */
|
|
322
|
+
/**
|
|
323
|
+
* 剥掉 eject 产物的 provenance 头,返回 `{ header, body }`。
|
|
324
|
+
*
|
|
325
|
+
* 三方合并要用它:产物带头、基线不带,不剥的话那几行会被当成"宿主的插入",
|
|
326
|
+
* 与上游在同一位置的任何改动撞成冲突——而那是一次凭空的冲突。
|
|
327
|
+
*/
|
|
328
|
+
export function splitProvenanceHeader(content: string): { header: string; body: string } {
|
|
329
|
+
const lines = content.split('\n');
|
|
330
|
+
let end = 0;
|
|
331
|
+
while (end < lines.length && lines[end].startsWith('//')) end += 1;
|
|
332
|
+
// 头必须真的含 provenance 标记;否则这只是文件开头的普通注释,不该剥
|
|
333
|
+
const header = lines.slice(0, end).join('\n');
|
|
334
|
+
if (!header.includes(PROVENANCE_MARK)) return { header: '', body: content };
|
|
335
|
+
return { header, body: lines.slice(end).join('\n').replace(/^\n/, '') };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* 把一份上游原文按 eject 的同一张表改写导入。
|
|
340
|
+
*
|
|
341
|
+
* 三方合并要把基线与上游都搬到"宿主坐标系"里:产物里的导入是改写过的,
|
|
342
|
+
* 而基线与上游是原始相对路径。不搬的话,每一条 import 都会被当成宿主的改动,
|
|
343
|
+
* 于是上游任何一次 import 调整都变成冲突。
|
|
344
|
+
*/
|
|
345
|
+
export function rewriteImportsForHost(source: string): string {
|
|
346
|
+
return source.replace(
|
|
347
|
+
/(from\s+|import\s*\(\s*)(['"])([^'"]+)\2/g,
|
|
348
|
+
(whole, prefix: string, quote: string, specifier: string) => {
|
|
349
|
+
const result = rewriteImport(specifier);
|
|
350
|
+
return 'error' in result ? whole : `${prefix}${quote}${result.to}${quote}`;
|
|
351
|
+
},
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export function readProvenance(content: string): ComponentProvenance | null {
|
|
356
|
+
const from = content.match(
|
|
357
|
+
new RegExp(`${PROVENANCE_MARK}\\s+([\\w-]+)@([^\\s]+)\\s+(\\S+)`),
|
|
358
|
+
);
|
|
359
|
+
const hash = content.match(/@soma-ejected-sha256\s+([0-9a-f]{64})/);
|
|
360
|
+
if (!from || !hash) return null;
|
|
361
|
+
return { from: from[1], version: from[2], source: from[3], sha256: hash[1] };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* 对比 eject 产物与上游当前源码。
|
|
366
|
+
*
|
|
367
|
+
* 比的是**上游的旧版与新版**(用产物里记的 sha256 判定上游是否动过),
|
|
368
|
+
* 不是「产物 vs 上游」——产物本来就该被宿主改,拿它去比只会满屏都是宿主自己的改动。
|
|
369
|
+
*/
|
|
370
|
+
export function diffEjectedComponent(ejectedFile: string, uiRoot: string): ComponentDiffResult {
|
|
371
|
+
if (!fs.existsSync(ejectedFile)) {
|
|
372
|
+
throw new ComponentEjectError(`找不到文件 ${ejectedFile}`);
|
|
373
|
+
}
|
|
374
|
+
const content = fs.readFileSync(ejectedFile, 'utf8');
|
|
375
|
+
const provenance = readProvenance(content);
|
|
376
|
+
if (!provenance) {
|
|
377
|
+
throw new ComponentEjectError(
|
|
378
|
+
`${ejectedFile} 里没有 provenance 头,它不是 \`soma component eject\` 的产物`,
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const upstreamPath = path.join(uiRoot, provenance.source);
|
|
383
|
+
if (!fs.existsSync(upstreamPath)) {
|
|
384
|
+
throw new ComponentEjectError(
|
|
385
|
+
`上游文件 ${provenance.source} 已不存在——该组件可能已改名或被删除`,
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
const upstream = fs.readFileSync(upstreamPath, 'utf8');
|
|
389
|
+
const currentSha256 = sha256Of(upstream);
|
|
390
|
+
const componentName = path.basename(ejectedFile).replace(/\.ts$/, '');
|
|
391
|
+
const currentVersion = readPackageVersion(uiRoot);
|
|
392
|
+
|
|
393
|
+
if (currentSha256 === provenance.sha256) {
|
|
394
|
+
return { componentName, changed: false, ejectedFrom: provenance, currentVersion, currentSha256 };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// 基线:eject 时落盘的上游原文。找得到才有真 diff;找不到就如实说,不伪造。
|
|
398
|
+
const basePath = path.join(path.dirname(ejectedFile), BASE_DIR, path.basename(ejectedFile));
|
|
399
|
+
const base = fs.existsSync(basePath) ? fs.readFileSync(basePath, 'utf8') : null;
|
|
400
|
+
if (base !== null && sha256Of(base) !== provenance.sha256) {
|
|
401
|
+
throw new ComponentEjectError(
|
|
402
|
+
`基线文件 ${basePath} 与 provenance 记录的 sha256 不一致——它被改动过。`
|
|
403
|
+
+ '\n 基线是 eject 那一刻的上游原文,不该被编辑;请从版本控制恢复它',
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
return {
|
|
408
|
+
componentName,
|
|
409
|
+
changed: true,
|
|
410
|
+
ejectedFrom: provenance,
|
|
411
|
+
currentVersion,
|
|
412
|
+
currentSha256,
|
|
413
|
+
hasBaseline: base !== null,
|
|
414
|
+
unified: base !== null
|
|
415
|
+
? renderUnifiedDiff(provenance.source, `(soma-ui@${provenance.version})`, `(soma-ui@${currentVersion})`, base, upstream)
|
|
416
|
+
: undefined,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* 极简统一 diff(LCS)。刻意不引第三方 diff 依赖:
|
|
422
|
+
* 供应链闸门要为每个新依赖负责,而这里要的只是「让人看见改了哪几行」。
|
|
423
|
+
*/
|
|
424
|
+
export function renderUnifiedDiff(
|
|
425
|
+
label: string,
|
|
426
|
+
oldTag: string,
|
|
427
|
+
newTag: string,
|
|
428
|
+
oldText: string,
|
|
429
|
+
newText: string,
|
|
430
|
+
): string {
|
|
431
|
+
const a = oldText.split('\n');
|
|
432
|
+
const b = newText.split('\n');
|
|
433
|
+
const lcs = longestCommonSubsequence(a, b);
|
|
434
|
+
const lines: string[] = [`--- ${label} ${oldTag}`, `+++ ${label} ${newTag}`];
|
|
435
|
+
|
|
436
|
+
let i = 0;
|
|
437
|
+
let j = 0;
|
|
438
|
+
for (const [ai, bj] of lcs) {
|
|
439
|
+
while (i < ai) lines.push(`-${a[i++]}`);
|
|
440
|
+
while (j < bj) lines.push(`+${b[j++]}`);
|
|
441
|
+
lines.push(` ${a[i]}`);
|
|
442
|
+
i += 1;
|
|
443
|
+
j += 1;
|
|
444
|
+
}
|
|
445
|
+
while (i < a.length) lines.push(`-${a[i++]}`);
|
|
446
|
+
while (j < b.length) lines.push(`+${b[j++]}`);
|
|
447
|
+
return lines.join('\n');
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** 返回配对索引序列 [[aIndex, bIndex], …] */
|
|
451
|
+
function longestCommonSubsequence(a: string[], b: string[]): Array<[number, number]> {
|
|
452
|
+
const rows = a.length;
|
|
453
|
+
const cols = b.length;
|
|
454
|
+
// 行数 × 列数在组件源码尺度(千行级)下完全可接受
|
|
455
|
+
const table: number[][] = Array.from({ length: rows + 1 }, () => new Array<number>(cols + 1).fill(0));
|
|
456
|
+
for (let i = rows - 1; i >= 0; i -= 1) {
|
|
457
|
+
for (let j = cols - 1; j >= 0; j -= 1) {
|
|
458
|
+
table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const pairs: Array<[number, number]> = [];
|
|
462
|
+
let i = 0;
|
|
463
|
+
let j = 0;
|
|
464
|
+
while (i < rows && j < cols) {
|
|
465
|
+
if (a[i] === b[j]) {
|
|
466
|
+
pairs.push([i, j]);
|
|
467
|
+
i += 1;
|
|
468
|
+
j += 1;
|
|
469
|
+
} else if (table[i + 1][j] >= table[i][j + 1]) i += 1;
|
|
470
|
+
else j += 1;
|
|
471
|
+
}
|
|
472
|
+
return pairs;
|
|
473
|
+
}
|