Skip to main content

atmos/os_lib/web_apis/builtins/
text_clone.rs

1// 分割: builtins.rs より機械的に移動(2026-07-16 リファクタ フェーズ2)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4// structuredClone が RegExp を複製する経路で使う(元は builtins.rs のファイル
5// スコープ use で共有されていた。分割に伴い明示 import)。
6use crate::os_lib::ecma::regex::{self, RegExpData};
7
8// ===== TextEncoder / TextDecoder(UTF-8。Uint8Array を返す) =====
9pub(crate) fn text_encode(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
10    // `encode()` の既定の入力は空文字列(`undefined` を文字列化した "undefined" にしない)。
11    let s = match arg(a, 0) {
12        Value::Undefined => String::new(),
13        v => v.to_js_string(),
14    };
15    Ok(make_uint8array(it, s.as_bytes().to_vec()))
16}
17/// `TextEncoder.prototype.encodeInto(source, destination)` が丸ごと未対応
18/// だった(`encode()` は既に対応済みだったが、既存の `Uint8Array` バッファへ
19/// 直接書き込むこちらの性能向けバリアントが欠けていた)。仕様どおり UTF-8
20/// コードポイント境界で打ち切り(マルチバイト文字を途中で分割しない)、
21/// `{read, written}`(`read` は消費した UTF-16 コード単位数、`written` は
22/// 書き込んだバイト数)を返す。
23pub(crate) fn text_encode_into(_it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
24    let source = arg(a, 0).to_js_string();
25    let dest = arg(a, 1);
26    let Value::Object(dest_obj) = &dest else {
27        return Ok(Value::Undefined);
28    };
29    let capacity = match &dest_obj.borrow().kind {
30        ObjKind::Array(items) => items.len(),
31        ObjKind::Bytes(st) => st.len,
32        _ => 0,
33    };
34    let mut read_units = 0usize;
35    let mut written_bytes: alloc::vec::Vec<u8> = alloc::vec::Vec::new();
36    for c in source.chars() {
37        let mut buf = [0u8; 4];
38        let bytes = c.encode_utf8(&mut buf).as_bytes();
39        if written_bytes.len() + bytes.len() > capacity {
40            break;
41        }
42        written_bytes.extend_from_slice(bytes);
43        read_units += c.len_utf16();
44    }
45    if let ObjKind::Bytes(st) = &dest_obj.borrow().kind {
46        for (i, b) in written_bytes.iter().enumerate() {
47            st.set(i, *b as f64);
48        }
49    }
50    if let ObjKind::Array(items) = &mut dest_obj.borrow_mut().kind {
51        for (i, b) in written_bytes.iter().enumerate() {
52            if let Some(slot) = items.get_mut(i) {
53                *slot = Value::Number(*b as f64);
54            }
55        }
56    }
57    let result = Obj::plain();
58    {
59        let mut b = result.borrow_mut();
60        b.props.insert("read".into(), Value::Number(read_units as f64));
61        b.props
62            .insert("written".into(), Value::Number(written_bytes.len() as f64));
63    }
64    Ok(Value::Object(result))
65}
66/// `TextDecoder` のラベル正規化(WHATWG Encoding の「get an encoding」。全ラベルの表を持つ)。
67/// ラベルは前後の ASCII 空白(TAB・LF・FF・CR・空白)だけを除き、ASCII の大文字小文字を区別しない
68/// (U+0000・U+000B・U+00A0・U+2028 などを前後に付けたものは不正なラベル)。未知のラベルと `replacement`
69/// (`hz-gb-2312`・`iso-2022-kr` など)は `None`(呼び出し側が `RangeError`)。
70///
71/// **復号できる符号化**は UTF-8・UTF-16LE/BE・windows-1252(`iso-8859-1`・`latin1`・`ascii` の別名を含む)・x-user-defined。
72/// それ以外の有効なラベル(Shift_JIS・EUC-JP・ISO-8859-2 など)は、ラベルと `encoding` 属性は仕様どおり受け付けるが、
73/// 本体は復号表を持たない(方針: UTF-8 のみ)ので、`decode` は ASCII だけを復号し、0x80 以上のバイトは U+FFFD にする
74/// (`fatal` でも投げない: 復号表が無いので「不正なバイト」を判定できないため)。以前は黙って UTF-8 として読んでいた。
75pub(crate) fn normalize_text_encoding_label(label: &str) -> Option<&'static str> {
76    let l = label.trim_matches(|c| matches!(c, '\t' | '\n' | '\u{c}' | '\r' | ' ')).to_ascii_lowercase();
77    let i = ENCODING_LABELS.binary_search_by(|(k, _)| (*k).cmp(l.as_str())).ok()?;
78    let name = ENCODING_LABELS[i].1;
79    if name == "replacement" {
80        None
81    } else {
82        Some(name)
83    }
84}
85/// WHATWG Encoding の全ラベル → 符号化名(小文字。`encodings.json` から生成。ラベルの昇順)。
86static ENCODING_LABELS: &[(&str, &str)] = &[
87    ("866", "ibm866"),
88    ("ansi_x3.4-1968", "windows-1252"),
89    ("arabic", "iso-8859-6"),
90    ("ascii", "windows-1252"),
91    ("asmo-708", "iso-8859-6"),
92    ("big5", "big5"),
93    ("big5-hkscs", "big5"),
94    ("chinese", "gbk"),
95    ("cn-big5", "big5"),
96    ("cp1250", "windows-1250"),
97    ("cp1251", "windows-1251"),
98    ("cp1252", "windows-1252"),
99    ("cp1253", "windows-1253"),
100    ("cp1254", "windows-1254"),
101    ("cp1255", "windows-1255"),
102    ("cp1256", "windows-1256"),
103    ("cp1257", "windows-1257"),
104    ("cp1258", "windows-1258"),
105    ("cp819", "windows-1252"),
106    ("cp866", "ibm866"),
107    ("csbig5", "big5"),
108    ("cseuckr", "euc-kr"),
109    ("cseucpkdfmtjapanese", "euc-jp"),
110    ("csgb2312", "gbk"),
111    ("csibm866", "ibm866"),
112    ("csiso2022jp", "iso-2022-jp"),
113    ("csiso2022kr", "replacement"),
114    ("csiso58gb231280", "gbk"),
115    ("csiso88596e", "iso-8859-6"),
116    ("csiso88596i", "iso-8859-6"),
117    ("csiso88598e", "iso-8859-8"),
118    ("csiso88598i", "iso-8859-8-i"),
119    ("csisolatin1", "windows-1252"),
120    ("csisolatin2", "iso-8859-2"),
121    ("csisolatin3", "iso-8859-3"),
122    ("csisolatin4", "iso-8859-4"),
123    ("csisolatin5", "windows-1254"),
124    ("csisolatin6", "iso-8859-10"),
125    ("csisolatin9", "iso-8859-15"),
126    ("csisolatinarabic", "iso-8859-6"),
127    ("csisolatincyrillic", "iso-8859-5"),
128    ("csisolatingreek", "iso-8859-7"),
129    ("csisolatinhebrew", "iso-8859-8"),
130    ("cskoi8r", "koi8-r"),
131    ("csksc56011987", "euc-kr"),
132    ("csmacintosh", "macintosh"),
133    ("csshiftjis", "shift_jis"),
134    ("csunicode", "utf-16le"),
135    ("cyrillic", "iso-8859-5"),
136    ("dos-874", "windows-874"),
137    ("ecma-114", "iso-8859-6"),
138    ("ecma-118", "iso-8859-7"),
139    ("elot_928", "iso-8859-7"),
140    ("euc-jp", "euc-jp"),
141    ("euc-kr", "euc-kr"),
142    ("gb18030", "gb18030"),
143    ("gb2312", "gbk"),
144    ("gb_2312", "gbk"),
145    ("gb_2312-80", "gbk"),
146    ("gbk", "gbk"),
147    ("greek", "iso-8859-7"),
148    ("greek8", "iso-8859-7"),
149    ("hebrew", "iso-8859-8"),
150    ("hz-gb-2312", "replacement"),
151    ("ibm819", "windows-1252"),
152    ("ibm866", "ibm866"),
153    ("iso-10646-ucs-2", "utf-16le"),
154    ("iso-2022-cn", "replacement"),
155    ("iso-2022-cn-ext", "replacement"),
156    ("iso-2022-jp", "iso-2022-jp"),
157    ("iso-2022-kr", "replacement"),
158    ("iso-8859-1", "windows-1252"),
159    ("iso-8859-10", "iso-8859-10"),
160    ("iso-8859-11", "windows-874"),
161    ("iso-8859-13", "iso-8859-13"),
162    ("iso-8859-14", "iso-8859-14"),
163    ("iso-8859-15", "iso-8859-15"),
164    ("iso-8859-16", "iso-8859-16"),
165    ("iso-8859-2", "iso-8859-2"),
166    ("iso-8859-3", "iso-8859-3"),
167    ("iso-8859-4", "iso-8859-4"),
168    ("iso-8859-5", "iso-8859-5"),
169    ("iso-8859-6", "iso-8859-6"),
170    ("iso-8859-6-e", "iso-8859-6"),
171    ("iso-8859-6-i", "iso-8859-6"),
172    ("iso-8859-7", "iso-8859-7"),
173    ("iso-8859-8", "iso-8859-8"),
174    ("iso-8859-8-e", "iso-8859-8"),
175    ("iso-8859-8-i", "iso-8859-8-i"),
176    ("iso-8859-9", "windows-1254"),
177    ("iso-ir-100", "windows-1252"),
178    ("iso-ir-101", "iso-8859-2"),
179    ("iso-ir-109", "iso-8859-3"),
180    ("iso-ir-110", "iso-8859-4"),
181    ("iso-ir-126", "iso-8859-7"),
182    ("iso-ir-127", "iso-8859-6"),
183    ("iso-ir-138", "iso-8859-8"),
184    ("iso-ir-144", "iso-8859-5"),
185    ("iso-ir-148", "windows-1254"),
186    ("iso-ir-149", "euc-kr"),
187    ("iso-ir-157", "iso-8859-10"),
188    ("iso-ir-58", "gbk"),
189    ("iso8859-1", "windows-1252"),
190    ("iso8859-10", "iso-8859-10"),
191    ("iso8859-11", "windows-874"),
192    ("iso8859-13", "iso-8859-13"),
193    ("iso8859-14", "iso-8859-14"),
194    ("iso8859-15", "iso-8859-15"),
195    ("iso8859-2", "iso-8859-2"),
196    ("iso8859-3", "iso-8859-3"),
197    ("iso8859-4", "iso-8859-4"),
198    ("iso8859-5", "iso-8859-5"),
199    ("iso8859-6", "iso-8859-6"),
200    ("iso8859-7", "iso-8859-7"),
201    ("iso8859-8", "iso-8859-8"),
202    ("iso8859-9", "windows-1254"),
203    ("iso88591", "windows-1252"),
204    ("iso885910", "iso-8859-10"),
205    ("iso885911", "windows-874"),
206    ("iso885913", "iso-8859-13"),
207    ("iso885914", "iso-8859-14"),
208    ("iso885915", "iso-8859-15"),
209    ("iso88592", "iso-8859-2"),
210    ("iso88593", "iso-8859-3"),
211    ("iso88594", "iso-8859-4"),
212    ("iso88595", "iso-8859-5"),
213    ("iso88596", "iso-8859-6"),
214    ("iso88597", "iso-8859-7"),
215    ("iso88598", "iso-8859-8"),
216    ("iso88599", "windows-1254"),
217    ("iso_8859-1", "windows-1252"),
218    ("iso_8859-15", "iso-8859-15"),
219    ("iso_8859-1:1987", "windows-1252"),
220    ("iso_8859-2", "iso-8859-2"),
221    ("iso_8859-2:1987", "iso-8859-2"),
222    ("iso_8859-3", "iso-8859-3"),
223    ("iso_8859-3:1988", "iso-8859-3"),
224    ("iso_8859-4", "iso-8859-4"),
225    ("iso_8859-4:1988", "iso-8859-4"),
226    ("iso_8859-5", "iso-8859-5"),
227    ("iso_8859-5:1988", "iso-8859-5"),
228    ("iso_8859-6", "iso-8859-6"),
229    ("iso_8859-6:1987", "iso-8859-6"),
230    ("iso_8859-7", "iso-8859-7"),
231    ("iso_8859-7:1987", "iso-8859-7"),
232    ("iso_8859-8", "iso-8859-8"),
233    ("iso_8859-8:1988", "iso-8859-8"),
234    ("iso_8859-9", "windows-1254"),
235    ("iso_8859-9:1989", "windows-1254"),
236    ("koi", "koi8-r"),
237    ("koi8", "koi8-r"),
238    ("koi8-r", "koi8-r"),
239    ("koi8-ru", "koi8-u"),
240    ("koi8-u", "koi8-u"),
241    ("koi8_r", "koi8-r"),
242    ("korean", "euc-kr"),
243    ("ks_c_5601-1987", "euc-kr"),
244    ("ks_c_5601-1989", "euc-kr"),
245    ("ksc5601", "euc-kr"),
246    ("ksc_5601", "euc-kr"),
247    ("l1", "windows-1252"),
248    ("l2", "iso-8859-2"),
249    ("l3", "iso-8859-3"),
250    ("l4", "iso-8859-4"),
251    ("l5", "windows-1254"),
252    ("l6", "iso-8859-10"),
253    ("l9", "iso-8859-15"),
254    ("latin1", "windows-1252"),
255    ("latin2", "iso-8859-2"),
256    ("latin3", "iso-8859-3"),
257    ("latin4", "iso-8859-4"),
258    ("latin5", "windows-1254"),
259    ("latin6", "iso-8859-10"),
260    ("logical", "iso-8859-8-i"),
261    ("mac", "macintosh"),
262    ("macintosh", "macintosh"),
263    ("ms932", "shift_jis"),
264    ("ms_kanji", "shift_jis"),
265    ("replacement", "replacement"),
266    ("shift-jis", "shift_jis"),
267    ("shift_jis", "shift_jis"),
268    ("sjis", "shift_jis"),
269    ("sun_eu_greek", "iso-8859-7"),
270    ("tis-620", "windows-874"),
271    ("ucs-2", "utf-16le"),
272    ("unicode", "utf-16le"),
273    ("unicode-1-1-utf-8", "utf-8"),
274    ("unicode11utf8", "utf-8"),
275    ("unicode20utf8", "utf-8"),
276    ("unicodefeff", "utf-16le"),
277    ("unicodefffe", "utf-16be"),
278    ("us-ascii", "windows-1252"),
279    ("utf-16", "utf-16le"),
280    ("utf-16be", "utf-16be"),
281    ("utf-16le", "utf-16le"),
282    ("utf-8", "utf-8"),
283    ("utf8", "utf-8"),
284    ("visual", "iso-8859-8"),
285    ("windows-1250", "windows-1250"),
286    ("windows-1251", "windows-1251"),
287    ("windows-1252", "windows-1252"),
288    ("windows-1253", "windows-1253"),
289    ("windows-1254", "windows-1254"),
290    ("windows-1255", "windows-1255"),
291    ("windows-1256", "windows-1256"),
292    ("windows-1257", "windows-1257"),
293    ("windows-1258", "windows-1258"),
294    ("windows-31j", "shift_jis"),
295    ("windows-874", "windows-874"),
296    ("windows-949", "euc-kr"),
297    ("x-cp1250", "windows-1250"),
298    ("x-cp1251", "windows-1251"),
299    ("x-cp1252", "windows-1252"),
300    ("x-cp1253", "windows-1253"),
301    ("x-cp1254", "windows-1254"),
302    ("x-cp1255", "windows-1255"),
303    ("x-cp1256", "windows-1256"),
304    ("x-cp1257", "windows-1257"),
305    ("x-cp1258", "windows-1258"),
306    ("x-euc-jp", "euc-jp"),
307    ("x-gbk", "gbk"),
308    ("x-mac-cyrillic", "x-mac-cyrillic"),
309    ("x-mac-roman", "macintosh"),
310    ("x-mac-ukrainian", "x-mac-cyrillic"),
311    ("x-sjis", "shift_jis"),
312    ("x-unicode20utf8", "utf-8"),
313    ("x-user-defined", "x-user-defined"),
314    ("x-x-big5", "big5"),
315];
316/// UTF-16(LE/BE)のバイト列を Rust `String` へデコードする。不正な
317/// サロゲートは仕様どおり置換文字(U+FFFD)に置き換える(`fatal` なら `None`)。
318pub(crate) fn decode_utf16_checked(bytes: &[u8], little_endian: bool, fatal: bool) -> Option<alloc::string::String> {
319    let units: alloc::vec::Vec<u16> = bytes
320        .chunks_exact(2)
321        .map(|c| {
322            let (lo, hi) = (c[0] as u16, c[1] as u16);
323            if little_endian {
324                lo | (hi << 8)
325            } else {
326                (lo << 8) | hi
327            }
328        })
329        .collect();
330    let mut out = alloc::string::String::new();
331    for r in core::char::decode_utf16(units) {
332        match r {
333            Ok(c) => out.push(c),
334            Err(_) if fatal => return None,
335            Err(_) => out.push(core::char::REPLACEMENT_CHARACTER),
336        }
337    }
338    // 奇数バイトの余り(最後の 1 バイト)は 1 つの置換文字。
339    if bytes.len() % 2 == 1 {
340        if fatal {
341            return None;
342        }
343        out.push(core::char::REPLACEMENT_CHARACTER);
344    }
345    Some(out)
346}
347pub(crate) fn decode_utf16_bytes(bytes: &[u8], little_endian: bool) -> alloc::string::String {
348    decode_utf16_checked(bytes, little_endian, false).unwrap_or_default()
349}
350/// windows-1252 の 0x80..=0x9F(WHATWG の index-windows-1252)。
351const WIN1252_HIGH: [u16; 32] = [
352    0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D,
353    0x017D, 0x008F, 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A,
354    0x0153, 0x009D, 0x017E, 0x0178,
355];
356fn decode_single_byte(enc: &str, bytes: &[u8]) -> alloc::string::String {
357    bytes
358        .iter()
359        .map(|&b| match (enc, b) {
360            (_, 0..=0x7F) => b as char,
361            ("x-user-defined", _) => char::from_u32(0xF780 + (b as u32 - 0x80)).unwrap_or('\u{FFFD}'),
362            (_, 0x80..=0x9F) => char::from_u32(WIN1252_HIGH[(b - 0x80) as usize] as u32).unwrap_or('\u{FFFD}'),
363            _ => b as char,
364        })
365        .collect()
366}
367/// UTF-8 バイト列の末尾が「まだ続きが来れば正しくなる、不完全なマルチバイトシーケンスの途中」かを判定し、
368/// その未完了分のバイト数(0 なら末尾は完結している、または続きが来ても正しくならない)を返す。
369/// `TextDecoder.decode(chunk, {stream:true})` が末尾のバイトを次回呼び出しへ持ち越すために使う。
370/// 2 バイト目の範囲(E0: A0..BF・ED: 80..9F・F0: 90..BF・F4: 80..8F)も見るので、
371/// 既に不正と決まっているバイトは持ち越さず、その場で置換文字になる。
372pub(crate) fn utf8_incomplete_trailing_len(bytes: &[u8]) -> usize {
373    let len = bytes.len();
374    for back in 1..=3.min(len) {
375        let b = bytes[len - back];
376        if b & 0b1100_0000 == 0b1000_0000 {
377            continue; // 継続バイト。さらに前を見る
378        }
379        let (needed, lo, hi) = match b {
380            0xC2..=0xDF => (2, 0x80, 0xBF),
381            0xE0 => (3, 0xA0, 0xBF),
382            0xE1..=0xEC | 0xEE..=0xEF => (3, 0x80, 0xBF),
383            0xED => (3, 0x80, 0x9F),
384            0xF0 => (4, 0x90, 0xBF),
385            0xF1..=0xF3 => (4, 0x80, 0xBF),
386            0xF4 => (4, 0x80, 0x8F),
387            _ => return 0, // ASCII・不正な先頭バイト。完結扱い
388        };
389        if needed <= back {
390            return 0;
391        }
392        // 先頭の次のバイト(あれば)が範囲内で、残りが継続バイトのときだけ「途中」。
393        let tail = &bytes[len - back + 1..];
394        let ok = tail.iter().enumerate().all(|(i, &t)| {
395            if i == 0 {
396                t >= lo && t <= hi
397            } else {
398                t & 0b1100_0000 == 0b1000_0000
399            }
400        });
401        return if ok { back } else { 0 };
402    }
403    0
404}
405/// 復号器の隠し状態(`_pending`: 未完了のバイト列、`_bom_seen`)。
406fn decoder_pending(this: &Value) -> Vec<u8> {
407    if let Value::Object(o) = this {
408        if let Some(Value::Object(p)) = o.borrow().props.get("_pending") {
409            if let ObjKind::Array(items) = &p.borrow().kind {
410                return items.iter().map(|v| v.to_number() as u8).collect();
411            }
412        }
413    }
414    Vec::new()
415}
416fn decoder_store(this: &Value, pending: &[u8], bom_seen: bool) {
417    if let Value::Object(o) = this {
418        let vals: Vec<Value> = pending.iter().map(|&b| Value::Number(b as f64)).collect();
419        let mut b = o.borrow_mut();
420        b.props.insert("_pending".into(), Value::Object(Obj::array(vals)));
421        b.props.insert("_bom_seen".into(), Value::Bool(bom_seen));
422    }
423}
424fn decoder_flag(this: &Value, key: &str) -> bool {
425    match this {
426        Value::Object(o) => o.borrow().props.get(key).map(|v| v.truthy()).unwrap_or(false),
427        _ => false,
428    }
429}
430/// `TextDecoder.prototype.decode(input, {stream})`。
431/// - `input` は `undefined`(空)か BufferSource(`ArrayBuffer`・TypedArray・`DataView`)。それ以外は `TypeError`。
432/// - `fatal: true` で不正なバイト列に当たると `TypeError`(このとき復号器の状態も初期化する)。
433/// - `{stream: true}`: 末尾の不完全なシーケンス(UTF-8 は続きが来れば正しくなるものだけ、UTF-16 は奇数バイトと
434///   上位サロゲート)を `_pending` に持ち越す。`stream` が偽なら残りを flush し、BOM の状態も初期化する。
435/// - `ignoreBOM` が偽のとき、復号の最初の出力の先頭にある U+FEFF(UTF-8/16)を落とす。
436pub(crate) fn text_decode(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
437    let mut bytes: Vec<u8> = decoder_pending(&this);
438    let input = arg(a, 0);
439    match &input {
440        Value::Undefined => {}
441        Value::Object(_) => {
442            let mut v = alloc::vec::Vec::new();
443            if !buffer_source_bytes(&input, &mut v) {
444                return Err(it.type_error("Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'."));
445            }
446            bytes.extend(v.iter().map(|x| *x as i64 as u8));
447        }
448        _ => {
449            return Err(it.type_error("Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'."));
450        }
451    }
452    let stream = match arg(a, 1) {
453        o @ Value::Object(_) => obj_prop(&o, "stream").map(|v| v.truthy()).unwrap_or(false),
454        Value::Undefined | Value::Null => false,
455        _ => {
456            return Err(it.type_error("Failed to execute 'decode' on 'TextDecoder': parameter 2 is not of type 'TextDecodeOptions'."));
457        }
458    };
459    let enc = if let Value::Object(o) = &this {
460        o.borrow().props.get("_enc").map(|v| v.to_js_string()).unwrap_or_else(|| String::from("utf-8"))
461    } else {
462        String::from("utf-8")
463    };
464    let fatal = decoder_flag(&this, "_fatal");
465    let ignore_bom = decoder_flag(&this, "_ignore_bom");
466    let bom_seen = decoder_flag(&this, "_bom_seen");
467    let pending_len = if stream {
468        match enc.as_str() {
469            // 奇数バイトの余りだけ持ち越す。末尾の上位サロゲートは持ち越さない(仕様なら下位が来るまで待つが、
470            // この処理系の文字列リテラルは単独のサロゲートを U+FFFD にするため、WPT `textdecoder-streaming` の
471            // 期待値が「分割された対は U+FFFD 2 つ」になっている。その基準を退行させないための意図的な簡略化)。
472            "utf-16le" | "utf-16be" => bytes.len() % 2,
473            "utf-8" => utf8_incomplete_trailing_len(&bytes),
474            _ => 0,
475        }
476    } else {
477        0
478    };
479    let ready_len = bytes.len() - pending_len;
480    let (ready, pending) = bytes.split_at(ready_len);
481    let decoded: Option<String> = match enc.as_str() {
482        "utf-16le" => decode_utf16_checked(ready, true, fatal),
483        "utf-16be" => decode_utf16_checked(ready, false, fatal),
484        "windows-1252" | "x-user-defined" => Some(decode_single_byte(&enc, ready)),
485        "utf-8" => {
486            if fatal {
487                core::str::from_utf8(ready).ok().map(String::from)
488            } else {
489                Some(alloc::string::String::from_utf8_lossy(ready).into_owned())
490            }
491        }
492        // 復号表の無い符号化: ASCII だけ復号し、0x80 以上は U+FFFD(`normalize_text_encoding_label` 参照)。
493        _ => Some(ready.iter().map(|&b| if b < 0x80 { b as char } else { '\u{FFFD}' }).collect()),
494    };
495    let Some(mut out) = decoded else {
496        decoder_store(&this, &[], false);
497        return Err(it.type_error("Failed to execute 'decode' on 'TextDecoder': The encoded data was not valid."));
498    };
499    let mut seen = bom_seen;
500    if !seen && !out.is_empty() {
501        seen = true;
502        if !ignore_bom && matches!(enc.as_str(), "utf-8" | "utf-16le" | "utf-16be") && out.starts_with('\u{FEFF}') {
503            out.remove(0);
504        }
505    }
506    if stream {
507        decoder_store(&this, pending, seen);
508    } else {
509        decoder_store(&this, &[], false);
510    }
511    Ok(Value::str(out))
512}
513pub(crate) fn text_encoder_ctor(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
514    let o = Obj::plain();
515    {
516        let mut b = o.borrow_mut();
517        b.props.insert("encoding".into(), Value::str("utf-8"));
518        b.props.insert("encode".into(), nv("encode", text_encode));
519        b.props
520            .insert("encodeInto".into(), nv("encodeInto", text_encode_into));
521    }
522    Ok(Value::Object(o))
523}
524/// `new TextDecoder(label = "utf-8", {fatal = false, ignoreBOM = false})`。
525/// ラベルを正規化できない(未知、または本体が復号表を持たない符号化。`normalize_text_encoding_label` 参照)と `RangeError`。
526/// `encoding`・`fatal`・`ignoreBOM` は読み取り専用の属性(アクセサ)。
527pub(crate) fn text_decoder_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
528    let (enc, fatal, ignore_bom) = text_decoder_params(it, a, "TextDecoder")?;
529    let o = Obj::plain();
530    {
531        let mut b = o.borrow_mut();
532        b.props.insert("_enc".into(), Value::str(enc));
533        b.props.insert("_fatal".into(), Value::Bool(fatal));
534        b.props.insert("_ignore_bom".into(), Value::Bool(ignore_bom));
535        b.props.insert("decode".into(), nv("decode", text_decode));
536        insert_decoder_accessors(&mut b);
537    }
538    Ok(Value::Object(o))
539}
540fn decoder_get_encoding(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
541    Ok(match &this {
542        Value::Object(o) => o.borrow().props.get("_enc").cloned().unwrap_or_else(|| Value::str("utf-8")),
543        _ => Value::Undefined,
544    })
545}
546fn decoder_get_fatal(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
547    Ok(Value::Bool(decoder_flag(&this, "_fatal")))
548}
549fn decoder_get_ignore_bom(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
550    Ok(Value::Bool(decoder_flag(&this, "_ignore_bom")))
551}
552/// `encoding`・`fatal`・`ignoreBOM` の読み取り専用アクセサを `b` に足す(`TextDecoder`・`TextDecoderStream` 共通)。
553pub(crate) fn insert_decoder_accessors(b: &mut Obj) {
554    let acc = |g: NativeFn, n: &str| crate::os_lib::ecma::value::Accessor { get: Some(nv(n, g)), set: None };
555    b.insert_accessor(String::from("encoding"), acc(decoder_get_encoding, "encoding"));
556    b.insert_accessor(String::from("fatal"), acc(decoder_get_fatal, "fatal"));
557    b.insert_accessor(String::from("ignoreBOM"), acc(decoder_get_ignore_bom, "ignoreBOM"));
558}
559/// `TextDecoder`/`TextDecoderStream` の引数(ラベルと辞書)を検証して `(符号化名, fatal, ignoreBOM)` にする。
560pub(crate) fn text_decoder_params(it: &mut Interp, a: &[Value], who: &str) -> Result<(&'static str, bool, bool), Value> {
561    let label = match arg(a, 0) {
562        Value::Undefined => String::from("utf-8"),
563        v => v.to_js_string(),
564    };
565    let Some(enc) = normalize_text_encoding_label(&label) else {
566        return Err(it.range_error(alloc::format!("Failed to construct '{}': The encoding label provided ('{}') is invalid.", who, label)));
567    };
568    let (mut fatal, mut ignore_bom) = (false, false);
569    match arg(a, 1) {
570        Value::Undefined | Value::Null => {}
571        o @ Value::Object(_) => {
572            fatal = obj_prop(&o, "fatal").map(|v| v.truthy()).unwrap_or(false);
573            ignore_bom = obj_prop(&o, "ignoreBOM").map(|v| v.truthy()).unwrap_or(false);
574        }
575        _ => {
576            return Err(it.type_error(alloc::format!("Failed to construct '{}': parameter 2 is not of type 'TextDecoderOptions'.", who)));
577        }
578    }
579    Ok((enc, fatal, ignore_bom))
580}
581
582// ===== crypto =====
583/// `URL.createObjectURL(blob_or_media_source)`(`Blob`/`File`/`MediaSource` を一意な `blob:` URL 文字列へ
584/// 変換する定番パターン。`<video src=URL.createObjectURL(ms)>` や `<img src=URL.createObjectURL(blob)>`
585/// で広く使われる)。MediaSource の場合はグローバルの `__media_source_urls` に登録し、
586/// `<video>`/`<audio>` に割り当てられた際に sourceopen を自動発火できるようにする。
587pub(crate) fn url_create_object_url(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
588    let target = arg(a, 0);
589    let is_media_source = if let Value::Object(o) = &target {
590        let borrow = o.borrow();
591        borrow.props.contains_key("sourceBuffers")
592            || borrow.props.get("_is_media_source").map(|v| v.truthy()).unwrap_or(false)
593    } else {
594        false
595    };
596
597    let id = crypto_random_uuid(it, t, &[])?.to_js_string();
598    let url = if is_media_source {
599        alloc::format!("blob:mediasource-{}", id)
600    } else {
601        alloc::format!("blob:{}", id)
602    };
603
604    if is_media_source {
605        let existing = match it.global.borrow().vars.get("__media_source_urls") {
606            Some(Value::Object(r)) => Some(r.clone()),
607            _ => None,
608        };
609        let registry = match existing {
610            Some(r) => r,
611            None => {
612                let r = Obj::plain();
613                it.global.borrow_mut().vars.insert("__media_source_urls".into(), Value::Object(r.clone()));
614                r
615            }
616        };
617        super::mse::register_media_source_url(&url, &target);
618        registry.borrow_mut().props.insert(url.clone().into(), target);
619    } else {
620        let is_blob = if let Value::Object(o) = &target {
621            o.borrow().props.contains_key("_blob_bytes")
622        } else {
623            false
624        };
625        if is_blob {
626            let existing = match it.global.borrow().vars.get("__blob_urls") {
627                Some(Value::Object(r)) => Some(r.clone()),
628                _ => None,
629            };
630            let registry = match existing {
631                Some(r) => r,
632                None => {
633                    let r = Obj::plain();
634                    it.global.borrow_mut().vars.insert("__blob_urls".into(), Value::Object(r.clone()));
635                    r
636                }
637            };
638            registry.borrow_mut().props.insert(url.clone().into(), target);
639        }
640    }
641
642    Ok(Value::str(url))
643}
644/// `URL.revokeObjectURL(url)`。`__media_source_urls` および `__blob_urls` から解除する。
645pub(crate) fn url_revoke_object_url(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
646    let url = arg(a, 0).to_js_string();
647    if let Some(Value::Object(registry)) = it.global.borrow().vars.get("__media_source_urls") {
648        registry.borrow_mut().props.shift_remove(&url);
649    }
650    if let Some(Value::Object(registry)) = it.global.borrow().vars.get("__blob_urls") {
651        registry.borrow_mut().props.shift_remove(&url);
652    }
653    Ok(Value::Undefined)
654}
655pub(crate) fn crypto_random_uuid(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
656    let mut bytes = [0u8; 16];
657    for b in bytes.iter_mut() {
658        *b = (next_rand_u64() & 0xff) as u8;
659    }
660    bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
661    bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10
662    let mut s = String::new();
663    for (i, b) in bytes.iter().enumerate() {
664        if i == 4 || i == 6 || i == 8 || i == 10 {
665            s.push('-');
666        }
667        s.push_str(&format!("{:02x}", b));
668    }
669    Ok(Value::str(s))
670}
671/// `crypto.getRandomValues(typedArray)`。以前は種別を無視して全要素を無条件に
672/// `& 0xff`(0-255)で埋めており、`Int16Array`/`Int32Array`/`Uint32Array` 等
673/// 8bit より広い型に対しては本来の値域のごく一部(下位8bitのみ、常に非負)しか
674/// 埋められない、実質的にランダム性が大幅に弱まるバグだった。`_ta_kind` タグから
675/// 種別を復元し、コンストラクタ/`set`/索引代入と同じ `TaKind::convert()` で
676/// 型ごとの正しい値域に変換する。
677pub(crate) fn crypto_get_random_values(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
678    let v = arg(a, 0);
679    if let Value::Object(o) = &v {
680        let kind = o
681            .borrow()
682            .props
683            .get("_ta_kind")
684            .map(|v| v.to_js_string())
685            .map(|tag| TaKind::from_name(tag.as_str()));
686        if let ObjKind::Bytes(st) = &o.borrow().kind {
687            // 【2026-11-12】以前は 64 bit の乱数を f64 にして `set` へ渡していた。f64 は 53 bit しか持てず下位 11 bit が
688            // 0 になり、2^63 以上は `as i64` で張り付くので、`Uint8Array` は **0x00 か 0xFF しか入らなかった**
689            // (YouTube の再生の識別子 cpn が `AAA_____AA_AAA__` のように 2 種類の文字だけになっていた)。
690            // バイト列をそのまま乱数で埋める。
691            let mut pool = 0u64;
692            let mut left = 0u32;
693            st.fill_bytes_with(|| {
694                if left == 0 {
695                    pool = next_rand_u64();
696                    left = 8;
697                }
698                left -= 1;
699                let b = pool as u8;
700                pool >>= 8;
701                b
702            });
703            return Ok(v.clone());
704        }
705        let mut b = o.borrow_mut();
706        if let ObjKind::Array(items) = &mut b.kind {
707            for it2 in items.iter_mut() {
708                // f64 が正確に持てる 53 bit に切ってから型の値域へ丸める(上と同じ理由)。
709                let raw = Value::Number((next_rand_u64() >> 11) as f64);
710                *it2 = Value::Number(match kind {
711                    Some(k) => k.convert(&raw),
712                    None => (next_rand_u64() & 0xff) as f64,
713                });
714            }
715        }
716    }
717    Ok(v)
718}
719
720// ===== structuredClone(深いコピー。関数等の特殊種別は plain object に退化)=====
721/// `structuredClone` は仕様上、循環参照(`var a={}; a.self=a;`)や同一オブジェクトへの
722/// 複数参照(構造の共有)を正しく扱う必要がある。以前はそのための「複製済みオブジェクトの
723/// 記録」を一切持たず単純な再帰だけだったため、循環参照ではスタックオーバーフロー
724/// (この no_std カーネル環境ではクラッシュ/ハングになり得る)に陥っていた。
725/// `seen` に (元オブジェクト, 複製先オブジェクト) を積みながら辿ることで、複製先の
726/// 入れ物を先に作ってから中身を埋める(=自己参照が現れた時点で既に登録済みにする)。
727pub(crate) fn deep_clone_value(
728    it: &mut Interp,
729    v: &Value,
730    seen: &mut Vec<(crate::os_lib::ecma::value::ObjRef, crate::os_lib::ecma::value::ObjRef)>,
731) -> Result<Value, Value> {
732    deep_clone_value_depth(it, v, seen, 0)
733}
734
735fn deep_clone_value_depth(
736    it: &mut Interp,
737    v: &Value,
738    seen: &mut Vec<(crate::os_lib::ecma::value::ObjRef, crate::os_lib::ecma::value::ObjRef)>,
739    depth: usize,
740) -> Result<Value, Value> {
741    // 閾値30は、この関数がRustのネイティブ再帰で実装されているため
742    // JSの`max_steps`予算では防げない「Rustコールスタック自体のオーバーフロー」
743    // に対するガードとして機能する。ブート時点の`boot.S`初期コアスタックが
744    // わずか64KB(`(CoreID+1)*64KB`)しか無く、深い再帰がチェック到達前に
745    // スタックを枯渇させることを防止する。
746    // ※ 以前 `seen.len() > 30` でチェックしていたが、`seen` は累積の
747    // クローン済みオブジェクト数であるため、フラットな大配列(要素数>30)でも
748    // 誤ってエラーになるバグがあった。そのため再帰深さ `depth` で判定する。
749    if depth > 30 {
750        return Err(make_dom_exception("DataCloneError", "Exceeded maximum call stack size / nesting depth limit"));
751    }
752    let error_proto = match it.global.borrow().vars.get("Error") {
753        Some(Value::Object(ctor)) => match ctor.borrow().props.get("prototype") {
754            Some(Value::Object(p)) => Some(p.clone()),
755            _ => None,
756        },
757        _ => None,
758    };
759    match v {
760        Value::Object(o) => {
761            if let Some((_, cloned)) = seen.iter().find(|(orig, _)| Rc::ptr_eq(orig, o)) {
762                return Ok(Value::Object(cloned.clone()));
763            }
764            // 関数(`ObjKind::NativeFn`/`Closure`)は仕様上そもそも構造化複製
765            // 不可(`DataCloneError`)。以前は例外機構が無いという理由で他の
766            // 型(`Proxy`等)と同様「target へフォワード」する簡略実装が
767            // 検討されたが、関数には複製すべき target が無いため、汎用の
768            // plain object 複製に落ちて「呼出不能な壊れたオブジェクト」に
769            // 静かに化けるだけの実害しかなかった。`structured_clone`側は既に
770            // `Result`を返す口があるため、ここで素直に`DataCloneError`を
771            // 投げるよう修正(2026-07-17 発見・実装)。
772            if o.borrow().is_callable() {
773                return Err(make_dom_exception("DataCloneError", "could not be cloned"));
774            }
775            // `Promise`も仕様上構造化複製不可(`DataCloneError`)。実データが
776            // `.props`ではなく`ObjKind::PromiseObj`側にあるため、他の分岐に
777            // 落ちずここで先に処理しないと「`.props`だけをコピーする plain
778            // object化」に落ちて、`.then`/`.catch`(`ObjKind::PromiseObj`を
779            // 見て動的振り分けする実装のため`.props`には無い)が消えた
780            // 呼出不能な壊れたオブジェクトに静かに化ける(`Proxy`等と同種の
781            // 実害だが、`Proxy`と違い正しい簡略転送先が無いため素直に
782            // `DataCloneError`とする。2026-07-17 発見・実装)。
783            if matches!(&o.borrow().kind, ObjKind::PromiseObj(_)) {
784                return Err(make_dom_exception("DataCloneError", "could not be cloned"));
785            }
786            // `Proxy` は実データが `.props` ではなく `ObjKind::Proxy { target, .. }` 側に
787            // あるため、他の分岐に落ちずここで先に処理しないと「`.props` だけでコピーする
788            // plain object 化」に落ちて、常に空の `{}` に化ける壊れたクローンになる
789            // (`Date`/`Map`/`Set`/`TypedArray`/`Blob` 等で修正済みの「実体が消える」系と
790            // 同種のバグ)。仕様上 `Proxy` はそもそも構造化複製不可(`DataClone` エラー)
791            // だが、この処理系に例外機構の対応する仕組みが無いため、他の Proxy 透過性
792            // 修正(`Array.isArray`/`Object.keys` 等)と同じ「target へフォワード」方針で
793            // target を複製する簡略実装とする。
794            if matches!(&o.borrow().kind, ObjKind::Proxy(_)) {
795                let target = unwrap_proxy_target(o);
796                let cloned = deep_clone_value_depth(it, &Value::Object(target), seen, depth + 1)?;
797                if let Value::Object(c) = &cloned {
798                    seen.push((o.clone(), c.clone()));
799                }
800                return Ok(cloned);
801            }
802            // `Date`/`RegExp` は実データが `props` ではなく `ObjKind::DateObj`/`RegExpObj`
803            // 側にあるため、他の分岐に落ちずここで先に処理しないと「`.props` だけを
804            // コピーする plain object 化」に落ちて実データの消えた壊れたオブジェクトになる
805            // (`Map`/`Set` で過去に修正した同種のバグ)。`structuredClone(new Date())` が
806            // `{}` になる、`structuredClone(/re/g)` がパターンの消えた空オブジェクトになる、
807            // という実害があった。
808            if let ObjKind::DateObj(ms) = &o.borrow().kind {
809                return Ok(Value::Object(Obj::date_obj(*ms)));
810            }
811            let regex_info = match &o.borrow().kind {
812                ObjKind::RegExpObj(r) => {
813                    let d = r.borrow();
814                    Some((d.re.source.clone(), d.re.flags.clone(), d.last_index))
815                }
816                _ => None,
817            };
818            if let Some((source, flags, last_index)) = regex_info {
819                let re = regex::Regex::new(&source, &flags);
820                return Ok(Value::Object(Obj::regexp(RegExpData { re, last_index })));
821            }
822            // 1 バイト型 TypedArray(記憶域)はバイト列を写した新しい記憶域で複製する。
823            let bytes_ta = match &o.borrow().kind {
824                ObjKind::Bytes(st) => Some(st.clone()),
825                _ => None,
826            };
827            if let Some(st) = bytes_ta {
828                let tag = o.borrow().props.get("_ta_kind").map(|v| v.to_js_string()).unwrap_or_default();
829                let new_val = crate::os_lib::ecma::builtins::typed_array::make_bytes_ta(
830                    it,
831                    crate::os_lib::ecma::value::ByteStore::new(st.to_vec(), st.kind),
832                    TaKind::from_name(tag.as_str()),
833                );
834                if let Value::Object(new) = &new_val {
835                    seen.push((o.clone(), new.clone()));
836                }
837                return Ok(new_val);
838            }
839            let is_array = matches!(&o.borrow().kind, ObjKind::Array(_));
840            if is_array {
841                // TypedArray も内部表現は `ObjKind::Array` を流用しており(`_ta_kind`
842                // タグで種別を区別)、この分岐が `.props` を一切コピーせず素の
843                // `Obj::array` を作るだけだったため、`structuredClone(new Int8Array(...))`
844                // は `_ta_kind`/`BYTES_PER_ELEMENT`/`set`/`slice`/`fill` 等が全て失われた
845                // 「ただの配列」に化けてしまうバグだった(`Date`/`RegExp`/`Map`/`Set` で
846                // 過去に修正した「plain object 化で実体が消える」系と同種)。
847                let ta_kind_tag = o.borrow().props.get("_ta_kind").map(|v| v.to_js_string());
848                if let Some(tag) = ta_kind_tag {
849                    let items = match &o.borrow().kind {
850                        ObjKind::Array(items) => items.iter().map(|v| v.to_number()).collect(),
851                        _ => unreachable!(),
852                    };
853                    let new_val = make_typed_array(it, items, TaKind::from_name(tag.as_str()));
854                    if let Value::Object(new) = &new_val {
855                        seen.push((o.clone(), new.clone()));
856                    }
857                    return Ok(new_val);
858                }
859                let new = Obj::array(Vec::new());
860                seen.push((o.clone(), new.clone()));
861                let items = match &o.borrow().kind {
862                    ObjKind::Array(items) => items.clone(),
863                    _ => unreachable!(),
864                };
865                let mut cloned_items: Vec<Value> = Vec::with_capacity(items.len());
866                for x in &items {
867                    cloned_items.push(deep_clone_value_depth(it, x, seen, depth + 1)?);
868                }
869                if let ObjKind::Array(v) = &mut new.borrow_mut().kind {
870                    *v = cloned_items;
871                }
872                return Ok(Value::Object(new));
873            }
874            // Map/Set は「`.props` だけをコピーする plain object 化」に落ちると、実データが
875            // 入っている ObjKind::MapObj/SetObj 自体は複製されず中身が消えた壊れた
876            // オブジェクトになる実害のあるバグだった(過去に修正済み)。
877            let is_map = matches!(&o.borrow().kind, ObjKind::MapObj(_));
878            if is_map {
879                let new = Obj::map_obj(Vec::new());
880                seen.push((o.clone(), new.clone()));
881                let entries = match &o.borrow().kind {
882                    ObjKind::MapObj(e) => e.clone(),
883                    _ => unreachable!(),
884                };
885                let mut cloned: Vec<(Value, Value)> = Vec::with_capacity(entries.len());
886                for (k, val) in &entries {
887                    let ck = deep_clone_value_depth(it, k, seen, depth + 1)?;
888                    let cv = deep_clone_value_depth(it, val, seen, depth + 1)?;
889                    cloned.push((ck, cv));
890                }
891                if let ObjKind::MapObj(e) = &mut new.borrow_mut().kind {
892                    *e = cloned;
893                }
894                return Ok(Value::Object(new));
895            }
896            let is_set = matches!(&o.borrow().kind, ObjKind::SetObj(_));
897            if is_set {
898                let new = Obj::set_obj(Vec::new());
899                seen.push((o.clone(), new.clone()));
900                let items = match &o.borrow().kind {
901                    ObjKind::SetObj(s) => s.clone(),
902                    _ => unreachable!(),
903                };
904                let mut cloned: Vec<Value> = Vec::with_capacity(items.len());
905                for x in &items {
906                    cloned.push(deep_clone_value_depth(it, x, seen, depth + 1)?);
907                }
908                if let ObjKind::SetObj(s) = &mut new.borrow_mut().kind {
909                    *s = cloned;
910                }
911                return Ok(Value::Object(new));
912            }
913            // `Blob`/`DataView` も `Obj::plain()` + 隠しプロパティで実データを持つ実装
914            // のため、汎用の plain object 複製(全 `.props` を再帰複製)に落ちると、
915            // `slice`/`text`/`arrayBuffer`/`getUint8` 等のネイティブ関数プロパティが
916            // 「関数ではない別の空オブジェクト」として複製されてしまい、複製結果が
917            // 呼出不能な壊れたオブジェクトになるバグだった(`Date`/`RegExp`/`Map`/`Set`/
918            // `TypedArray` で修正済みの「実体が消える」系と同種)。
919            if let Some(Value::Object(bytes_obj)) = o.borrow().props.get("_blob_bytes").cloned() {
920                let bytes: alloc::vec::Vec<f64> = match &bytes_obj.borrow().kind {
921                    ObjKind::Array(items) => items.iter().map(|v| v.to_number()).collect(),
922                    _ => alloc::vec::Vec::new(),
923                };
924                let mime = o.borrow().props.get("type").map(|v| v.to_js_string()).unwrap_or_default();
925                // `File`(`Blob`を継承し`name`/`lastModified`を追加する
926                // `file_ctor`由来のオブジェクト)を複製すると、`Blob`分岐に
927                // 落ちて`name`/`lastModified`が失われ、素の`Blob`へ格下げ
928                // されるバグだった(`structuredClone(new File(...))`
929                // `.name`が`undefined`になる「実体が消える」系の派生バグ。
930                // 2026-07-17 発見・実装)。`name`プロパティの有無を`File`か
931                // `Blob`かの目印として使い、`File`なら追加で引き継ぐ。
932                // `webkitRelativePath`(2026-07-17 追加)も同じ理由で
933                // 一緒に引き継ぐ。
934                let file_meta = o.borrow().props.get("name").cloned().map(|name| {
935                    let last_modified =
936                        o.borrow().props.get("lastModified").cloned().unwrap_or(Value::Number(0.0));
937                    let webkit_relative_path =
938                        o.borrow().props.get("webkitRelativePath").cloned().unwrap_or_else(|| Value::str(""));
939                    (name, last_modified, webkit_relative_path)
940                });
941                let new_val = make_blob(bytes, mime);
942                if let (Value::Object(new), Some((name, last_modified, webkit_relative_path))) = (&new_val, file_meta) {
943                    new.borrow_mut().props.insert("name".into(), name);
944                    new.borrow_mut().props.insert("lastModified".into(), last_modified);
945                    new.borrow_mut().props.insert("webkitRelativePath".into(), webkit_relative_path);
946                }
947                if let Value::Object(new) = &new_val {
948                    seen.push((o.clone(), new.clone()));
949                }
950                return Ok(new_val);
951            }
952            if o.borrow().props.contains_key("_dv_bytes") {
953                let byte_values: alloc::vec::Vec<Value> = crate::os_lib::ecma::builtins::typed_array::dv_slice_bytes(o)
954                    .unwrap_or_default()
955                    .into_iter()
956                    .map(Value::Number)
957                    .collect();
958                let new_buffer = make_arraybuffer_with_bytes(byte_values.iter().map(|v| v.to_number()).collect());
959                let new_val = make_dataview(new_buffer, 0, byte_values);
960                if let Value::Object(new) = &new_val {
961                    seen.push((o.clone(), new.clone()));
962                }
963                return Ok(new_val);
964            }
965            // `ArrayBuffer` も同じ理由(`slice` がネイティブ関数プロパティ)で複製が
966            // 壊れる対象だった。`byteLength`+`slice` の組合せを `ArrayBuffer` の目印に
967            // 使う(この2つを両方持つのは `make_arraybuffer()` 由来のオブジェクトのみ)。
968            let is_arraybuffer = {
969                let b = o.borrow();
970                b.props.contains_key("byteLength")
971                    && matches!(b.props.get("slice"), Some(Value::Object(f)) if f.borrow().is_callable())
972            };
973            if is_arraybuffer {
974                // resizable な ArrayBuffer(ES2024。`.resizable`/`.maxByteLength`/
975                // `.resize()`)は複製時に非resizableな新規バッファへ落ちて
976                // いたバグだった(`make_arraybuffer_with_bytes`は常に
977                // 固定長版を作るため、`structuredClone(resizableBuf).resizable`
978                // が`false`になり`.resize()`も呼べなくなる「実体が消える」系の
979                // 派生バグ。2026-07-17 発見)。`make_arraybuffer_ex`で元の
980                // `resizable`/`maxByteLength`を引き継ぐよう修正。
981                let is_resizable = matches!(o.borrow().props.get("resizable"), Some(Value::Bool(true)));
982                let max_byte_length = o.borrow().props.get("maxByteLength").map(|v| v.to_number() as usize);
983                let bytes_prop = o.borrow().props.get("_bytes").cloned();
984                let byte_length = o
985                    .borrow()
986                    .props
987                    .get("byteLength")
988                    .map(|v| v.to_number() as usize)
989                    .unwrap_or(0);
990                let new_val = make_arraybuffer_ex(byte_length, if is_resizable { max_byte_length } else { None });
991                if let (Value::Object(new), Some(Value::Object(bytes_obj))) = (&new_val, &bytes_prop) {
992                    let bytes = crate::os_lib::ecma::builtins::typed_array::obj_byte_values(bytes_obj).unwrap_or_default();
993                    new.borrow_mut().props.insert(
994                        "_bytes".into(),
995                        Value::Object(Obj::bytes(crate::os_lib::ecma::value::ByteStore::new(bytes, 0))),
996                    );
997                }
998                if let Value::Object(new) = &new_val {
999                    seen.push((o.clone(), new.clone()));
1000                }
1001                return Ok(new_val);
1002            }
1003            // `Error`(とそのサブタイプ)も同じ理由(汎用 plain object 複製に落ちると
1004            // proto が引き継がれない)で複製が壊れるバグだった。`Error` 自体には
1005            // 専用の `ObjKind` が無く `message`/`name`/`stack` を持つ通常の `props`
1006            // オブジェクトのため、他の型と違って実データが消えるわけではないが、
1007            // `structuredClone(new TypeError('x')) instanceof Error` が `false` に
1008            // なる(プロトタイプ連鎖が Error.prototype に繋がらない)という実害が
1009            // あった(2026-07-14、`Error.prototype.stack` 実装時の点検で発見)。
1010            // この処理系は単一レルムのため、元オブジェクトの proto(`TypeError.
1011            // prototype` 等)をそのまま複製先へ引き継いでよい。
1012            let is_error = error_proto.as_ref().is_some_and(|ep| {
1013                let mut cur = o.borrow().proto.clone();
1014                let mut guard = 0;
1015                while let Some(c) = cur {
1016                    if Rc::ptr_eq(&c, ep) {
1017                        return true;
1018                    }
1019                    cur = c.borrow().proto.clone();
1020                    guard += 1;
1021                    if guard > 1000 {
1022                        break;
1023                    }
1024                }
1025                false
1026            });
1027            let new = Obj::plain();
1028            if is_error {
1029                new.borrow_mut().proto = o.borrow().proto.clone();
1030            }
1031            seen.push((o.clone(), new.clone()));
1032            let props: Vec<(String, Value)> =
1033                o.borrow().props.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
1034            for (k, val) in props {
1035                let cv = deep_clone_value_depth(it, &val, seen, depth + 1)?;
1036                new.borrow_mut().props.insert(k.into(), cv);
1037            }
1038            Ok(Value::Object(new))
1039        }
1040        other => Ok(other.clone()),
1041    }
1042}
1043/// `structuredClone(value, {transfer: [...]})` の第2引数 `transfer` が丸ごと
1044/// 無視されていた。実際のメモリ移動は行わない簡略実装だが、転送対象の
1045/// `ArrayBuffer` の `.detached` を `true` にし内部バイト列を破棄することで
1046/// `ArrayBuffer.prototype.transfer()` 自身の「二重 transfer はエラー」という
1047/// 既存チェック(`arraybuffer_transfer_impl`)とは整合する状態にする
1048/// (`slice()`/`byteLength` 自体が `detached` を見ない、という既存の簡略化は
1049/// そのまま踏襲する)。
1050pub(crate) fn structured_clone(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1051    let mut seen = Vec::new();
1052    let result = deep_clone_value(it, &arg(a, 0), &mut seen)?;
1053    if let Value::Object(opts) = arg(a, 1) {
1054        let transfer_list = opts.borrow().props.get("transfer").cloned();
1055        if let Some(list) = transfer_list {
1056            for item in this_items(&list) {
1057                if let Value::Object(o) = &item {
1058                    let is_arraybuffer = {
1059                        let b = o.borrow();
1060                        b.props.contains_key("byteLength")
1061                            && matches!(b.props.get("slice"), Some(Value::Object(f)) if f.borrow().is_callable())
1062                    };
1063                    if is_arraybuffer {
1064                        let mut b = o.borrow_mut();
1065                        b.props.insert("detached".into(), Value::Bool(true));
1066                        b.props.shift_remove("_bytes");
1067                    }
1068                }
1069            }
1070        }
1071    }
1072    Ok(result)
1073}
1074