@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/px-rem.mjs ADDED
@@ -0,0 +1,488 @@
1
+ // px ⇄ rem / em 単位変換&フォントスケール表(tools.first-ch.com/px-rem/ と同一ロジック)
2
+ //
3
+ // 「変換コア」ブロックは site 側の site/px-rem/app.js と同一の実装。
4
+ // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
+ // 使っているのは Number/String/RegExp だけなので、ブラウザ版のコードをそのまま持ってこられる。
6
+ import { readFile, writeFile } from 'node:fs/promises';
7
+ import { basename } from 'node:path';
8
+
9
+ /* ==================== ここから変換コア(site / MCP で同一) ==================== */
10
+
11
+ export const PR_DEFAULT_ROOT = 16; // ブラウザ既定のルートフォントサイズ
12
+ const PR_MAX_DECIMALS = 6; // 表示・丸めに使う小数の上限(rem は 1/16 刻みなので4桁あれば割り切れる)
13
+ const PR_MAX_SIZE = 1000; // 基準サイズとして受け付ける上限 px
14
+
15
+ // スケール表に並べる標準サイズ(12〜64px)。用途ラベルは表示側で日英に訳す
16
+ export const PR_SCALE_SIZES = [12, 13, 14, 15, 16, 18, 20, 24, 28, 32, 36, 40, 48, 56, 64];
17
+ const PR_SCALE_ROLE = {
18
+ 12: 'CAPTION', 13: 'FINE', 14: 'SMALL', 15: 'BODY_SM', 16: 'BODY', 18: 'BODY_LG',
19
+ 20: 'H4', 24: 'H3', 28: 'H2_SP', 32: 'H2', 36: 'H1_SP', 40: 'H1',
20
+ 48: 'TITLE', 56: 'HERO', 64: 'HERO_LG',
21
+ };
22
+
23
+ // CSS一括変換の向き。base は換算の基準(root=ルート / parent=親要素)
24
+ export const PR_CSS_DIRECTIONS = {
25
+ px2rem: { from: 'px', to: 'rem', base: 'root' },
26
+ px2em: { from: 'px', to: 'em', base: 'parent' },
27
+ rem2px: { from: 'rem', to: 'px', base: 'root' },
28
+ em2px: { from: 'em', to: 'px', base: 'parent' },
29
+ };
30
+
31
+ const PR_PT_PER_PX = 72 / 96; // CSSの1ptは1/72インチ・1pxは1/96インチ
32
+
33
+ /** 基準サイズとして使える正の数へ寄せる(不正なら fallback) */
34
+ export function prSize(v, fallback) {
35
+ const n = typeof v === 'string' ? Number(String(v).trim()) : Number(v);
36
+ if (!Number.isFinite(n) || n <= 0 || n > PR_MAX_SIZE) return fallback;
37
+ return n;
38
+ }
39
+
40
+ /**
41
+ * 指定桁で四捨五入する。
42
+ * 8.325 * 100 が 832.4999… になるような二進浮動小数の誤差で1桁ずれないよう、
43
+ * 絶対値に比例した微小量を足してから丸める(負数は0から遠い側へ寄せる)。
44
+ */
45
+ export function prRound(n, decimals) {
46
+ if (!Number.isFinite(n)) return n;
47
+ const d = Math.max(0, Math.min(PR_MAX_DECIMALS, Math.trunc(decimals)));
48
+ const p = Math.pow(10, d);
49
+ const scaled = n * p;
50
+ const eps = Math.abs(scaled) * Number.EPSILON * 4;
51
+ const r = scaled < 0 ? -Math.round(-scaled + eps) : Math.round(scaled + eps);
52
+ return r / p;
53
+ }
54
+
55
+ /**
56
+ * 数値をCSSに書ける文字列へ。
57
+ * precision が 'auto'(既定)なら末尾の0を落とす(0.750000 → 0.75)。
58
+ * 数値なら桁を固定する(0.75 を桁数3で 0.750)。
59
+ */
60
+ export function prFormat(n, precision) {
61
+ if (!Number.isFinite(n)) return '';
62
+ if (precision === undefined || precision === null || precision === 'auto' || precision === '') {
63
+ let s = prRound(n, PR_MAX_DECIMALS).toFixed(PR_MAX_DECIMALS);
64
+ s = s.replace(/0+$/, '').replace(/\.$/, '');
65
+ return s === '-0' ? '0' : s;
66
+ }
67
+ const d = Math.max(0, Math.min(PR_MAX_DECIMALS, Math.trunc(Number(precision) || 0)));
68
+ const s = prRound(n, d).toFixed(d);
69
+ return /^-0(\.0*)?$/.test(s) ? s.slice(1) : s;
70
+ }
71
+
72
+ // 「24」「24px」「1.5 rem」「62.5%」のような1つの長さ
73
+ const PR_LENGTH_RE = /^([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*(px|rem|em|pt|%)?$/i;
74
+
75
+ /**
76
+ * 長さの文字列を {value, unit} へ。単位が無ければ fallbackUnit(既定 px)とみなす。
77
+ * 読めなければ null(0 と区別するため例外にはしない)。
78
+ */
79
+ export function prParseLength(input, fallbackUnit) {
80
+ const s = String(input === undefined || input === null ? '' : input).trim();
81
+ if (!s) return null;
82
+ const m = PR_LENGTH_RE.exec(s);
83
+ if (!m) return null;
84
+ const value = Number(m[1]);
85
+ if (!Number.isFinite(value)) return null;
86
+ return { value, unit: (m[2] || fallbackUnit || 'px').toLowerCase() };
87
+ }
88
+
89
+ /**
90
+ * 基準サイズの指定(16 / '16px' / '62.5%' / '12pt')を px の数値へ。
91
+ * % と rem / em は「ブラウザ既定の16pxに対する割合」として読む(html { font-size: 62.5% } → 10px)。
92
+ */
93
+ export function prResolveBase(input, fallback) {
94
+ const fb = prSize(fallback, PR_DEFAULT_ROOT);
95
+ if (input === undefined || input === null || input === '') return fb;
96
+ const parsed = typeof input === 'number'
97
+ ? { value: input, unit: 'px' }
98
+ : prParseLength(input, 'px');
99
+ if (!parsed) return fb;
100
+ const px = parsed.unit === '%' ? (parsed.value / 100) * PR_DEFAULT_ROOT
101
+ : parsed.unit === 'pt' ? parsed.value / PR_PT_PER_PX
102
+ : parsed.unit === 'px' ? parsed.value
103
+ : parsed.value * PR_DEFAULT_ROOT;
104
+ return prSize(px, fb);
105
+ }
106
+
107
+ /**
108
+ * 1つの長さを px / rem / em / pt へ相互換算する。
109
+ * @param {object} opts
110
+ * @param {number|string} opts.value 入力値
111
+ * @param {'px'|'rem'|'em'|'pt'|'%'} [opts.unit='px'] 入力の単位
112
+ * @param {number} [opts.root=16] ルート(html要素)のフォントサイズ px
113
+ * @param {number} [opts.parent] 親要素のフォントサイズ px(em の基準。既定は root と同じ)
114
+ * @returns {object|null} 換算結果(読めない入力なら null)
115
+ */
116
+ export function prConvert(opts) {
117
+ const o = opts || {};
118
+ const root = prSize(o.root, PR_DEFAULT_ROOT);
119
+ const parent = prSize(o.parent, root);
120
+ const unit = String(o.unit || 'px').toLowerCase();
121
+ const value = typeof o.value === 'string' ? Number(String(o.value).trim()) : Number(o.value);
122
+ if (!Number.isFinite(value)) return null;
123
+
124
+ let px;
125
+ if (unit === 'px') px = value;
126
+ else if (unit === 'rem') px = value * root;
127
+ else if (unit === 'em') px = value * parent;
128
+ else if (unit === 'pt') px = value / PR_PT_PER_PX;
129
+ else if (unit === '%') px = (value / 100) * parent;
130
+ else return null;
131
+
132
+ return {
133
+ input: { value, unit },
134
+ root,
135
+ parent,
136
+ px,
137
+ rem: px / root,
138
+ em: px / parent,
139
+ pt: px * PR_PT_PER_PX,
140
+ percent: (px / parent) * 100,
141
+ };
142
+ }
143
+
144
+ /**
145
+ * よく使うフォントサイズのスケール表を作る。
146
+ * @param {object} [opts] root / parent / sizes
147
+ */
148
+ export function prScale(opts) {
149
+ const o = opts || {};
150
+ const root = prSize(o.root, PR_DEFAULT_ROOT);
151
+ const parent = prSize(o.parent, root);
152
+ const sizes = Array.isArray(o.sizes) && o.sizes.length ? o.sizes : PR_SCALE_SIZES;
153
+ return sizes
154
+ .map((px) => Number(px))
155
+ .filter((px) => Number.isFinite(px) && px > 0)
156
+ .map((px) => ({
157
+ px,
158
+ rem: px / root,
159
+ em: px / parent,
160
+ pt: px * PR_PT_PER_PX,
161
+ role: PR_SCALE_ROLE[px] || 'OTHER',
162
+ }));
163
+ }
164
+
165
+ // 数値+単位。sticky(y)で位置を指定して照合する
166
+ const PR_NUM_RE = /(-?(?:\d+(?:\.\d+)?|\.\d+))(px|rem|em)(?![a-zA-Z0-9_])/iy;
167
+ // 直前がこれらの文字なら識別子の途中(--size-16px など)なので触らない
168
+ const PR_IDENT_BEFORE = /[A-Za-z0-9_.#%-]/;
169
+
170
+ /**
171
+ * CSS(や値の羅列)の中の長さの単位をまとめて変換する。
172
+ * コメント・文字列・url() の中身は触らない。プロパティ名を追いかけているので
173
+ * 除外プロパティの指定と、@media などアットルールの前置きのスキップができる。
174
+ *
175
+ * @param {string} css 変換するCSS
176
+ * @param {object} [opts]
177
+ * @param {'px2rem'|'px2em'|'rem2px'|'em2px'} [opts.direction='px2rem']
178
+ * @param {number} [opts.root=16] ルートのフォントサイズ px
179
+ * @param {number} [opts.parent] 親要素のフォントサイズ px(em の基準)
180
+ * @param {number|'auto'} [opts.precision='auto'] 小数の桁
181
+ * @param {number} [opts.minPx=0] 換算後の絶対値がこれ未満のpxは変換しない(1pxの罫線を残す用)
182
+ * @param {boolean} [opts.zeroUnitless=true] 0 を単位なしの 0 にする
183
+ * @param {boolean} [opts.skipMedia=true] @media などアットルールの前置きは変換しない
184
+ * @param {string[]} [opts.ignoreProps=[]] 変換しないプロパティ(前方一致)
185
+ */
186
+ export function prConvertCss(css, opts) {
187
+ const o = opts || {};
188
+ const dir = PR_CSS_DIRECTIONS[o.direction] || PR_CSS_DIRECTIONS.px2rem;
189
+ const root = prSize(o.root, PR_DEFAULT_ROOT);
190
+ const parent = prSize(o.parent, root);
191
+ const base = dir.base === 'parent' ? parent : root;
192
+ const precision = o.precision === undefined ? 'auto' : o.precision;
193
+ const minPx = Number.isFinite(Number(o.minPx)) ? Math.abs(Number(o.minPx)) : 0;
194
+ const zeroUnitless = o.zeroUnitless !== false;
195
+ const skipMedia = o.skipMedia !== false;
196
+ const ignore = (Array.isArray(o.ignoreProps) ? o.ignoreProps : [])
197
+ .map((s) => String(s).trim().toLowerCase())
198
+ .filter(Boolean);
199
+
200
+ const src = String(css === undefined || css === null ? '' : css);
201
+ const len = src.length;
202
+ const stats = { found: 0, converted: 0, zeroed: 0, skipped_small: 0, skipped_media: 0, skipped_prop: 0 };
203
+
204
+ let out = '';
205
+ let i = 0;
206
+ let pending = ''; // 直前の区切りからここまで(プロパティ名の取り出しに使う)
207
+ let prop = ''; // 現在の宣言のプロパティ名
208
+ let atRule = ''; // アットルールの前置きにいるならその名前
209
+ let depth = 0; // 丸括弧の深さ
210
+
211
+ while (i < len) {
212
+ const ch = src.charAt(i);
213
+
214
+ // コメント(中の { } ; は状態に反映しない=コメントアウトされた指定に引きずられない)
215
+ if (ch === '/' && src.charAt(i + 1) === '*') {
216
+ const end = src.indexOf('*/', i + 2);
217
+ const stop = end === -1 ? len : end + 2;
218
+ out += src.slice(i, stop);
219
+ i = stop;
220
+ continue;
221
+ }
222
+ // 文字列(content: "10px" などを書き換えない)
223
+ if (ch === '"' || ch === "'") {
224
+ let j = i + 1;
225
+ while (j < len) {
226
+ const c = src.charAt(j);
227
+ if (c === '\\') { j += 2; continue; }
228
+ j += 1;
229
+ if (c === ch || c === '\n') break;
230
+ }
231
+ out += src.slice(i, j);
232
+ i = j;
233
+ continue;
234
+ }
235
+ // url(...) は data URI に "…px" のような並びが出うるので中身ごと素通し
236
+ if ((ch === 'u' || ch === 'U') && /^url\(/i.test(src.substr(i, 4))) {
237
+ const end = src.indexOf(')', i);
238
+ const stop = end === -1 ? len : end + 1;
239
+ out += src.slice(i, stop);
240
+ i = stop;
241
+ continue;
242
+ }
243
+
244
+ // 区切り記号で宣言の状態を更新する
245
+ if (ch === '(') { depth += 1; out += ch; pending += ch; i += 1; continue; }
246
+ if (ch === ')') { depth = Math.max(0, depth - 1); out += ch; pending += ch; i += 1; continue; }
247
+ if (ch === '{' || ch === '}' || ch === ';') {
248
+ prop = ''; pending = ''; atRule = ''; depth = 0;
249
+ out += ch; i += 1;
250
+ continue;
251
+ }
252
+ if (ch === '@' && !pending.trim()) {
253
+ const m = /^@[-a-zA-Z]+/.exec(src.substr(i, 32));
254
+ atRule = m ? m[0].slice(1).toLowerCase() : 'at';
255
+ out += ch; pending += ch; i += 1;
256
+ continue;
257
+ }
258
+ if (ch === ':' && depth === 0 && !atRule) {
259
+ const name = pending.trim().toLowerCase();
260
+ prop = /^[-a-zA-Z_][-a-zA-Z0-9_]*$/.test(name) ? name : '';
261
+ pending = '';
262
+ out += ch; i += 1;
263
+ continue;
264
+ }
265
+
266
+ // 数値+単位
267
+ PR_NUM_RE.lastIndex = i;
268
+ const m = PR_NUM_RE.exec(src);
269
+ if (m) {
270
+ const prev = i > 0 ? src.charAt(i - 1) : '';
271
+ if (prev && PR_IDENT_BEFORE.test(prev)) {
272
+ out += ch; pending += ch; i += 1;
273
+ continue;
274
+ }
275
+ const whole = m[0];
276
+ const num = Number(m[1]);
277
+ const unit = m[2].toLowerCase();
278
+ let replaced = null;
279
+ if (unit === dir.from && Number.isFinite(num)) {
280
+ stats.found += 1;
281
+ const px = dir.from === 'px' ? num : num * base;
282
+ const propIgnored = ignore.some((p) => prop === p || prop.indexOf(p) === 0);
283
+ if (skipMedia && atRule) {
284
+ stats.skipped_media += 1;
285
+ } else if (propIgnored) {
286
+ stats.skipped_prop += 1;
287
+ } else if (num === 0) {
288
+ replaced = zeroUnitless ? '0' : '0' + dir.to;
289
+ if (zeroUnitless) stats.zeroed += 1; else stats.converted += 1;
290
+ } else if (Math.abs(px) < minPx) {
291
+ stats.skipped_small += 1;
292
+ } else {
293
+ replaced = prFormat(dir.to === 'px' ? px : px / base, precision) + dir.to;
294
+ stats.converted += 1;
295
+ }
296
+ }
297
+ out += replaced === null ? whole : replaced;
298
+ pending += whole;
299
+ i += whole.length;
300
+ continue;
301
+ }
302
+
303
+ out += ch;
304
+ pending += ch;
305
+ // プロパティ名を拾うのに長い文字列は要らない(巨大な入力でも増え続けないようにする)
306
+ if (pending.length > 240) pending = pending.slice(-120);
307
+ i += 1;
308
+ }
309
+
310
+ return {
311
+ text: out,
312
+ direction: o.direction && PR_CSS_DIRECTIONS[o.direction] ? o.direction : 'px2rem',
313
+ root,
314
+ parent,
315
+ base,
316
+ stats,
317
+ };
318
+ }
319
+
320
+ /* ==================== ここまで変換コア ==================== */
321
+
322
+ // スケール表の用途ラベル。site側は同じコードを日英それぞれの文へ訳している
323
+ const PR_ROLE_TEXT = {
324
+ CAPTION: '注釈・キャプション', FINE: '細目・注意書き', SMALL: '小さめの本文・UIラベル',
325
+ BODY_SM: '本文(やや小)', BODY: '本文(ブラウザ既定)', BODY_LG: 'リード文・大きめの本文',
326
+ H4: '小見出し(h4)', H3: '中見出し(h3)', H2_SP: '見出し(h2・モバイル)', H2: '見出し(h2)',
327
+ H1_SP: '大見出し(h1・モバイル)', H1: '大見出し(h1)', TITLE: 'ページタイトル',
328
+ HERO: 'ヒーロー見出し', HERO_LG: 'ヒーロー見出し(大)', OTHER: '—',
329
+ };
330
+
331
+ // 指摘事項のコードを日本語の文へ
332
+ const PR_NOTE_TEXT = {
333
+ ROOT_NOT_16: (n) => `基準(ルート)を ${n}px として計算しました。ブラウザの既定は16pxなので、閲覧者が文字サイズを変えている場合は見え方が変わります。`,
334
+ ROOT_625: () => 'ルート10px(62.5%テクニック)です。暗算はしやすくなりますが、書いたremがすべてブラウザ既定の8分の5になるため、文字を大きく設定している閲覧者の拡大幅が意図より小さくなります。ルートは100%のままにして、換算した値を書く方が安全です。',
335
+ EM_PARENT: (n) => `em は親要素のフォントサイズ(${n}px)が基準です。入れ子にすると掛け算になるので、フォントサイズの指定には rem の方が安全です。`,
336
+ NOT_EXACT: (v) => `${v} は割り切れないため丸めています(ブラウザは内部でより高い精度を保つので、見た目の差は0.01px未満です)。`,
337
+ NOTHING_FOUND: (u) => `変換対象が見つかりませんでした(${u} の値がありません)。`,
338
+ SKIPPED_SMALL: (n) => `${n}箇所は minPx 未満だったのでそのまま残しました(1pxの罫線をremにすると環境によって太さがばらつくためです)。`,
339
+ SKIPPED_MEDIA: (n) => `${n}箇所は @media などアットルールの条件だったのでそのまま残しました(skipMedia=false で変換できます)。`,
340
+ SKIPPED_PROP: (n) => `${n}箇所は ignoreProps に一致するプロパティだったのでそのまま残しました。`,
341
+ ZEROED: (n) => `${n}箇所の 0 は単位なしの 0 にしました(zeroUnitless=false でそのまま残せます)。`,
342
+ };
343
+
344
+ export class PxRemError extends Error {}
345
+
346
+ const prNote = (code, arg) => ({ code, message: PR_NOTE_TEXT[code] ? PR_NOTE_TEXT[code](arg) : code });
347
+
348
+ /**
349
+ * 長さを px / rem / em / pt へ換算するか、CSSの単位をまとめて置き換える。
350
+ *
351
+ * value を渡すと1つの値の換算(よく使うサイズのスケール表つき)、
352
+ * css / path を渡すとCSS全体の一括変換になる。
353
+ *
354
+ * @param {object} opts
355
+ * @param {number|string} [opts.value] 換算する値('1.5rem' のように単位を含めてもよい)
356
+ * @param {'px'|'rem'|'em'|'pt'|'%'} [opts.unit='px'] value の単位
357
+ * @param {string} [opts.css] 一括変換するCSS(value / path と排他)
358
+ * @param {string} [opts.path] 一括変換するCSSファイルの絶対パス(value / css と排他)
359
+ * @param {string} [opts.outputPath] 変換後のCSSを書き出す絶対パス(指定すると本文は返さない)
360
+ * @param {'px2rem'|'px2em'|'rem2px'|'em2px'} [opts.direction='px2rem'] 一括変換の向き
361
+ * @param {number|string} [opts.root=16] ルート(html要素)のフォントサイズ px('62.5%' も可)
362
+ * @param {number|string} [opts.parent] 親要素のフォントサイズ px(emの基準。既定は root と同じ)
363
+ * @param {number|'auto'} [opts.precision='auto'] 小数の桁(auto は末尾の0を落とす)
364
+ * @param {number} [opts.minPx=2] 一括変換で、この値未満のpxは変換しない
365
+ * @param {boolean} [opts.zeroUnitless=true] 0 を単位なしの 0 にする
366
+ * @param {boolean} [opts.skipMedia=true] @media などアットルールの条件は変換しない
367
+ * @param {string[]} [opts.ignoreProps] 変換しないプロパティ(前方一致。例 ['border','box-shadow'])
368
+ * @param {boolean} [opts.scale=true] 値の換算のときにスケール表を返す
369
+ */
370
+ export async function pxRemConvert(opts = {}) {
371
+ const hasCss = typeof opts.css === 'string';
372
+ const hasPath = typeof opts.path === 'string' && opts.path !== '';
373
+ const hasValue = opts.value !== undefined && opts.value !== null && String(opts.value).trim() !== '';
374
+ if (hasCss && hasPath) throw new PxRemError('css と path は同時に指定できません');
375
+ if ((hasCss || hasPath) && hasValue) throw new PxRemError('value と css / path は同時に指定できません');
376
+ if (!hasCss && !hasPath && !hasValue) {
377
+ throw new PxRemError('value(換算する値)か css / path(一括変換するCSS)のどちらかを渡してください');
378
+ }
379
+
380
+ const root = prResolveBase(opts.root, PR_DEFAULT_ROOT);
381
+ const parent = prResolveBase(opts.parent, root);
382
+ const precision = opts.precision === undefined || opts.precision === null ? 'auto' : opts.precision;
383
+ const fmt = (n) => prFormat(n, precision);
384
+
385
+ const baseNotes = [];
386
+ if (root !== PR_DEFAULT_ROOT) baseNotes.push(prNote('ROOT_NOT_16', prFormat(root, 'auto')));
387
+ if (Math.abs(root - 10) < 0.001) baseNotes.push(prNote('ROOT_625'));
388
+
389
+ /* ---- CSSの一括変換 ---- */
390
+ if (hasCss || hasPath) {
391
+ const direction = opts.direction || 'px2rem';
392
+ if (!PR_CSS_DIRECTIONS[direction]) {
393
+ throw new PxRemError(`direction は px2rem / px2em / rem2px / em2px のいずれか: ${opts.direction}`);
394
+ }
395
+ const dir = PR_CSS_DIRECTIONS[direction];
396
+ const input = hasCss ? opts.css : await readFile(opts.path, 'utf8');
397
+ const minPx = opts.minPx === undefined || opts.minPx === null ? 2 : Number(opts.minPx);
398
+ const r = prConvertCss(input, {
399
+ direction,
400
+ root,
401
+ parent,
402
+ precision,
403
+ minPx,
404
+ zeroUnitless: opts.zeroUnitless,
405
+ skipMedia: opts.skipMedia,
406
+ ignoreProps: opts.ignoreProps,
407
+ });
408
+
409
+ const notes = baseNotes.slice();
410
+ if (dir.base === 'parent' && parent !== root) notes.push(prNote('EM_PARENT', prFormat(parent, 'auto')));
411
+ if (!r.stats.found) notes.push(prNote('NOTHING_FOUND', dir.from));
412
+ if (r.stats.skipped_small) notes.push(prNote('SKIPPED_SMALL', r.stats.skipped_small));
413
+ if (r.stats.skipped_media) notes.push(prNote('SKIPPED_MEDIA', r.stats.skipped_media));
414
+ if (r.stats.skipped_prop) notes.push(prNote('SKIPPED_PROP', r.stats.skipped_prop));
415
+ if (r.stats.zeroed) notes.push(prNote('ZEROED', r.stats.zeroed));
416
+
417
+ const result = {
418
+ mode: 'css',
419
+ direction,
420
+ source: hasCss ? { type: 'text' } : { path: opts.path, name: basename(opts.path) },
421
+ root,
422
+ parent,
423
+ options: {
424
+ precision,
425
+ min_px: minPx,
426
+ zero_unitless: opts.zeroUnitless !== false,
427
+ skip_media: opts.skipMedia !== false,
428
+ ignore_props: Array.isArray(opts.ignoreProps) ? opts.ignoreProps : [],
429
+ },
430
+ stats: r.stats,
431
+ text: r.text,
432
+ notes,
433
+ };
434
+ if (opts.outputPath) {
435
+ await writeFile(opts.outputPath, r.text, 'utf8');
436
+ result.output = opts.outputPath;
437
+ // ファイルに書けたなら本文は重複した重い情報でしかない
438
+ delete result.text;
439
+ }
440
+ return result;
441
+ }
442
+
443
+ /* ---- 1つの値の換算 ---- */
444
+ const parsed = prParseLength(opts.value, opts.unit || 'px');
445
+ if (!parsed) throw new PxRemError(`value を数値として読めません: ${opts.value}`);
446
+ if (opts.unit && ['px', 'rem', 'em', 'pt', '%'].indexOf(String(opts.unit).toLowerCase()) === -1) {
447
+ throw new PxRemError(`unit は px / rem / em / pt / % のいずれか: ${opts.unit}`);
448
+ }
449
+ const r = prConvert({ value: parsed.value, unit: parsed.unit, root, parent });
450
+ if (!r) throw new PxRemError(`value を換算できません: ${opts.value}`);
451
+
452
+ const remStr = prFormat(r.rem, 'auto');
453
+ // 表示した rem を px へ戻して一致するか(1e-9 は二進小数の誤差を吸収するための幅)
454
+ const exact = Math.abs(Number(remStr) * root - r.px) < 1e-9;
455
+
456
+ const notes = baseNotes.slice();
457
+ if (parent !== root) notes.push(prNote('EM_PARENT', prFormat(parent, 'auto')));
458
+ if (!exact) notes.push(prNote('NOT_EXACT', remStr + 'rem'));
459
+
460
+ const result = {
461
+ mode: 'value',
462
+ input: { value: parsed.value, unit: parsed.unit },
463
+ root,
464
+ parent,
465
+ px: r.px,
466
+ rem: r.rem,
467
+ em: r.em,
468
+ pt: r.pt,
469
+ formatted: {
470
+ px: fmt(r.px) + 'px',
471
+ rem: fmt(r.rem) + 'rem',
472
+ em: fmt(r.em) + 'em',
473
+ pt: fmt(r.pt) + 'pt',
474
+ },
475
+ css: `font-size: ${fmt(r.rem)}rem; /* ${fmt(r.px)}px */`,
476
+ exact,
477
+ notes,
478
+ };
479
+ if (opts.scale !== false) {
480
+ result.scale = prScale({ root, parent }).map((row) => ({
481
+ px: row.px,
482
+ rem: fmt(row.rem) + 'rem',
483
+ em: fmt(row.em) + 'em',
484
+ role: PR_ROLE_TEXT[row.role] || row.role,
485
+ }));
486
+ }
487
+ return result;
488
+ }