@first-ch/tools-mcp 0.4.1 → 0.24.1

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/uuid.mjs ADDED
@@ -0,0 +1,238 @@
1
+ // UUID v4 / ULID の一括生成
2
+ // (tools.first-ch.com/uuid/ と同一の仕様)
3
+ //
4
+ // 生成のコア(randomBytes / uuidV4FromBytes / encodeUlidTime / encodeUlidRandom /
5
+ // bumpUlidRandom / generateIds / formatIds / decodeUlid)は site 側(site/uuid/app.js)と
6
+ // 対になっている。2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
7
+ //
8
+ // 乱数は node:crypto の randomBytes(CSPRNG)のみを使う。Math.random は使わない。
9
+ // ULIDは同一ミリ秒内で単調増加させる(乱数部を+1する)。これをしないと、一括生成した分が
10
+ // 「同じ時刻の中で順不同」になり、ULIDの売りである辞書順=生成順が崩れる。
11
+ import { randomBytes as nodeRandomBytes } from 'node:crypto';
12
+
13
+ export class UuidError extends Error {}
14
+
15
+ /** Crockford's Base32。紛らわしい I / L / O / U を除いた32文字(ULIDの表記に使う) */
16
+ const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
17
+ export const MAX_COUNT = 100;
18
+ const TIME_LEN = 10; // ULIDのタイムスタンプ部(48bit)
19
+ const RAND_LEN = 16; // ULIDのランダム部(80bit)
20
+ const MAX_TIME = 281474976710655; // 2^48 - 1
21
+
22
+ /** 暗号論的乱数をnバイト返す(site側は crypto.getRandomValues) */
23
+ function randomBytes(n) {
24
+ return nodeRandomBytes(n);
25
+ }
26
+
27
+ const HEX = [];
28
+ for (let i = 0; i < 256; i += 1) HEX.push((i + 0x100).toString(16).slice(1));
29
+
30
+ /**
31
+ * 16バイトの乱数を RFC 9562 の UUID v4 にする。
32
+ * 7バイト目の上位4bitをバージョン(0100 = 4)、9バイト目の上位2bitをバリアント(10)に固定する。
33
+ * 残りの122bitが乱数。
34
+ */
35
+ export function uuidV4FromBytes(bytes) {
36
+ const b = Uint8Array.from(bytes);
37
+ b[6] = (b[6] & 0x0f) | 0x40;
38
+ b[8] = (b[8] & 0x3f) | 0x80;
39
+ const h = HEX;
40
+ return (
41
+ h[b[0]] + h[b[1]] + h[b[2]] + h[b[3]] + '-' +
42
+ h[b[4]] + h[b[5]] + '-' +
43
+ h[b[6]] + h[b[7]] + '-' +
44
+ h[b[8]] + h[b[9]] + '-' +
45
+ h[b[10]] + h[b[11]] + h[b[12]] + h[b[13]] + h[b[14]] + h[b[15]]
46
+ );
47
+ }
48
+
49
+ /** ミリ秒(UNIX時間)を Crockford Base32 の10文字にする */
50
+ export function encodeUlidTime(ms) {
51
+ let t = Math.floor(ms);
52
+ if (!Number.isFinite(t) || t < 0 || t > MAX_TIME) throw new UuidError('ULIDに入れられる時刻の範囲外です(0 〜 2^48-1 ミリ秒)');
53
+ let out = '';
54
+ for (let i = 0; i < TIME_LEN; i += 1) {
55
+ const mod = t % 32;
56
+ out = CROCKFORD[mod] + out;
57
+ t = (t - mod) / 32;
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /** 80bitの乱数を Crockford Base32 の16文字にする */
63
+ export function encodeUlidRandom(bytes) {
64
+ let out = '';
65
+ // 256 は 32 の倍数なので、バイトの下位5bitを取っても分布は偏らない
66
+ for (let i = 0; i < RAND_LEN; i += 1) out += CROCKFORD[bytes[i] & 0x1f];
67
+ return out;
68
+ }
69
+
70
+ /**
71
+ * ULIDのランダム部を1つ進める(単調増加)。同じミリ秒内に複数生成するときに使う。
72
+ * 末尾から桁上がりさせ、16文字すべてが 'Z' なら null(そのミリ秒では作り切った)。
73
+ */
74
+ export function bumpUlidRandom(rand) {
75
+ const chars = rand.split('');
76
+ for (let i = chars.length - 1; i >= 0; i -= 1) {
77
+ const idx = CROCKFORD.indexOf(chars[i]);
78
+ if (idx < CROCKFORD.length - 1) {
79
+ chars[i] = CROCKFORD[idx + 1];
80
+ return chars.join('');
81
+ }
82
+ chars[i] = CROCKFORD[0];
83
+ }
84
+ return null;
85
+ }
86
+
87
+ /** ULIDの先頭10文字から生成時刻(ミリ秒)を読む。26文字でなければ null */
88
+ export function decodeUlid(id) {
89
+ const s = String(id == null ? '' : id).trim().toUpperCase();
90
+ if (s.length !== TIME_LEN + RAND_LEN) return null;
91
+ let ms = 0;
92
+ for (let i = 0; i < TIME_LEN; i += 1) {
93
+ const idx = CROCKFORD.indexOf(s[i]);
94
+ if (idx === -1) return null;
95
+ ms = ms * 32 + idx;
96
+ }
97
+ for (let i = TIME_LEN; i < s.length; i += 1) {
98
+ if (CROCKFORD.indexOf(s[i]) === -1) return null;
99
+ }
100
+ return { time: ms, timePart: s.slice(0, TIME_LEN), randomPart: s.slice(TIME_LEN) };
101
+ }
102
+
103
+ /**
104
+ * IDをcount件生成する。
105
+ * @param {{type?: string, count?: number, time?: number, rand?: (n: number) => Uint8Array}} opts
106
+ * @returns {{type: string, count: number, ids: string[], time: number}}
107
+ */
108
+ export function generateIds(opts) {
109
+ const o = opts || {};
110
+ const type = o.type === 'ulid' ? 'ulid' : 'uuid';
111
+ const count = Math.min(Math.max(Math.floor(Number(o.count) || 1), 1), MAX_COUNT);
112
+ const rand = o.rand || randomBytes;
113
+ const time = o.time === undefined || o.time === null ? Date.now() : Math.floor(Number(o.time));
114
+ const ids = [];
115
+ if (type === 'uuid') {
116
+ // 1件ずつ乱数を取るより、まとめて取ったほうが速い(100件でも16KB未満)
117
+ const bulk = rand(16 * count);
118
+ for (let i = 0; i < count; i += 1) ids.push(uuidV4FromBytes(bulk.subarray(i * 16, i * 16 + 16)));
119
+ return { type, count, ids, time };
120
+ }
121
+ const timePart = encodeUlidTime(time);
122
+ let randomPart = encodeUlidRandom(rand(RAND_LEN));
123
+ ids.push(timePart + randomPart);
124
+ for (let i = 1; i < count; i += 1) {
125
+ // 同じミリ秒なので乱数部を+1する(辞書順=生成順を保つ)
126
+ const next = bumpUlidRandom(randomPart);
127
+ randomPart = next === null ? encodeUlidRandom(rand(RAND_LEN)) : next;
128
+ ids.push(timePart + randomPart);
129
+ }
130
+ return { type, count, ids, time };
131
+ }
132
+
133
+ export const FORMATS = ['plain', 'json', 'csv', 'quoted'];
134
+
135
+ /**
136
+ * 生成したIDを表記オプションと出力形式に合わせて1つの文字列にする。
137
+ * @param {string[]} ids
138
+ * @param {{format?: string, uppercase?: boolean, hyphens?: boolean, braces?: boolean, type?: string}} opts
139
+ */
140
+ export function formatIds(ids, opts) {
141
+ const o = opts || {};
142
+ const type = o.type === 'ulid' ? 'ulid' : 'uuid';
143
+ const format = FORMATS.indexOf(o.format) === -1 ? 'plain' : o.format;
144
+ // UUIDの既定は小文字(RFC 9562)、ULIDの既定は大文字(Crockford Base32)
145
+ const upper = o.uppercase === undefined ? type === 'ulid' : !!o.uppercase;
146
+ const list = ids.map((id) => {
147
+ let s = upper ? id.toUpperCase() : id.toLowerCase();
148
+ if (type === 'uuid') {
149
+ if (o.hyphens === false) s = s.replace(/-/g, '');
150
+ if (o.braces) s = '{' + s + '}';
151
+ }
152
+ return s;
153
+ });
154
+ if (format === 'json') return JSON.stringify(list, null, 2);
155
+ if (format === 'csv') return list.join(',');
156
+ if (format === 'quoted') return list.map((s) => '"' + s + '"').join(',\n');
157
+ return list.join('\n');
158
+ }
159
+
160
+ /* ==================== MCPツールの入口 ==================== */
161
+
162
+ /** ISO8601文字列・ミリ秒の数値・秒の数値のいずれでも受け取れるようにする */
163
+ function parseTime(value) {
164
+ if (value === undefined || value === null || value === '') return Date.now();
165
+ if (typeof value === 'number') {
166
+ if (!Number.isFinite(value)) throw new UuidError('timestamp が数値として読めません');
167
+ // 10桁までなら秒とみなす(JWTなどの慣習に合わせる)
168
+ return value < 1e11 ? Math.floor(value * 1000) : Math.floor(value);
169
+ }
170
+ const s = String(value).trim();
171
+ if (/^\d+$/.test(s)) return parseTime(Number(s));
172
+ const ms = Date.parse(s);
173
+ if (Number.isNaN(ms)) throw new UuidError(`timestamp を日時として読めません: ${s}`);
174
+ return ms;
175
+ }
176
+
177
+ /**
178
+ * uuid_generate ツール本体。
179
+ * @param {{type?: string, count?: number, format?: string, uppercase?: boolean,
180
+ * hyphens?: boolean, braces?: boolean, timestamp?: string|number}} opts
181
+ */
182
+ export function uuidGenerate(opts = {}) {
183
+ const rawType = String(opts.type == null ? 'uuid' : opts.type).trim().toLowerCase();
184
+ const type = rawType === 'ulid' ? 'ulid'
185
+ : (rawType === '' || rawType === 'uuid' || rawType === 'uuid4' || rawType === 'v4' || rawType === 'uuid_v4') ? 'uuid'
186
+ : null;
187
+ if (type === null) throw new UuidError(`type は uuid か ulid を指定してください(受け取った値: ${opts.type})`);
188
+
189
+ const rawCount = opts.count === undefined || opts.count === null ? 1 : Number(opts.count);
190
+ if (!Number.isFinite(rawCount) || Math.floor(rawCount) !== rawCount) throw new UuidError('count は整数で指定してください');
191
+ if (rawCount < 1 || rawCount > MAX_COUNT) throw new UuidError(`count は 1〜${MAX_COUNT} で指定してください(受け取った値: ${opts.count})`);
192
+
193
+ const format = opts.format === undefined || opts.format === null || opts.format === '' ? 'plain' : String(opts.format);
194
+ if (FORMATS.indexOf(format) === -1) throw new UuidError(`format は ${FORMATS.join(' / ')} のいずれかを指定してください(受け取った値: ${opts.format})`);
195
+
196
+ if (opts.timestamp !== undefined && opts.timestamp !== null && type !== 'ulid') {
197
+ throw new UuidError('timestamp は ULID のときだけ指定できます(UUID v4 に時刻は入りません)');
198
+ }
199
+ const time = type === 'ulid' ? parseTime(opts.timestamp) : Date.now();
200
+
201
+ const res = generateIds({ type, count: rawCount, time });
202
+ const fmtOpts = {
203
+ type,
204
+ format,
205
+ uppercase: opts.uppercase,
206
+ hyphens: opts.hyphens,
207
+ braces: opts.braces,
208
+ };
209
+ const text = formatIds(res.ids, fmtOpts);
210
+ const ids = formatIds(res.ids, Object.assign({}, fmtOpts, { format: 'plain' })).split('\n');
211
+
212
+ const out = {
213
+ type,
214
+ count: res.count,
215
+ format,
216
+ ids,
217
+ text,
218
+ length: ids[0].length,
219
+ duplicates: res.count - new Set(ids).size,
220
+ local_only: true,
221
+ };
222
+ if (type === 'ulid') {
223
+ const d = decodeUlid(res.ids[0]);
224
+ out.timestamp = {
225
+ unix_ms: d.time,
226
+ iso: new Date(d.time).toISOString(),
227
+ encoded: d.timePart,
228
+ };
229
+ out.monotonic = true;
230
+ out.note = '同一ミリ秒内はランダム部を+1して単調増加させているため、辞書順が生成順と一致します。';
231
+ } else {
232
+ out.version = 4;
233
+ out.variant = 'RFC 9562 (10xx)';
234
+ out.random_bits = 122;
235
+ out.note = '乱数は node:crypto の randomBytes(CSPRNG)です。Math.random は使いません。';
236
+ }
237
+ return out;
238
+ }