import DOMPurify from 'dompurify';
import { marked } from 'marked';
import { diffLines, createTwoFilesPatch } from 'diff';
import { text, num, choice, assert, parseJSON, csvRows, csv, table, numeric, date, esc, canvas, svgDoc, svgResults, label, json, plain } from './common.js';
const sample = '项目,数量,状态\n设计,12,完成\n研发,20,进行中\n验收,8,待办';
const csvInput = () => text('data', 'CSV表格', sample, true);
const htmlDocument = (title, body, style = '') => `<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'"><title>${esc(title)}</title><style>body{max-width:960px;margin:32px auto;padding:0 20px;font:16px/1.7 system-ui;color:#203c32;overflow-wrap:anywhere}table{border-collapse:collapse}td,th{border:1px solid #c9d9d0;padding:8px}pre{white-space:pre-wrap;overflow-wrap:anywhere}a{color:#167d68}${style}</style></head><body>${body}</body></html>`;
const safeHTML = (value) => DOMPurify.sanitize(value, { ALLOWED_TAGS: ['h1','h2','h3','h4','h5','h6','p','br','hr','strong','b','em','i','s','del','code','pre','blockquote','ul','ol','li','table','thead','tbody','tr','th','td','a','div','span'], ALLOWED_ATTR: ['href','title','colspan','rowspan','start'], ALLOW_DATA_ATTR: false, FORBID_TAGS: ['script','style','iframe','object','embed','form','input','img','svg','math','video','audio','link','meta','base'] });
export const table_image = (() => ({ fields: [csvInput(), text('title', '表格标题', '数据表')], async run({ values: v }) {
const rows = csvRows(v.data); assert(rows.length <= 41 && rows[0].length <= 10, '图片表格最多40条数据、10列。'); const ctx = canvas(1, 1).getContext('2d'); ctx.font = '13px sans-serif';
const widths = rows[0].map((_, i) => Math.min(260, Math.max(100, ...rows.map((r) => ctx.measureText(r[i]).width + 24)))); const wrap = (s, width) => { const lines = []; let line = ''; for (const c of s) { if (c === '\n' || ctx.measureText(line + c).width > width - 20) { lines.push(line); line = c === '\n' ? '' : c; } else line += c; } lines.push(line); assert(lines.length <= 4, '单元格超过4行,请缩短内容。'); return lines; };
let y = 55, body = label(v.title, 20, 28, 'font-size="18"'); for (const [i, row] of rows.entries()) { const lines = row.map((s, j) => wrap(s, widths[j])), height = Math.max(...lines.map((l) => l.length)) * 20 + 14; let x = 20; lines.forEach((l, j) => { body += `<rect x="${x}" y="${y}" width="${widths[j]}" height="${height}" fill="${i === 0 ? '#d4e9df' : i % 2 ? '#ffffff' : '#f3f7f4'}" stroke="#c3d2ca"/>` + l.map((s, k) => label(s, x + 10, y + 22 + k * 20, i === 0 ? 'font-weight="bold"' : '')).join(''); x += widths[j]; }); y += height; }
assert(y + 20 <= 4096, '表格图像过高。'); return [...await svgResults(svgDoc(body, widths.reduce((a, b) => a + b, 0) + 40, y + 20, v.title), 'table'), csv(rows, 'table.csv')];
} }))();
export const csv_json = (() => ({ fields: [choice('direction', '转换方向', [['csv-json', 'CSV → JSON对象数组'], ['json-csv', 'JSON对象数组 → CSV']]), text('data', 'CSV或JSON内容', sample, true)], async run({ values: v }) {
if (v.direction === 'csv-json') { const t = table(v.data, 1); return [json(t.rows.map((r) => Object.fromEntries(t.header.map((h, i) => [h, r[i]]))), 'table.json')]; }
const data = parseJSON(v.data); assert(Array.isArray(data) && data.length >= 1 && data.length <= 199 && data.every((d) => d && typeof d === 'object' && !Array.isArray(d)), 'JSON需为1–199条对象组成的数组。'); const headers = [...new Set(data.flatMap(Object.keys))]; assert(headers.length >= 1 && headers.length <= 30, '最多30个字段。'); const rows = data.map((d) => headers.map((key) => { const value = d[key]; assert(value === null || value === undefined || ['string','number','boolean'].includes(typeof value), 'CSV不支持嵌套对象或数组。'); return value == null ? '' : String(value); })); return [csv([headers, ...rows], 'table.csv')];
} }))();
export const table_transform = (() => ({ fields: [csvInput(), choice('operation', '行列操作', [['transpose', '行列转置(含首行)'], ['reverse-rows', '倒转数据行'], ['reverse-columns', '倒转列顺序']])], async run({ values: v }) {
const rows = csvRows(v.data); let result; if (v.operation === 'transpose') { assert(rows.length <= 30, '转置后最多30列,请减少输入行数。'); result = rows[0].map((_, i) => rows.map((r) => r[i])); } else if (v.operation === 'reverse-rows') result = [rows[0], ...rows.slice(1).reverse()]; else result = rows.map((r) => [...r].reverse()); return [csv(result), json({ input: [rows.length, rows[0].length], output: [result.length, result[0].length], operation: v.operation }, 'transform.json')];
} }))();
export const markdown_table = (() => ({ fields: [csvInput(), choice('align', '列对齐', [['left', '左'], ['center', '居中'], ['right', '右']])], async run({ values: v }) {
const rows = csvRows(v.data); assert(rows.length >= 2, '需要表头和数据。'); const clean = (s) => s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('\\', '\\\\').replaceAll('|', '\\|').replace(/\r?\n/g, '<br>');
const row = (r) => '| ' + r.map(clean).join(' | ') + ' |', delimiter = { left: ':---', center: ':---:', right: '---:' }[v.align]; return [plain([row(rows[0]), '| ' + rows[0].map(() => delimiter).join(' | ') + ' |', ...rows.slice(1).map(row)].join('\n') + '\n', 'table.md', 'text/markdown')];
} }))();
export const data_clean = (() => ({ fields: [csvInput(), choice('trim', '空白整理', [['trim', '去除首尾空白'], ['keep', '保持原值']]), choice('dedupe', '重复行', [['remove', '去除完全重复行'], ['keep', '保留']]), num('sortColumn', '排序列(0不排序)', 0, 0, 30), choice('sortType', '排序方法', [['text', '文字升序'], ['numeric', '数值升序']])], async run({ values: v }) {
const t = table(v.data, 1); assert(v.sortColumn <= t.header.length, '排序列超出表格。'); let rows = t.rows.map((r) => r.map((s) => v.trim === 'trim' ? s.trim() : s)), changed = 0, duplicates = 0; rows.forEach((r, i) => r.forEach((s, j) => { if (s !== t.rows[i][j]) changed++; }));
if (v.dedupe === 'remove') { const seen = new Set(); rows = rows.filter((r) => { const key = JSON.stringify(r); if (seen.has(key)) { duplicates++; return false; } seen.add(key); return true; }); }
if (v.sortColumn) { const i = v.sortColumn - 1; if (v.sortType === 'numeric') rows.forEach((r) => numeric(r[i], '排序列')); rows.sort((a, b) => v.sortType === 'numeric' ? Number(a[i]) - Number(b[i]) : a[i].localeCompare(b[i], 'zh-CN')); }
return [csv([t.header, ...rows], 'cleaned.csv'), json({ inputRows: t.rows.length, outputRows: rows.length, trimmedCells: changed, removedDuplicateRows: duplicates, sorting: v.sortColumn ? { column: v.sortColumn, type: v.sortType } : null }, 'clean-report.json')];
} }))();
export const text_diff = (() => ({ fields: [text('before', '原文本', '第一行\n旧内容\n第三行\n', true), text('after', '新文本', '第一行\n新内容\n第三行\n新增内容\n', true)], async run({ values: v }) {
assert(v.before.length + v.after.length <= 30000 && v.before.split('\n').length + v.after.split('\n').length <= 2000, '总文本最多30000字符、2000行。'); const changes = diffLines(v.before, v.after, { timeout: 2000 }); assert(changes, '差异计算超时,请缩小文本。');
const body = '<h1>文本差异</h1>' + changes.map((c) => `<pre style="background:${c.added ? '#d9f3e3' : c.removed ? '#ffe1e3' : '#f5f7f5'}"><strong>${c.added ? '+' : c.removed ? '−' : ' '}</strong> ${esc(c.value)}</pre>`).join('');
return [plain(htmlDocument('文本差异', body), 'diff.html', 'text/html'), plain(createTwoFilesPatch('before.txt', 'after.txt', v.before, v.after), 'changes.patch'), json({ addedLines: changes.filter((c) => c.added).reduce((n, c) => n + c.count, 0), removedLines: changes.filter((c) => c.removed).reduce((n, c) => n + c.count, 0), changes }, 'diff.json')];
} }))();
export const markdown_export = (() => ({ fields: [text('title', '文档标题', '项目说明'), text('data', 'Markdown内容', '# 项目说明\n\n这是本地文档。\n\n- 免费开源\n- 浏览器本地处理\n\n| 项目 | 状态 |\n| --- | --- |\n| 示例 | 完成 |', true)], async run({ values: v }) {
const body = safeHTML(marked.parse(v.data, { async: false, gfm: true })); return [plain(htmlDocument(v.title, body), 'document.html', 'text/html'), plain(v.data, 'source.md', 'text/markdown')];
} }))();
export const html_text = (() => ({ fields: [text('data', 'HTML内容', '<h1>项目说明</h1><p>工具在本地运行。</p><p><a href="https://example.com">资料链接</a></p>', true)], async run({ values: v }) {
const safe = safeHTML(v.data), doc = new DOMParser().parseFromString(safe, 'text/html'), links = [...doc.querySelectorAll('a[href]')].map((a) => ({ text: a.textContent, href: a.getAttribute('href') }));
doc.querySelectorAll('br').forEach((node) => node.replaceWith('\n')); doc.querySelectorAll('p,div,li,h1,h2,h3,h4,h5,h6,blockquote,tr,pre').forEach((node) => { node.prepend('\n'); node.append('\n'); });
const text = doc.body.textContent.replace(/[\t ]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim(); assert(text, '未提取到正文。');
return [plain(text, 'body.txt'), json({ links, characters: [...text].length }, 'links.json')];
} }))();
export const json_tree = (() => ({ fields: [text('data', 'JSON内容', '{"项目":"工具站","工具":[{"名称":"压缩","本地":true},{"名称":"图表","本地":true}],"版本":2}', true)], async run({ values: v }) {
const data = parseJSON(v.data), nodes = []; function walk(value, path, depth, parent) { assert(depth <= 12 && nodes.length < 150, '结构图最多150个节点、12层。'); const i = nodes.length, complex = value !== null && typeof value === 'object'; nodes.push({ path, depth, parent, type: value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value, value: complex ? undefined : value, summary: complex ? Array.isArray(value) ? `Array(${value.length})` : `Object(${Object.keys(value).length})` : JSON.stringify(value) }); if (complex) for (const [k, child] of Object.entries(value)) walk(child, path + '/' + k.replaceAll('~', '~0').replaceAll('/', '~1'), depth + 1, i); } walk(data, '', 0, null);
const body = nodes.map((n, i) => { const x = 26 + n.depth * 40, y = 36 + i * 24, edge = n.parent === null ? '' : `<path d="M${26 + nodes[n.parent].depth * 40} ${36 + n.parent * 24}V${y}H${x}" fill="none" stroke="#bbd0c5"/>`, name = n.path.split('/').at(-1) || '$', value = `${name}: ${n.summary}`; return edge + `<circle cx="${x}" cy="${y}" r="3" fill="#167d68"/>` + label(value.length > 65 ? value.slice(0, 62) + '…' : value, x + 8, y + 4); }).join('');
return [...await svgResults(svgDoc(body, 1200, 60 + nodes.length * 24, 'JSON结构图'), 'json-tree'), json(nodes, 'json-paths.json')];
} }))();
export const timeline_chart = (() => ({ fields: [text('data', '日期、事件CSV', '日期,事件\n2026-01-01,项目启动\n2026-01-15,首版验收\n2026-02-01,开放使用', true), text('title', '标题', '项目时间线')], async run({ values: v }) {
const t = table(v.data); assert(t.header.length === 2 && t.rows.length <= 30, '时间线需要日期、事件两列,最多30项。'); const events = t.rows.map(([day, event]) => ({ date: day, timestamp: date(day), event })).sort((a, b) => a.timestamp - b.timestamp); assert(events.every((e) => [...e.event].length <= 45), '事件说明最多45字符。');
const body = label(v.title, 24, 30, 'font-size="18"') + `<line x1="165" x2="165" y1="65" y2="${65 + (events.length - 1) * 65}" stroke="#b6d7c7" stroke-width="3"/>` + events.map((e, i) => { const y = 65 + i * 65; return label(e.date, 145, y + 5, 'text-anchor="end"') + `<circle cx="165" cy="${y}" r="6" fill="#167d68"/>` + label(e.event, 185, y + 5); }).join('');
return [...await svgResults(svgDoc(body, 960, 85 + events.length * 65, v.title), 'timeline'), json({ events, spacing: '按事件等距排列,日期升序' }, 'timeline.json')];
} }))();