dsh-cookie-cleaner 0.6.4 → 0.7.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.
package/src/patch-read.js CHANGED
@@ -1,199 +1,251 @@
1
- /**
2
- * dsh-cookie-cleaner — profile patch 的**只读**解析器。
3
- *
4
- * 为什么手写而不引 YAML 库:插件要能在客户端关闭、宿主不存在的时候裸跑(npm bin),
5
- * 引第三方 YAML 会把「多一个依赖就多一次装机风险」搬进一个清理工具。
6
- * 代价被诚实地框住:这里只认 profile patch 层的**实际语法子集**——
7
- * 顶层块序列 `- ` 在第 0 列;`- id:` 覆盖行 / `- insert:` 新增行;
8
- * 条目字段 `id|name|config` 缩进 2;config 键缩进 4(靠「比 config: 更深」判定);
9
- * 值形态只认 数字 / 布尔 / `'quoted'` / `[a, b]` / `[]` / `!!js 表达式`;行尾 ` #` 注释可剥。
10
- * 遇到子集外的构造(多文档、锚点、行内 flow 映射、游离缩进)一律 `ok:false` + 原因,
11
- * 由内核报 P11/skipped——**猜错的判定比不判定更坏**。
12
- *
13
- * 本模块只做数据,不判档、不写盘。
14
- */
15
- import fs from 'node:fs'
16
-
17
- /** 行的字段/值识别(行首 `- ` 与深度都直接在本层处理,不另存正则)。 */
18
- const KEY_VALUE = /^(\w+):\s*(.*)$/
19
-
20
- /** 解析一个 YAML 标量(够用子集)。`!!js` 前缀转成内核认识的 {__jsExpr}。 */
21
- function parseScalar(raw) {
22
- const text = String(raw ?? '').trim()
23
- if (text === '' || text === '~' || text === 'null') return undefined
24
- if (text.startsWith('!!js ')) return { __jsExpr: text.slice(5).trim() }
25
- if (text === '[]') return []
26
- if (text.startsWith('[') && text.endsWith(']')) {
27
- const inner = text.slice(1, -1).trim()
28
- if (inner === '') return []
29
- return inner.split(',').map((part) => stripQuotes(part.trim()))
30
- }
31
- if (/^[-+]?\d+$/.test(text)) return Number(text)
32
- if (/^[-+]?\d*\.\d+$/.test(text)) return Number(text)
33
- if (text === 'true' || text === 'false') return text === 'true'
34
- return stripQuotes(text)
35
- }
36
-
37
- function stripQuotes(text) {
38
- if (text.length >= 2 && ((text.startsWith("'") && text.endsWith("'")) || (text.startsWith('"') && text.endsWith('"')))) {
39
- return text.slice(1, -1)
40
- }
41
- return text
42
- }
43
-
44
- /** 剥行尾注释(` #` 才算,行首 `#` 是整行注释,交给调用方跳过)。 */
45
- function stripComment(line) {
46
- const idx = line.indexOf(' #')
47
- return idx === -1 ? line : line.slice(0, idx)
48
- }
49
-
50
- function indentOf(line) {
51
- return line.match(/^\s*/)[0].length
52
- }
53
-
54
- function applyField(entry, key, raw) {
55
- if (key === 'id') entry.id = String(parseScalar(raw) ?? '')
56
- else if (key === 'name') entry.name = parseScalar(raw)
57
- else if (key === 'config') entry.config = entry.config ?? {}
58
- else entry[key] = parseScalar(raw)
59
- }
60
-
61
- /**
62
- * 解析 patch 文本。
63
- *
64
- * 只读**本层需要看到的深度**:顶层行(indent 0)与它的 `id|name|config`(indent 2)、
65
- * config 键(indent 4);insert 块的新增条目(indent 4 及其字段 indent 6)。
66
- * **更深的嵌套(如 `providers:` 里的模型列表)直接跳过而不是判错**——真实 profile
67
- * 大量存在这种结构,把它们当语法错误会误报“整层失效”(真机踩到)。
68
- * @param {string} text
69
- * @returns {{ok: boolean, reason?: string, rows: Array<object>, hadFlowRoot: boolean, skippedDeep: number}}
70
- */
71
- export function parsePatchText(text) {
72
- const rows = []
73
- let current = null // 当前顶层行
74
- let entry = null // 当前正在填字段的条目(顶层行本身,或 insert 的子条目)
75
- let fieldsIndent = 2 // 当前条目字段的缩进(顶层行 2;insert 子条目 6)
76
- let inConfig = false
77
- let configIndent = -1
78
- let hadFlowRoot = false
79
- let blockAfterFlowRoot = false
80
- let skippedDeep = 0
81
- const fail = (reason) => ({ ok: false, reason, rows, hadFlowRoot, skippedDeep })
82
-
83
- for (const rawLine of String(text ?? '').split(/\r?\n/)) {
84
- const line = stripComment(rawLine)
85
- if (line.trim() === '' || /^\s*#/.test(line)) continue
86
- if (/^\[\]\s*$/.test(line)) { hadFlowRoot = true; continue }
87
- if (/^---/.test(line) || /^[^#]*&\w+/.test(line)) return fail('unsupported yaml construct')
88
-
89
- const indent = indentOf(line)
90
- const item = /^\s*-\s+(.*)$/.exec(line)
91
-
92
- if (item !== null && indent === 0) {
93
- if (hadFlowRoot) blockAfterFlowRoot = true
94
- inConfig = false
95
- configIndent = -1
96
- fieldsIndent = 2
97
- const content = item[1].trim()
98
- current = { insert: /^insert:\s*$/.test(content), bareId: !/^id:/.test(content) }
99
- rows.push(current)
100
- entry = current
101
- if (current.insert) continue
102
- const kv = content.match(KEY_VALUE)
103
- if (kv === null) return fail(`unparsable row header: ${content.slice(0, 40)}`)
104
- if (kv[1] === 'config') {
105
- if (/^\{.*\}$/.test(kv[2].trim())) return fail('inline flow map')
106
- configIndent = fieldsIndent
107
- inConfig = true
108
- applyField(entry, 'config', kv[2])
109
- }
110
- else applyField(entry, kv[1], kv[2])
111
- continue
112
- }
113
-
114
- if (item !== null && indent > 0) {
115
- // insert 块的新增条目(indent 4);再深就是 config 里的嵌套列表 → 跳过不判
116
- if (current !== null && current.insert === true && indent === 4) {
117
- inConfig = false
118
- configIndent = -1
119
- fieldsIndent = indent + 2
120
- entry = { insert: false, bareId: false }
121
- current.entries = current.entries ?? []
122
- current.entries.push(entry)
123
- const kv = item[1].trim().match(KEY_VALUE)
124
- if (kv !== null) applyField(entry, kv[1], kv[2])
125
- continue
126
- }
127
- skippedDeep += 1
128
- continue
129
- }
130
-
131
- const kv = line.trim().match(KEY_VALUE)
132
- if (kv === null) { skippedDeep += 1; continue }
133
- if (entry === null) return fail('unexpected top-level indentation')
134
-
135
- // config 的键:深度必须恰好比 `config:` 本身多 2;更深的值是嵌套结构,不属于本次判定
136
- if (inConfig && indent === configIndent + 2) {
137
- if (/^\{.*\}$/.test(kv[2].trim())) return fail('inline flow map')
138
- entry.config = entry.config ?? {}
139
- entry.config[kv[1]] = parseScalar(kv[2])
140
- continue
141
- }
142
- if (inConfig && indent > configIndent + 2) { skippedDeep += 1; continue }
143
- inConfig = false
144
- if (indent !== fieldsIndent) { skippedDeep += 1; continue }
145
- if (kv[1] === 'config') {
146
- if (/^\{.*\}$/.test(kv[2].trim())) return fail('inline flow map')
147
- configIndent = indent
148
- inConfig = kv[2].trim() === ''
149
- applyField(entry, 'config', kv[2])
150
- continue
151
- }
152
- applyField(entry, kv[1], kv[2])
153
- }
154
-
155
- if (hadFlowRoot && (blockAfterFlowRoot || rows.length > 0)) {
156
- // P11 的真实成因:模板根 `[]` 是 flow 序列,其后再接分块行会让**整层**失效
157
- return fail('flow root `[]` followed by block rows')
158
- }
159
- return { ok: true, rows, hadFlowRoot, skippedDeep }
160
- }
161
-
162
- /** insert 块新增的条目 id(覆盖行的判定用不到,留给报告「本层新增了哪些行」)。 */
163
- export function insertedIds(rows) {
164
- const out = []
165
- for (const row of rows ?? []) {
166
- if (row.insert !== true) continue
167
- for (const item of row.entries ?? []) if (item.id) out.push(item.id)
168
- }
169
- return out
170
- }
171
-
172
- /**
173
- * 读文件并解析。不存在 = `exists:false`(不算失败,交 P1 判缺);解析不了 = `ok:false`。
174
- * @param {string} file
175
- * @returns {{path:string, exists:boolean, text:string, parsed:ReturnType<typeof parsePatchText>}}
176
- */
177
- export function readPatchFile(file) {
178
- try {
179
- const text = fs.readFileSync(file, 'utf8')
180
- return { path: file, exists: true, text, parsed: parsePatchText(text) }
181
- } catch (e) {
182
- const code = e && e.code
183
- if (code === 'ENOENT') return { path: file, exists: false, text: '', parsed: { ok: true, rows: [], hadFlowRoot: false } }
184
- return { path: file, exists: false, text: '', parsed: { ok: false, reason: String(code || (e && e.message)), rows: [], hadFlowRoot: false } }
185
- }
186
- }
187
-
188
- /** 取某个 id 的覆盖行(后写的赢——与 applyEntryPatches 的顺序语义一致)。 */
189
- export function findOverrideRow(parsed, id) {
190
- if (!parsed || !Array.isArray(parsed.rows)) return undefined
191
- const hits = parsed.rows.filter((row) => row.insert === false && row.id === id)
192
- return hits.length === 0 ? undefined : hits[hits.length - 1]
193
- }
194
-
195
- /** 该 id 在本层是否被提到(覆盖行或 insert 的新条目)。 */
196
- export function mentionsId(parsed, id) {
197
- if (!parsed || !Array.isArray(parsed.rows)) return false
198
- return parsed.rows.some((row) => (row.insert === false && row.id === id) || (row.insert === true && (row.entries ?? []).some((item) => item.id === id)))
199
- }
1
+ /**
2
+ * dsh-cookie-cleaner — profile patch 的**只读**解析器。
3
+ *
4
+ * 为什么手写而不引 YAML 库:插件要能在客户端关闭、宿主不存在的时候裸跑(npm bin),
5
+ * 引第三方 YAML 会把「多一个依赖就多一次装机风险」搬进一个清理工具。
6
+ * 代价被诚实地框住:这里只认 profile patch 层的**实际语法子集**——
7
+ * 顶层块序列 `- ` 在第 0 列;`- id:` 覆盖行 / `- insert:` 新增行;
8
+ * 条目字段 `id|name|config` 缩进 2;config 键缩进 4(靠「比 config: 更深」判定);
9
+ * 值形态只认 数字 / 布尔 / `'quoted'` / `[a, b]` / `[]` / `{a: 1}` / `{}` / `!!js 表达式`;
10
+ * 跨行 flow(`{` 或 `[` 未在本行闭合)整段跳过;行尾 ` #` 注释可剥。
11
+ * 遇到子集外的**结构**(多文档 `---`、锚点 `&x`、模板根 `[]` 之后又接分块行)才 `ok:false` + 原因,
12
+ * 由内核报 P11;**值的形态不参与这个判定**——`{}` 这类合法 flow 映射曾经被当成整层非法,
13
+ * 导致一处 `providers: {}` 让全层 112 行一起失效(issue #1,2026-11-17)。
14
+ * 取舍仍是同一条:**猜错的判定比不判定更坏**,所以值解析不了时降级为「值未知」,不升级为整层失败。
15
+ *
16
+ * 本模块只做数据,不判档、不写盘。
17
+ */
18
+ import fs from 'node:fs'
19
+
20
+ /** 行的字段/值识别(行首 `- ` 与深度都直接在本层处理,不另存正则)。 */
21
+ const KEY_VALUE = /^(\w+):\s*(.*)$/
22
+
23
+ /** 解析一个 YAML 标量(够用子集)。`!!js` 前缀转成内核认识的 {__jsExpr}。 */
24
+ function parseScalar(raw) {
25
+ const text = String(raw ?? '').trim()
26
+ if (text === '' || text === '~' || text === 'null') return undefined
27
+ if (text.startsWith('!!js ')) return { __jsExpr: text.slice(5).trim() }
28
+ if (text === '[]') return []
29
+ // 跨行 flow(本行只写了开括号):值未知,但**不是语法错误**——不升级为整层失败。
30
+ if (text.startsWith('[')) {
31
+ if (!text.endsWith(']')) return undefined
32
+ const inner = text.slice(1, -1).trim()
33
+ if (inner === '') return []
34
+ return inner.split(',').map((part) => stripQuotes(part.trim()))
35
+ }
36
+ if (text.startsWith('{')) {
37
+ if (!text.endsWith('}')) return undefined
38
+ return parseFlowMap(text)
39
+ }
40
+ if (/^[-+]?\d+$/.test(text)) return Number(text)
41
+ if (/^[-+]?\d*\.\d+$/.test(text)) return Number(text)
42
+ if (text === 'true' || text === 'false') return text === 'true'
43
+ return stripQuotes(text)
44
+ }
45
+
46
+ /**
47
+ * 解析行内 flow 映射(`{}` / `{a: 1, b: "x"}`)。
48
+ *
49
+ * 只做**值层面**的尽力而为:嵌套 flow、无法识别的键、跨行截断一律返回 `undefined`
50
+ * (= 值未知),由调用方当作「这个值读不出来」——**绝不因此把整层判成非法**。
51
+ * 这条边界就是 issue #1 的教训:`providers: {}` 是完全合法的 YAML,
52
+ * 曾经被判成 `inline flow map` 而让整层 112 行一起失效。
53
+ */
54
+ function parseFlowMap(text) {
55
+ const inner = text.slice(1, -1).trim()
56
+ if (inner === '') return {}
57
+ // 嵌套 flow / 键值对里有括号:本子集不展开,交回「值未知」
58
+ if (/[{}[\]]/.test(inner)) return undefined
59
+ const out = {}
60
+ for (const part of splitFlow(inner)) {
61
+ const at = part.indexOf(':')
62
+ if (at <= 0) return undefined
63
+ out[stripQuotes(part.slice(0, at).trim())] = parseScalar(part.slice(at + 1))
64
+ }
65
+ return out
66
+ }
67
+
68
+ /** 按逗号切 flow 内容,引号内的逗号不算分隔符。 */
69
+ function splitFlow(inner) {
70
+ const parts = []
71
+ let buf = ''
72
+ let quote = ''
73
+ for (const ch of inner) {
74
+ if (quote !== '') {
75
+ if (ch === quote) quote = ''
76
+ buf += ch
77
+ continue
78
+ }
79
+ if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue }
80
+ if (ch === ',') { parts.push(buf); buf = ''; continue }
81
+ buf += ch
82
+ }
83
+ if (buf.trim() !== '') parts.push(buf)
84
+ return parts.map((p) => p.trim()).filter((p) => p !== '')
85
+ }
86
+
87
+ function stripQuotes(text) {
88
+ if (text.length >= 2 && ((text.startsWith("'") && text.endsWith("'")) || (text.startsWith('"') && text.endsWith('"')))) {
89
+ return text.slice(1, -1)
90
+ }
91
+ return text
92
+ }
93
+
94
+ /** 剥行尾注释(` #` 才算,行首 `#` 是整行注释,交给调用方跳过)。 */
95
+ function stripComment(line) {
96
+ const idx = line.indexOf(' #')
97
+ return idx === -1 ? line : line.slice(0, idx)
98
+ }
99
+
100
+ function indentOf(line) {
101
+ return line.match(/^\s*/)[0].length
102
+ }
103
+
104
+ function applyField(entry, key, raw) {
105
+ if (key === 'id') entry.id = String(parseScalar(raw) ?? '')
106
+ else if (key === 'name') entry.name = parseScalar(raw)
107
+ else if (key === 'config') {
108
+ // `config: {...}` 给了 flow 映射就用它;给空/跨行则开一个空壳等后续缩进行填。
109
+ const value = parseScalar(raw)
110
+ entry.config = value !== null && typeof value === 'object' && !Array.isArray(value) ? value : (entry.config ?? {})
111
+ }
112
+ else entry[key] = parseScalar(raw)
113
+ }
114
+
115
+ /**
116
+ * 解析 patch 文本。
117
+ *
118
+ * 只读**本层需要看到的深度**:顶层行(indent 0)与它的 `id|name|config`(indent 2)、
119
+ * config 键(indent 4);insert 块的新增条目(indent 4 及其字段 indent 6)。
120
+ * **更深的嵌套(如 `providers:` 里的模型列表)直接跳过而不是判错**——真实 profile
121
+ * 大量存在这种结构,把它们当语法错误会误报“整层失效”(真机踩到)。
122
+ * @param {string} text
123
+ * @returns {{ok: boolean, reason?: string, rows: Array<object>, hadFlowRoot: boolean, skippedDeep: number}}
124
+ */
125
+ export function parsePatchText(text) {
126
+ const rows = []
127
+ let current = null // 当前顶层行
128
+ let entry = null // 当前正在填字段的条目(顶层行本身,或 insert 的子条目)
129
+ let fieldsIndent = 2 // 当前条目字段的缩进(顶层行 2;insert 子条目 6)
130
+ let inConfig = false
131
+ let configIndent = -1
132
+ let hadFlowRoot = false
133
+ let blockAfterFlowRoot = false
134
+ let skippedDeep = 0
135
+ const fail = (reason) => ({ ok: false, reason, rows, hadFlowRoot, skippedDeep })
136
+
137
+ for (const rawLine of String(text ?? '').split(/\r?\n/)) {
138
+ const line = stripComment(rawLine)
139
+ if (line.trim() === '' || /^\s*#/.test(line)) continue
140
+ if (/^\[\]\s*$/.test(line)) { hadFlowRoot = true; continue }
141
+ if (/^---/.test(line) || /^[^#]*&\w+/.test(line)) return fail('unsupported yaml construct')
142
+
143
+ const indent = indentOf(line)
144
+ const item = /^\s*-\s+(.*)$/.exec(line)
145
+
146
+ if (item !== null && indent === 0) {
147
+ if (hadFlowRoot) blockAfterFlowRoot = true
148
+ inConfig = false
149
+ configIndent = -1
150
+ fieldsIndent = 2
151
+ const content = item[1].trim()
152
+ current = { insert: /^insert:\s*$/.test(content), bareId: !/^id:/.test(content) }
153
+ rows.push(current)
154
+ entry = current
155
+ if (current.insert) continue
156
+ const kv = content.match(KEY_VALUE)
157
+ if (kv === null) return fail(`unparsable row header: ${content.slice(0, 40)}`)
158
+ if (kv[1] === 'config') {
159
+ // `- config: {...}` 的 flow 写法:整段作为 config 值解析,不再判整层非法。
160
+ configIndent = fieldsIndent
161
+ inConfig = kv[2].trim() === ''
162
+ applyField(entry, 'config', kv[2])
163
+ }
164
+ else applyField(entry, kv[1], kv[2])
165
+ continue
166
+ }
167
+
168
+ if (item !== null && indent > 0) {
169
+ // insert 块的新增条目(indent 4);再深就是 config 里的嵌套列表 → 跳过不判
170
+ if (current !== null && current.insert === true && indent === 4) {
171
+ inConfig = false
172
+ configIndent = -1
173
+ fieldsIndent = indent + 2
174
+ entry = { insert: false, bareId: false }
175
+ current.entries = current.entries ?? []
176
+ current.entries.push(entry)
177
+ const kv = item[1].trim().match(KEY_VALUE)
178
+ if (kv !== null) applyField(entry, kv[1], kv[2])
179
+ continue
180
+ }
181
+ skippedDeep += 1
182
+ continue
183
+ }
184
+
185
+ const kv = line.trim().match(KEY_VALUE)
186
+ if (kv === null) { skippedDeep += 1; continue }
187
+ if (entry === null) return fail('unexpected top-level indentation')
188
+
189
+ // config 的键:深度必须恰好比 `config:` 本身多 2;更深的值是嵌套结构,不属于本次判定
190
+ if (inConfig && indent === configIndent + 2) {
191
+ entry.config = entry.config ?? {}
192
+ entry.config[kv[1]] = parseScalar(kv[2])
193
+ continue
194
+ }
195
+ if (inConfig && indent > configIndent + 2) { skippedDeep += 1; continue }
196
+ inConfig = false
197
+ if (indent !== fieldsIndent) { skippedDeep += 1; continue }
198
+ if (kv[1] === 'config') {
199
+ configIndent = indent
200
+ inConfig = kv[2].trim() === ''
201
+ applyField(entry, 'config', kv[2])
202
+ continue
203
+ }
204
+ applyField(entry, kv[1], kv[2])
205
+ }
206
+
207
+ if (hadFlowRoot && (blockAfterFlowRoot || rows.length > 0)) {
208
+ // P11 的真实成因:模板根 `[]` 是 flow 序列,其后再接分块行会让**整层**失效
209
+ return fail('flow root `[]` followed by block rows')
210
+ }
211
+ return { ok: true, rows, hadFlowRoot, skippedDeep }
212
+ }
213
+
214
+ /** insert 块新增的条目 id(覆盖行的判定用不到,留给报告「本层新增了哪些行」)。 */
215
+ export function insertedIds(rows) {
216
+ const out = []
217
+ for (const row of rows ?? []) {
218
+ if (row.insert !== true) continue
219
+ for (const item of row.entries ?? []) if (item.id) out.push(item.id)
220
+ }
221
+ return out
222
+ }
223
+
224
+ /**
225
+ * 读文件并解析。不存在 = `exists:false`(不算失败,交 P1 判缺);解析不了 = `ok:false`。
226
+ * @param {string} file
227
+ * @returns {{path:string, exists:boolean, text:string, parsed:ReturnType<typeof parsePatchText>}}
228
+ */
229
+ export function readPatchFile(file) {
230
+ try {
231
+ const text = fs.readFileSync(file, 'utf8')
232
+ return { path: file, exists: true, text, parsed: parsePatchText(text) }
233
+ } catch (e) {
234
+ const code = e && e.code
235
+ if (code === 'ENOENT') return { path: file, exists: false, text: '', parsed: { ok: true, rows: [], hadFlowRoot: false } }
236
+ return { path: file, exists: false, text: '', parsed: { ok: false, reason: String(code || (e && e.message)), rows: [], hadFlowRoot: false } }
237
+ }
238
+ }
239
+
240
+ /** 取某个 id 的覆盖行(后写的赢——与 applyEntryPatches 的顺序语义一致)。 */
241
+ export function findOverrideRow(parsed, id) {
242
+ if (!parsed || !Array.isArray(parsed.rows)) return undefined
243
+ const hits = parsed.rows.filter((row) => row.insert === false && row.id === id)
244
+ return hits.length === 0 ? undefined : hits[hits.length - 1]
245
+ }
246
+
247
+ /** 该 id 在本层是否被提到(覆盖行或 insert 的新条目)。 */
248
+ export function mentionsId(parsed, id) {
249
+ if (!parsed || !Array.isArray(parsed.rows)) return false
250
+ return parsed.rows.some((row) => (row.insert === false && row.id === id) || (row.insert === true && (row.entries ?? []).some((item) => item.id === id)))
251
+ }