@first-ch/tools-mcp 0.4.1 → 0.24.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/README.md +52 -4
- package/aspect-ratio.mjs +706 -0
- package/base64.mjs +356 -0
- package/color.mjs +629 -0
- package/cron.mjs +633 -0
- package/diff.mjs +322 -0
- package/hash.mjs +234 -0
- package/html-escape.mjs +308 -0
- package/json-yaml.mjs +1693 -0
- package/jwt.mjs +639 -0
- package/lib.mjs +103 -0
- package/markdown-table.mjs +641 -0
- package/marp-theme.css +51 -0
- package/marp.mjs +219 -0
- package/package.json +130 -3
- package/px-rem.mjs +488 -0
- package/qr.mjs +744 -0
- package/server.mjs +942 -2
- package/sql-format.mjs +694 -0
- package/testdata.mjs +608 -0
- package/unixtime.mjs +505 -0
- package/url.mjs +415 -0
- package/user-agent.mjs +633 -0
- package/uuid.mjs +238 -0
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
// Markdown テーブル整形・CSV/TSV 変換(tools.first-ch.com/markdown-table/ と同一ロジック)
|
|
2
|
+
//
|
|
3
|
+
// 「変換コア」ブロックは site 側の site/markdown-table/app.js と同一の実装。
|
|
4
|
+
// 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
|
|
5
|
+
// 使っているのは String/RegExp/Array だけなので、ブラウザ版のコードをそのまま持ってこられる。
|
|
6
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
7
|
+
import { basename } from 'node:path';
|
|
8
|
+
|
|
9
|
+
/* ==================== ここから変換コア(site / MCP で同一) ==================== */
|
|
10
|
+
|
|
11
|
+
export const MT_IN_FORMATS = ['auto', 'tsv', 'csv', 'ssv', 'markdown'];
|
|
12
|
+
export const MT_OUT_FORMATS = ['markdown', 'csv', 'tsv', 'ssv', 'html', 'json'];
|
|
13
|
+
export const MT_ALIGNS = ['none', 'left', 'center', 'right'];
|
|
14
|
+
export const MT_HEADER_MODES = ['first', 'none', 'auto'];
|
|
15
|
+
export const MT_DELIMS = { tsv: '\t', csv: ',', ssv: ';', markdown: '|' };
|
|
16
|
+
const MT_MIN_DASH = 3; // 区切り行のハイフンの最小本数
|
|
17
|
+
const MT_DETECT_LINES = 50; // 区切り文字の自動判定に見る行数
|
|
18
|
+
|
|
19
|
+
// 見た目の桁を2つ使う文字(East Asian Wide / Fullwidth)。等幅フォントでの桁揃えに使う
|
|
20
|
+
const MT_WIDE_RANGES = [
|
|
21
|
+
[0x1100, 0x115f], [0x2e80, 0x303e], [0x3041, 0x33ff], [0x3400, 0x4dbf],
|
|
22
|
+
[0x4e00, 0x9fff], [0xa000, 0xa4cf], [0xa960, 0xa97f], [0xac00, 0xd7a3],
|
|
23
|
+
[0xf900, 0xfaff], [0xfe10, 0xfe19], [0xfe30, 0xfe6f], [0xff00, 0xff60],
|
|
24
|
+
[0xffe0, 0xffe6], [0x1b000, 0x1b001], [0x1f200, 0x1f251], [0x1f300, 0x1f64f],
|
|
25
|
+
[0x1f900, 0x1f9ff], [0x20000, 0x3fffd],
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
// 数値とみなす書き方(桁区切り・通貨記号・単位まで含めて右寄せの判定に使う)
|
|
29
|
+
const MT_NUM_RE = /^[+-]?[¥$€£]?\s*(\d+|\d{1,3}(,\d{3})+)(\.\d+)?\s*(%|%|円|px|pt|em|rem|kg|g|km|m)?$/;
|
|
30
|
+
|
|
31
|
+
/** その符号位置が占める桁数(結合文字と異体字セレクタは0桁) */
|
|
32
|
+
function mtCharWidth(cp) {
|
|
33
|
+
if (cp === 0x200b || cp === 0xfeff || cp === 0xfe0f || cp === 0xfe0e) return 0;
|
|
34
|
+
if (cp >= 0x0300 && cp <= 0x036f) return 0;
|
|
35
|
+
if (cp >= 0x200c && cp <= 0x200f) return 0;
|
|
36
|
+
for (const r of MT_WIDE_RANGES) {
|
|
37
|
+
if (cp >= r[0] && cp <= r[1]) return 2;
|
|
38
|
+
}
|
|
39
|
+
return 1;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 文字列の表示幅。eastAsian が真なら全角を2桁で数える。
|
|
44
|
+
* 偽のときは符号位置の数(サロゲートペアを2つと数えない)。
|
|
45
|
+
*/
|
|
46
|
+
export function mtWidth(s, eastAsian) {
|
|
47
|
+
const str = String(s === undefined || s === null ? '' : s);
|
|
48
|
+
let w = 0;
|
|
49
|
+
for (const ch of str) {
|
|
50
|
+
const cp = ch.codePointAt(0);
|
|
51
|
+
w += eastAsian ? mtCharWidth(cp) : (mtCharWidth(cp) === 0 ? 0 : 1);
|
|
52
|
+
}
|
|
53
|
+
return w;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 改行コードをLFへ揃え、先頭のBOMを落とす */
|
|
57
|
+
function mtNormalizeEol(text) {
|
|
58
|
+
return String(text === undefined || text === null ? '' : text).replace(/^/, '').replace(/\r\n?/g, '\n');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 区切り文字で1つの表に読む(RFC 4180 の引用符に対応)。
|
|
63
|
+
* "" は " 1文字、引用符の中の区切り文字・改行はセルの一部として扱う。
|
|
64
|
+
*/
|
|
65
|
+
export function mtParseDelimited(text, delim) {
|
|
66
|
+
const s = mtNormalizeEol(text);
|
|
67
|
+
const rows = [];
|
|
68
|
+
let row = [];
|
|
69
|
+
let cell = '';
|
|
70
|
+
let quoted = false;
|
|
71
|
+
let sawQuote = false;
|
|
72
|
+
let unterminated = false;
|
|
73
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
74
|
+
const ch = s[i];
|
|
75
|
+
if (quoted) {
|
|
76
|
+
if (ch === '"') {
|
|
77
|
+
if (s[i + 1] === '"') { cell += '"'; i += 1; continue; }
|
|
78
|
+
quoted = false;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
cell += ch;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (ch === '"' && cell === '') { quoted = true; sawQuote = true; continue; }
|
|
85
|
+
if (ch === delim) { row.push(cell); cell = ''; continue; }
|
|
86
|
+
if (ch === '\n') { row.push(cell); rows.push(row); row = []; cell = ''; continue; }
|
|
87
|
+
cell += ch;
|
|
88
|
+
}
|
|
89
|
+
if (quoted) unterminated = true;
|
|
90
|
+
row.push(cell);
|
|
91
|
+
rows.push(row);
|
|
92
|
+
// 末尾の空行(最後の改行の後ろ)は表の行として数えない
|
|
93
|
+
while (rows.length > 1 && rows[rows.length - 1].length === 1 && rows[rows.length - 1][0] === '') rows.pop();
|
|
94
|
+
return { rows, quoted: sawQuote, unterminated };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 区切り行(|---|:--:| など)か */
|
|
98
|
+
export function mtIsSeparatorRow(line) {
|
|
99
|
+
const t = String(line).trim();
|
|
100
|
+
if (!t || t.indexOf('-') === -1) return false;
|
|
101
|
+
return /^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?$/.test(t);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Markdownの1行をセルへ分ける(\| はセルの中の | として扱う) */
|
|
105
|
+
export function mtSplitMarkdownRow(line) {
|
|
106
|
+
let t = String(line).trim();
|
|
107
|
+
if (t.startsWith('|')) t = t.slice(1);
|
|
108
|
+
if (t.endsWith('|') && !t.endsWith('\\|')) t = t.slice(0, -1);
|
|
109
|
+
const cells = [];
|
|
110
|
+
let cur = '';
|
|
111
|
+
for (let i = 0; i < t.length; i += 1) {
|
|
112
|
+
const ch = t[i];
|
|
113
|
+
if (ch === '\\' && t[i + 1] === '|') { cur += '|'; i += 1; continue; }
|
|
114
|
+
if (ch === '|') { cells.push(cur); cur = ''; continue; }
|
|
115
|
+
cur += ch;
|
|
116
|
+
}
|
|
117
|
+
cells.push(cur);
|
|
118
|
+
return cells.map((c) => c.trim());
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** セル内の <br> を改行へ戻す(Markdown→CSV で1セル1行に復元するため) */
|
|
122
|
+
function mtUnbr(s) {
|
|
123
|
+
return String(s).replace(/<br\s*\/?>/gi, '\n');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Markdownの表を読む。区切り行のコロンから列ごとの配置も取る */
|
|
127
|
+
export function mtParseMarkdown(text) {
|
|
128
|
+
const lines = mtNormalizeEol(text).split('\n');
|
|
129
|
+
const rows = [];
|
|
130
|
+
let aligns = null;
|
|
131
|
+
let sepAt = -1;
|
|
132
|
+
for (const line of lines) {
|
|
133
|
+
if (line.trim() === '') continue;
|
|
134
|
+
if (aligns === null && rows.length > 0 && mtIsSeparatorRow(line)) {
|
|
135
|
+
aligns = mtSplitMarkdownRow(line).map((c) => {
|
|
136
|
+
const left = c.startsWith(':');
|
|
137
|
+
const right = c.endsWith(':');
|
|
138
|
+
if (left && right) return 'center';
|
|
139
|
+
if (right) return 'right';
|
|
140
|
+
if (left) return 'left';
|
|
141
|
+
return 'none';
|
|
142
|
+
});
|
|
143
|
+
sepAt = rows.length;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (line.indexOf('|') === -1) continue; // 表の外の行(見出しや本文)は捨てる
|
|
147
|
+
rows.push(mtSplitMarkdownRow(line).map(mtUnbr));
|
|
148
|
+
}
|
|
149
|
+
return { rows, aligns, separatorAt: sepAt };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 1行を区切り文字で割ったときの列数 */
|
|
153
|
+
function mtFieldCount(line, delim) {
|
|
154
|
+
return mtParseDelimited(line, delim).rows[0].length;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* 入力の形式を当てる。
|
|
159
|
+
* 区切り行のあるパイプ表ならMarkdown、それ以外はタブ→カンマ→セミコロンの順に
|
|
160
|
+
* 「同じ列数の行がいちばん揃うもの」を採る。
|
|
161
|
+
*/
|
|
162
|
+
export function mtDetect(text) {
|
|
163
|
+
const s = mtNormalizeEol(text);
|
|
164
|
+
const lines = s.split('\n').filter((l) => l.trim() !== '');
|
|
165
|
+
if (!lines.length) return { format: 'tsv', delimiter: '\t', columns: 0, confident: false };
|
|
166
|
+
const piped = lines.filter((l) => l.indexOf('|') !== -1).length;
|
|
167
|
+
if (piped >= 2 && lines.some(mtIsSeparatorRow)) {
|
|
168
|
+
return { format: 'markdown', delimiter: '|', columns: 0, confident: true };
|
|
169
|
+
}
|
|
170
|
+
const head = lines.slice(0, MT_DETECT_LINES);
|
|
171
|
+
let best = null;
|
|
172
|
+
for (const format of ['tsv', 'csv', 'ssv']) {
|
|
173
|
+
const delim = MT_DELIMS[format];
|
|
174
|
+
const counts = head.map((l) => mtFieldCount(l, delim));
|
|
175
|
+
const freq = new Map();
|
|
176
|
+
for (const c of counts) freq.set(c, (freq.get(c) || 0) + 1);
|
|
177
|
+
let columns = 1;
|
|
178
|
+
let hits = 0;
|
|
179
|
+
for (const [c, n] of freq) {
|
|
180
|
+
if (n > hits || (n === hits && c > columns)) { columns = c; hits = n; }
|
|
181
|
+
}
|
|
182
|
+
if (columns < 2) continue;
|
|
183
|
+
const score = hits / counts.length;
|
|
184
|
+
if (!best || score > best.score + 1e-9 || (Math.abs(score - best.score) < 1e-9 && columns > best.columns)) {
|
|
185
|
+
best = { format, delimiter: delim, columns, score, confident: true };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// 区切りが見つからないときは1列のTSVとして扱う(貼り直しの手掛かりは呼び出し側で出す)
|
|
189
|
+
return best || { format: 'tsv', delimiter: '\t', columns: 1, confident: false };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* 入力を2次元配列へ。format='auto' なら自動判定する。
|
|
194
|
+
* 返り値の source には判定結果(形式・区切り文字)が入る。
|
|
195
|
+
*/
|
|
196
|
+
export function mtParse(text, format) {
|
|
197
|
+
const want = MT_IN_FORMATS.indexOf(format) === -1 ? 'auto' : format;
|
|
198
|
+
const detected = mtDetect(text);
|
|
199
|
+
const use = want === 'auto' ? detected.format : want;
|
|
200
|
+
if (use === 'markdown') {
|
|
201
|
+
const md = mtParseMarkdown(text);
|
|
202
|
+
return {
|
|
203
|
+
rows: md.rows,
|
|
204
|
+
aligns: md.aligns,
|
|
205
|
+
source: { format: 'markdown', delimiter: '|', detected: want === 'auto', quoted: false, unterminated: false },
|
|
206
|
+
separatorAt: md.separatorAt,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
const r = mtParseDelimited(text, MT_DELIMS[use]);
|
|
210
|
+
return {
|
|
211
|
+
rows: r.rows,
|
|
212
|
+
aligns: null,
|
|
213
|
+
source: { format: use, delimiter: MT_DELIMS[use], detected: want === 'auto', quoted: r.quoted, unterminated: r.unterminated },
|
|
214
|
+
separatorAt: -1,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** 行と列を入れ替える */
|
|
219
|
+
export function mtTranspose(rows) {
|
|
220
|
+
const cols = rows.reduce((m, r) => Math.max(m, r.length), 0);
|
|
221
|
+
const out = [];
|
|
222
|
+
for (let c = 0; c < cols; c += 1) {
|
|
223
|
+
const row = [];
|
|
224
|
+
for (let r = 0; r < rows.length; r += 1) row.push(rows[r][c] === undefined ? '' : rows[r][c]);
|
|
225
|
+
out.push(row);
|
|
226
|
+
}
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* 表を長方形に整える(空行を捨て、短い行に空セルを足し、必要なら転置する)。
|
|
232
|
+
* ragged には列数が足りずに補った行の数が入る。
|
|
233
|
+
*/
|
|
234
|
+
export function mtNormalize(rows, opts) {
|
|
235
|
+
const o = opts || {};
|
|
236
|
+
let out = rows.map((r) => r.map((c) => {
|
|
237
|
+
const s = mtNormalizeEol(c);
|
|
238
|
+
return o.trim === false ? s : s.trim();
|
|
239
|
+
}));
|
|
240
|
+
if (o.skipEmpty !== false) out = out.filter((r) => r.some((c) => c !== ''));
|
|
241
|
+
const cols0 = out.reduce((m, r) => Math.max(m, r.length), 0);
|
|
242
|
+
let ragged = 0;
|
|
243
|
+
out = out.map((r) => {
|
|
244
|
+
if (r.length >= cols0) return r;
|
|
245
|
+
ragged += 1;
|
|
246
|
+
return r.concat(new Array(cols0 - r.length).fill(''));
|
|
247
|
+
});
|
|
248
|
+
if (o.transpose) out = mtTranspose(out);
|
|
249
|
+
const columns = out.reduce((m, r) => Math.max(m, r.length), 0);
|
|
250
|
+
return { rows: out, columns, ragged };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** 数値だけが並ぶ列か(右寄せの自動判定に使う) */
|
|
254
|
+
export function mtIsNumeric(s) {
|
|
255
|
+
const t = String(s).trim();
|
|
256
|
+
return t !== '' && MT_NUM_RE.test(t);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* 列ごとの配置を決める。指定のない('none')列だけ、数値列なら右寄せへ倒す。
|
|
261
|
+
* body には見出しを除いた行を渡す。
|
|
262
|
+
*/
|
|
263
|
+
export function mtAutoAligns(body, aligns, autoNumber) {
|
|
264
|
+
const out = aligns.slice();
|
|
265
|
+
if (!autoNumber) return out;
|
|
266
|
+
for (let c = 0; c < out.length; c += 1) {
|
|
267
|
+
if (out[c] !== 'none') continue;
|
|
268
|
+
let seen = 0;
|
|
269
|
+
let ok = true;
|
|
270
|
+
for (const row of body) {
|
|
271
|
+
const v = row[c] === undefined ? '' : row[c];
|
|
272
|
+
if (v === '') continue;
|
|
273
|
+
seen += 1;
|
|
274
|
+
if (!mtIsNumeric(v)) { ok = false; break; }
|
|
275
|
+
}
|
|
276
|
+
if (ok && seen > 0) out[c] = 'right';
|
|
277
|
+
}
|
|
278
|
+
return out;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Markdownのセルとして安全な1行の文字列にする */
|
|
282
|
+
function mtEscapeCell(s, opts) {
|
|
283
|
+
const o = opts || {};
|
|
284
|
+
let t = mtNormalizeEol(s);
|
|
285
|
+
if (o.escapePipes !== false) t = t.replace(/\|/g, '\\|');
|
|
286
|
+
t = t.replace(/\n/g, o.multiline === 'space' ? ' ' : '<br>');
|
|
287
|
+
return t;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** 表示幅 w まで、配置に合わせて空白を足す */
|
|
291
|
+
function mtPad(text, w, align, eastAsian) {
|
|
292
|
+
const pad = w - mtWidth(text, eastAsian);
|
|
293
|
+
if (pad <= 0) return text;
|
|
294
|
+
if (align === 'right') return ' '.repeat(pad) + text;
|
|
295
|
+
if (align === 'center') {
|
|
296
|
+
const l = Math.floor(pad / 2);
|
|
297
|
+
return ' '.repeat(l) + text + ' '.repeat(pad - l);
|
|
298
|
+
}
|
|
299
|
+
return text + ' '.repeat(pad);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** 区切り行の1セル(幅 w・配置 align)。w<=0 なら桁を揃えない短い形 */
|
|
303
|
+
function mtSeparatorCell(w, align) {
|
|
304
|
+
if (w <= 0) {
|
|
305
|
+
if (align === 'center') return ':' + '-'.repeat(MT_MIN_DASH) + ':';
|
|
306
|
+
if (align === 'right') return '-'.repeat(MT_MIN_DASH) + ':';
|
|
307
|
+
if (align === 'left') return ':' + '-'.repeat(MT_MIN_DASH);
|
|
308
|
+
return '-'.repeat(MT_MIN_DASH);
|
|
309
|
+
}
|
|
310
|
+
const width = Math.max(w, MT_MIN_DASH);
|
|
311
|
+
if (align === 'center') return ':' + '-'.repeat(width - 2) + ':';
|
|
312
|
+
if (align === 'right') return '-'.repeat(width - 1) + ':';
|
|
313
|
+
if (align === 'left') return ':' + '-'.repeat(width - 1);
|
|
314
|
+
return '-'.repeat(width);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Markdownの表を組み立てる。
|
|
319
|
+
* header は見出し行(配列)、body は残りの行。pad=true で桁を揃える。
|
|
320
|
+
*/
|
|
321
|
+
export function mtBuildMarkdown(header, body, aligns, opts) {
|
|
322
|
+
const o = opts || {};
|
|
323
|
+
const eastAsian = o.eastAsian !== false;
|
|
324
|
+
const cols = aligns.length;
|
|
325
|
+
const esc = (row) => {
|
|
326
|
+
const r = [];
|
|
327
|
+
for (let c = 0; c < cols; c += 1) r.push(mtEscapeCell(row[c] === undefined ? '' : row[c], o));
|
|
328
|
+
return r;
|
|
329
|
+
};
|
|
330
|
+
const head = esc(header);
|
|
331
|
+
const rows = body.map(esc);
|
|
332
|
+
const widths = [];
|
|
333
|
+
for (let c = 0; c < cols; c += 1) {
|
|
334
|
+
if (!o.pad) { widths.push(0); continue; }
|
|
335
|
+
let w = MT_MIN_DASH;
|
|
336
|
+
w = Math.max(w, mtWidth(head[c], eastAsian));
|
|
337
|
+
for (const r of rows) w = Math.max(w, mtWidth(r[c], eastAsian));
|
|
338
|
+
// コロンを2つ置く中央揃えは3桁だと線が1本になるので下限を上げる
|
|
339
|
+
if (aligns[c] === 'center') w = Math.max(w, MT_MIN_DASH + 2);
|
|
340
|
+
widths.push(w);
|
|
341
|
+
}
|
|
342
|
+
const line = (cells) => '| ' + cells.join(' | ') + ' |';
|
|
343
|
+
const out = [];
|
|
344
|
+
out.push(line(head.map((c, i) => (o.pad ? mtPad(c, widths[i], aligns[i], eastAsian) : c))));
|
|
345
|
+
out.push(line(aligns.map((a, i) => mtSeparatorCell(widths[i], a))));
|
|
346
|
+
for (const r of rows) {
|
|
347
|
+
out.push(line(r.map((c, i) => (o.pad ? mtPad(c, widths[i], aligns[i], eastAsian) : c))));
|
|
348
|
+
}
|
|
349
|
+
return out.join('\n') + '\n';
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** 区切り文字・引用符・改行を含むセルを引用符で囲む(RFC 4180) */
|
|
353
|
+
export function mtQuote(v, delim) {
|
|
354
|
+
const s = String(v === undefined || v === null ? '' : v);
|
|
355
|
+
if (s === '') return s;
|
|
356
|
+
if (s.indexOf(delim) !== -1 || s.indexOf('"') !== -1 || /[\n\r]/.test(s) || /^\s|\s$/.test(s)) {
|
|
357
|
+
return '"' + s.replace(/"/g, '""') + '"';
|
|
358
|
+
}
|
|
359
|
+
return s;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** CSV / TSV / セミコロン区切りを組み立てる */
|
|
363
|
+
export function mtBuildDelimited(rows, delim, eol) {
|
|
364
|
+
const nl = eol === 'crlf' ? '\r\n' : '\n';
|
|
365
|
+
return rows.map((r) => r.map((c) => mtQuote(c, delim)).join(delim)).join(nl) + nl;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** HTMLの特殊文字を実体参照へ */
|
|
369
|
+
function mtEscapeHtml(s) {
|
|
370
|
+
return String(s === undefined || s === null ? '' : s)
|
|
371
|
+
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** <table> を組み立てる(見出しが空の配列なら thead を出さない) */
|
|
375
|
+
export function mtBuildHtml(header, body, aligns, opts) {
|
|
376
|
+
const o = opts || {};
|
|
377
|
+
const cell = (tag, v, align) => {
|
|
378
|
+
const style = align && align !== 'none' ? ` style="text-align:${align}"` : '';
|
|
379
|
+
const text = mtEscapeHtml(v).replace(/\n/g, '<br>');
|
|
380
|
+
return ` <${tag}${style}>${text}</${tag}>`;
|
|
381
|
+
};
|
|
382
|
+
const out = ['<table>'];
|
|
383
|
+
if (header && header.length) {
|
|
384
|
+
out.push(' <thead>', ' <tr>');
|
|
385
|
+
for (let c = 0; c < aligns.length; c += 1) out.push(cell('th', header[c], aligns[c]));
|
|
386
|
+
out.push(' </tr>', ' </thead>');
|
|
387
|
+
}
|
|
388
|
+
out.push(' <tbody>');
|
|
389
|
+
for (const row of body) {
|
|
390
|
+
out.push(' <tr>');
|
|
391
|
+
for (let c = 0; c < aligns.length; c += 1) out.push(cell('td', row[c], aligns[c]));
|
|
392
|
+
out.push(' </tr>');
|
|
393
|
+
}
|
|
394
|
+
out.push(' </tbody>', '</table>');
|
|
395
|
+
return out.join('\n') + (o.eol === 'crlf' ? '\r\n' : '\n');
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** JSON(見出しがあればオブジェクトの配列・無ければ配列の配列) */
|
|
399
|
+
export function mtBuildJson(header, body, useHeader) {
|
|
400
|
+
if (!useHeader) return JSON.stringify(body, null, 2) + '\n';
|
|
401
|
+
const keys = [];
|
|
402
|
+
const seen = new Map();
|
|
403
|
+
for (let c = 0; c < header.length; c += 1) {
|
|
404
|
+
let k = String(header[c] === undefined ? '' : header[c]).trim() || 'col' + (c + 1);
|
|
405
|
+
if (seen.has(k)) {
|
|
406
|
+
const n = seen.get(k) + 1;
|
|
407
|
+
seen.set(k, n);
|
|
408
|
+
k = k + '_' + n;
|
|
409
|
+
} else {
|
|
410
|
+
seen.set(k, 1);
|
|
411
|
+
}
|
|
412
|
+
keys.push(k);
|
|
413
|
+
}
|
|
414
|
+
const out = body.map((row) => {
|
|
415
|
+
const o = {};
|
|
416
|
+
for (let c = 0; c < keys.length; c += 1) o[keys[c]] = row[c] === undefined ? '' : row[c];
|
|
417
|
+
return o;
|
|
418
|
+
});
|
|
419
|
+
return JSON.stringify(out, null, 2) + '\n';
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/* ==================== ここまで変換コア ==================== */
|
|
423
|
+
|
|
424
|
+
export class MarkdownTableError extends Error {}
|
|
425
|
+
|
|
426
|
+
// 指摘の文面(site側は同じ code を日英の T テーブルで出し分けている)
|
|
427
|
+
const NOTE_TEXT = {
|
|
428
|
+
DETECTED: (p) => `${p.format}として読みました(1行あたり ${p.columns} 列)。`,
|
|
429
|
+
NO_DELIMITER: () => 'タブ・カンマ・セミコロンのいずれも見つからず、1行が1セルになりました。別の区切り文字なら from で指定してください。',
|
|
430
|
+
RAGGED: (p) => `セルの数が足りない行が ${p.count} 行ありました。いちばん長い行に合わせて ${p.columns} 列になるよう空セルを補いました。`,
|
|
431
|
+
QUOTED: () => '引用符で囲まれたセルを外して読みました("" は " 1文字として扱っています)。',
|
|
432
|
+
UNTERMINATED: () => '引用符が閉じられていません。以降をすべて1つのセルとして読みました(元データに余分な " が無いか確かめてください)。',
|
|
433
|
+
NO_HEADER_MD: () => '元のMarkdownに区切り行(|---|)が無かったので、1行目を見出しとして読みました。',
|
|
434
|
+
PIPES: (p) => `セルの中の「|」を ${p.count} 個エスケープしました(\\| =表が壊れないようにするため)。`,
|
|
435
|
+
NEWLINES: (p) => `セルの中の改行を ${p.count} 個 ${p.how} に置き換えました。Markdownの表はセル内に生の改行を書けません。`,
|
|
436
|
+
WIDE: () => '全角文字を2桁として数えて桁を揃えました。等幅フォントでは縦線が揃います(プロポーショナルフォントでは揃いません)。',
|
|
437
|
+
WIDE_OFF: () => '全角文字がありますが1桁として数えています。等幅フォントでは縦線が揃わないので eastAsian=true を指定してください。',
|
|
438
|
+
NUMERIC: (p) => `数値だけが並ぶ列を ${p.count} 列見つけたので右寄せ(---:)にしました。`,
|
|
439
|
+
HTML_IN_CELL: (p) => `HTMLタグを含むセルが ${p.count} 個あります。GFMではタグとして解釈されます。`,
|
|
440
|
+
EMPTY_HEADER: (p) => `見出しのセルが ${p.count} 個空です。GFMの表は見出し行を省けないため、空のまま残しています。`,
|
|
441
|
+
DUP_HEADER: (p) => `見出しが重複しています: ${p.items.join(' / ')}。表としては成立しますが、後から列を指す手がかりが無くなります。`,
|
|
442
|
+
ONE_ROW: () => '行が1つしかないため、見出しだけの表になりました。',
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
const mtNote = (code, params) => ({ code, message: NOTE_TEXT[code] ? NOTE_TEXT[code](params || {}) : code });
|
|
446
|
+
|
|
447
|
+
const FORMAT_TEXT = {
|
|
448
|
+
tsv: 'TSV(タブ区切り)',
|
|
449
|
+
csv: 'CSV(カンマ区切り)',
|
|
450
|
+
ssv: 'セミコロン区切り',
|
|
451
|
+
markdown: 'Markdownの表',
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* TSV / CSV / Markdown の表を読み取り、Markdown・CSV・TSV・HTML・JSON へ変換する。
|
|
456
|
+
*
|
|
457
|
+
* @param {object} opts
|
|
458
|
+
* @param {string} [opts.text] 対象テキスト(path と排他)
|
|
459
|
+
* @param {string} [opts.path] 対象ファイルの絶対パス(UTF-8として読む)
|
|
460
|
+
* @param {string} [opts.outputPath] 結果を書き出す絶対パス(指定すると text は返さない)
|
|
461
|
+
* @param {'auto'|'tsv'|'csv'|'ssv'|'markdown'} [opts.from='auto'] 入力の形式
|
|
462
|
+
* @param {'markdown'|'csv'|'tsv'|'ssv'|'html'|'json'} [opts.to='markdown'] 出力の形式
|
|
463
|
+
* @param {'first'|'auto'|'none'} [opts.header='first'] 1行目の扱い
|
|
464
|
+
* @param {'auto'|'none'|'left'|'center'|'right'} [opts.align='auto'] 全列の配置
|
|
465
|
+
* @param {string[]} [opts.aligns] 列ごとの配置(align より優先)
|
|
466
|
+
* @param {boolean} [opts.pad=true] 桁を揃えるか(Markdown出力のみ)
|
|
467
|
+
* @param {boolean} [opts.eastAsian=true] 全角を2桁として数えるか
|
|
468
|
+
* @param {boolean} [opts.autoNumber=true] 数値だけの列を右寄せにするか
|
|
469
|
+
* @param {boolean} [opts.trim=true] セルの前後の空白を削るか
|
|
470
|
+
* @param {boolean} [opts.skipEmpty=true] 空行を飛ばすか
|
|
471
|
+
* @param {boolean} [opts.transpose=false] 行と列を入れ替えるか
|
|
472
|
+
* @param {'br'|'space'} [opts.multiline='br'] セル内の改行の書き方
|
|
473
|
+
* @param {'lf'|'crlf'} [opts.eol='lf'] 出力の改行コード
|
|
474
|
+
*/
|
|
475
|
+
export async function markdownTable(opts = {}) {
|
|
476
|
+
const hasText = typeof opts.text === 'string';
|
|
477
|
+
if (hasText === Boolean(opts.path)) throw new MarkdownTableError('text か path のどちらか一方を渡してください');
|
|
478
|
+
|
|
479
|
+
const from = opts.from === undefined || opts.from === null ? 'auto' : String(opts.from);
|
|
480
|
+
if (MT_IN_FORMATS.indexOf(from) === -1) throw new MarkdownTableError(`from は ${MT_IN_FORMATS.join(' / ')} のいずれか: ${opts.from}`);
|
|
481
|
+
const to = opts.to === undefined || opts.to === null ? 'markdown' : String(opts.to);
|
|
482
|
+
if (MT_OUT_FORMATS.indexOf(to) === -1) throw new MarkdownTableError(`to は ${MT_OUT_FORMATS.join(' / ')} のいずれか: ${opts.to}`);
|
|
483
|
+
const headerMode = opts.header === undefined || opts.header === null ? 'first' : String(opts.header);
|
|
484
|
+
if (MT_HEADER_MODES.indexOf(headerMode) === -1) throw new MarkdownTableError(`header は ${MT_HEADER_MODES.join(' / ')} のいずれか: ${opts.header}`);
|
|
485
|
+
const align = opts.align === undefined || opts.align === null ? 'auto' : String(opts.align);
|
|
486
|
+
if (MT_ALIGNS.concat(['auto']).indexOf(align) === -1) throw new MarkdownTableError(`align は auto / ${MT_ALIGNS.join(' / ')} のいずれか: ${opts.align}`);
|
|
487
|
+
if (opts.aligns !== undefined && !Array.isArray(opts.aligns)) throw new MarkdownTableError('aligns は配置の配列で渡してください');
|
|
488
|
+
if (Array.isArray(opts.aligns)) {
|
|
489
|
+
for (const a of opts.aligns) {
|
|
490
|
+
if (a !== '' && a !== null && a !== undefined && MT_ALIGNS.indexOf(String(a)) === -1) {
|
|
491
|
+
throw new MarkdownTableError(`aligns の要素は ${MT_ALIGNS.join(' / ')} のいずれか: ${a}`);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const input = hasText ? opts.text : await readFile(opts.path, 'utf8');
|
|
497
|
+
const pad = opts.pad !== false;
|
|
498
|
+
const eastAsian = opts.eastAsian !== false;
|
|
499
|
+
const autoNumber = opts.autoNumber !== false;
|
|
500
|
+
const multiline = opts.multiline === 'space' ? 'space' : 'br';
|
|
501
|
+
const eol = opts.eol === 'crlf' ? 'crlf' : 'lf';
|
|
502
|
+
|
|
503
|
+
const parsed = mtParse(input, from);
|
|
504
|
+
const norm = mtNormalize(parsed.rows, {
|
|
505
|
+
trim: opts.trim !== false,
|
|
506
|
+
skipEmpty: opts.skipEmpty !== false,
|
|
507
|
+
transpose: opts.transpose === true,
|
|
508
|
+
});
|
|
509
|
+
const rows = norm.rows;
|
|
510
|
+
const columns = norm.columns;
|
|
511
|
+
if (!rows.length || columns === 0) throw new MarkdownTableError('表として読める行がありませんでした(入力が空です)');
|
|
512
|
+
|
|
513
|
+
const useHeader = headerMode !== 'none';
|
|
514
|
+
let header;
|
|
515
|
+
let body;
|
|
516
|
+
if (headerMode === 'first') {
|
|
517
|
+
header = rows[0];
|
|
518
|
+
body = rows.slice(1);
|
|
519
|
+
} else if (headerMode === 'auto') {
|
|
520
|
+
header = [];
|
|
521
|
+
for (let c = 0; c < columns; c += 1) header.push('col' + (c + 1));
|
|
522
|
+
body = rows;
|
|
523
|
+
} else {
|
|
524
|
+
header = new Array(columns).fill('');
|
|
525
|
+
body = rows;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// 配置: 元のMarkdownの指定 → align → aligns(列ごと)→ 数値列の自動右寄せ
|
|
529
|
+
let aligns = new Array(columns).fill(align === 'auto' ? 'none' : align);
|
|
530
|
+
if (align === 'auto' && parsed.aligns && opts.transpose !== true) {
|
|
531
|
+
for (let c = 0; c < columns; c += 1) {
|
|
532
|
+
if (parsed.aligns[c]) aligns[c] = parsed.aligns[c];
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
const beforeAuto = aligns.slice();
|
|
536
|
+
aligns = mtAutoAligns(body, aligns, autoNumber);
|
|
537
|
+
let numericCols = 0;
|
|
538
|
+
for (let c = 0; c < columns; c += 1) if (aligns[c] !== beforeAuto[c]) numericCols += 1;
|
|
539
|
+
if (Array.isArray(opts.aligns)) {
|
|
540
|
+
for (let c = 0; c < columns; c += 1) {
|
|
541
|
+
const a = opts.aligns[c];
|
|
542
|
+
if (a) aligns[c] = String(a);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const buildOpts = { pad, eastAsian, multiline, escapePipes: true };
|
|
547
|
+
let text = '';
|
|
548
|
+
if (to === 'markdown') {
|
|
549
|
+
text = mtBuildMarkdown(header, body, aligns, buildOpts);
|
|
550
|
+
} else if (to === 'html') {
|
|
551
|
+
text = mtBuildHtml(useHeader ? header : null, body, aligns, {});
|
|
552
|
+
} else if (to === 'json') {
|
|
553
|
+
text = mtBuildJson(header, body, useHeader);
|
|
554
|
+
} else {
|
|
555
|
+
// 区切り形式はセル内の改行を引用符の中にそのまま持つので、改行コードは組み立て側で決める
|
|
556
|
+
const all = useHeader ? [header].concat(body) : body;
|
|
557
|
+
text = mtBuildDelimited(all, MT_DELIMS[to], eol);
|
|
558
|
+
}
|
|
559
|
+
// Markdown / HTML / JSON はセル内に生の改行を残さないため、まとめて置換して構わない
|
|
560
|
+
if (eol === 'crlf' && to !== 'csv' && to !== 'tsv' && to !== 'ssv') text = text.replace(/\n/g, '\r\n');
|
|
561
|
+
|
|
562
|
+
/* ---- 指摘 ---- */
|
|
563
|
+
const notes = [];
|
|
564
|
+
if (parsed.source.detected) {
|
|
565
|
+
if (parsed.source.format !== 'markdown' && columns === 1 && opts.transpose !== true) {
|
|
566
|
+
notes.push(mtNote('NO_DELIMITER'));
|
|
567
|
+
} else {
|
|
568
|
+
notes.push(mtNote('DETECTED', { format: FORMAT_TEXT[parsed.source.format], columns }));
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (parsed.source.unterminated) notes.push(mtNote('UNTERMINATED'));
|
|
572
|
+
if (parsed.source.quoted) notes.push(mtNote('QUOTED'));
|
|
573
|
+
if (parsed.source.format === 'markdown' && parsed.separatorAt === -1) notes.push(mtNote('NO_HEADER_MD'));
|
|
574
|
+
if (norm.ragged) notes.push(mtNote('RAGGED', { count: norm.ragged, columns }));
|
|
575
|
+
|
|
576
|
+
let pipes = 0;
|
|
577
|
+
let breaks = 0;
|
|
578
|
+
let wide = false;
|
|
579
|
+
let htmlCells = 0;
|
|
580
|
+
for (const row of rows) {
|
|
581
|
+
for (const cell of row) {
|
|
582
|
+
if (cell.indexOf('|') !== -1) pipes += 1;
|
|
583
|
+
if (cell.indexOf('\n') !== -1) breaks += 1;
|
|
584
|
+
if (!wide && mtWidth(cell, true) !== mtWidth(cell, false)) wide = true;
|
|
585
|
+
if (/<[a-z][^>]*>/i.test(cell)) htmlCells += 1;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (to === 'markdown') {
|
|
589
|
+
if (pipes) notes.push(mtNote('PIPES', { count: pipes }));
|
|
590
|
+
if (breaks) notes.push(mtNote('NEWLINES', { count: breaks, how: multiline === 'br' ? '<br>' : '半角スペース' }));
|
|
591
|
+
if (numericCols) notes.push(mtNote('NUMERIC', { count: numericCols }));
|
|
592
|
+
if (wide && pad) notes.push(mtNote(eastAsian ? 'WIDE' : 'WIDE_OFF'));
|
|
593
|
+
if (htmlCells) notes.push(mtNote('HTML_IN_CELL', { count: htmlCells }));
|
|
594
|
+
}
|
|
595
|
+
if (headerMode === 'first') {
|
|
596
|
+
const empties = header.filter((h) => String(h).trim() === '').length;
|
|
597
|
+
if (empties) notes.push(mtNote('EMPTY_HEADER', { count: empties }));
|
|
598
|
+
const seen = new Map();
|
|
599
|
+
const dups = [];
|
|
600
|
+
for (const h of header) {
|
|
601
|
+
const k = String(h).trim();
|
|
602
|
+
if (!k) continue;
|
|
603
|
+
if (seen.has(k)) { if (dups.indexOf(k) === -1) dups.push(k); } else seen.set(k, 1);
|
|
604
|
+
}
|
|
605
|
+
if (dups.length) notes.push(mtNote('DUP_HEADER', { items: dups }));
|
|
606
|
+
if (!body.length) notes.push(mtNote('ONE_ROW'));
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const result = {
|
|
610
|
+
format: to,
|
|
611
|
+
source: Object.assign(
|
|
612
|
+
hasText ? { type: 'text' } : { path: opts.path, name: basename(opts.path) },
|
|
613
|
+
{ format: parsed.source.format, delimiter: parsed.source.delimiter, detected: parsed.source.detected },
|
|
614
|
+
),
|
|
615
|
+
text,
|
|
616
|
+
rows: rows.length,
|
|
617
|
+
columns,
|
|
618
|
+
cells: rows.length * columns,
|
|
619
|
+
body_rows: body.length,
|
|
620
|
+
header: useHeader ? header : null,
|
|
621
|
+
aligns,
|
|
622
|
+
options: {
|
|
623
|
+
header: headerMode,
|
|
624
|
+
align,
|
|
625
|
+
pad,
|
|
626
|
+
east_asian: eastAsian,
|
|
627
|
+
auto_number: autoNumber,
|
|
628
|
+
transpose: opts.transpose === true,
|
|
629
|
+
multiline,
|
|
630
|
+
eol,
|
|
631
|
+
},
|
|
632
|
+
notes,
|
|
633
|
+
};
|
|
634
|
+
if (opts.outputPath) {
|
|
635
|
+
await writeFile(opts.outputPath, text, 'utf8');
|
|
636
|
+
result.output = opts.outputPath;
|
|
637
|
+
// ファイルに書けたなら本文は重複した重い情報でしかない
|
|
638
|
+
delete result.text;
|
|
639
|
+
}
|
|
640
|
+
return result;
|
|
641
|
+
}
|