@allbluecn/dsh-compat 0.0.0-stage → 0.0.2

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.
@@ -0,0 +1,250 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // DSH patch 数据原语单测(规格 §4.1.1 / §5 一致性用例 2)。
6
+ // - merge.ts applyPatches:id 定向 + **逐 key 覆盖** + 未提及 key 保留 + 同 key 后层胜
7
+ // (「整 config 替换」仅指 config 这一个 key,不做深合并)
8
+ // - yaml.ts parsePatchYaml:真实 DSH cordis.patch.yml 结构 → PatchLine[]
9
+ // - eval.ts evalDisabled / evalPatchExpression:!!js 白名单求值(禁 eval/new Function)
10
+ //
11
+ // 逐 key 用例 1-7 锁死 DSH vendor patch 语义(本任务核心重写点)。
12
+
13
+ import { describe, expect, it } from 'vitest'
14
+ import { applyPatches } from '../merge'
15
+ import { parsePatchYaml } from '../yaml'
16
+ import { evalDisabled, evalPatchExpression } from '../eval'
17
+ import { extractInsert } from '../types'
18
+ import type { PatchFile, PatchLine } from '../types'
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // applyPatches —— 迁移用例(原 kernel.test.ts,语义已由整行替换改为逐 key 覆盖)
22
+ // ---------------------------------------------------------------------------
23
+
24
+ describe('applyPatches(迁移用例)', () => {
25
+ it('按 id 覆盖,整 config 替换(config 单 key 原子)', () => {
26
+ const base = [{ id: 'a', name: 'pkg/a', config: { x: 1 } }]
27
+ const user = [{ id: 'a', name: 'pkg/a', config: { y: 2 } }]
28
+ const merged = applyPatches(base, user)
29
+ expect(merged).toHaveLength(1)
30
+ expect(merged[0].config).toEqual({ y: 2 }) // 整 config 替换(config 单 key),非深合并
31
+ })
32
+
33
+ it('未覆盖的行保留', () => {
34
+ const merged = applyPatches(
35
+ [{ id: 'a', name: 'a' }, { id: 'b', name: 'b' }],
36
+ [{ id: 'b', disabled: true }],
37
+ )
38
+ expect(merged).toHaveLength(2)
39
+ expect(merged.find((l) => l.id === 'a')?.name).toBe('a')
40
+ expect(merged.find((l) => l.id === 'b')?.disabled).toBe(true)
41
+ })
42
+
43
+ it('保持首次出现顺序', () => {
44
+ const merged = applyPatches(
45
+ [{ id: 'a' }, { id: 'b' }, { id: 'c' }],
46
+ [{ id: 'b', config: 1 }],
47
+ )
48
+ expect(merged.map((l) => l.id)).toEqual(['a', 'b', 'c'])
49
+ })
50
+
51
+ it('接受 PatchFile 形态', () => {
52
+ const merged = applyPatches(
53
+ { insert: [{ id: 'a', name: 'a' }] },
54
+ { insert: [{ id: 'a', disabled: true }] },
55
+ )
56
+ expect(merged[0].disabled).toBe(true)
57
+ })
58
+ })
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // applyPatches —— 逐 key 语义用例 1-7(规格 §5 一致性用例 2,核心重写点)
62
+ // ---------------------------------------------------------------------------
63
+
64
+ describe('applyPatches(逐 key 覆盖语义)', () => {
65
+ it('用例 1:未提及 key 保留前层值', () => {
66
+ const base = [{ id: 'x', name: 'pkg', config: { a: 1 } }]
67
+ const user = [{ id: 'x', disabled: true }]
68
+ const merged = applyPatches(base, user)
69
+ expect(merged).toHaveLength(1)
70
+ // name/config 未被用户层提及 → 保留 base 值
71
+ expect(merged[0].name).toBe('pkg')
72
+ expect(merged[0].config).toEqual({ a: 1 })
73
+ // disabled 被提及 → 覆盖
74
+ expect(merged[0].disabled).toBe(true)
75
+ })
76
+
77
+ it('用例 2:同 key 后层胜', () => {
78
+ const base = [{ id: 'x', disabled: false }]
79
+ const user = [{ id: 'x', disabled: true }]
80
+ const merged = applyPatches(base, user)
81
+ expect(merged[0].disabled).toBe(true)
82
+ })
83
+
84
+ it('用例 3:id 定向,首次出现位置保留', () => {
85
+ const merged = applyPatches(
86
+ [{ id: 'a', name: 'a' }, { id: 'b', name: 'b' }, { id: 'c', name: 'c' }],
87
+ [{ id: 'c', disabled: true }, { id: 'a', disabled: true }],
88
+ )
89
+ // 输出顺序按首次出现(a/b/c),不随后层覆盖顺序改变
90
+ expect(merged.map((l) => l.id)).toEqual(['a', 'b', 'c'])
91
+ expect(merged.find((l) => l.id === 'a')?.disabled).toBe(true)
92
+ expect(merged.find((l) => l.id === 'c')?.disabled).toBe(true)
93
+ expect(merged.find((l) => l.id === 'b')?.name).toBe('b')
94
+ })
95
+
96
+ it('用例 4:非 string id / 无 id 行跳过,不崩', () => {
97
+ const merged = applyPatches([
98
+ { id: 'a', name: 'a' },
99
+ { id: 123 } as unknown as PatchLine,
100
+ {} as unknown as PatchLine,
101
+ { id: 'b', name: 'b' },
102
+ ])
103
+ expect(merged.map((l) => l.id)).toEqual(['a', 'b'])
104
+ })
105
+
106
+ it('用例 5:整 config 替换仅指 config 单 key(不深合并)', () => {
107
+ const base = [{ id: 'x', config: { a: 1, b: 2 } }]
108
+ const user = [{ id: 'x', config: { a: 9 } }]
109
+ const merged = applyPatches(base, user)
110
+ // 整个 config 值被后层的 config 替换,**不是** { a:9, b:2 } 深合并
111
+ expect(merged[0].config).toEqual({ a: 9 })
112
+ })
113
+
114
+ it('用例 6:多层链式逐 key,各自提及不同 key 全部保留', () => {
115
+ const merged = applyPatches(
116
+ [{ id: 'x', name: 'pkg', config: { a: 1 } }],
117
+ [{ id: 'x', disabled: false }],
118
+ [{ id: 'x', name: 'pkg-v2', disabled: true }],
119
+ )
120
+ expect(merged).toHaveLength(1)
121
+ // 三层各提及 key 逐 key 累积:name(层3胜) / config(层1) / disabled(层3胜)
122
+ expect(merged[0].name).toBe('pkg-v2')
123
+ expect(merged[0].config).toEqual({ a: 1 })
124
+ expect(merged[0].disabled).toBe(true)
125
+ })
126
+
127
+ it('用例 7:合并后的行喂 evalDisabled,boolean/string/undefined 三态各一断言', () => {
128
+ const ctx = { get: (k: string) => (k === 'profileContext' ? 'web' : undefined) }
129
+ const merged = applyPatches(
130
+ [
131
+ { id: 'bool', disabled: true },
132
+ { id: 'str', disabled: "!ctx.get('missing')" },
133
+ { id: 'undef', name: 'pkg' },
134
+ ],
135
+ [
136
+ { id: 'bool', name: 'pkg' },
137
+ { id: 'str', name: 'pkg' },
138
+ { id: 'undef', disabled: "!ctx.get('profileContext')" },
139
+ ],
140
+ )
141
+ // boolean 直传:true=停用
142
+ expect(evalDisabled(merged[0], ctx)).toBe(true)
143
+ // string 表达式:!undefined = true → 停用
144
+ expect(evalDisabled(merged[1], ctx)).toBe(true)
145
+ // 合并后 disabled 为 string(未提及 disabled 的 base 行保留到合并结果,
146
+ // 但这里 undef 行 base 无 disabled、用户层给了表达式):!truthy = false → 启用
147
+ expect(merged[2].disabled).toBe("!ctx.get('profileContext')")
148
+ expect(evalDisabled(merged[2], ctx)).toBe(false)
149
+ })
150
+ })
151
+
152
+ // ---------------------------------------------------------------------------
153
+ // evalPatchExpression / evalDisabled —— 迁移用例(!!js 白名单求值器)
154
+ // ---------------------------------------------------------------------------
155
+
156
+ describe('evalPatchExpression / evalDisabled', () => {
157
+ const ctx = { get: (k: string) => (k === 'profileContext' ? 'web' : undefined) }
158
+
159
+ it('求值 ctx.get 与比较运算', () => {
160
+ expect(evalPatchExpression("ctx.get('profileContext') === 'web'", ctx)).toBe(true)
161
+ expect(evalPatchExpression("!ctx.get('missing')", ctx)).toBe(true)
162
+ expect(evalPatchExpression("ctx.get('missing') || 'fallback'", ctx)).toBe('fallback')
163
+ })
164
+
165
+ it('求值字面量与逻辑组合', () => {
166
+ expect(evalPatchExpression('true', ctx)).toBe(true)
167
+ expect(evalPatchExpression('!false', ctx)).toBe(true)
168
+ expect(evalPatchExpression('1 + 2 * 3', ctx)).toBe(7)
169
+ expect(evalPatchExpression("'a' === 'a' && 1 < 2", ctx)).toBe(true)
170
+ })
171
+
172
+ it('未知裸标识符容错为 undefined', () => {
173
+ expect(evalPatchExpression('someUnknownVar', ctx)).toBeUndefined()
174
+ })
175
+
176
+ it('拒绝非法结构(括号不匹配)', () => {
177
+ expect(() => evalPatchExpression('(1 + 2', ctx)).toThrow(SyntaxError)
178
+ })
179
+
180
+ it('evalDisabled:boolean/undefined/表达式三态(disabled:true=停用,对齐 DSH)', () => {
181
+ expect(evalDisabled({ id: 'x' }, ctx)).toBe(false) // undefined=启用
182
+ expect(evalDisabled({ id: 'x', disabled: true }, ctx)).toBe(true) // true=停用
183
+ expect(evalDisabled({ id: 'x', disabled: false }, ctx)).toBe(false) // false=启用
184
+ expect(
185
+ evalDisabled({ id: 'x', disabled: "!ctx.get('missing')" }, ctx),
186
+ ).toBe(true) // 表达式 truthy=停用
187
+ expect(
188
+ evalDisabled({ id: 'x', disabled: "!ctx.get('profileContext')" }, ctx),
189
+ ).toBe(false) // profileContext 存在 → !truthy = false → 启用
190
+ })
191
+
192
+ it('不使用 eval/new Function(无原型链逃逸)', () => {
193
+ // 尝试访问全局构造器:裸标识符被容错为 undefined,无法逃逸
194
+ expect(evalPatchExpression('globalThis', ctx)).toBeUndefined()
195
+ expect(evalPatchExpression('process', ctx)).toBeUndefined()
196
+ expect(evalPatchExpression('constructor', ctx)).toBeUndefined()
197
+ })
198
+ })
199
+
200
+ // ---------------------------------------------------------------------------
201
+ // parsePatchYaml —— 迁移用例(真实 DSH patch 结构)
202
+ // ---------------------------------------------------------------------------
203
+
204
+ describe('parsePatchYaml', () => {
205
+ it('解析 - insert: 包裹 + id/name/disabled(bool|!!js)/config + 注释', () => {
206
+ const text = `
207
+ # dsh-base bundle patch(注释行)
208
+ - insert:
209
+ - id: tool-bash
210
+ name: '@deepseek-ai/dsh-tool-bash'
211
+
212
+ - id: plugin-manager
213
+ name: '@deepseek-ai/dsh-plugin-manager'
214
+ disabled: !!js "!ctx.get('profileContext')"
215
+
216
+ - id: hmr
217
+ name: '@deepseek-ai/dsh-hmr'
218
+ disabled: true
219
+ config:
220
+ root: []
221
+ `
222
+ const lines = parsePatchYaml(text)
223
+ expect(lines.map((l) => l.id)).toEqual(['tool-bash', 'plugin-manager', 'hmr'])
224
+ expect(lines[0].name).toBe('@deepseek-ai/dsh-tool-bash')
225
+ // !!js tag 解析为字符串表达式(value),保留供白名单求值器,不经 eval
226
+ expect(lines[1].disabled).toBe("!ctx.get('profileContext')")
227
+ expect(lines[2].disabled).toBe(true)
228
+ expect(lines[2].config).toEqual({ root: [] })
229
+ })
230
+
231
+ it('接受裸 row(无 - insert: 包裹)', () => {
232
+ const lines = parsePatchYaml('- id: a\n name: pkg\n')
233
+ expect(lines).toEqual([{ id: 'a', name: 'pkg' }])
234
+ })
235
+
236
+ it('缺 id 的 row 跳过', () => {
237
+ const lines = parsePatchYaml('- insert:\n - name: no-id\n - id: ok\n')
238
+ expect(lines.map((l) => l.id)).toEqual(['ok'])
239
+ })
240
+
241
+ it('顶层非 list 抛 SyntaxError', () => {
242
+ expect(() => parsePatchYaml('insert: []\n')).toThrow(SyntaxError)
243
+ })
244
+
245
+ it('extractInsert 容忍 PatchFile 与裸数组', () => {
246
+ const file: PatchFile = { insert: [{ id: 'a' }] }
247
+ expect(extractInsert(file)).toEqual([{ id: 'a' }])
248
+ expect(extractInsert([{ id: 'b' }])).toEqual([{ id: 'b' }])
249
+ })
250
+ })
@@ -0,0 +1,343 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // `!!js` 白名单表达式求值器(安全子集)——自 kernel/patch.ts 抽出。
6
+ //
7
+ // **安全靠它**:禁 eval / new Function,仅支持白名单结构,无注入面。
8
+ // ExprParser / ESCAPES 逐字搬迁,未改白名单求值逻辑。
9
+
10
+ import type { PatchLine } from './types'
11
+
12
+ /**
13
+ * 求值某行的 disabled 决策。
14
+ *
15
+ * - boolean:直接作为结论(true = 停用,false = 启用)
16
+ * - string:作为 `!!js` 表达式求值(返回 truthy 即停用)
17
+ * - undefined:启用(返回 false)
18
+ *
19
+ * @param line patch 行
20
+ * @param ctx 求值上下文,暴露 `get(key)`(白名单读取 service/config)
21
+ */
22
+ export function evalDisabled(
23
+ line: PatchLine,
24
+ ctx: { get(key: string): unknown },
25
+ ): boolean {
26
+ const d = line.disabled
27
+ if (d === undefined) return false
28
+ if (typeof d === 'boolean') return d
29
+ // string:!!js 表达式,truthy 即 disabled
30
+ return Boolean(evalPatchExpression(d, ctx))
31
+ }
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // 白名单表达式求值器(!!js 安全子集)
35
+ // ---------------------------------------------------------------------------
36
+
37
+ /**
38
+ * 求值 `!!js` 表达式的安全子集。
39
+ *
40
+ * 支持(覆盖 DSH patch 实际用法,见 base/cordis.patch.yml):
41
+ * - 字面量:字符串('/")、数字、true/false/null、undefined
42
+ * - ctx.get('key') / ctx.get("key")
43
+ * - 一元:! - +
44
+ * - 二元:|| && === !== == != < > <= >= + - * / %
45
+ * - 括号、成员取值 ctx.a.b(只读)
46
+ *
47
+ * **禁止**:函数调用(除 ctx.get)、赋值、new、模板字符串、属性写、
48
+ * 任意标识符(未知标识符解析为 undefined,不抛错——与 DSH loader 容错一致)。
49
+ * 不使用 eval / new Function,无注入面。
50
+ *
51
+ * @throws SyntaxError 仅当表达式结构非法(括号不匹配、运算符缺操作数)。
52
+ */
53
+ export function evalPatchExpression(
54
+ expr: string,
55
+ ctx: { get(key: string): unknown },
56
+ ): unknown {
57
+ const parser = new ExprParser(expr, ctx)
58
+ const result = parser.parseExpression()
59
+ parser.skipWs()
60
+ if (parser.pos < parser.src.length) {
61
+ throw new SyntaxError(`!!js 表达式存在多余内容: ${expr}`)
62
+ }
63
+ return result
64
+ }
65
+
66
+ /** 表达式求值上下文。 */
67
+ interface EvalContext {
68
+ get(key: string): unknown
69
+ }
70
+
71
+ class ExprParser {
72
+ pos = 0
73
+
74
+ constructor(
75
+ readonly src: string,
76
+ private readonly ctx: EvalContext,
77
+ ) {}
78
+
79
+ skipWs(): void {
80
+ while (this.pos < this.src.length && /\s/.test(this.src[this.pos])) this.pos++
81
+ }
82
+
83
+ peek(): string {
84
+ return this.src[this.pos] ?? ''
85
+ }
86
+
87
+ /** expression := or */
88
+ parseExpression(): unknown {
89
+ return this.parseOr()
90
+ }
91
+
92
+ private parseOr(): unknown {
93
+ let left = this.parseAnd()
94
+ for (;;) {
95
+ this.skipWs()
96
+ if (this.src.startsWith('||', this.pos)) {
97
+ this.pos += 2
98
+ const right = this.parseAnd()
99
+ left = left || right
100
+ } else break
101
+ }
102
+ return left
103
+ }
104
+
105
+ private parseAnd(): unknown {
106
+ let left = this.parseEquality()
107
+ for (;;) {
108
+ this.skipWs()
109
+ if (this.src.startsWith('&&', this.pos)) {
110
+ this.pos += 2
111
+ const right = this.parseEquality()
112
+ left = left && right
113
+ } else break
114
+ }
115
+ return left
116
+ }
117
+
118
+ private parseEquality(): unknown {
119
+ let left = this.parseComparison()
120
+ for (;;) {
121
+ this.skipWs()
122
+ const op = this.matchOp(['===', '!==', '==', '!='])
123
+ if (!op) break
124
+ const right = this.parseComparison()
125
+ left =
126
+ op === '===' ? left === right :
127
+ op === '!==' ? left !== right :
128
+ op === '==' ? left == right : // eslint-disable-line eqeqeq
129
+ left != right // eslint-disable-line eqeqeq
130
+ }
131
+ return left
132
+ }
133
+
134
+ private parseComparison(): unknown {
135
+ let left = this.parseAdditive()
136
+ for (;;) {
137
+ this.skipWs()
138
+ const op = this.matchOp(['<=', '>=', '<', '>'])
139
+ if (!op) break
140
+ const right = this.parseAdditive()
141
+ left =
142
+ op === '<' ? (left as number) < (right as number) :
143
+ op === '>' ? (left as number) > (right as number) :
144
+ op === '<=' ? (left as number) <= (right as number) :
145
+ (left as number) >= (right as number)
146
+ }
147
+ return left
148
+ }
149
+
150
+ private parseAdditive(): unknown {
151
+ let left = this.parseMultiplicative()
152
+ for (;;) {
153
+ this.skipWs()
154
+ const op = this.matchOp(['+', '-'])
155
+ if (!op) break
156
+ const right = this.parseMultiplicative()
157
+ left = op === '+' ? (left as number) + (right as number) : (left as number) - (right as number)
158
+ }
159
+ return left
160
+ }
161
+
162
+ private parseMultiplicative(): unknown {
163
+ let left = this.parseUnary()
164
+ for (;;) {
165
+ this.skipWs()
166
+ const op = this.matchOp(['*', '/', '%'])
167
+ if (!op) break
168
+ const right = this.parseUnary()
169
+ left =
170
+ op === '*' ? (left as number) * (right as number) :
171
+ op === '/' ? (left as number) / (right as number) :
172
+ (left as number) % (right as number)
173
+ }
174
+ return left
175
+ }
176
+
177
+ private parseUnary(): unknown {
178
+ this.skipWs()
179
+ const ch = this.peek()
180
+ if (ch === '!') {
181
+ this.pos++
182
+ return !this.parseUnary()
183
+ }
184
+ if (ch === '-') {
185
+ this.pos++
186
+ return -(this.parseUnary() as number)
187
+ }
188
+ if (ch === '+') {
189
+ this.pos++
190
+ return +(this.parseUnary() as number)
191
+ }
192
+ return this.parsePrimary()
193
+ }
194
+
195
+ private parsePrimary(): unknown {
196
+ this.skipWs()
197
+ const ch = this.peek()
198
+
199
+ if (ch === '(') {
200
+ this.pos++
201
+ const val = this.parseExpression()
202
+ this.skipWs()
203
+ if (this.peek() !== ')') throw new SyntaxError('括号不匹配')
204
+ this.pos++
205
+ return this.parseMemberAccess(val)
206
+ }
207
+
208
+ // 字符串
209
+ if (ch === "'" || ch === '"') {
210
+ return this.parseString(ch)
211
+ }
212
+
213
+ // 数字
214
+ if (/[0-9]/.test(ch)) {
215
+ return this.parseNumber()
216
+ }
217
+
218
+ // 标识符 / 关键字 / ctx
219
+ if (/[A-Za-z_$]/.test(ch)) {
220
+ return this.parseIdentifier()
221
+ }
222
+
223
+ throw new SyntaxError(`!!js 表达式非法字符: '${ch}' (pos ${this.pos})`)
224
+ }
225
+
226
+ private parseString(quote: string): string {
227
+ this.pos++ // 跳过开引号
228
+ let out = ''
229
+ while (this.pos < this.src.length && this.src[this.pos] !== quote) {
230
+ const c = this.src[this.pos]
231
+ if (c === '\\') {
232
+ this.pos++
233
+ const esc = this.src[this.pos]
234
+ out += ESCAPES[esc] ?? esc
235
+ } else {
236
+ out += c
237
+ }
238
+ this.pos++
239
+ }
240
+ if (this.pos >= this.src.length) throw new SyntaxError('字符串未闭合')
241
+ this.pos++ // 跳过闭引号
242
+ return out
243
+ }
244
+
245
+ private parseNumber(): number {
246
+ let start = this.pos
247
+ while (this.pos < this.src.length && /[0-9.]/.test(this.src[this.pos])) this.pos++
248
+ return Number(this.src.slice(start, this.pos))
249
+ }
250
+
251
+ private parseIdentifier(): unknown {
252
+ let start = this.pos
253
+ while (this.pos < this.src.length && /[A-Za-z0-9_$]/.test(this.src[this.pos])) this.pos++
254
+ const name = this.src.slice(start, this.pos)
255
+
256
+ // 关键字
257
+ if (name === 'true') return true
258
+ if (name === 'false') return false
259
+ if (name === 'null') return null
260
+ if (name === 'undefined') return undefined
261
+
262
+ // ctx.get('key') / ctx.<member>
263
+ if (name === 'ctx') {
264
+ this.skipWs()
265
+ if (this.peek() === '.') {
266
+ this.pos++
267
+ start = this.pos
268
+ while (this.pos < this.src.length && /[A-Za-z0-9_$]/.test(this.src[this.pos])) this.pos++
269
+ const member = this.src.slice(start, this.pos)
270
+ if (member === 'get') {
271
+ return this.parseCtxGet()
272
+ }
273
+ // ctx.<其它成员>:本期只读 ctx.get,其余返回 undefined(容错)
274
+ return undefined
275
+ }
276
+ return undefined
277
+ }
278
+
279
+ // 未知裸标识符:容错为 undefined(对齐 DSH loader)
280
+ return undefined
281
+ }
282
+
283
+ /** 解析 ctx.get('key') 或 ctx.get("key")。 */
284
+ private parseCtxGet(): unknown {
285
+ this.skipWs()
286
+ if (this.peek() !== '(') throw new SyntaxError('ctx.get 缺少 (')
287
+ this.pos++
288
+ this.skipWs()
289
+ const quote = this.peek()
290
+ if (quote !== "'" && quote !== '"') throw new SyntaxError('ctx.get 参数须为字符串字面量')
291
+ const key = this.parseString(quote)
292
+ this.skipWs()
293
+ if (this.peek() !== ')') throw new SyntaxError('ctx.get 括号不匹配')
294
+ this.pos++
295
+ return this.ctx.get(key)
296
+ }
297
+
298
+ /** 主值后的成员链取值(只读):a.b.c。 */
299
+ private parseMemberAccess(base: unknown): unknown {
300
+ let val = base
301
+ for (;;) {
302
+ this.skipWs()
303
+ if (this.peek() === '.') {
304
+ // 确保不是 ctx.get(已处理)——这里处理普通对象的只读成员
305
+ const next = this.src[this.pos + 1]
306
+ if (/[A-Za-z0-9_$]/.test(next ?? '')) {
307
+ this.pos++ // 跳过 .
308
+ let start = this.pos
309
+ while (this.pos < this.src.length && /[A-Za-z0-9_$]/.test(this.src[this.pos])) this.pos++
310
+ const member = this.src.slice(start, this.pos)
311
+ val =
312
+ val && typeof val === 'object'
313
+ ? (val as Record<string, unknown>)[member]
314
+ : undefined
315
+ continue
316
+ }
317
+ }
318
+ break
319
+ }
320
+ return val
321
+ }
322
+
323
+ private matchOp(ops: readonly string[]): string | null {
324
+ this.skipWs()
325
+ for (const op of ops) {
326
+ if (this.src.startsWith(op, this.pos)) {
327
+ this.pos += op.length
328
+ return op
329
+ }
330
+ }
331
+ return null
332
+ }
333
+ }
334
+
335
+ const ESCAPES: Record<string, string> = {
336
+ n: '\n',
337
+ t: '\t',
338
+ r: '\r',
339
+ '\\': '\\',
340
+ "'": "'",
341
+ '"': '"',
342
+ 0: '\0',
343
+ }
@@ -0,0 +1,45 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // 多层 patch 合并(DSH vendor patch 语义,规格 §4.1.1 / §5)。
6
+ //
7
+ // 与旧 kernel/patch.ts 的「整行替换」不同,本实现是 **id 定向 + 逐 key 覆盖**:
8
+ // - **id 定向**:按 `line.id` 匹配,首次出现位置保留(order 数组)。
9
+ // - **逐 key 覆盖**:后层同 id 行只覆盖它**显式提及的 key**;未提及 key 保留前层值。
10
+ // - **同 key 后层胜**:`{ ...existing, ...line }` 的展开序保证。
11
+ // - **「整 config 替换」仅指 config 这一个 key** 被后层提及且为对象时,整个 config
12
+ // 值被后层的 config 替换——**不对 config 内部做深合并**(DSH vendor 语义:patch 行的
13
+ // config 是原子的)。
14
+ // - 非 string id 的行跳过(保持原行为)。
15
+
16
+ import type { PatchFile, PatchLine } from './types'
17
+ import { extractInsert } from './types'
18
+
19
+ /**
20
+ * 多层 patch 合并:按 id 定向,逐 key 覆盖,未提及 key 保留,同 key 后层胜。
21
+ *
22
+ * @param layers 按应用顺序排列的层(base → 用户 → 插件追加)
23
+ * @returns 合并后的 patch 行(保持首次出现的相对顺序,覆盖只更新被提及的 key)
24
+ */
25
+ export function applyPatches(
26
+ ...layers: ReadonlyArray<PatchFile | PatchLine[]>
27
+ ): PatchLine[] {
28
+ const byId = new Map<string, PatchLine>()
29
+ const order: string[] = []
30
+ for (const layer of layers) {
31
+ for (const line of extractInsert(layer)) {
32
+ if (!line || typeof line.id !== 'string') continue
33
+ const existing = byId.get(line.id)
34
+ if (!existing) {
35
+ // 首次出现:记录位置 + 内容
36
+ order.push(line.id)
37
+ byId.set(line.id, { ...line })
38
+ } else {
39
+ // 同 id 后层:逐 key 覆盖,未提及 key 保留前层值(规格 §5 / DSH vendor 语义)
40
+ byId.set(line.id, { ...existing, ...line })
41
+ }
42
+ }
43
+ }
44
+ return order.map((id) => byId.get(id) as PatchLine)
45
+ }
@@ -0,0 +1,37 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // DSH patch 数据原语 —— 类型定义(供 yaml/merge/eval 共享,避免循环 import)。
6
+ //
7
+ // patch 是**纯数据**:每行 = { id, name?, disabled?, config?, ... },语义见
8
+ // 2026-11-06-dsh-investigation/14-plugin-system.md §3.1。本文件只放类型 +
9
+ // `extractInsert`(patch 文件/行的 insert 列表提取),零依赖。
10
+
11
+ /** 一条 patch 行(已解析)。 */
12
+ export interface PatchLine {
13
+ /** 稳定 id,定向与覆盖的唯一依据。 */
14
+ id: string
15
+ /** 包的子路径导出,如 '@deepseek-ai/dsh-tool-bash' 或其 '/tools' 子路径。 */
16
+ name?: string
17
+ /**
18
+ * 启停:false = 停用;string = `!!js` 表达式(如 `"!ctx.get('profileContext')"`);
19
+ * undefined/true = 启用。
20
+ */
21
+ disabled?: boolean | string
22
+ /** 插件配置(整块替换,不合并)。 */
23
+ config?: unknown
24
+ /** 保留原始 YAML 序号,便于诊断。 */
25
+ __order?: number
26
+ }
27
+
28
+ /** patch 文件形态:`- insert: [...]` 的展开。 */
29
+ export interface PatchFile {
30
+ insert: PatchLine[]
31
+ }
32
+
33
+ /** 提取 patch 文件/行的 insert 列表(容忍已是数组的输入)。 */
34
+ export function extractInsert(patch: PatchFile | PatchLine[]): PatchLine[] {
35
+ if (Array.isArray(patch)) return patch
36
+ return patch.insert ?? []
37
+ }