Repository navigation
Expand file tree
/
Copy pathtext-conversion.js
More file actions
325 lines (298 loc) · 11.9 KB
/
Copy pathtext-conversion.js
File metadata and controls
325 lines (298 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
const { parse } = require("csv-parse/sync");
const { marked, Marked } = require("marked");
const TurndownService = require("turndown");
const { markdownExtensions } = require("./markdown-math");
function createTurndownService() {
const service = new TurndownService({
headingStyle: "atx",
codeBlockStyle: "fenced"
});
service.addRule("tables", {
filter: "table",
replacement(content, node) {
if (isComplexTable(node)) return `\n\n${serializeSafeTable(node)}\n\n`;
return `\n\n${simpleTableToMarkdown(node)}\n\n`;
}
});
return service;
}
let sharedTurndownService = null;
function sharedTurndown() {
if (!sharedTurndownService) sharedTurndownService = createTurndownService();
return sharedTurndownService;
}
function isComplexTable(table) {
if (table.querySelector("table")) return true;
return Array.from(table.querySelectorAll("th, td"))
.some((cell) => cell.hasAttribute("rowspan") || cell.hasAttribute("colspan"));
}
function markdownTableCell(cell) {
const html = cell.innerHTML.replace(/\r?\n/g, "<br>");
return sharedTurndown()
.turndown(html)
.trim()
.replace(/\\/g, "\\\\")
.replace(/\|/g, "\\|")
.replace(/(?:\s*\n\s*)+/g, "<br>");
}
function simpleTableToMarkdown(table) {
const rows = Array.from(table.querySelectorAll("tr")).map((row) =>
Array.from(row.children)
.filter((cell) => cell.nodeName === "TH" || cell.nodeName === "TD")
.map(markdownTableCell)
).filter((row) => row.length > 0);
if (rows.length === 0) return "";
const width = Math.max(...rows.map((row) => row.length));
const normalized = rows.map((row) => [...row, ...Array(width - row.length).fill("")]);
const formatRow = (row) => `| ${row.join(" | ")} |`;
return [
formatRow(normalized[0]),
formatRow(Array(width).fill("---")),
...normalized.slice(1).map(formatRow)
].join("\n");
}
function escapeHtmlText(value) {
return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
function escapeHtmlAttribute(value) {
return escapeHtmlText(value).replace(/"/g, """);
}
function isSafeMarkdownLink(href) {
const value = String(href || "").trim();
if (!value) return false;
if (/^(?:https?:|mailto:)/i.test(value)) return true;
return /^(?:#|\/|\.\/|\.\.\/)/.test(value);
}
function isSafeMarkdownImage(href) {
const value = String(href || "").trim();
if (!value || /[\u0000-\u001f\u007f\\]/.test(value) || value.startsWith("//")) return false;
if (/^data:image\/(?:png|jpe?g|gif|webp|avif);base64,/i.test(value)) return true;
return !/^[a-z][a-z\d+.-]*:/i.test(value);
}
function markdownToHtml(markdown) {
const renderer = new marked.Renderer();
renderer.html = (html) => /^<\/?(?:u|mark)\s*>$/i.test(html) ? html.toLowerCase() : escapeHtmlText(html);
renderer.link = (href, title, text) => {
if (!isSafeMarkdownLink(href)) return text;
const titleAttribute = title ? ` title="${escapeHtmlAttribute(title)}"` : "";
return `<a href="${escapeHtmlAttribute(href)}"${titleAttribute}>${text}</a>`;
};
renderer.image = (href, title, text) => {
if (!isSafeMarkdownImage(href)) return escapeHtmlText(text);
const titleAttribute = title ? ` title="${escapeHtmlAttribute(title)}"` : "";
return `<img src="${escapeHtmlAttribute(href)}" alt="${escapeHtmlAttribute(text)}"${titleAttribute}>`;
};
const parser = new Marked({ extensions: markdownExtensions() });
const body = parser.parse(String(markdown || ""), {
async: false,
gfm: true,
mangle: false,
headerIds: false,
renderer
});
return `<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Converted document</title></head>
<body>
${body.trim()}
</body>
</html>`;
}
function serializeSafeTable(node) {
if (node.nodeType === 3) return escapeHtmlText(node.nodeValue || "");
if (node.nodeType !== 1) return "";
const tag = node.nodeName.toLowerCase();
if (["script", "style", "iframe", "object", "embed"].includes(tag)) return "";
const allowed = new Set([
"table", "caption", "thead", "tbody", "tfoot", "tr", "th", "td",
"strong", "b", "em", "i", "code", "br", "p", "ul", "ol", "li"
]);
const children = Array.from(node.childNodes).map(serializeSafeTable).join("");
if (!allowed.has(tag)) return children;
if (tag === "br") return "<br>";
let attributes = "";
if (tag === "th" || tag === "td") {
for (const name of ["rowspan", "colspan"]) {
const raw = node.getAttribute(name);
if (/^[1-9]\d*$/.test(raw || "")) attributes += ` ${name}="${raw}"`;
}
}
return `<${tag}${attributes}>${children}</${tag}>`;
}
function htmlToMarkdown(html) {
return createTurndownService().turndown(String(html || "")).trim();
}
function csvToJsonObjects(csv) {
try {
return parse(String(csv || ""), {
bom: true,
columns: (headers) => {
const normalized = headers.map((header, index) => String(header || `column_${index + 1}`));
const seen = new Set();
const forbidden = new Set(["__proto__", "prototype", "constructor"]);
for (const header of normalized) {
const key = header.toLowerCase();
if (forbidden.has(key)) throw new Error(`CSV 表头不安全:${header}`);
if (seen.has(key)) throw new Error(`CSV 表头重复:${header}`);
seen.add(key);
}
return normalized;
},
skip_empty_lines: true,
relax_column_count: false,
relax_quotes: false
});
} catch (error) {
const wrapped = new Error(`CSV 解析失败:列数或引号格式不合法。${error?.message ? ` ${error.message}` : ""}`);
wrapped.code = "CSV_PARSE_FAILED";
wrapped.cause = error;
throw wrapped;
}
}
// CSV -> Markdown 表格:用严格 CSV 解析(同 csvToJsonObjects),避免把原始 CSV 文本
// 原样当作 Markdown 输出(v0.3.5 的假实现)。单元格内的 | 与换行做转义。
function csvToMarkdown(csv) {
let records;
try {
records = parse(String(csv || ""), {
bom: true,
skip_empty_lines: true,
relax_column_count: false,
relax_quotes: false
});
} catch (error) {
const wrapped = new Error(`CSV 解析失败:列数或引号格式不合法。${error?.message ? ` ${error.message}` : ""}`);
wrapped.code = "CSV_PARSE_FAILED";
wrapped.cause = error;
throw wrapped;
}
if (!records.length) return "";
const width = records.reduce((max, row) => Math.max(max, row.length), 0);
const normalized = records.map((row) => [...row, ...Array(width - row.length).fill("")]);
const escapeCell = (value) => {
const CR = String.fromCharCode(13);
return String(value ?? "")
.replace(/\\/g, "\\\\")
.replace(/\|/g, "\\|")
.split(CR + "\n").join("\n")
.replace(/\n/g, "<br>");
};
const formatRow = (row) => `| ${row.map(escapeCell).join(" | ")} |`;
return [
formatRow(normalized[0]),
formatRow(Array(width).fill("---")),
...normalized.slice(1).map(formatRow)
].join("\n");
}
// CSV -> HTML 表格:严格解析(同 csvToMarkdown),生成带边框的 HTML 表格。
// 用于 csv->html 直接输出与 csv->pdf(HTML 中转 LibreOffice)——LibreOffice 的
// csv 导入过滤器在 headless 下是假成功(exit 0 但零输出),不能直接转。
function csvToHtmlTable(csv) {
let records;
try {
records = parse(String(csv || ""), {
bom: true,
skip_empty_lines: true,
relax_column_count: false,
relax_quotes: false
});
} catch (error) {
const wrapped = new Error(`CSV 解析失败:列数或引号格式不合法。${error?.message ? ` ${error.message}` : ""}`);
wrapped.code = "CSV_PARSE_FAILED";
wrapped.cause = error;
throw wrapped;
}
if (!records.length) return "<p>(空 CSV)</p>";
const width = records.reduce((max, row) => Math.max(max, row.length), 0);
const normalized = records.map((row) => [...row, ...Array(width - row.length).fill("")]);
const cell = (value) => `<td>${escapeHtmlText(String(value ?? ""))}</td>`;
const rows = normalized.map((row) => `<tr>${row.map(cell).join("")}</tr>`).join("\n");
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>CSV table</title>
<style>
body{font-family:Arial,"Microsoft YaHei",sans-serif;margin:24px}
table{border-collapse:collapse;width:100%}
th,td{border:1px solid #999;padding:6px 10px;text-align:left;vertical-align:top}
tr:first-child{font-weight:bold;background:#f5f5f5}
</style>
</head>
<body>
<table>
${rows}
</table>
</body>
</html>`;
}
function stableJsonStringify(value) {
if (value instanceof JsonNumber) return value.source;
if (Array.isArray(value)) return `[${value.map(stableJsonStringify).join(",")}]`;
if (value && typeof value === "object") {
return `{${Object.keys(value).sort().map((key) =>
`${JSON.stringify(key)}:${stableJsonStringify(value[key])}`
).join(",")}}`;
}
return JSON.stringify(value);
}
function flattenJsonObject(value, prefix = "", output = Object.create(null)) {
for (const key of Object.keys(value || {}).sort()) {
const path = prefix ? `${prefix}.${key}` : key;
const nested = value[key];
if (nested instanceof JsonNumber) setFlattenedValue(output, path, nested.source);
else if (Array.isArray(nested)) setFlattenedValue(output, path, stableJsonStringify(nested));
else if (nested && typeof nested === "object" && Object.keys(nested).length) flattenJsonObject(nested, path, output);
else if (nested && typeof nested === "object") setFlattenedValue(output, path, "{}");
else setFlattenedValue(output, path, nested === null ? "null" : nested);
}
return output;
}
function setFlattenedValue(output, path, value) {
if (Object.prototype.hasOwnProperty.call(output, path)) {
const error = new Error(`JSON 转 CSV 失败:字段路径冲突:${path}`);
error.code = "JSON_CSV_PATH_COLLISION";
error.path = path;
throw error;
}
output[path] = value;
}
class JsonNumber {
constructor(source) { this.source = source; }
toString() { return this.source; }
}
function parseJsonNumbersExactly(source) {
// Validate using the platform JSON grammar, then replace only numeric tokens
// outside strings before materialization. Numeric spelling never enters a
// floating-point Number, including integers above 2^53 and decimal fractions.
const validated = JSON.parse(source);
let marker = "__flyingmouse_json_number__";
// Check decoded strings as well: a user string can spell the prefix with JSON
// unicode escapes, which must never be mistaken for one of our placeholders.
const decodedContent = JSON.stringify(validated);
while (source.includes(marker) || decodedContent.includes(marker)) marker += "_";
const numbers = [];
const rewritten = source.replace(/"(?:\\[\s\S]|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (token) => {
if (token[0] === '"') return token;
numbers.push(token);
return JSON.stringify(`${marker}${numbers.length - 1}`);
});
return JSON.parse(rewritten, (_key, value) => typeof value === "string" && value.startsWith(marker)
? new JsonNumber(numbers[Number(value.slice(marker.length))]) : value);
}
function jsonToCsv(jsonText) {
const data = parseJsonNumbersExactly(String(jsonText || ""));
const rows = (Array.isArray(data) ? data : [data]).map((row) => {
if (row === null || typeof row !== "object" || row instanceof JsonNumber || Array.isArray(row) || !Object.keys(row).length) {
return { value: row instanceof JsonNumber ? row.source : row === null ? "null" : typeof row === "object" ? stableJsonStringify(row) : row };
}
return flattenJsonObject(row);
});
const headers = [...new Set(rows.flatMap((row) => Object.keys(row)))].sort();
const quote = (value) => `"${String(value ?? "").replaceAll('"', '""')}"`;
return [
headers.map(quote).join(","),
...rows.map((row) => headers.map((header) => quote(row[header])).join(","))
].join("\n");
}
module.exports = { createTurndownService, htmlToMarkdown, markdownToHtml, csvToJsonObjects, csvToMarkdown, csvToHtmlTable, jsonToCsv };