soma-core 2.2.8 → 2.2.9

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.
Files changed (93) hide show
  1. package/core/build/compiler/full-manifest-builder.ts +1 -1
  2. package/core/build/compiler/host-config-sync.cjs +1 -1
  3. package/core/build/compiler/soma-manifest-webpack-plugin.js +2 -6
  4. package/core/build/compiler/soma-precompile.js +80 -4
  5. package/core/client/a11y/announcer.ts +2 -16
  6. package/core/client/base/SomaPageRootBase.ts +2 -2
  7. package/core/client/base/defineSomaView.ts +11 -2
  8. package/core/client/base/runtime-services.types.ts +57 -0
  9. package/core/client/data/role-gate.ts +2 -8
  10. package/core/client/engine/event-engine.ts +1 -0
  11. package/core/client/engines/diff/adapter-jsdiff.ts +27 -8
  12. package/core/client/engines/diff/index.ts +81 -6
  13. package/core/client/engines/diff/items.ts +212 -0
  14. package/core/client/engines/diff/port.ts +140 -3
  15. package/core/client/engines/diff/prose.ts +443 -0
  16. package/core/client/engines/engine-adapters.ts +6 -0
  17. package/core/client/engines/highlight/adapter-lezer.ts +109 -0
  18. package/core/client/engines/highlight/index.ts +135 -0
  19. package/core/client/engines/highlight/port.ts +92 -0
  20. package/core/client/engines/markdown/adapter-markdown-it.ts +65 -0
  21. package/core/client/engines/markdown/blocks.ts +335 -0
  22. package/core/client/engines/markdown/index.ts +51 -0
  23. package/core/client/engines/markdown/port.ts +94 -0
  24. package/core/client/engines/markdown/vendor-modules.d.ts +6 -0
  25. package/core/client/engines/structured/adapter-js-yaml.ts +33 -0
  26. package/core/client/engines/structured/index.ts +139 -0
  27. package/core/client/engines/structured/port.ts +59 -0
  28. package/core/client/infra/http/SomaHttpService.ts +2 -4
  29. package/core/client/infra/notify/DefaultNotifyService.ts +2 -3
  30. package/core/client/infra/permission/SomaPermission.ts +1 -1
  31. package/core/client/render-ports/notify-renderer.ts +2 -46
  32. package/core/client/runtime/SomaRuntimeServices.ts +16 -45
  33. package/core/server/host/app-config-composer.ts +6 -52
  34. package/core/server/host/host-config-paths.cjs +2 -100
  35. package/core/server/host/precompiled-manifest.ts +69 -0
  36. package/core/server/infra/host-config-paths.cjs +100 -0
  37. package/core/server/page-assets.ts +2 -70
  38. package/core/server/runtime-space/bindings.ts +33 -4
  39. package/core/server/runtime-space/store.ts +16 -1
  40. package/core/shared/app-config-merge.ts +59 -0
  41. package/core/shared/registry-generated/limits.ts +80 -4
  42. package/core/shared/types/announcer.types.ts +18 -0
  43. package/core/shared/types/notify.types.ts +26 -0
  44. package/core/shared/types/role-gate.types.ts +11 -0
  45. package/dist/browser/runtime-bundle.manifest.json +50 -7
  46. package/dist/browser/soma-runtime.js +120741 -104799
  47. package/dist/core/index.cjs +113807 -97854
  48. package/dist/host-native/aot-builder.cjs +277 -189
  49. package/dist/host-native/native-server.cjs +196 -72
  50. package/dist/lsp/component-tree.cjs +80 -4
  51. package/dist/types/build/compiler/full-manifest-builder.d.ts +1 -1
  52. package/dist/types/client/a11y/announcer.d.ts +2 -14
  53. package/dist/types/client/base/SomaPageRootBase.d.ts +2 -2
  54. package/dist/types/client/base/runtime-services.types.d.ts +50 -0
  55. package/dist/types/client/data/role-gate.d.ts +2 -8
  56. package/dist/types/client/engines/diff/index.d.ts +1 -1
  57. package/dist/types/client/engines/diff/items.d.ts +24 -0
  58. package/dist/types/client/engines/diff/port.d.ts +124 -2
  59. package/dist/types/client/engines/diff/prose.d.ts +80 -0
  60. package/dist/types/client/engines/engine-adapters.d.ts +6 -0
  61. package/dist/types/client/engines/highlight/adapter-lezer.d.ts +6 -0
  62. package/dist/types/client/engines/highlight/index.d.ts +15 -0
  63. package/dist/types/client/engines/highlight/port.d.ts +64 -0
  64. package/dist/types/client/engines/markdown/adapter-markdown-it.d.ts +6 -0
  65. package/dist/types/client/engines/markdown/blocks.d.ts +29 -0
  66. package/dist/types/client/engines/markdown/index.d.ts +9 -0
  67. package/dist/types/client/engines/markdown/port.d.ts +166 -0
  68. package/dist/types/client/engines/structured/adapter-js-yaml.d.ts +6 -0
  69. package/dist/types/client/engines/structured/index.d.ts +29 -0
  70. package/dist/types/client/engines/structured/port.d.ts +45 -0
  71. package/dist/types/client/infra/http/SomaHttpService.d.ts +1 -1
  72. package/dist/types/client/infra/notify/DefaultNotifyService.d.ts +2 -3
  73. package/dist/types/client/infra/permission/SomaPermission.d.ts +1 -1
  74. package/dist/types/client/render-ports/notify-renderer.d.ts +1 -56
  75. package/dist/types/client/runtime/SomaRuntimeServices.d.ts +9 -44
  76. package/dist/types/server/host/app-config-composer.d.ts +2 -3
  77. package/dist/types/server/host/host-config-paths.d.cts +2 -7
  78. package/dist/types/server/host/precompiled-manifest.d.ts +5 -0
  79. package/dist/types/server/infra/host-config-paths.d.cts +7 -0
  80. package/dist/types/server/page-assets.d.ts +2 -5
  81. package/dist/types/server/runtime-space/store.d.ts +4 -0
  82. package/dist/types/shared/app-config-merge.d.ts +3 -0
  83. package/dist/types/shared/registry-generated/limits.d.ts +78 -4
  84. package/dist/types/shared/types/announcer.types.d.ts +14 -0
  85. package/dist/types/shared/types/notify.types.d.ts +36 -0
  86. package/dist/types/shared/types/role-gate.types.d.ts +8 -0
  87. package/host-native/src/aot-builder.ts +12 -5
  88. package/host-native/src/dev-chunk-gc.ts +104 -0
  89. package/host-native/src/host-prepare.ts +1 -1
  90. package/host-native/src/manifest-http.ts +1 -1
  91. package/host-native/src/page-http.ts +2 -67
  92. package/host-native/src/page-payload-cache.ts +68 -0
  93. package/package.json +16 -2
@@ -0,0 +1,443 @@
1
+ // 散文两级差异流水线(内容展示批次 ①;依据「参考文本差异组件笔记」B.2 两级策略与 B-实测 3)。
2
+ //
3
+ // 段 → 句 → 词:
4
+ // 1. 切段(按换行,空行丢弃);每段归一化(NFKC + 空白折叠 + 去汉字与拉丁之间的空白)作判等键。
5
+ // 2. 段级对齐(适配器 `chars` 粒度 + 每个不同的键映射为一个私用区字符,即 diff-match-patch 的 linesToChars 技巧)。
6
+ // 3. 同一删增区间内按相似度(字符多重集 Dice)单调贪心配对:≥ pairAt 视为「改写」,否则「删 + 增」。
7
+ // 4. 配上的段再按句(`Intl.Segmenter` sentence;没有则按 `。!?!?;;` 切)重复 2–3;配上的句做词级差异
8
+ // (有汉字 → `words-zh`;无汉字 → `words`),在归一化文本上求片段,再按下标映射回原文显示。
9
+ // 5. 孤字吸收:夹在两处改动之间、长度 ≤ absorbOrphan 的非标点相同片段并入改动。
10
+ // 6. 兜底:两侧都非空且整体相似度 < rewriteBelow → 整段替换(kind = rewrite)。
11
+ // 纯函数 + 适配器的 `diff`;不读 DOM、不 import 任何 soma 包之外的东西(可迁出,见独立仓库候选)。
12
+
13
+ import type { DiffFragment, DiffMode, DiffPart, ProseBlock, ProseDegraded, ProseDiff, SomaDiffAdapter } from './port';
14
+
15
+ export interface ProseConfig {
16
+ readonly nfkc: boolean;
17
+ readonly collapseWhitespace: boolean;
18
+ readonly newline: boolean;
19
+ readonly pairAt: number;
20
+ readonly rewriteBelow: number;
21
+ readonly absorbOrphan: number;
22
+ readonly maxChars: number;
23
+ readonly maxCharsPerCompare: number;
24
+ readonly maxAlignTokens: number;
25
+ readonly maxPairMatrix: number;
26
+ }
27
+
28
+ /** 一次计算的共享上下文:时限、退化标记、实际粒度 */
29
+ export interface ProseRun {
30
+ readonly adapter: SomaDiffAdapter;
31
+ readonly deadline: number;
32
+ degraded?: ProseDegraded;
33
+ usedChars: boolean;
34
+ usedZh: boolean;
35
+ }
36
+
37
+ const now = (): number => (typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now());
38
+ export const clock = now;
39
+
40
+ const HAN = /[⺀-⿟぀-ヿ㐀-䶿一-鿿豈-﫿]/u;
41
+ const CJK_PUNCT = /[ -〿＀-￯“”‘’…—]/u;
42
+ const PUNCT = /^[\p{P}\p{S}\s]+$/u;
43
+ const SPACE = /\s/u;
44
+
45
+ export const hasHan = (s: string): boolean => HAN.test(s);
46
+ const isCjk = (ch: string): boolean => HAN.test(ch) || CJK_PUNCT.test(ch);
47
+
48
+ export interface Normalized {
49
+ /** 归一化文本(判等、相似度、词级差异都在它上面算) */
50
+ readonly text: string;
51
+ /** text 的第 i 个码元来自原文第 origin[i] 个码元 */
52
+ readonly origin: readonly number[];
53
+ readonly source: string;
54
+ }
55
+
56
+ /** 归一化并记下每个码元的原文下标(显示用原文,判等用归一化文本) */
57
+ export function normalizeWithMap(source: string, cfg: Pick<ProseConfig, 'nfkc' | 'collapseWhitespace' | 'newline'>): Normalized {
58
+ const chars: string[] = [];
59
+ const origin: number[] = [];
60
+ let i = 0;
61
+ for (const cp of source) {
62
+ const at = i;
63
+ i += cp.length;
64
+ if (cfg.newline && cp === '\r') continue;
65
+ let mapped = cfg.nfkc ? cp.normalize('NFKC') : cp;
66
+ if (cfg.collapseWhitespace && SPACE.test(mapped)) mapped = ' ';
67
+ for (const unit of mapped.split('')) { chars.push(unit); origin.push(at); }
68
+ }
69
+ if (!cfg.collapseWhitespace) return { text: chars.join(''), origin, source };
70
+ // 折叠空白:去首尾、连续空白留一个、汉字 / 中文标点与任何字符之间的空白去掉
71
+ const outC: string[] = [];
72
+ const outO: number[] = [];
73
+ for (let k = 0; k < chars.length; k += 1) {
74
+ const ch = chars[k];
75
+ if (ch !== ' ') { outC.push(ch); outO.push(origin[k]); continue; }
76
+ const prev = outC.length > 0 ? outC[outC.length - 1] : '';
77
+ if (prev === '' || prev === ' ') continue;
78
+ let n = k + 1;
79
+ while (n < chars.length && chars[n] === ' ') n += 1;
80
+ const next = n < chars.length ? chars[n] : '';
81
+ if (next === '' || isCjk(prev) || isCjk(next)) continue;
82
+ outC.push(' '); outO.push(origin[k]);
83
+ }
84
+ return { text: outC.join(''), origin: outO, source };
85
+ }
86
+
87
+ /** 归一化片段 [s, e) → 原文切片 */
88
+ function originSlice(n: Normalized, s: number, e: number): string {
89
+ const from = s === 0 ? 0 : n.origin[s];
90
+ const to = e >= n.text.length ? n.source.length : n.origin[e];
91
+ return n.source.slice(from, to);
92
+ }
93
+
94
+ /** 字符多重集 Dice(按码点):配对用,便宜、同步 */
95
+ export function diceSimilarity(a: string, b: string): number {
96
+ const ca = Array.from(a);
97
+ const cb = Array.from(b);
98
+ if (ca.length + cb.length === 0) return 1;
99
+ const bag = new Map<string, number>();
100
+ for (const ch of ca) bag.set(ch, (bag.get(ch) ?? 0) + 1);
101
+ let common = 0;
102
+ for (const ch of cb) {
103
+ const left = bag.get(ch) ?? 0;
104
+ if (left > 0) { common += 1; bag.set(ch, left - 1); }
105
+ }
106
+ return (2 * common) / (ca.length + cb.length);
107
+ }
108
+
109
+ const cpLen = (s: string): number => Array.from(s).length;
110
+
111
+ // ── 序列对齐(经适配器)──────────────────────────────────────────────────────
112
+
113
+ export type AlignOp = { readonly op: 'eq'; readonly a: number; readonly b: number } | { readonly op: 'del'; readonly a: number } | { readonly op: 'ins'; readonly b: number };
114
+
115
+ // Unicode 私有使用区(BMP PUA U+E000..U+F8FF):按字符码点边界取值,避免裸十六进制字面量
116
+ const PUA_BASE = '\uE000'.codePointAt(0)!;
117
+ const PUA_END = '\uF8FF'.codePointAt(0)!;
118
+ const PUA_SIZE = PUA_END - PUA_BASE + 1;
119
+
120
+ /** 两个键序列的 LCS 对齐:每个不同的键映射为一个私用区字符后交适配器 `chars` 粒度。null = 超时或不同键过多 */
121
+ export async function alignKeys(run: ProseRun, aKeys: readonly string[], bKeys: readonly string[], maxTokens: number): Promise<AlignOp[] | null> {
122
+ if (aKeys.length === 0 || bKeys.length === 0) {
123
+ return [...aKeys.map((_, a) => ({ op: 'del' as const, a })), ...bKeys.map((_, b) => ({ op: 'ins' as const, b }))];
124
+ }
125
+ const ids = new Map<string, number>();
126
+ const code = (k: string): string => {
127
+ let id = ids.get(k);
128
+ if (id === undefined) { id = ids.size; ids.set(k, id); }
129
+ return String.fromCharCode(PUA_BASE + (id % PUA_SIZE));
130
+ };
131
+ const sa = aKeys.map(code).join('');
132
+ const sb = bKeys.map(code).join('');
133
+ if (ids.size > Math.min(maxTokens, PUA_SIZE)) return null;
134
+ const parts = await safeDiff(run, sa, sb, 'chars');
135
+ if (parts === null) return null;
136
+ const ops: AlignOp[] = [];
137
+ let ia = 0;
138
+ let ib = 0;
139
+ for (const p of parts) {
140
+ for (let k = 0; k < p.text.length; k += 1) {
141
+ if (p.op === 'equal') ops.push({ op: 'eq', a: ia++, b: ib++ });
142
+ else if (p.op === 'delete') ops.push({ op: 'del', a: ia++ });
143
+ else ops.push({ op: 'ins', b: ib++ });
144
+ }
145
+ }
146
+ if (ia !== aKeys.length || ib !== bKeys.length) return null;
147
+ return ops;
148
+ }
149
+
150
+ /** 适配器调用:带剩余时限;超时 / 抛错 → null(并记退化) */
151
+ export async function safeDiff(run: ProseRun, a: string, b: string, mode: DiffMode): Promise<readonly DiffPart[] | null> {
152
+ const left = Math.floor(run.deadline - now());
153
+ if (left <= 0) { run.degraded ??= 'timeout'; return null; }
154
+ try {
155
+ const parts = await run.adapter.diff(a, b, mode, { timeoutMs: left });
156
+ if (parts === null) run.degraded ??= 'timeout';
157
+ return parts;
158
+ } catch {
159
+ run.degraded ??= 'timeout';
160
+ return null;
161
+ }
162
+ }
163
+
164
+ /** 一段删增区间内的单调贪心配对:按相似度从高到低取,且保持两侧顺序 */
165
+ export function pairRun(dels: readonly string[], inss: readonly string[], at: number, maxMatrix: number): Map<number, number> {
166
+ const pairs = new Map<number, number>();
167
+ if (dels.length === 0 || inss.length === 0 || dels.length * inss.length > maxMatrix) return pairs;
168
+ const cand: { d: number; i: number; s: number }[] = [];
169
+ for (let d = 0; d < dels.length; d += 1) {
170
+ for (let i = 0; i < inss.length; i += 1) {
171
+ const s = diceSimilarity(dels[d], inss[i]);
172
+ if (s >= at) cand.push({ d, i, s });
173
+ }
174
+ }
175
+ cand.sort((x, y) => y.s - x.s || x.d - y.d || x.i - y.i);
176
+ const usedI = new Set<number>();
177
+ for (const c of cand) {
178
+ if (pairs.has(c.d) || usedI.has(c.i)) continue;
179
+ // 保序:不能与已有配对交叉
180
+ let crosses = false;
181
+ for (const [d, i] of pairs) if ((d < c.d && i > c.i) || (d > c.d && i < c.i)) { crosses = true; break; }
182
+ if (crosses) continue;
183
+ pairs.set(c.d, c.i);
184
+ usedI.add(c.i);
185
+ }
186
+ return pairs;
187
+ }
188
+
189
+ /** 对齐结果按「相同 / 删增区间」分组后配对,产出单元级操作序列 */
190
+ export type UnitOp = { readonly op: 'eq'; readonly a: number; readonly b: number } | { readonly op: 'mod'; readonly a: number; readonly b: number } | { readonly op: 'del'; readonly a: number } | { readonly op: 'ins'; readonly b: number };
191
+
192
+ export function pairAligned(ops: readonly AlignOp[], aKeys: readonly string[], bKeys: readonly string[], at: number, maxMatrix: number): UnitOp[] {
193
+ const out: UnitOp[] = [];
194
+ let k = 0;
195
+ while (k < ops.length) {
196
+ const op = ops[k];
197
+ if (op.op === 'eq') { out.push(op); k += 1; continue; }
198
+ const dels: number[] = [];
199
+ const inss: number[] = [];
200
+ while (k < ops.length && ops[k].op !== 'eq') {
201
+ const o = ops[k];
202
+ if (o.op === 'del') dels.push(o.a); else if (o.op === 'ins') inss.push(o.b);
203
+ k += 1;
204
+ }
205
+ const pairs = pairRun(dels.map((a) => aKeys[a]), inss.map((b) => bKeys[b]), at, maxMatrix);
206
+ // 按保序配对把区间排成:未配的删 / 增依次放在配对之前
207
+ let di = 0;
208
+ let ii = 0;
209
+ const ordered = [...pairs.entries()].sort((x, y) => x[0] - y[0]);
210
+ for (const [d, i] of ordered) {
211
+ for (; di < d; di += 1) out.push({ op: 'del', a: dels[di] });
212
+ for (; ii < i; ii += 1) out.push({ op: 'ins', b: inss[ii] });
213
+ out.push({ op: 'mod', a: dels[d], b: inss[i] });
214
+ di = d + 1;
215
+ ii = i + 1;
216
+ }
217
+ for (; di < dels.length; di += 1) out.push({ op: 'del', a: dels[di] });
218
+ for (; ii < inss.length; ii += 1) out.push({ op: 'ins', b: inss[ii] });
219
+ }
220
+ return out;
221
+ }
222
+
223
+ // ── 切段 / 切句 ───────────────────────────────────────────────────────────────
224
+
225
+ export function splitParagraphs(text: string): string[] {
226
+ return text.split(/\r?\n/u).filter((line) => line.trim() !== '');
227
+ }
228
+
229
+ interface SentenceSegmenter { segment(s: string): Iterable<{ segment: string }> }
230
+ let sentenceSeg: SentenceSegmenter | null | undefined;
231
+ function sentenceSegmenter(): SentenceSegmenter | null {
232
+ if (sentenceSeg !== undefined) return sentenceSeg;
233
+ const ctor = (Intl as unknown as { Segmenter?: new (l: string, o: { granularity: 'sentence' }) => SentenceSegmenter }).Segmenter;
234
+ sentenceSeg = typeof ctor === 'function' ? new ctor('zh', { granularity: 'sentence' }) : null;
235
+ return sentenceSeg;
236
+ }
237
+
238
+ /** 运行时是否有 `Intl.Segmenter`(无 → 词级退回逐字,摘要条注「按字比较」) */
239
+ export function hasSegmenter(): boolean {
240
+ return typeof (Intl as unknown as { Segmenter?: unknown }).Segmenter === 'function';
241
+ }
242
+
243
+ export function splitSentences(paragraph: string): string[] {
244
+ const seg = sentenceSegmenter();
245
+ const out: string[] = [];
246
+ if (seg !== null) {
247
+ for (const s of seg.segment(paragraph)) if (s.segment !== '') out.push(s.segment);
248
+ } else {
249
+ const re = /[^。!?!?;;]*[。!?!?;;]+[”’」』))]*\s*|[^。!?!?;;]+$/gu;
250
+ for (const m of paragraph.matchAll(re)) if (m[0] !== '') out.push(m[0]);
251
+ }
252
+ return out.length > 0 ? out : [paragraph];
253
+ }
254
+
255
+ // ── 片段工具 ─────────────────────────────────────────────────────────────────
256
+
257
+ /** 合并相邻同类片段;每个改动簇内删在前、增在后 */
258
+ export function tidy(frags: readonly DiffFragment[]): DiffFragment[] {
259
+ const out: DiffFragment[] = [];
260
+ let del = '';
261
+ let ins = '';
262
+ const flush = (): void => {
263
+ if (del !== '') out.push({ op: 'del', v: del });
264
+ if (ins !== '') out.push({ op: 'ins', v: ins });
265
+ del = '';
266
+ ins = '';
267
+ };
268
+ for (const f of frags) {
269
+ if (f.v === '') continue;
270
+ if (f.op === 'del') del += f.v;
271
+ else if (f.op === 'ins') ins += f.v;
272
+ else {
273
+ flush();
274
+ const last = out[out.length - 1];
275
+ if (last !== undefined && last.op === 'eq') out[out.length - 1] = { op: 'eq', v: last.v + f.v };
276
+ else out.push(f);
277
+ }
278
+ }
279
+ flush();
280
+ return out;
281
+ }
282
+
283
+ /** 孤字吸收:两处改动之间、长度 ≤ max 的非标点相同片段并入两侧改动 */
284
+ export function absorbOrphans(frags: readonly DiffFragment[], max: number): DiffFragment[] {
285
+ if (max <= 0) return tidy(frags);
286
+ const out: DiffFragment[] = [];
287
+ for (let k = 0; k < frags.length; k += 1) {
288
+ const f = frags[k];
289
+ const prev = frags[k - 1];
290
+ const next = frags[k + 1];
291
+ if (f.op === 'eq' && prev !== undefined && next !== undefined && prev.op !== 'eq' && next.op !== 'eq' && cpLen(f.v) <= max && !PUNCT.test(f.v)) {
292
+ out.push({ op: 'del', v: f.v }, { op: 'ins', v: f.v });
293
+ } else out.push(f);
294
+ }
295
+ return tidy(out);
296
+ }
297
+
298
+ /** 改动簇数(导航「第 i / 共 k 处」的 k) */
299
+ export function countChanges(frags: readonly DiffFragment[]): number {
300
+ let n = 0;
301
+ let inChange = false;
302
+ for (const f of frags) {
303
+ if (f.op === 'eq') inChange = false;
304
+ else if (!inChange) { n += 1; inChange = true; }
305
+ }
306
+ return n;
307
+ }
308
+
309
+ // ── 词级 / 句级 / 段级 ────────────────────────────────────────────────────────
310
+
311
+ /** 两句(已配对)的词级片段:归一化文本上求差异,按下标映射回原文 */
312
+ async function diffWordsMapped(run: ProseRun, cfg: ProseConfig, a: string, b: string): Promise<DiffFragment[]> {
313
+ const na = normalizeWithMap(a, cfg);
314
+ const nb = normalizeWithMap(b, cfg);
315
+ if (na.text === nb.text) return [{ op: 'eq', v: b }];
316
+ const whole: DiffFragment[] = [{ op: 'del', v: a }, { op: 'ins', v: b }];
317
+ if (na.text.length + nb.text.length > cfg.maxCharsPerCompare) { run.degraded ??= 'too-large'; return whole; }
318
+ const zh = hasHan(na.text) || hasHan(nb.text);
319
+ let mode: DiffMode = zh ? 'words-zh' : 'words';
320
+ if (zh && !hasSegmenter()) { mode = 'chars'; run.usedChars = true; run.degraded ??= 'no-segmenter'; }
321
+ if (zh && mode === 'words-zh') run.usedZh = true;
322
+ let parts = await safeDiff(run, na.text, nb.text, mode);
323
+ if (parts === null) return whole;
324
+ let mapped = mapParts(parts, na, nb);
325
+ if (mapped === null && mode !== 'chars') {
326
+ // 词粒度的片段拼不回归一化文本(库对空白的处理)→ 逐字重算一次
327
+ parts = await safeDiff(run, na.text, nb.text, 'chars');
328
+ mapped = parts === null ? null : mapParts(parts, na, nb);
329
+ }
330
+ return mapped ?? whole;
331
+ }
332
+
333
+ function mapParts(parts: readonly DiffPart[], na: Normalized, nb: Normalized): DiffFragment[] | null {
334
+ const out: DiffFragment[] = [];
335
+ let ia = 0;
336
+ let ib = 0;
337
+ for (const p of parts) {
338
+ const len = p.text.length;
339
+ if (p.op === 'equal') {
340
+ if (na.text.slice(ia, ia + len) !== p.text || nb.text.slice(ib, ib + len) !== p.text) return null;
341
+ out.push({ op: 'eq', v: originSlice(nb, ib, ib + len) });
342
+ ia += len;
343
+ ib += len;
344
+ } else if (p.op === 'delete') {
345
+ if (na.text.slice(ia, ia + len) !== p.text) return null;
346
+ out.push({ op: 'del', v: originSlice(na, ia, ia + len) });
347
+ ia += len;
348
+ } else {
349
+ if (nb.text.slice(ib, ib + len) !== p.text) return null;
350
+ out.push({ op: 'ins', v: originSlice(nb, ib, ib + len) });
351
+ ib += len;
352
+ }
353
+ }
354
+ if (ia !== na.text.length || ib !== nb.text.length) return null;
355
+ return out;
356
+ }
357
+
358
+ /** 两段(已配对):句级对齐 + 配对 + 句内词级 */
359
+ async function diffParagraph(run: ProseRun, cfg: ProseConfig, a: string, b: string): Promise<DiffFragment[]> {
360
+ const sa = splitSentences(a);
361
+ const sb = splitSentences(b);
362
+ const ka = sa.map((s) => normalizeWithMap(s, cfg).text);
363
+ const kb = sb.map((s) => normalizeWithMap(s, cfg).text);
364
+ const aligned = await alignKeys(run, ka, kb, cfg.maxAlignTokens);
365
+ if (aligned === null) return [{ op: 'del', v: a }, { op: 'ins', v: b }];
366
+ const units = pairAligned(aligned, ka, kb, cfg.pairAt, cfg.maxPairMatrix);
367
+ const frags: DiffFragment[] = [];
368
+ for (const u of units) {
369
+ if (u.op === 'eq') frags.push({ op: 'eq', v: sb[u.b] });
370
+ else if (u.op === 'del') frags.push({ op: 'del', v: sa[u.a] });
371
+ else if (u.op === 'ins') frags.push({ op: 'ins', v: sb[u.b] });
372
+ else frags.push(...(await diffWordsMapped(run, cfg, sa[u.a], sb[u.b])));
373
+ }
374
+ return absorbOrphans(frags, cfg.absorbOrphan);
375
+ }
376
+
377
+ function statsOf(blocks: readonly ProseBlock[]): ProseDiff['stats'] {
378
+ let ins = 0;
379
+ let del = 0;
380
+ let changes = 0;
381
+ for (const blk of blocks) {
382
+ for (const f of blk.fragments) {
383
+ if (f.op === 'ins') ins += cpLen(f.v.replace(/\s+/gu, ''));
384
+ else if (f.op === 'del') del += cpLen(f.v.replace(/\s+/gu, ''));
385
+ }
386
+ if (blk.op === 'ins' || blk.op === 'del') changes += 1;
387
+ else if (blk.op === 'mod') changes += countChanges(blk.fragments);
388
+ }
389
+ return { insChars: ins, delChars: del, changes };
390
+ }
391
+
392
+ function similarityOf(blocks: readonly ProseBlock[], aLen: number, bLen: number): number {
393
+ if (aLen + bLen === 0) return 1;
394
+ let eq = 0;
395
+ for (const blk of blocks) for (const f of blk.fragments) if (f.op === 'eq') eq += cpLen(f.v.replace(/\s+/gu, ''));
396
+ return Math.min(1, (2 * eq) / (aLen + bLen));
397
+ }
398
+
399
+ const compact = (s: string): number => cpLen(s.replace(/\s+/gu, ''));
400
+
401
+ /** 整段替换:旧版每段删除、新版每段新增(上下堆叠) */
402
+ function rewriteBlocks(pa: readonly string[], pb: readonly string[]): ProseBlock[] {
403
+ return [...pa.map((v) => ({ op: 'del' as const, fragments: [{ op: 'del' as const, v }] })), ...pb.map((v) => ({ op: 'ins' as const, fragments: [{ op: 'ins' as const, v }] }))];
404
+ }
405
+
406
+ /** 散文两级差异主入口(输入已校验为字符串) */
407
+ export async function runProse(run: ProseRun, cfg: ProseConfig, a: string, b: string): Promise<ProseDiff> {
408
+ const pa = splitParagraphs(a);
409
+ const pb = splitParagraphs(b);
410
+ const granularity = (): ProseDiff['granularity'] => (run.usedChars ? 'chars' : run.usedZh ? 'words-zh' : (hasHan(a) || hasHan(b)) ? (hasSegmenter() ? 'words-zh' : 'chars') : 'words');
411
+ const aLen = compact(a);
412
+ const bLen = compact(b);
413
+ const finish = (kind: ProseDiff['kind'], blocks: ProseBlock[], formatOnly = false): ProseDiff => {
414
+ const stats = statsOf(blocks);
415
+ const out: ProseDiff = { kind, formatOnly, similarity: kind === 'same' ? 1 : similarityOf(blocks, aLen, bLen), blocks, stats, granularity: granularity() };
416
+ return run.degraded !== undefined ? { ...out, degraded: run.degraded } : out;
417
+ };
418
+
419
+ if (a.length + b.length > cfg.maxChars) {
420
+ run.degraded = 'too-large';
421
+ return finish(pa.length > 0 && pb.length > 0 ? 'rewrite' : 'inline', rewriteBlocks(pa, pb));
422
+ }
423
+ const ka = pa.map((p) => normalizeWithMap(p, cfg).text);
424
+ const kb = pb.map((p) => normalizeWithMap(p, cfg).text);
425
+ if (ka.length === kb.length && ka.every((k, i) => k === kb[i])) {
426
+ return finish('same', pb.map((v) => ({ op: 'eq', fragments: [{ op: 'eq', v }] })), a !== b);
427
+ }
428
+ if (pa.length === 0 || pb.length === 0) return finish('inline', rewriteBlocks(pa, pb));
429
+
430
+ const aligned = await alignKeys(run, ka, kb, cfg.maxAlignTokens);
431
+ if (aligned === null) return finish('rewrite', rewriteBlocks(pa, pb));
432
+ const units = pairAligned(aligned, ka, kb, cfg.pairAt, cfg.maxPairMatrix);
433
+ const blocks: ProseBlock[] = [];
434
+ for (const u of units) {
435
+ if (u.op === 'eq') blocks.push({ op: 'eq', fragments: [{ op: 'eq', v: pb[u.b] }] });
436
+ else if (u.op === 'del') blocks.push({ op: 'del', fragments: [{ op: 'del', v: pa[u.a] }] });
437
+ else if (u.op === 'ins') blocks.push({ op: 'ins', fragments: [{ op: 'ins', v: pb[u.b] }] });
438
+ else blocks.push({ op: 'mod', fragments: await diffParagraph(run, cfg, pa[u.a], pb[u.b]) });
439
+ }
440
+ const sim = similarityOf(blocks, aLen, bLen);
441
+ if (sim < cfg.rewriteBelow) return finish('rewrite', rewriteBlocks(pa, pb));
442
+ return finish('inline', blocks);
443
+ }
@@ -11,6 +11,9 @@ import type { SomaChartAdapter } from './chart/port';
11
11
  import type { SomaDragAdapter } from './dnd/port';
12
12
  import type { SomaDiffAdapter } from './diff/port';
13
13
  import type { SomaQrAdapter } from './qrcode/port';
14
+ import type { SomaHighlightAdapter } from './highlight/port';
15
+ import type { SomaStructuredAdapter } from './structured/port';
16
+ import type { SomaMarkdownAdapter } from './markdown/port';
14
17
 
15
18
  /** 各引擎端口可替换的适配器;键 = 端口,值 = 该端口 `port.ts` 导出的适配器类型 */
16
19
  export interface SomaEngineAdapters {
@@ -24,6 +27,9 @@ export interface SomaEngineAdapters {
24
27
  readonly dnd: SomaDragAdapter;
25
28
  readonly diff: SomaDiffAdapter;
26
29
  readonly qrcode: SomaQrAdapter;
30
+ readonly highlight: SomaHighlightAdapter;
31
+ readonly structured: SomaStructuredAdapter;
32
+ readonly markdown: SomaMarkdownAdapter;
27
33
  }
28
34
 
29
35
  export type SomaEngineId = keyof SomaEngineAdapters;
@@ -0,0 +1,109 @@
1
+ // Lezer 缺省适配器(内容展示批次 ③):全仓唯一 import `@lezer/*` 的文件,只用动态 import()。
2
+ // 只读高亮用 Lezer 语法 + `@lezer/highlight`(highlightTree + tagHighlighter),与第 ⑤ 批 CodeMirror 6 编辑器同一套语法定义。
3
+ // 记号种类由 Lezer 标签确定性映射到 14 种闭集;解析按 advance() 分步,超过时限返回 'timeout'。
4
+
5
+ import { loadEngineModule, type EngineLoadTelemetry } from '../load';
6
+ import type { CodeSpan, CodeTokenKind, SomaHighlightAdapter } from './port';
7
+
8
+ interface PartialParse { advance(): unknown | null }
9
+ interface LezerParser { startParse(input: string): PartialParse; configure?(config: Record<string, unknown>): LezerParser }
10
+ interface Tag { readonly id: number }
11
+ type TagFn = (tag: Tag) => Tag;
12
+ interface TagsTable extends Record<string, Tag | TagFn> {}
13
+ interface HighlightModule {
14
+ tags: TagsTable;
15
+ tagHighlighter(spec: readonly { tag: Tag | readonly Tag[]; class: string }[]): unknown;
16
+ highlightTree(tree: unknown, highlighter: unknown, putStyle: (from: number, to: number, classes: string) => void): void;
17
+ }
18
+
19
+ export interface LezerAdapterOptions { readonly telemetry?: EngineLoadTelemetry }
20
+
21
+ /** 规范 id → 加载该语言的 Lezer 解析器 */
22
+ type ParserLoader = () => Promise<LezerParser>;
23
+ const parserOf = (mod: unknown): LezerParser => (mod as { parser: LezerParser }).parser;
24
+
25
+ function loaders(telemetry: EngineLoadTelemetry | undefined): Readonly<Record<string, ParserLoader>> {
26
+ const load = (key: string, loader: () => Promise<unknown>): Promise<unknown> => loadEngineModule('highlight', loader, { telemetry, key });
27
+ const js = (): Promise<LezerParser> => load('javascript', () => import('@lezer/javascript')).then(parserOf);
28
+ const dialect = (d: string) => async (): Promise<LezerParser> => {
29
+ const p = await js();
30
+ return p.configure ? p.configure({ dialect: d }) : p;
31
+ };
32
+ return {
33
+ json: () => load('json', () => import('@lezer/json')).then(parserOf),
34
+ yaml: () => load('yaml', () => import('@lezer/yaml')).then(parserOf),
35
+ javascript: js,
36
+ typescript: dialect('ts'),
37
+ jsx: dialect('jsx'),
38
+ tsx: dialect('jsx ts'),
39
+ python: () => load('python', () => import('@lezer/python')).then(parserOf),
40
+ css: () => load('css', () => import('@lezer/css')).then(parserOf),
41
+ html: () => load('html', () => import('@lezer/html')).then(parserOf),
42
+ xml: () => load('xml', () => import('@lezer/xml')).then(parserOf),
43
+ markdown: () => load('markdown', () => import('@lezer/markdown')).then(parserOf),
44
+ java: () => load('java', () => import('@lezer/java')).then(parserOf),
45
+ go: () => load('go', () => import('@lezer/go')).then(parserOf),
46
+ };
47
+ }
48
+
49
+ /** Lezer 标签 → 记号种类(tagHighlighter 按标签层级取最具体的一条) */
50
+ function kindSpec(t: TagsTable): { tag: Tag | readonly Tag[]; class: CodeTokenKind }[] {
51
+ const tag = (name: string): Tag | undefined => (typeof t[name] === 'object' ? (t[name] as Tag) : undefined);
52
+ const fn = (mod: string, base: string): Tag | undefined => {
53
+ const m = t[mod];
54
+ const b = tag(base);
55
+ return typeof m === 'function' && b !== undefined ? (m as TagFn)(b) : undefined;
56
+ };
57
+ const list = (...xs: (Tag | undefined)[]): Tag[] => xs.filter((x): x is Tag => x !== undefined);
58
+ const rows: { tag: Tag[]; class: CodeTokenKind }[] = [
59
+ { tag: list(tag('comment'), tag('lineComment'), tag('blockComment'), tag('docComment')), class: 'comment' },
60
+ { tag: list(tag('keyword'), tag('controlKeyword'), tag('definitionKeyword'), tag('moduleKeyword'), tag('operatorKeyword'), tag('modifier'), tag('self'), tag('heading')), class: 'keyword' },
61
+ { tag: list(tag('string'), tag('docString'), tag('character'), tag('regexp'), tag('attributeValue'), tag('url'), tag('monospace')), class: 'string' },
62
+ { tag: list(tag('number'), tag('integer'), tag('float')), class: 'number' },
63
+ { tag: list(tag('bool'), tag('null'), tag('atom'), tag('unit'), tag('escape'), fn('constant', 'name'), fn('standard', 'name')), class: 'constant' },
64
+ { tag: list(fn('function', 'variableName'), fn('function', 'propertyName'), tag('macroName')), class: 'function' },
65
+ { tag: list(tag('typeName'), tag('className'), tag('namespace')), class: 'type' },
66
+ { tag: list(tag('variableName'), tag('labelName'), fn('definition', 'variableName')), class: 'variable' },
67
+ { tag: list(tag('propertyName'), fn('definition', 'propertyName')), class: 'property' },
68
+ { tag: list(tag('operator'), tag('arithmeticOperator'), tag('logicOperator'), tag('bitwiseOperator'), tag('compareOperator'), tag('updateOperator'), tag('definitionOperator'), tag('typeOperator'), tag('controlOperator'), tag('derefOperator')), class: 'operator' },
69
+ { tag: list(tag('punctuation'), tag('separator'), tag('bracket'), tag('angleBracket'), tag('squareBracket'), tag('paren'), tag('brace'), tag('processingInstruction'), tag('meta')), class: 'punctuation' },
70
+ { tag: list(tag('tagName')), class: 'tag' },
71
+ { tag: list(tag('attributeName')), class: 'attribute' },
72
+ ];
73
+ return rows.filter((r) => r.tag.length > 0);
74
+ }
75
+
76
+ const KINDS: ReadonlySet<string> = new Set(['comment', 'keyword', 'string', 'number', 'constant', 'function', 'type', 'variable', 'property', 'operator', 'punctuation', 'tag', 'attribute']);
77
+
78
+ const now = (): number => (typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now());
79
+
80
+ export function createLezerAdapter(adapterOptions: LezerAdapterOptions = {}): SomaHighlightAdapter {
81
+ const table = loaders(adapterOptions.telemetry);
82
+ let highlighter: Promise<{ mod: HighlightModule; hl: unknown }> | null = null;
83
+ const loadHighlight = (): Promise<{ mod: HighlightModule; hl: unknown }> => {
84
+ highlighter ??= loadEngineModule<HighlightModule>('highlight', () => import('@lezer/highlight') as unknown as Promise<HighlightModule>, { telemetry: adapterOptions.telemetry, key: 'core' })
85
+ .then((mod) => ({ mod, hl: mod.tagHighlighter(kindSpec(mod.tags)) }))
86
+ .catch((e: unknown) => { highlighter = null; throw e; });
87
+ return highlighter;
88
+ };
89
+ return {
90
+ languages: () => Object.keys(table),
91
+ async tokenize(code, language, options) {
92
+ const loader = table[language];
93
+ if (loader === undefined) return 'unsupported';
94
+ const [{ mod, hl }, parser] = await Promise.all([loadHighlight(), loader()]);
95
+ const parse = parser.startParse(code);
96
+ let tree: unknown = null;
97
+ while (tree === null) {
98
+ tree = parse.advance();
99
+ if (tree === null && now() > options.deadline) return 'timeout';
100
+ }
101
+ const spans: CodeSpan[] = [];
102
+ mod.highlightTree(tree, hl, (from, to, classes) => {
103
+ const kind = classes.split(' ').find((c) => KINDS.has(c));
104
+ if (kind !== undefined && to > from) spans.push({ from, to, kind: kind as CodeTokenKind });
105
+ });
106
+ return spans;
107
+ },
108
+ };
109
+ }