70 lines
2 KiB
TypeScript
70 lines
2 KiB
TypeScript
// packages/core/src/csv.ts
|
|
// CSV 셀 이스케이프(수식 주입 방어 포함) 및 RFC 4180 행 파서 정본 (W5-05).
|
|
|
|
const DANGEROUS_CSV_FORMULA_PREFIX = /^[=+\-@]/
|
|
|
|
export interface CsvCellOptions {
|
|
/** 스프레드시트 수식 문자(=, +, -, @) 앞에 작은따옴표(')를 붙여 방어할지 여부 (기본 false: 따옴표 래핑만 수행) */
|
|
prefixFormulaWithApostrophe?: boolean
|
|
}
|
|
|
|
export function csvCell(value: unknown, options?: CsvCellOptions): string {
|
|
if (value === null || value === undefined) return ''
|
|
let text = String(value)
|
|
if (options?.prefixFormulaWithApostrophe && DANGEROUS_CSV_FORMULA_PREFIX.test(text)) {
|
|
text = `'${text}`
|
|
return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text
|
|
}
|
|
const escaped = text.replace(/"/g, '""')
|
|
const needsQuotes = /[",\r\n]/.test(escaped) || DANGEROUS_CSV_FORMULA_PREFIX.test(escaped)
|
|
return needsQuotes ? `"${escaped}"` : escaped
|
|
}
|
|
|
|
export function parseCsvRows(input: string): string[][] {
|
|
const source = input.charCodeAt(0) === 0xfeff ? input.slice(1) : input
|
|
const rows: string[][] = []
|
|
let row: string[] = []
|
|
let field = ''
|
|
let inQuotes = false
|
|
|
|
for (let i = 0; i < source.length; i += 1) {
|
|
const char = source[i]
|
|
if (inQuotes) {
|
|
if (char === '"') {
|
|
if (source[i + 1] === '"') {
|
|
field += '"'
|
|
i += 1
|
|
} else {
|
|
inQuotes = false
|
|
}
|
|
} else {
|
|
field += char
|
|
}
|
|
continue
|
|
}
|
|
|
|
if (char === '"') {
|
|
inQuotes = true
|
|
} else if (char === ',') {
|
|
row.push(field)
|
|
field = ''
|
|
} else if (char === '\r' || char === '\n') {
|
|
if (char === '\r' && source[i + 1] === '\n') {
|
|
i += 1
|
|
}
|
|
row.push(field)
|
|
rows.push(row)
|
|
row = []
|
|
field = ''
|
|
} else {
|
|
field += char
|
|
}
|
|
}
|
|
|
|
if (field.length > 0 || row.length > 0) {
|
|
row.push(field)
|
|
rows.push(row)
|
|
}
|
|
|
|
return rows.filter((candidate) => candidate.some((cell) => cell.trim().length > 0))
|
|
}
|