dsh-git-bugfix 0.0.0-stage → 0.1.0

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/lib/xlsx.js ADDED
@@ -0,0 +1,526 @@
1
+ /**
2
+ * Zero-dependency reader for defect spreadsheet exports (`.xlsx` and `.csv`).
3
+ *
4
+ * For `.xlsx` workbooks (Office Open XML ZIP containers holding `xl/workbook.xml`,
5
+ * worksheet XML, and shared strings), this module reads the first worksheet with
6
+ * `node:zlib` for raw deflate and small regex scanners, then maps header aliases
7
+ * onto the defect fields the fixer uses. For `.csv`, it decodes UTF-8 or GB18030.
8
+ */
9
+
10
+ import { inflateRawSync } from 'node:zlib'
11
+
12
+ /** ZIP local file header signature. */
13
+ const SIG_LOCAL = 0x04034b50
14
+ /** ZIP central directory header signature. */
15
+ const SIG_CENTRAL = 0x02014b50
16
+ /** ZIP end-of-central-directory signature. */
17
+ const SIG_EOCD = 0x06054b50
18
+ const MAX_ENTRY_BYTES = 16 * 1024 * 1024
19
+ const MAX_WORKBOOK_BYTES = 64 * 1024 * 1024
20
+ /** Built-in Excel number formats that render as dates or times. */
21
+ const BUILTIN_DATE_FORMATS = new Set([14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47])
22
+
23
+ /** Header aliases, in priority order; first exact match wins. */
24
+ const HEADER_ALIASES = {
25
+ id: ['Bug序号', '缺陷编号', '缺陷序号', 'bug序号', 'Bug编号', '问题编号', '工单号', '编号', '序号', 'id', 'bugid', 'issueid', 'key'],
26
+ title: ['缺陷概述', '缺陷标题', 'bug概述', '缺陷描述', '问题描述', '问题概述', '故障描述', '标题', '概述', '描述', '摘要', '主题', 'title', 'summary', 'subject', 'description', 'issue', 'bug'],
27
+ analysis: ['缺陷分析', '原因分析', '详细描述', '问题详情', '详情', '分析', '复现步骤', 'detail', 'analysis', 'repro'],
28
+ severity: ['严重程度', '严重级别', '优先级', '级别', 'severity', 'priority'],
29
+ state: ['缺陷状态', '缺陷当前状态', '问题状态', '状态', 'status', 'state'],
30
+ tags: ['问题标签', '标签', '分类', '模块', 'tags', 'label', 'category'],
31
+ note: ['注释信息', '备注', '处理说明', '说明', 'note', 'comment', 'remark'],
32
+ url: ['缺陷链接', '缺陷地址', '链接', '地址', 'url', 'link'],
33
+ plan: ['计划名称', '测试计划', 'plan'],
34
+ creator: ['创建人', '提出人', '报告人', '登记人', '提交人', 'creator', 'reporter', 'author'],
35
+ fixer: ['修复人', '处理人', '责任人', '指派给', 'assignee', 'fixer', 'owner'],
36
+ registeredAt: ['登记时间', '创建时间', '提交时间', '日期', '时间', 'created', 'date'],
37
+ requirement: ['关联需求名称', '关联需求', '需求', 'requirement'],
38
+ reopenCount: ['重新打开次数', '重开次数', 'reopen'],
39
+ standardStatus: ['标准版状态'],
40
+ standardOwner: ['标准版责任人'],
41
+ platform: ['测试平台', '平台', 'platform'],
42
+ version: ['版本号', '版本', 'version'],
43
+ }
44
+
45
+ /**
46
+ * Decode the XML entities that appear in cell text.
47
+ * @param {string} text - raw XML text content.
48
+ * @returns {string} decoded text.
49
+ */
50
+ function decodeXml(text) {
51
+ return text
52
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16)))
53
+ .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number.parseInt(dec, 10)))
54
+ .replace(/&lt;/g, '<')
55
+ .replace(/&gt;/g, '>')
56
+ .replace(/&quot;/g, '"')
57
+ .replace(/&apos;/g, "'")
58
+ .replace(/&amp;/g, '&')
59
+ }
60
+
61
+ /**
62
+ * Extract the visible text of one shared-string or inline-string fragment:
63
+ * strip rich-run properties and phonetic hints, then concatenate the text
64
+ * nodes so multi-run cells read as one string.
65
+ * @param {string} xml - fragment inner XML.
66
+ * @returns {string} plain text.
67
+ */
68
+ function xmlText(xml) {
69
+ const cleaned = xml
70
+ .replace(/<rPh\b[\s\S]*?<\/rPh>/g, '')
71
+ .replace(/<rPr\b[\s\S]*?<\/rPr>/g, '')
72
+ .replace(/<phoneticPr\b[^>]*\/>/g, '')
73
+ const runs = [...cleaned.matchAll(/<t\b[^>]*>([\s\S]*?)<\/t>/g)].map(match => match[1])
74
+ if (runs.length > 0) return decodeXml(runs.join(''))
75
+ return decodeXml(cleaned.replace(/<[^>]+>/g, ''))
76
+ }
77
+
78
+ /**
79
+ * Read the central directory of a ZIP container.
80
+ * @param {Buffer} buffer - the whole `.xlsx` file.
81
+ * @returns {Map<string, { method: number, compressedSize: number, localOffset: number }>}
82
+ * entry name to its central-directory facts.
83
+ */
84
+ function readZipDirectory(buffer) {
85
+ const minimum = Math.max(0, buffer.length - 0xffff - 22)
86
+ let eocd = -1
87
+ for (let offset = buffer.length - 22; offset >= minimum; offset -= 1) {
88
+ if (buffer.readUInt32LE(offset) === SIG_EOCD) {
89
+ eocd = offset
90
+ break
91
+ }
92
+ }
93
+ if (eocd < 0) throw new Error('不是有效的 xlsx(未找到 ZIP 目录结尾)')
94
+ const entries = buffer.readUInt16LE(eocd + 10)
95
+ const directoryOffset = buffer.readUInt32LE(eocd + 16)
96
+ if (entries === 0xffff || directoryOffset === 0xffffffff) {
97
+ throw new Error('暂不支持 ZIP64 格式的 xlsx')
98
+ }
99
+ const directory = new Map()
100
+ const budget = { remaining: MAX_WORKBOOK_BYTES }
101
+ let cursor = directoryOffset
102
+ for (let index = 0; index < entries; index += 1) {
103
+ if (cursor + 46 > buffer.length || buffer.readUInt32LE(cursor) !== SIG_CENTRAL) {
104
+ throw new Error('xlsx 的 ZIP 目录损坏')
105
+ }
106
+ const method = buffer.readUInt16LE(cursor + 10)
107
+ const compressedSize = buffer.readUInt32LE(cursor + 20)
108
+ const nameLength = buffer.readUInt16LE(cursor + 28)
109
+ const extraLength = buffer.readUInt16LE(cursor + 30)
110
+ const commentLength = buffer.readUInt16LE(cursor + 32)
111
+ const localOffset = buffer.readUInt32LE(cursor + 42)
112
+ const name = buffer.toString('utf8', cursor + 46, cursor + 46 + nameLength)
113
+ directory.set(name, { method, compressedSize, localOffset, budget })
114
+ cursor += 46 + nameLength + extraLength + commentLength
115
+ }
116
+ return directory
117
+ }
118
+
119
+ /**
120
+ * Read and inflate one ZIP entry.
121
+ * @param {Buffer} buffer - the whole package.
122
+ * @param {{ method: number, compressedSize: number, localOffset: number }} entry - central directory facts.
123
+ * @returns {Buffer} the entry bytes.
124
+ */
125
+ function readZipEntry(buffer, entry) {
126
+ const offset = entry.localOffset
127
+ if (buffer.readUInt32LE(offset) !== SIG_LOCAL) throw new Error('xlsx 的 ZIP 条目损坏')
128
+ const nameLength = buffer.readUInt16LE(offset + 26)
129
+ const extraLength = buffer.readUInt16LE(offset + 28)
130
+ const start = offset + 30 + nameLength + extraLength
131
+ const data = buffer.subarray(start, start + entry.compressedSize)
132
+ const limit = Math.min(MAX_ENTRY_BYTES, entry.budget.remaining)
133
+ if (limit <= 0 || (entry.method === 0 && data.length > limit)) throw new Error('xlsx 解压内容过大')
134
+ let bytes
135
+ if (entry.method === 0) bytes = Buffer.from(data)
136
+ else if (entry.method === 8) bytes = inflateRawSync(data, { maxOutputLength: limit })
137
+ else throw new Error(`不支持的 xlsx 压缩方式:${entry.method}`)
138
+ entry.budget.remaining -= bytes.length
139
+ return bytes
140
+ }
141
+
142
+ /**
143
+ * Read an entry's text if it exists.
144
+ * @param {Map<string, { method: number, compressedSize: number, localOffset: number }>} directory - package index.
145
+ * @param {Buffer} buffer - the whole package.
146
+ * @param {string} name - entry path.
147
+ * @returns {string | undefined} UTF-8 text or undefined.
148
+ */
149
+ function readText(directory, buffer, name) {
150
+ const entry = directory.get(name)
151
+ if (entry === undefined) return undefined
152
+ return readZipEntry(buffer, entry).toString('utf8')
153
+ }
154
+
155
+ /**
156
+ * A1-style cell reference to a zero-based column index.
157
+ * @param {string} reference - cell reference such as `AB12`.
158
+ * @returns {number} zero-based column index.
159
+ */
160
+ function columnIndex(reference) {
161
+ const letters = /^[A-Z]+/i.exec(reference)?.[0] ?? ''
162
+ let index = 0
163
+ for (const character of letters.toUpperCase()) index = index * 26 + (character.charCodeAt(0) - 64)
164
+ return Math.max(0, index - 1)
165
+ }
166
+
167
+ /**
168
+ * Convert an Excel serial day number to a display string.
169
+ * @param {number} serial - Excel date/time serial.
170
+ * @param {boolean} withTime - whether the number format carried a time part.
171
+ * @returns {string} `YYYY-MM-DD` or `YYYY-MM-DD HH:mm:ss`.
172
+ */
173
+ function formatExcelDate(serial, withTime) {
174
+ const days = Math.floor(serial)
175
+ const fraction = serial - days
176
+ const date = new Date(Date.UTC(1899, 11, 30) + days * 86400000 + Math.round(fraction * 86400000))
177
+ if (!Number.isFinite(date.getTime())) return String(serial)
178
+ const pad = value => String(value).padStart(2, '0')
179
+ const dateText = `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`
180
+ if (!withTime) return dateText
181
+ return `${dateText} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}`
182
+ }
183
+
184
+ /**
185
+ * Decide whether a number format renders a date or a time.
186
+ * @param {number} id - number format id.
187
+ * @param {string | undefined} code - custom format code, when the id is custom.
188
+ * @returns {{ date: boolean, time: boolean }} the rendering facts.
189
+ */
190
+ function classifyNumberFormat(id, code) {
191
+ if (BUILTIN_DATE_FORMATS.has(id)) {
192
+ const time = id >= 18 && id <= 22 || id === 45 || id === 46 || id === 47
193
+ return { date: true, time }
194
+ }
195
+ if (code === undefined) return { date: false, time: false }
196
+ const bare = code
197
+ .replace(/"[^"]*"/g, '')
198
+ .replace(/\\./g, '')
199
+ .replace(/\[[^\]]*\]/g, '')
200
+ return { date: /[yd]/i.test(bare), time: /[hs]/i.test(bare) }
201
+ }
202
+
203
+ /**
204
+ * Parse `xl/styles.xml` into cell style facts.
205
+ * @param {string | undefined} xml - styles part text.
206
+ * @returns {{ dateStyles: boolean[], timeStyles: boolean[] }} style flags by cellXfs index.
207
+ */
208
+ function readStyles(xml) {
209
+ const dateStyles = []
210
+ const timeStyles = []
211
+ if (xml === undefined) return { dateStyles, timeStyles }
212
+ const formats = new Map()
213
+ for (const match of xml.matchAll(/<numFmt\b([^>]*)\/?>/g)) {
214
+ const attributes = match[1]
215
+ const id = Number.parseInt(/\bnumFmtId="(\d+)"/.exec(attributes)?.[1] ?? '', 10)
216
+ const code = /\bformatCode="([^"]*)"/.exec(attributes)?.[1]
217
+ if (Number.isFinite(id)) formats.set(id, code === undefined ? '' : decodeXml(code))
218
+ }
219
+ const cellXfs = /<cellXfs\b[^>]*>([\s\S]*?)<\/cellXfs>/.exec(xml)?.[1] ?? ''
220
+ for (const match of cellXfs.matchAll(/<xf\b([^>]*)\/?>/g)) {
221
+ const id = Number.parseInt(/\bnumFmtId="(\d+)"/.exec(match[1])?.[1] ?? '0', 10)
222
+ const { date, time } = classifyNumberFormat(Number.isFinite(id) ? id : 0, formats.get(id))
223
+ dateStyles.push(date)
224
+ timeStyles.push(time)
225
+ }
226
+ return { dateStyles, timeStyles }
227
+ }
228
+
229
+ /**
230
+ * Resolve the worksheet path the first sheet of the workbook points at.
231
+ * @param {Map<string, unknown>} directory - package index.
232
+ * @param {Buffer} buffer - the whole package.
233
+ * @returns {string | undefined} worksheet entry path.
234
+ */
235
+ function firstWorksheetPath(directory, buffer) {
236
+ const workbook = readText(directory, buffer, 'xl/workbook.xml')
237
+ const relId = workbook === undefined
238
+ ? undefined
239
+ : /<sheet\b[^>]*\br:id="([^"]+)"/.exec(workbook)?.[1]
240
+ if (relId !== undefined) {
241
+ const rels = readText(directory, buffer, 'xl/_rels/workbook.xml.rels')
242
+ const relPattern = new RegExp(`<Relationship\\b[^>]*\\bId="${relId}"[^>]*>`, 'i')
243
+ const relation = rels === undefined ? undefined : relPattern.exec(rels)?.[0]
244
+ const target = relation === undefined ? undefined : /\bTarget="([^"]+)"/.exec(relation)?.[1]
245
+ if (target !== undefined) {
246
+ const normalized = target.replace(/^\/?xl\//, '').replace(/^\.\//, '')
247
+ const candidate = normalized.startsWith('xl/') ? normalized : `xl/${normalized}`
248
+ if (directory.has(candidate)) return candidate
249
+ }
250
+ }
251
+ const sheets = [...directory.keys()]
252
+ .filter(name => /^xl\/worksheets\/sheet\d+\.xml$/.test(name))
253
+ .sort((left, right) => left.localeCompare(right, 'en', { numeric: true }))
254
+ return sheets[0]
255
+ }
256
+
257
+ /**
258
+ * Read one worksheet into a dense row matrix of display strings.
259
+ * @param {string} sheetXml - worksheet part text.
260
+ * @param {string[]} sharedStrings - shared string table.
261
+ * @param {{ dateStyles: boolean[], timeStyles: boolean[] }} styles - cell style facts.
262
+ * @returns {string[][]} rows, sparse cells filled with empty strings.
263
+ */
264
+ function readSheetRows(sheetXml, sharedStrings, styles) {
265
+ const rows = []
266
+ for (const rowMatch of sheetXml.matchAll(/<row\b([^>]*?)(?:\/>|>([\s\S]*?)<\/row>)/g)) {
267
+ const rowNumber = Number.parseInt(/\br="(\d+)"/.exec(rowMatch[1])?.[1] ?? '', 10)
268
+ const body = rowMatch[2] ?? ''
269
+ const values = []
270
+ for (const cellMatch of body.matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
271
+ const attributes = cellMatch[1]
272
+ const inner = cellMatch[2] ?? ''
273
+ const reference = /\br="([A-Z]+)\d+"/i.exec(attributes)?.[1] ?? ''
274
+ const type = /\bt="([^"]+)"/.exec(attributes)?.[1] ?? 'n'
275
+ const styleIndex = Number.parseInt(/\bs="(\d+)"/.exec(attributes)?.[1] ?? '', 10)
276
+ let value = ''
277
+ if (type === 's') {
278
+ const index = Number.parseInt(/<v>([\s\S]*?)<\/v>/.exec(inner)?.[1] ?? '', 10)
279
+ value = sharedStrings[index] ?? ''
280
+ } else if (type === 'inlineStr') {
281
+ value = xmlText(/<is\b[^>]*>([\s\S]*?)<\/is>/.exec(inner)?.[1] ?? '')
282
+ } else if (type === 'b') {
283
+ value = (/<v>([\s\S]*?)<\/v>/.exec(inner)?.[1] ?? '').trim() === '1' ? '是' : '否'
284
+ } else if (type === 'str' || type === 'e') {
285
+ value = decodeXml(/<v>([\s\S]*?)<\/v>/.exec(inner)?.[1] ?? '')
286
+ } else {
287
+ const raw = (/<v>([\s\S]*?)<\/v>/.exec(inner)?.[1] ?? '').trim()
288
+ const numeric = Number(raw)
289
+ const dateStyle = Number.isFinite(styleIndex) && styleIndex >= 0
290
+ ? styles.dateStyles[styleIndex] === true
291
+ : false
292
+ if (dateStyle && raw !== '' && Number.isFinite(numeric)) {
293
+ const timeStyle = styles.timeStyles[styleIndex] === true
294
+ value = numeric > 0 && numeric < 1
295
+ ? formatExcelDate(numeric, true).replace(/^\d{4}-\d{2}-\d{2}\s/, '')
296
+ : formatExcelDate(numeric, timeStyle)
297
+ } else {
298
+ value = raw
299
+ }
300
+ }
301
+ const index = columnIndex(reference)
302
+ while (values.length < index) values.push('')
303
+ values[index] = value
304
+ }
305
+ const index = Number.isFinite(rowNumber) && rowNumber > 0 ? rowNumber - 1 : rows.length
306
+ while (rows.length < index) rows.push([])
307
+ rows[index] = values
308
+ }
309
+ return rows
310
+ }
311
+
312
+ /**
313
+ * Parse the first worksheet of a defect-export workbook.
314
+ * @param {Buffer | Uint8Array} input - workbook bytes.
315
+ * @returns {{ sheetName: string | undefined, rows: string[][] }} the dense row matrix.
316
+ */
317
+ export function readWorkbookRows(input) {
318
+ const buffer = Buffer.isBuffer(input) ? input : Buffer.from(input)
319
+ const directory = readZipDirectory(buffer)
320
+ const workbook = readText(directory, buffer, 'xl/workbook.xml')
321
+ const sheetName = workbook === undefined
322
+ ? undefined
323
+ : decodeXml(/<sheet\b[^>]*\bname="([^"]*)"/.exec(workbook)?.[1] ?? '')
324
+ const shared = readText(directory, buffer, 'xl/sharedStrings.xml')
325
+ const sharedStrings = shared === undefined
326
+ ? []
327
+ : [...shared.matchAll(/<si\b[^>]*>([\s\S]*?)<\/si>/g)].map(match => xmlText(match[1]))
328
+ const styles = readStyles(readText(directory, buffer, 'xl/styles.xml'))
329
+ const sheetPath = firstWorksheetPath(directory, buffer)
330
+ if (sheetPath === undefined) throw new Error('xlsx 中没有找到工作表')
331
+ const sheetXml = readText(directory, buffer, sheetPath)
332
+ if (sheetXml === undefined) throw new Error(`xlsx 中缺少工作表数据:${sheetPath}`)
333
+ const rows = readSheetRows(sheetXml, sharedStrings, styles)
334
+ return { sheetName: sheetName === '' ? undefined : sheetName, rows }
335
+ }
336
+
337
+ /**
338
+ * Normalize a header cell for alias matching.
339
+ * @param {string} value - raw header text.
340
+ * @returns {string} trimmed text without trailing punctuation.
341
+ */
342
+ function normalizeHeader(value) {
343
+ return String(value).replace(/[\s\u3000]+/g, '').replace(/[::]+$/, '')
344
+ }
345
+
346
+ /**
347
+ * Map one header row onto the canonical defect field indexes.
348
+ * @param {string[]} header - header cells.
349
+ * @returns {Record<string, number>} field name to zero-based column index.
350
+ */
351
+ export function mapHeader(header) {
352
+ const normalized = header.map(normalizeHeader)
353
+ const indexes = {}
354
+ for (const [field, aliases] of Object.entries(HEADER_ALIASES)) {
355
+ let found = -1
356
+ for (const alias of aliases) {
357
+ found = normalized.indexOf(normalizeHeader(alias))
358
+ if (found >= 0) break
359
+ }
360
+ if (found < 0) {
361
+ for (const alias of aliases) {
362
+ found = normalized.findIndex(cell => cell !== '' && cell.includes(normalizeHeader(alias)))
363
+ if (found >= 0) break
364
+ }
365
+ }
366
+ if (found >= 0) indexes[field] = found
367
+ }
368
+ return indexes
369
+ }
370
+
371
+ /**
372
+ * Trim a cell for display and storage.
373
+ * @param {string | undefined} value - raw cell value.
374
+ * @returns {string} trimmed value.
375
+ */
376
+ function cellText(value) {
377
+ return value === undefined ? '' : String(value).trim()
378
+ }
379
+
380
+ /**
381
+ * Strip the `1003.0` style integer formatting some exports leave in number cells.
382
+ * @param {string} value - raw cell value.
383
+ * @returns {string} integer text when the value is one.
384
+ */
385
+ function integerText(value) {
386
+ const text = cellText(value)
387
+ return /^\d+\.0+$/.test(text) ? text.replace(/\.0+$/, '') : text
388
+ }
389
+
390
+ /**
391
+ * Check whether a buffer looks like a ZIP archive (xlsx).
392
+ * @param {Buffer} buffer - raw file bytes.
393
+ * @returns {boolean} true when a ZIP signature is present.
394
+ */
395
+ function isZipBuffer(buffer) {
396
+ if (buffer.length >= 4 && buffer.readUInt32LE(0) === SIG_LOCAL) return true
397
+ const minimum = Math.max(0, buffer.length - 0xffff - 22)
398
+ for (let offset = buffer.length - 22; offset >= minimum; offset -= 1) {
399
+ if (buffer.readUInt32LE(offset) === SIG_EOCD) return true
400
+ }
401
+ return false
402
+ }
403
+
404
+ /**
405
+ * Decode CSV bytes, preferring UTF-8 and falling back to GB18030 for Windows Excel exports.
406
+ * @param {Buffer} buffer - raw CSV bytes.
407
+ * @returns {string} decoded text.
408
+ */
409
+ function decodeCsvText(buffer) {
410
+ let text = buffer.toString('utf8')
411
+ if (text.includes('\uFFFD')) {
412
+ try {
413
+ text = new TextDecoder('gb18030').decode(buffer)
414
+ } catch {
415
+ // keep utf8 text if gb18030 is unavailable
416
+ }
417
+ }
418
+ return text.replace(/^\uFEFF/, '')
419
+ }
420
+
421
+ /**
422
+ * Parse RFC-4180 CSV text into a dense row matrix.
423
+ * @param {string} text - CSV text.
424
+ * @returns {string[][]} rows.
425
+ */
426
+ function parseCsvRows(text) {
427
+ const rows = []
428
+ let row = []
429
+ let cell = ''
430
+ let inQuotes = false
431
+ for (let index = 0; index < text.length; index += 1) {
432
+ const ch = text[index]
433
+ if (inQuotes) {
434
+ if (ch === '"') {
435
+ if (text[index + 1] === '"') {
436
+ cell += '"'
437
+ index += 1
438
+ } else {
439
+ inQuotes = false
440
+ }
441
+ } else {
442
+ cell += ch
443
+ }
444
+ continue
445
+ }
446
+ if (ch === '"') {
447
+ inQuotes = true
448
+ } else if (ch === ',') {
449
+ row.push(cell)
450
+ cell = ''
451
+ } else if (ch === '\r' || ch === '\n') {
452
+ if (ch === '\r' && text[index + 1] === '\n') index += 1
453
+ row.push(cell)
454
+ rows.push(row)
455
+ row = []
456
+ cell = ''
457
+ } else {
458
+ cell += ch
459
+ }
460
+ }
461
+ if (cell !== '' || row.length > 0) {
462
+ row.push(cell)
463
+ rows.push(row)
464
+ }
465
+ return rows
466
+ }
467
+
468
+ /**
469
+ * Convert the first worksheet of an `.xlsx` or `.csv` export into defect rows.
470
+ * @param {Buffer | Uint8Array} input - workbook or CSV bytes.
471
+ * @param {string} [filename] - optional file name hint.
472
+ * @returns {{ sheetName: string | undefined, columns: string[], bugs: object[] }} parsed defects.
473
+ */
474
+ export function readBugList(input, filename = '') {
475
+ const buffer = Buffer.isBuffer(input) ? input : Buffer.from(input)
476
+ let sheetName
477
+ let rows
478
+ const isCsvName = filename.toLowerCase().endsWith('.csv')
479
+ if (!isCsvName && isZipBuffer(buffer)) {
480
+ const parsed = readWorkbookRows(buffer)
481
+ sheetName = parsed.sheetName
482
+ rows = parsed.rows
483
+ } else if (!buffer.includes(0) && (isCsvName || buffer.includes(10) || buffer.includes(13))) {
484
+ sheetName = 'CSV'
485
+ rows = parseCsvRows(decodeCsvText(buffer))
486
+ } else {
487
+ throw new Error('不是有效的 xlsx 或 csv 文件(未找到 ZIP 目录结尾)')
488
+ }
489
+ const headerIndex = rows.findIndex(row => row !== undefined && mapHeader(row).title !== undefined)
490
+ if (headerIndex < 0) throw new Error('没有在表格中找到「缺陷概述 / 问题描述」列,请确认表头包含描述或标题列')
491
+ const header = rows[headerIndex] ?? []
492
+ const columns = header.map(cellText)
493
+ const indexes = mapHeader(header)
494
+ const bugs = []
495
+ for (let rowIndex = headerIndex + 1; rowIndex < rows.length; rowIndex += 1) {
496
+ const row = rows[rowIndex] ?? []
497
+ const title = cellText(row[indexes.title])
498
+ const id = integerText(row[indexes.id])
499
+ if (title === '' && id === '') continue
500
+ const key = id !== '' ? `bug-${id}` : `row-${rowIndex + 1}`
501
+ bugs.push({
502
+ key,
503
+ row: rowIndex + 1,
504
+ id,
505
+ title,
506
+ analysis: cellText(row[indexes.analysis]),
507
+ severity: cellText(row[indexes.severity]),
508
+ state: cellText(row[indexes.state]),
509
+ tags: cellText(row[indexes.tags]),
510
+ note: cellText(row[indexes.note]),
511
+ url: cellText(row[indexes.url]),
512
+ plan: cellText(row[indexes.plan]),
513
+ creator: cellText(row[indexes.creator]),
514
+ fixer: cellText(row[indexes.fixer]),
515
+ registeredAt: cellText(row[indexes.registeredAt]),
516
+ requirement: cellText(row[indexes.requirement]),
517
+ reopenCount: integerText(row[indexes.reopenCount]),
518
+ standardStatus: cellText(row[indexes.standardStatus]),
519
+ standardOwner: cellText(row[indexes.standardOwner]),
520
+ platform: cellText(row[indexes.platform]),
521
+ version: cellText(row[indexes.version]),
522
+ })
523
+ }
524
+ if (bugs.length === 0) throw new Error('Excel 中没有读到缺陷行')
525
+ return { sheetName, columns, bugs }
526
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Auto Bug Fix",
4
+ "description": "Import defects from Excel/CSV or plain text and let the current session's AI fix each one in an isolated local Git worktree branched from your chosen base branch. Fixes land on one local bug-fix branch with conflict preview, AI conflict resolution, and per-defect withdraw/re-fix, then merge back with local git merge --no-ff. Remote push/fetch/pull are globally disabled.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Bug 自动修复",
4
+ "description": "支持从表格(Excel/CSV)或自由文字导入缺陷,让当前会话的 AI 在基于指定基线分支的独立本地 Git worktree 中逐个自动修复。修复提交汇总到一条本地 bug-fix 分支,支持冲突预览、AI 解决冲突、撤回重修,最后一次性非快进合并回基线分支。全局禁用了 git push/fetch/pull,不触碰远端。",
5
+ "detail": "docs/DETAIL.zh.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "dsh-git-bugfix",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/drypeek/dsh-git-bugfix.git"
7
+ },
8
+ "homepage": "https://github.com/drypeek/dsh-git-bugfix#readme",
9
+ "bugs": {
10
+ "url": "https://github.com/drypeek/dsh-git-bugfix/issues"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public",
14
+ "registry": "https://registry.npmjs.org/"
15
+ },
16
+ "description": "Import a defect spreadsheet (Excel/CSV) or text description and let the current session's AI fix each defect in an isolated local Git worktree, collect every fix on one local bug-fix branch, pause for questions, resolve conflicts, then merge into a chosen base branch.",
17
+ "type": "module",
18
+ "license": "MIT",
19
+ "keywords": [
20
+ "dsh",
21
+ "dsh-plugin",
22
+ "deepseek-harness",
23
+ "bug-fix",
24
+ "defect",
25
+ "git",
26
+ "worktree",
27
+ "automation"
28
+ ],
29
+ "engines": {
30
+ "node": ">=20",
31
+ "dsh": ">=0.2.2-rc.5 <0.3.0-0"
32
+ },
33
+ "scripts": {
34
+ "check": "node --check index.js && node --check client.js",
35
+ "test": "node --test test/xlsx.test.mjs test/git.test.mjs test/state.test.mjs test/fixer.test.mjs test/fixer-flow.test.mjs test/client.test.mjs test/package.test.mjs"
36
+ },
37
+ "exports": {
38
+ ".": "./index.js",
39
+ "./client": "./client.js",
40
+ "./locale/*.json": "./locale/*.json",
41
+ "./icon": "./icon.svg",
42
+ "./package.json": "./package.json"
43
+ },
44
+ "files": [
45
+ "index.js",
46
+ "client.js",
47
+ "lib",
48
+ "locale/*.json",
49
+ "cordis.patch.yml",
50
+ "docs",
51
+ "icon.svg",
52
+ "README.md",
53
+ "README.en.md",
54
+ "CHANGELOG.md",
55
+ "LICENSE"
56
+ ],
57
+ "dsh": {
58
+ "manifestVersion": 1,
59
+ "bundle": {
60
+ "patch": "./cordis.patch.yml"
61
+ },
62
+ "client": {
63
+ "platform": "web",
64
+ "immediately": true,
65
+ "inject": [
66
+ "@deepseek-ai/dsh-client-ui-conversation",
67
+ "@deepseek-ai/dsh-client-ui-sidebar-right"
68
+ ]
69
+ }
70
+ }
71
+ }