typewire 0.0.3

Derive-based cross-language type bridging with compile-time schema embedding and multi-target codegen
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
//! Derive-based cross-language type bridging for Rust.
//!
//! `typewire` provides the [`Typewire`] trait and a derive macro that generates
//! platform-specific conversion methods and compile-time schema records from
//! your Rust types. Define types once in Rust, get type-safe foreign-language
//! bindings and declarations automatically.
//!
//! Currently supported targets:
//! - **WebAssembly** (wasm32) — `to_js` / `from_js` / `patch_js` via
//!   `wasm-bindgen`, with TypeScript `.d.ts` generation
//! - **Kotlin** and **Swift** — planned
//!
//! # Quick start
//!
//! ```
//! use typewire::Typewire;
//!
//! #[derive(Typewire)]
//! #[typewire(rename_all = "camelCase")]
//! struct CreateUser {
//!   user_name: String,
//!   age: u32,
//!   email: Option<String>,
//! }
//!
//! // Option<T> fields implicitly default to None when absent
//! assert_eq!(<Option<String>>::or_default(), Some(None));
//!
//! // Non-optional types have no implicit default
//! assert!(String::or_default().is_none());
//! ```
//!
//! On `wasm32`, this generates conversions matching the serde wire shape
//! (`{ "userName": ..., "age": ..., "email": ... }`), plus a `patch_js`
//! that updates foreign objects in place by diffing only changed fields.
//!
//! # Pipeline
//!
//! ```text
//! #[derive(Typewire)]  →  encode (link section)  →  decode  →  declarations
//!      (derive)             (typewire-schema)        (CLI)      (codegen)
//! ```
//!
//! 1. [`#[derive(Typewire)]`](Typewire) analyzes types and emits platform-gated
//!    conversion methods + schema records in link sections (when the `schemas`
//!    feature is enabled)
//! 2. The `typewire` CLI extracts schema records from compiled binaries and
//!    generates typed declarations for the target language
//! 3. The generated declarations match the wire format of the Rust types
//!
//! # Built-in type implementations
//!
//! | Category | Types |
//! |----------|-------|
//! | Booleans | [`bool`] |
//! | Integers | [`i8`], [`i16`], [`i32`], [`u8`], [`u16`], [`u32`] (exact) |
//! | Big integers | [`i64`], [`u64`], [`i128`], [`u128`], [`isize`], [`usize`] |
//! | Floats | [`f32`], [`f64`] |
//! | Strings | [`String`], [`Cow<str>`](std::borrow::Cow), [`char`] |
//! | Unit | `()` |
//! | Options | [`Option<T>`] |
//! | Sequences | [`Vec<T>`], `[T; N]` |
//! | Maps | [`HashMap`](std::collections::HashMap), [`BTreeMap`](std::collections::BTreeMap) |
//! | Tuples | `(A, B, ...)` up to 12 elements |
//! | Smart pointers | [`Box<T>`], [`Arc<T>`](std::sync::Arc), [`Rc<T>`](std::rc::Rc) |
//!
//! With optional features: `uuid`, `chrono`, `url`, `bytes`, `indexmap`,
//! `serde_json`, `fractional_index`.
//!
//! # Features
//!
//! | Feature | What it enables |
//! |---------|----------------|
//! | `derive` *(default)* | Re-exports [`#[derive(Typewire)]`](Typewire) |
//! | `schemas` | Embeds schema records in link sections for codegen |
//! | `uuid` | [`Typewire`] impl for `uuid::Uuid` |
//! | `chrono` | [`Typewire`] impl for `chrono::DateTime` |
//! | `url` | [`Typewire`] impl for `url::Url` |
//! | `bytes` | [`Typewire`] impl for `bytes::Bytes` |
//! | `indexmap` | [`Typewire`] impls for `IndexMap` / `IndexSet` |
//! | `base64` | [`base64_encode`] / [`base64_decode`] helpers |
//! | `serde_json` | [`Typewire`] impl for `serde_json::Value` |
//! | `cli` | Binary target for schema extraction + declaration generation |

mod error;

/// Conversion errors produced during foreign-language value decoding.
///
/// See [`Error`] for variant documentation.
pub use error::Error;
/// Derive macro for the [`Typewire`] trait.
///
/// See the [`typewire_derive`] crate for the full attribute reference.
///
/// # Examples
///
/// Named struct with field renaming:
///
/// ```
/// use typewire::Typewire;
///
/// #[derive(Typewire)]
/// #[typewire(rename_all = "camelCase")]
/// struct User {
///   user_name: String,
///   email: Option<String>,
/// }
/// ```
///
/// Internally-tagged enum:
///
/// ```
/// use typewire::Typewire;
///
/// #[derive(Typewire)]
/// #[typewire(tag = "kind")]
/// enum Shape {
///   Circle { radius: f64 },
///   Rect { width: f64, height: f64 },
/// }
/// ```
///
/// Transparent newtype:
///
/// ```
/// use typewire::Typewire;
///
/// #[derive(Typewire)]
/// #[typewire(transparent)]
/// struct UserId(String);
/// ```
#[cfg(feature = "derive")]
pub use typewire_derive::Typewire;
/// Schema metadata crate, re-exported for use by generated code.
///
/// End users typically don't interact with this directly — it is used by
/// the derive macro and the `typewire` CLI. See [`typewire_schema`] for
/// the pipeline documentation.
pub use typewire_schema as schema;

/// Base64-encode bytes to a string using the standard alphabet.
///
/// Called by generated code for fields annotated with `#[typewire(base64)]`.
///
/// ```
/// # #[cfg(feature = "base64")] {
/// let encoded = typewire::base64_encode(b"hello");
/// assert_eq!(encoded, "aGVsbG8=");
/// # }
/// ```
#[cfg(feature = "base64")]
#[must_use]
pub fn base64_encode(bytes: &[u8]) -> String {
  use base64::Engine as _;
  base64::engine::general_purpose::STANDARD.encode(bytes)
}

/// Base64-decode a string to bytes using the standard alphabet.
///
/// Called by generated code for fields annotated with `#[typewire(base64)]`.
///
/// # Errors
///
/// Returns [`base64::DecodeError`] if the input is not valid base64.
///
/// ```
/// # #[cfg(feature = "base64")] {
/// let bytes = typewire::base64_decode("aGVsbG8=").unwrap();
/// assert_eq!(bytes, b"hello");
///
/// assert!(typewire::base64_decode("not valid!").is_err());
/// # }
/// ```
#[cfg(feature = "base64")]
pub fn base64_decode(s: &str) -> Result<Vec<u8>, base64::DecodeError> {
  use base64::Engine as _;
  base64::engine::general_purpose::STANDARD.decode(s)
}

/// Bidirectional conversion between Rust types and foreign-language values.
///
/// This is the core trait of the typewire framework. It provides:
///
/// - **`Ident` / `IDENT`** — a compile-time type identity used by the schema
///   pipeline to embed type metadata in link sections (always available)
/// - **`or_default()`** — implicit defaults for absent fields (always available)
/// - **Platform-specific methods** — conversion to/from foreign values, gated
///   by `#[cfg]` (e.g. `to_js`/`from_js`/`patch_js` on `wasm32`)
///
/// # Deriving
///
/// Use [`#[derive(Typewire)]`](typewire_derive) to generate all implementations
/// automatically. The derive respects serde-compatible attributes:
///
/// ```
/// use typewire::Typewire;
///
/// #[derive(Clone, PartialEq, Debug, Typewire)]
/// #[typewire(rename_all = "camelCase")]
/// struct Point {
///   x_coord: f64,
///   y_coord: f64,
/// }
///
/// // No implicit default for structs
/// assert!(Point::or_default().is_none());
/// ```
///
/// # Manual implementation
///
/// For types not covered by the derive, implement the trait directly.
/// The `Ident` type must be one of the [`coded`](schema::coded) ident
/// types (e.g. [`PrimitiveIdent`](schema::coded::PrimitiveIdent),
/// [`Ident<N>`](schema::coded::Ident)).
///
/// ```ignore
/// use typewire::{Typewire, schema};
///
/// struct MyId(u64);
///
/// impl Typewire for MyId {
///   type Ident = schema::coded::PrimitiveIdent;
///   const IDENT: Self::Ident =
///     schema::coded::PrimitiveIdent::new(schema::Scalar::u64);
///
///   fn or_default() -> Option<Self> { None }
///
///   // On wasm32, also implement to_js/from_js/patch_js.
/// }
/// ```
pub trait Typewire: Sized {
  /// Compile-time type identity, embedded in link sections for schema extraction.
  ///
  /// For derived types this is [`coded::Ident<N>`](schema::coded::Ident) (the type
  /// name). For primitives it is [`coded::PrimitiveIdent`](schema::coded::PrimitiveIdent).
  /// For compound types it is a nested ident like
  /// [`coded::OptionIdent`](schema::coded::OptionIdent) or
  /// [`coded::SeqIdent`](schema::coded::SeqIdent).
  type Ident: Copy + 'static;

  /// The identity constant for this type.
  const IDENT: Self::Ident;

  /// Returns the implicit default for this type when a field is absent.
  ///
  /// Most types return `None` (no default — the field is required).
  /// [`Option<T>`] returns `Some(None)`, making optional fields implicitly
  /// default to `None` without requiring `#[serde(default)]`.
  ///
  /// ```
  /// use typewire::Typewire;
  ///
  /// // Option<T> implicitly defaults to None
  /// assert_eq!(<Option<i32>>::or_default(), Some(None));
  ///
  /// // Most types require an explicit value
  /// assert!(i32::or_default().is_none());
  /// assert!(String::or_default().is_none());
  /// assert!(<Vec<u8>>::or_default().is_none());
  /// ```
  #[must_use]
  fn or_default() -> Option<Self> {
    None
  }

  /// Converts this Rust value to a foreign-language value.
  ///
  /// On `wasm32`: converts to a [`JsValue`](wasm_bindgen::JsValue).
  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue;

  /// Converts a foreign-language value into this Rust type.
  ///
  /// On `wasm32`: converts from a [`JsValue`](wasm_bindgen::JsValue).
  ///
  /// # Errors
  ///
  /// Returns an [`Error`] if the value cannot be converted (e.g. wrong
  /// type, out-of-range, or missing required fields).
  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error>;

  /// Lenient variant of [`from_js`](Typewire::from_js) for
  /// `#[typewire(lenient)]` fields.
  ///
  /// The default delegates to [`from_js`](Typewire::from_js). Collection
  /// types ([`Vec`], [`Option`], maps) override this to skip invalid
  /// elements or default to `None` instead of propagating errors, logging
  /// a warning for each skipped value.
  ///
  /// # Errors
  ///
  /// Returns an [`Error`] if the value cannot be converted and the type
  /// does not support lenient fallback.
  #[cfg(target_arch = "wasm32")]
  fn from_js_lenient(value: wasm_bindgen::JsValue, _field: &str) -> Result<Self, Error> {
    Self::from_js(value)
  }

  /// Patches an existing foreign-language value in place.
  ///
  /// Compares `self` (the new value) against `old` (the existing value).
  /// If they differ, calls `set` with the new representation. Structs
  /// recurse into fields, preserving object identity. Collections use
  /// LCS-based diffing to emit minimal splice operations.
  ///
  /// Every type must either derive or manually implement this method.
  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue));
}

/// Atomic patching: round-trips `old` through [`from_js`](Typewire::from_js),
/// compares with [`PartialEq`], and calls `set(new.to_js())` only if changed.
///
/// Used by `#[diffable(atomic)]` types and by the derive for primitives,
/// tuple structs, unit structs, and all-unit enums. Unlike structural
/// patching (which recurses into fields), this replaces the entire value.
#[cfg(target_arch = "wasm32")]
pub fn patch_js_atomic<T: Typewire + PartialEq>(
  new: &T,
  old: &wasm_bindgen::JsValue,
  set: impl FnOnce(wasm_bindgen::JsValue),
) {
  match T::from_js(old.clone()) {
    Ok(ref old_val) if new == old_val => {}
    _ => set(new.to_js()),
  }
}

// ---------------------------------------------------------------------------
// Link section statics for built-in types
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Primitive implementations (only compiled on wasm32)
// ---------------------------------------------------------------------------

#[cfg(target_arch = "wasm32")]
mod wasm {
  use wasm_bindgen::JsValue;

  /// Returns `true` if the value is `null` or `undefined`.
  pub fn is_nullish(v: &JsValue) -> bool {
    v.is_null() || v.is_undefined()
  }

  /// Extract an `f64` from a JS number value.
  pub fn as_safe_f64(v: &JsValue) -> Option<f64> {
    v.as_f64()
  }

  /// Lossless `usize` → `u32` on wasm32 (where `usize` is 32-bit).
  #[expect(clippy::cast_possible_truncation, reason = "wasm32: usize == u32")]
  pub const fn as_u32(n: usize) -> u32 {
    n as u32
  }

  /// `isize` → `u32` on wasm32 (for non-negative index arithmetic).
  #[expect(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "wasm32: isize is i32, values are non-negative indices"
  )]
  pub const fn isize_as_u32(n: isize) -> u32 {
    n as u32
  }
}

#[cfg(target_arch = "wasm32")]
impl Typewire for wasm_bindgen::JsValue {
  type Ident = schema::coded::Ident<3>;
  const IDENT: Self::Ident = schema::coded::Ident::new(*b"any");

  fn to_js(&self) -> wasm_bindgen::JsValue {
    self.clone()
  }

  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    Ok(value)
  }

  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(Self)) {
    if old != self {
      set(self.clone());
    }
  }
}

impl Typewire for bool {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::bool);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::from_bool(*self)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    value.as_bool().ok_or(Error::UnexpectedType { expected: "boolean" })
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

macro_rules! impl_typewire_small_int {
  ($($ty:ident),*) => {$(
    impl Typewire for $ty {
      type Ident = schema::coded::PrimitiveIdent;
      const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(
        schema::Scalar::$ty,
      );

      #[cfg(target_arch = "wasm32")]
      fn to_js(&self) -> wasm_bindgen::JsValue {
        wasm_bindgen::JsValue::from_f64(f64::from(*self))
      }

      #[cfg(target_arch = "wasm32")]
      fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
        let n = wasm::as_safe_f64(&value)
          .ok_or(Error::UnexpectedType { expected: "number" })?;
        #[expect(
          clippy::cast_possible_truncation,
          reason = "checked by round-trip comparison below"
        )]
        let v = n as $ty;
        if f64::from(v).to_bits() == n.to_bits() {
          Ok(v)
        } else {
          Err(Error::OutOfRange)
        }
      }

      #[cfg(target_arch = "wasm32")]
      fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
        patch_js_atomic(self, old, set);
      }
    }
  )*};
}

impl_typewire_small_int!(i8, i16, i32);

macro_rules! impl_typewire_small_uint {
  ($($ty:ident),*) => {$(
    impl Typewire for $ty {
      type Ident = schema::coded::PrimitiveIdent;
      const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(
        schema::Scalar::$ty,
      );

      #[cfg(target_arch = "wasm32")]
      fn to_js(&self) -> wasm_bindgen::JsValue {
        wasm_bindgen::JsValue::from_f64(f64::from(*self))
      }

      #[cfg(target_arch = "wasm32")]
      fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
        let n = wasm::as_safe_f64(&value)
          .ok_or(Error::UnexpectedType { expected: "number" })?;
        #[expect(
          clippy::cast_possible_truncation,
          clippy::cast_sign_loss,
          reason = "checked by round-trip comparison below"
        )]
        let v = n as $ty;
        if f64::from(v).to_bits() == n.to_bits() {
          Ok(v)
        } else {
          Err(Error::OutOfRange)
        }
      }

      #[cfg(target_arch = "wasm32")]
      fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
        patch_js_atomic(self, old, set);
      }
    }
  )*};
}

impl_typewire_small_uint!(u8, u16, u32);

impl Typewire for f32 {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::f32);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::from_f64(f64::from(*self))
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    let n = wasm::as_safe_f64(&value).ok_or(Error::UnexpectedType { expected: "number" })?;
    #[expect(clippy::cast_possible_truncation, reason = "f64 → f32 narrowing is intentional")]
    Ok(n as Self)
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

impl Typewire for f64 {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::f64);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::from_f64(*self)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    wasm::as_safe_f64(&value).ok_or(Error::UnexpectedType { expected: "number" })
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

macro_rules! impl_typewire_lossy {
  (unsigned: $($uty:ident),*; signed: $($sty:ident),*) => {
    $(impl_typewire_lossy!(@impl $uty, cast_possible_truncation, cast_sign_loss);)*
    $(impl_typewire_lossy!(@impl $sty, cast_possible_truncation);)*
  };
  (@impl $ty:ident, $($lint:ident),+) => {
    impl Typewire for $ty {
      type Ident = schema::coded::PrimitiveIdent;
      const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(
        schema::Scalar::$ty,
      );

      #[cfg(target_arch = "wasm32")]
      fn to_js(&self) -> wasm_bindgen::JsValue {
        #[expect(
          clippy::cast_precision_loss,
          reason = "JS numbers are f64 — precision loss is inherent"
        )]
        let number = *self as f64;
        #[expect(
          $(clippy::$lint,)+
          reason = "round-trip check detects precision loss"
        )]
        let roundtrip = number as $ty;
        if roundtrip != *self {
          log::warn!("lossy conversion of {self} to JS number: {number}");
        }

        wasm_bindgen::JsValue::from(number)
      }

      #[cfg(target_arch = "wasm32")]
      fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
        use wasm_bindgen::JsCast as _;

        if let Some(number) = wasm::as_safe_f64(&value) {
          #[expect(
            $(clippy::$lint,)+
            reason = "lossy conversion is intentional — saturates for out-of-range values"
          )]
          return Ok(number as $ty);
        }

        let bigint = value
          .dyn_into::<js_sys::BigInt>()
          .map_err(|_| Error::UnexpectedType { expected: "bigint" })?;
        <$ty>::try_from(bigint).map_err(|_| Error::OutOfRange)
      }

      #[cfg(target_arch = "wasm32")]
      fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
        patch_js_atomic(self, old, set);
      }
    }
  };
}

impl_typewire_lossy!(unsigned: u64, u128; signed: i64, i128);

impl Typewire for usize {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::usize);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    // On wasm32, usize is u32 — fits in f64 without precision loss.
    #[expect(
      clippy::cast_precision_loss,
      reason = "on wasm32 usize is u32, which fits exactly in f64"
    )]
    let n = *self as f64;
    wasm_bindgen::JsValue::from_f64(n)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    let n = wasm::as_safe_f64(&value).ok_or(Error::UnexpectedType { expected: "number" })?;
    #[expect(
      clippy::cast_possible_truncation,
      clippy::cast_sign_loss,
      reason = "on wasm32, usize is u32 — fits exactly in f64"
    )]
    Ok(n as Self)
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

impl Typewire for isize {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::isize);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    // On wasm32, isize is i32 — fits in f64 without precision loss.
    #[expect(
      clippy::cast_precision_loss,
      reason = "on wasm32 isize is i32, which fits exactly in f64"
    )]
    let n = *self as f64;
    wasm_bindgen::JsValue::from_f64(n)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    let n = wasm::as_safe_f64(&value).ok_or(Error::UnexpectedType { expected: "number" })?;
    #[expect(
      clippy::cast_possible_truncation,
      reason = "on wasm32, isize is i32 — fits exactly in f64"
    )]
    Ok(n as Self)
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

impl Typewire for char {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::char);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::from_str(&self.to_string())
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    let s = value.as_string().ok_or(Error::UnexpectedType { expected: "string" })?;
    let mut chars = s.chars();
    let Some(c) = chars.next() else {
      return Err(Error::InvalidValue { message: "empty string".into() });
    };
    if chars.next().is_some() {
      return Err(Error::InvalidValue { message: "expected single character".into() });
    }
    Ok(c)
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

impl Typewire for String {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::str);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::from_str(self)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    value.as_string().ok_or(Error::UnexpectedType { expected: "string" })
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

impl Typewire for std::borrow::Cow<'_, str> {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::str);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::from_str(self)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    value
      .as_string()
      .map(std::borrow::Cow::Owned)
      .ok_or(Error::UnexpectedType { expected: "string" })
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

impl Typewire for () {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::Unit);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::NULL
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(_value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    Ok(())
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, _old: &wasm_bindgen::JsValue, _set: impl FnOnce(wasm_bindgen::JsValue)) {
    // Unit type is a singleton — nothing to diff.
  }
}

// ---------------------------------------------------------------------------
// Compound types
// ---------------------------------------------------------------------------

impl<T: Typewire> Typewire for Option<T> {
  type Ident = schema::coded::OptionIdent<T::Ident>;
  const IDENT: Self::Ident = schema::coded::OptionIdent::new(T::IDENT);

  fn or_default() -> Option<Self> {
    Some(None)
  }

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    self.as_ref().map_or(wasm_bindgen::JsValue::NULL, Typewire::to_js)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    if wasm::is_nullish(&value) { Ok(None) } else { T::from_js(value).map(Some) }
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js_lenient(value: wasm_bindgen::JsValue, field: &str) -> Result<Self, Error> {
    if wasm::is_nullish(&value) {
      Ok(None)
    } else {
      match T::from_js(value) {
        Ok(v) => Ok(Some(v)),
        Err(e) => {
          log::warn!("{field}: defaulting to None: {e}");
          Ok(None)
        }
      }
    }
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    match self {
      None => {
        if !wasm::is_nullish(old) {
          set(wasm_bindgen::JsValue::NULL);
        }
      }
      Some(v) => {
        if wasm::is_nullish(old) {
          set(v.to_js());
        } else {
          v.patch_js(old, set);
        }
      }
    }
  }
}

/// Converts an iterator of `&T` references to a JS array via
/// [`Typewire::to_js`].
///
/// Convenience wrapper around [`array`] for borrowed iterators.
#[cfg(target_arch = "wasm32")]
pub fn array_ref<'a, T: Typewire + 'a>(
  iter: impl IntoIterator<Item = &'a T>,
) -> wasm_bindgen::JsValue {
  array(iter.into_iter().map(Typewire::to_js))
}

/// Converts an iterator of owned `JsValue`s into a JS array.
///
/// Pre-allocates if the iterator reports an exact size.
#[cfg(target_arch = "wasm32")]
pub fn array<T: Typewire>(iter: impl IntoIterator<Item = T>) -> wasm_bindgen::JsValue {
  let iter = iter.into_iter();
  let (low, high) = iter.size_hint();
  let arr;
  if Some(low) == high {
    arr = js_sys::Array::new_with_length(wasm::as_u32(low));
    for (i, item) in iter.enumerate() {
      arr.set(wasm::as_u32(i), item.to_js());
    }
  } else {
    arr = js_sys::Array::new();
    for item in iter {
      arr.push(&item.to_js());
    }
  }
  arr.into()
}

impl<T: Typewire> Typewire for Vec<T> {
  type Ident = schema::coded::SeqIdent<T::Ident>;
  const IDENT: Self::Ident = schema::coded::SeqIdent::new(T::IDENT);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    array_ref(self.iter())
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;

    let arr: js_sys::Array =
      value.dyn_into().map_err(|_| Error::UnexpectedType { expected: "array" })?;
    let mut out = Self::with_capacity(arr.length() as usize);
    for i in 0..arr.length() {
      out.push(T::from_js(arr.get(i))?);
    }
    Ok(out)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js_lenient(value: wasm_bindgen::JsValue, field: &str) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;

    let Some(arr) = value.dyn_ref::<js_sys::Array>() else {
      log::warn!("{field}: expected array, skipping (got {:?})", value.js_typeof());
      return Ok(Self::new());
    };
    let mut out = Self::with_capacity(arr.length() as usize);
    for i in 0..arr.length() {
      match T::from_js(arr.get(i)) {
        Ok(v) => out.push(v),
        Err(e) => log::warn!("{field}[{i}]: skipping invalid element: {e}"),
      }
    }
    Ok(out)
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_slice(self.iter(), old, set);
  }
}

/// LCS-based slice patching with `T::patch_js` delegation.
///
/// Builds a patched `JsValue` array by calling `T::patch_js` on each element
/// positionally. Unchanged elements keep the same JS reference as the old array.
/// Then uses `similar`'s LCS algorithm on the `JsValue` references (`===`) to
/// compute minimal splice operations.
///
/// Does NOT require `T: PartialEq` — comparison uses JS reference identity.
#[cfg(target_arch = "wasm32")]
#[expect(clippy::missing_panics_doc, reason = "built-in diff hooks never fail")]
pub fn patch_js_slice<'a, T: Typewire + 'a>(
  new: impl ExactSizeIterator<Item = &'a T> + Clone,
  old: &wasm_bindgen::JsValue,
  set: impl FnOnce(wasm_bindgen::JsValue),
) {
  use similar::algorithms::{Capture, Compact, Replace as SimilarReplace};
  use wasm_bindgen::JsCast as _;

  let Some(arr) = old.dyn_ref::<js_sys::Array>() else {
    set(array_ref(new));
    return;
  };

  let old_len = arr.length() as usize;
  let new_len = new.len();

  // Fast path: same length
  if old_len == new_len {
    for (i, elem) in new.enumerate() {
      let idx = wasm::as_u32(i);
      elem.patch_js(&arr.get(idx), |val| arr.set(idx, val));
    }
    return;
  }

  // Collect old JS references
  let old_refs: Vec<wasm_bindgen::JsValue> =
    (0..old_len).map(|i| arr.get(wasm::as_u32(i))).collect();

  // Build patched refs: for each new element, try patch_js against the
  // positionally corresponding old element. If unchanged, the old ref is kept.
  // If changed or new, we get a fresh JsValue.
  let mut patched_refs: Vec<wasm_bindgen::JsValue> = Vec::with_capacity(new_len);
  for (i, elem) in new.enumerate() {
    if i < old_len {
      let mut result = old_refs[i].clone();
      elem.patch_js(&old_refs[i], |v| result = v);
      patched_refs.push(result);
    } else {
      patched_refs.push(elem.to_js());
    }
  }

  // LCS diff on JsValue references — === compares by reference identity,
  // so unchanged elements (same ref) are matched as Equal.
  let mut d = Compact::new(SimilarReplace::new(Capture::new()), &old_refs, &patched_refs);
  similar::algorithms::lcs::diff(&mut d, &old_refs, 0..old_len, &patched_refs, 0..new_len)
    .expect("built-in diff hooks do not fail");

  let ops = d.into_inner().into_inner().into_ops();

  let mut offset: isize = 0;

  #[expect(clippy::cast_possible_wrap, reason = "wasm32 array indices fit in isize")]
  for op in ops {
    match op {
      similar::DiffOp::Equal { old_index, new_index, len } => {
        // Elements matched by reference — patch in place (already done
        // during patched_refs construction, but we need to update the
        // actual array if the position shifted due to prior splices)
        for ix in 0..len {
          let target_idx = wasm::as_u32(new_index + ix);
          let actual_idx = wasm::isize_as_u32((old_index + ix) as isize + offset);
          if actual_idx == target_idx {
            // Same position — the value is already patched_refs[i]
            // which may have been updated by patch_js
            arr.set(actual_idx, patched_refs[new_index + ix].clone());
          } else {
            // Position shifted — move element
            arr.set(target_idx, patched_refs[new_index + ix].clone());
          }
        }
      }
      similar::DiffOp::Delete { old_len, old_index, .. } => {
        let at = wasm::isize_as_u32(old_index as isize + offset);
        arr.splice_many(at, wasm::as_u32(old_len), &[]);
        offset -= old_len as isize;
      }
      similar::DiffOp::Insert { new_index, new_len, .. } => {
        arr.splice_many(wasm::as_u32(new_index), 0, &patched_refs[new_index..new_index + new_len]);
        offset += new_len as isize;
      }
      similar::DiffOp::Replace { old_index, old_len, new_index, new_len, .. } => {
        let at = wasm::isize_as_u32(old_index as isize + offset);
        arr.splice_many(at, wasm::as_u32(old_len), &patched_refs[new_index..new_index + new_len]);
        offset -= old_len as isize;
        offset += new_len as isize;
      }
    }
  }
}

macro_rules! impl_typewire_deref {
  ($($wrapper:ty),+) => {$(
    impl<T: Typewire> Typewire for $wrapper {
      type Ident = T::Ident;
      const IDENT: Self::Ident = T::IDENT;

      #[cfg(target_arch = "wasm32")]
      fn to_js(&self) -> wasm_bindgen::JsValue {
        (**self).to_js()
      }

      #[cfg(target_arch = "wasm32")]
      fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
        T::from_js(value).map(Self::from)
      }

      #[cfg(target_arch = "wasm32")]
      fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
        (**self).patch_js(old, set);
      }
    }
  )+};
}

impl_typewire_deref!(Box<T>, std::sync::Arc<T>, std::rc::Rc<T>);

impl<T: Typewire, const N: usize> Typewire for [T; N] {
  type Ident = schema::coded::SeqIdent<T::Ident>;
  const IDENT: Self::Ident = schema::coded::SeqIdent::new(T::IDENT);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    let arr = js_sys::Array::new_with_length(wasm::as_u32(N));
    for (i, item) in self.iter().enumerate() {
      arr.set(wasm::as_u32(i), item.to_js());
    }
    arr.into()
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;

    let arr: js_sys::Array =
      value.dyn_into().map_err(|_| Error::UnexpectedType { expected: "array" })?;
    if arr.length() as usize != N {
      return Err(Error::InvalidValue {
        message: format!("expected array of length {N}, got {}", arr.length()),
      });
    }
    // SAFETY: `MaybeUninit<T>` does not require initialisation, so an array
    // of `MaybeUninit` values is valid even when uninitialised.
    let mut out: [std::mem::MaybeUninit<T>; N] =
      unsafe { std::mem::MaybeUninit::uninit().assume_init() };
    for (i, slot) in out.iter_mut().enumerate() {
      match T::from_js(arr.get(wasm::as_u32(i))) {
        Ok(v) => {
          slot.write(v);
        }
        Err(e) => {
          // Drop already-initialized elements before returning.
          for already in &mut out[..i] {
            // SAFETY: elements at indices `0..i` have been initialised by
            // previous loop iterations.
            unsafe { already.assume_init_drop() };
          }
          return Err(e);
        }
      }
    }
    // SAFETY: all elements have been initialized.
    Ok(unsafe { std::mem::transmute_copy::<_, [T; N]>(&out) })
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    use wasm_bindgen::JsCast as _;
    let Some(arr) = old.dyn_ref::<js_sys::Array>() else {
      set(self.to_js());
      return;
    };
    for (i, elem) in self.iter().enumerate() {
      let idx = wasm::as_u32(i);
      elem.patch_js(&arr.get(idx), |v| arr.set(idx, v));
    }
  }
}

// --- Maps → JS objects ---

/// Patches a JS object in place by iterating new key-value entries, recursing
/// into each value's `patch_js`, and deleting keys that are no longer present.
///
/// Used by `HashMap`, `BTreeMap`, and `serde_json::Value::Object`.
#[cfg(target_arch = "wasm32")]
pub fn patch_js_map<'a, V: Typewire + 'a>(
  entries: impl IntoIterator<Item = (wasm_bindgen::JsValue, &'a V)>,
  contains_key: impl Fn(&wasm_bindgen::JsValue) -> bool,
  to_js: impl FnOnce() -> wasm_bindgen::JsValue,
  old: &wasm_bindgen::JsValue,
  set: impl FnOnce(wasm_bindgen::JsValue),
) {
  use wasm_bindgen::JsCast as _;

  let Some(old_obj) = old.dyn_ref::<js_sys::Object>() else {
    set(to_js());
    return;
  };
  // Arrays are objects in JS — don't patch an array as a keyed object
  if js_sys::Array::is_array(old) {
    set(to_js());
    return;
  }

  // Snapshot old keys before patching — avoids iterating newly-added keys
  // during the delete pass below.
  let old_keys = js_sys::Object::keys(old_obj);

  // Patch existing and new keys
  for (k_js, v) in entries {
    let old_v = js_sys::Reflect::get(old, &k_js).unwrap_or(wasm_bindgen::JsValue::UNDEFINED);
    v.patch_js(&old_v, |new_v| {
      let _ = js_sys::Reflect::set(old, &k_js, &new_v);
    });
  }

  // Delete keys present in old but not in new
  for i in 0..old_keys.length() {
    let key = old_keys.get(i);
    if !contains_key(&key) {
      let _ = js_sys::Reflect::delete_property(old_obj, &key);
    }
  }
}

impl<K: Typewire + Eq + core::hash::Hash, V: Typewire, S: ::std::hash::BuildHasher + Default>
  Typewire for std::collections::HashMap<K, V, S>
{
  type Ident = schema::coded::MapIdent<K::Ident, V::Ident>;
  const IDENT: Self::Ident = schema::coded::MapIdent::new(K::IDENT, V::IDENT);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    let obj = js_sys::Object::new();
    for (k, v) in self {
      // Reflect::set on a plain Object is infallible — safe to discard the result.
      // This applies to all `let _ = Reflect::set(...)` calls throughout this crate.
      let _ = js_sys::Reflect::set(&obj, &k.to_js(), &v.to_js());
    }
    obj.into()
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;
    let entries = js_sys::Object::entries(
      value.dyn_ref::<js_sys::Object>().ok_or(Error::UnexpectedType { expected: "object" })?,
    );
    let mut map = Self::default();
    map.reserve(entries.length() as usize);
    for i in 0..entries.length() {
      let pair: js_sys::Array =
        entries.get(i).dyn_into().map_err(|_| Error::UnexpectedType { expected: "array" })?;
      let key = K::from_js(pair.get(0))?;
      let val = V::from_js(pair.get(1))?;
      map.insert(key, val);
    }
    Ok(map)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js_lenient(value: wasm_bindgen::JsValue, field: &str) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;
    let Some(obj) = value.dyn_ref::<js_sys::Object>() else {
      log::warn!("{field}: expected object, skipping");
      return Ok(Self::default());
    };
    let entries = js_sys::Object::entries(obj);
    let mut map = Self::default();
    map.reserve(entries.length() as usize);
    for i in 0..entries.length() {
      let pair: js_sys::Array = entries.get(i).into();
      match (K::from_js(pair.get(0)), V::from_js(pair.get(1))) {
        (Ok(k), Ok(v)) => {
          map.insert(k, v);
        }
        (Err(e), _) | (_, Err(e)) => {
          log::warn!("{field}: skipping entry {i}: {e}");
        }
      }
    }
    Ok(map)
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_map(
      self.iter().map(|(k, v)| (k.to_js(), v)),
      |js_key| K::from_js(js_key.clone()).ok().is_some_and(|k| self.contains_key(&k)),
      || self.to_js(),
      old,
      set,
    );
  }
}

impl<K: Typewire + Ord, V: Typewire> Typewire for std::collections::BTreeMap<K, V> {
  type Ident = schema::coded::MapIdent<K::Ident, V::Ident>;
  const IDENT: Self::Ident = schema::coded::MapIdent::new(K::IDENT, V::IDENT);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    let obj = js_sys::Object::new();
    for (k, v) in self {
      let _ = js_sys::Reflect::set(&obj, &k.to_js(), &v.to_js());
    }
    obj.into()
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;
    let entries = js_sys::Object::entries(
      value.dyn_ref::<js_sys::Object>().ok_or(Error::UnexpectedType { expected: "object" })?,
    );
    let mut map = Self::new();
    for i in 0..entries.length() {
      let pair: js_sys::Array =
        entries.get(i).dyn_into().map_err(|_| Error::UnexpectedType { expected: "array" })?;
      let key = K::from_js(pair.get(0))?;
      let val = V::from_js(pair.get(1))?;
      map.insert(key, val);
    }
    Ok(map)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js_lenient(value: wasm_bindgen::JsValue, field: &str) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;
    let Some(obj) = value.dyn_ref::<js_sys::Object>() else {
      log::warn!("{field}: expected object, skipping");
      return Ok(Self::default());
    };
    let entries = js_sys::Object::entries(obj);
    let mut map = Self::new();
    for i in 0..entries.length() {
      let pair: js_sys::Array = if let Ok(a) = entries.get(i).dyn_into() {
        a
      } else {
        log::warn!("{field}: skipping entry {i}: not an array");
        continue;
      };
      match (K::from_js(pair.get(0)), V::from_js(pair.get(1))) {
        (Ok(k), Ok(v)) => {
          map.insert(k, v);
        }
        (Err(e), _) | (_, Err(e)) => {
          log::warn!("{field}: skipping entry {i}: {e}");
        }
      }
    }
    Ok(map)
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_map(
      self.iter().map(|(k, v)| (k.to_js(), v)),
      |js_key| K::from_js(js_key.clone()).ok().is_some_and(|k| self.contains_key(&k)),
      || self.to_js(),
      old,
      set,
    );
  }
}

// --- Tuples ---

macro_rules! impl_typewire_tuple {
  ($n:literal, $types:ident; $($idx:tt : $T:ident),+) => {
    impl<$($T: Typewire),+> Typewire for ($($T,)+) {
      type Ident = schema::coded::TupleIdent<
        schema::coded::$types<$($T::Ident),+>>;
      const IDENT: Self::Ident = schema::coded::TupleIdent::new(
        $n, schema::coded::$types($($T::IDENT),+));

      #[cfg(target_arch = "wasm32")]
      fn to_js(&self) -> wasm_bindgen::JsValue {
        let arr = js_sys::Array::new();
        $(arr.push(&self.$idx.to_js());)+
        arr.into()
      }

      #[cfg(target_arch = "wasm32")]
      fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
        let arr: js_sys::Array = value
          .try_into()
          .map_err(|_| Error::UnexpectedType { expected: "array" })?;
        Ok(($($T::from_js(arr.get($idx))?,)+))
      }

      #[cfg(target_arch = "wasm32")]
      fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
        use wasm_bindgen::JsCast as _;
        let Some(arr) = old.dyn_ref::<js_sys::Array>() else {
          set(self.to_js());
          return;
        };
        $(self.$idx.patch_js(&arr.get($idx), |v| arr.set($idx, v));)+
      }
    }
  };
}

impl_typewire_tuple!(1, Types1; 0: A);
impl_typewire_tuple!(2, Types2; 0: A, 1: B);
impl_typewire_tuple!(3, Types3; 0: A, 1: B, 2: C);
impl_typewire_tuple!(4, Types4; 0: A, 1: B, 2: C, 3: D);
impl_typewire_tuple!(5, Types5; 0: A, 1: B, 2: C, 3: D, 4: E);
impl_typewire_tuple!(6, Types6; 0: A, 1: B, 2: C, 3: D, 4: E, 5: F);
impl_typewire_tuple!(7, Types7; 0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G);
impl_typewire_tuple!(8, Types8; 0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H);
impl_typewire_tuple!(9, Types9; 0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I);
impl_typewire_tuple!(10, Types10; 0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J);
impl_typewire_tuple!(11, Types11; 0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K);
impl_typewire_tuple!(12, Types12; 0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L);

// ---------------------------------------------------------------------------
// Feature-gated implementations
// ---------------------------------------------------------------------------

#[cfg(feature = "uuid")]
impl Typewire for uuid::Uuid {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::Uuid);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::from_str(&self.to_string())
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    let s = value.as_string().ok_or(Error::UnexpectedType { expected: "string" })?;
    Self::try_parse(&s).map_err(|e| Error::InvalidValue { message: e.to_string() })
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

#[cfg(feature = "fractional_index")]
impl Typewire for fractional_index::FractionalIndex {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::FractionalIndex);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::from_str(&self.to_string())
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    let s = value.as_string().ok_or(Error::UnexpectedType { expected: "string" })?;
    Self::from_string(&s).map_err(|e| Error::InvalidValue { message: e.to_string() })
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

#[cfg(feature = "chrono")]
impl<Tz: chrono::TimeZone> Typewire for chrono::DateTime<Tz>
where
  Tz::Offset: core::fmt::Display,
  Self: From<chrono::DateTime<chrono::FixedOffset>>,
{
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::DateTime);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::from_str(&self.to_rfc3339())
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    let s = value.as_string().ok_or(Error::UnexpectedType { expected: "string" })?;
    chrono::DateTime::parse_from_rfc3339(&s)
      .map(Into::into)
      .map_err(|e| Error::InvalidValue { message: e.to_string() })
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

#[cfg(feature = "url")]
impl Typewire for url::Url {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::Url);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    wasm_bindgen::JsValue::from_str(self.as_str())
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    let s = value.as_string().ok_or(Error::UnexpectedType { expected: "string" })?;
    Self::parse(&s).map_err(|e| Error::InvalidValue { message: e.to_string() })
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

#[cfg(feature = "serde_json")]
impl Typewire for serde_json::Value {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::SerdeJsonValue);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    match self {
      Self::Null => wasm_bindgen::JsValue::NULL,
      Self::Bool(b) => wasm_bindgen::JsValue::from_bool(*b),
      // serde_json::Number always represents a finite JSON number, so as_f64()
      // only returns None for values outside f64 range (extremely rare). Fall
      // back to 0.0 and log rather than silently producing NaN.
      Self::Number(n) => {
        let v = n.as_f64().unwrap_or_else(|| {
          log::warn!("serde_json::Number {n} is not representable as f64, using 0.0");
          0.0
        });
        wasm_bindgen::JsValue::from_f64(v)
      }
      Self::String(s) => wasm_bindgen::JsValue::from_str(s),
      Self::Array(arr) => array_ref(arr.iter()),
      Self::Object(map) => {
        let obj = js_sys::Object::new();
        for (k, v) in map {
          let _ = js_sys::Reflect::set(&obj, &wasm_bindgen::JsValue::from_str(k), &v.to_js());
        }
        obj.into()
      }
    }
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;

    if value.is_null() || value.is_undefined() {
      Ok(Self::Null)
    } else if let Some(b) = value.as_bool() {
      Ok(Self::Bool(b))
    } else if let Some(n) = value.as_f64() {
      // JS only has f64 — recover integer representation for whole numbers
      // so that round-tripping preserves serde_json's i64/u64 distinction.
      if n.fract() == 0.0 {
        #[expect(
          clippy::cast_possible_truncation,
          reason = "intentional: detecting if f64 fits in i64"
        )]
        let i = n as i64;
        #[expect(
          clippy::float_cmp,
          clippy::cast_precision_loss,
          reason = "exact round-trip check: i64 → f64 → i64 preserves value"
        )]
        if i as f64 == n {
          return Ok(Self::Number(i.into()));
        }
        #[expect(
          clippy::cast_possible_truncation,
          clippy::cast_sign_loss,
          reason = "intentional: detecting if f64 fits in u64"
        )]
        let u = n as u64;
        #[expect(
          clippy::float_cmp,
          clippy::cast_precision_loss,
          reason = "exact round-trip check: u64 → f64 → u64 preserves value"
        )]
        if u as f64 == n {
          return Ok(Self::Number(u.into()));
        }
      }
      serde_json::Number::from_f64(n).map(serde_json::Value::Number).ok_or_else(|| {
        Error::InvalidValue { message: "invalid JSON number (NaN or Infinity)".into() }
      })
    } else if let Some(s) = value.as_string() {
      Ok(Self::String(s))
    } else if js_sys::Array::is_array(&value) {
      let arr = js_sys::Array::from(&value);
      let mut vec = Vec::with_capacity(arr.length() as usize);
      for i in 0..arr.length() {
        vec.push(Self::from_js(arr.get(i))?);
      }
      Ok(Self::Array(vec))
    } else if let Some(obj) = value.dyn_ref::<js_sys::Object>() {
      let entries = js_sys::Object::entries(obj);
      let mut map = serde_json::Map::with_capacity(entries.length() as usize);
      for i in 0..entries.length() {
        let pair = js_sys::Array::from(&entries.get(i));
        let key = pair.get(0).as_string().ok_or(Error::UnexpectedType { expected: "string" })?;
        let val = Self::from_js(pair.get(1))?;
        map.insert(key, val);
      }
      Ok(Self::Object(map))
    } else {
      Err(Error::UnexpectedType { expected: "JSON value" })
    }
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    // Type-erase `set` to break monomorphization recursion. serde_json::Value
    // is recursive (Array/Object contain Value), and each `impl FnOnce` closure
    // is a unique type. Without erasure the compiler generates an infinite chain
    // of distinct instantiations.
    let mut set = Some(set);
    patch_js_json_value(self, old, &mut |v| {
      (set.take().expect("patch_js set callback invoked more than once"))(v);
    });
  }
}

/// Inner helper for `serde_json::Value::patch_js`. Takes a `&mut dyn FnMut`
/// callback so all recursive calls through `patch_js_slice`/`patch_js_map`
/// share the same concrete monomorphization without a heap allocation.
#[cfg(all(feature = "serde_json", target_arch = "wasm32"))]
fn patch_js_json_value(
  value: &serde_json::Value,
  old: &wasm_bindgen::JsValue,
  set: &mut dyn FnMut(wasm_bindgen::JsValue),
) {
  match value {
    serde_json::Value::Null => {
      if !old.is_null() && !old.is_undefined() {
        set(wasm_bindgen::JsValue::NULL);
      }
    }
    serde_json::Value::Bool(b) => {
      if old.as_bool() != Some(*b) {
        set(wasm_bindgen::JsValue::from_bool(*b));
      }
    }
    serde_json::Value::Number(n) => {
      let f = n.as_f64().unwrap_or(f64::NAN);
      if old.as_f64() != Some(f) {
        set(wasm_bindgen::JsValue::from_f64(f));
      }
    }
    serde_json::Value::String(s) => {
      if old.as_string().as_deref() != Some(s.as_str()) {
        set(wasm_bindgen::JsValue::from_str(s));
      }
    }
    serde_json::Value::Array(arr) => {
      patch_js_slice(arr.iter(), old, set);
    }
    serde_json::Value::Object(map) => {
      patch_js_map(
        map.iter().map(|(k, v)| (wasm_bindgen::JsValue::from_str(k), v)),
        |js_key| js_key.as_string().is_some_and(|k| map.contains_key(&k)),
        || value.to_js(),
        old,
        set,
      );
    }
  }
}

#[cfg(feature = "bytes")]
impl Typewire for bytes::Bytes {
  type Ident = schema::coded::PrimitiveIdent;
  const IDENT: Self::Ident = schema::coded::PrimitiveIdent::new(schema::Scalar::Bytes);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    js_sys::Uint8ClampedArray::new_from_slice(self).into()
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;
    value.dyn_ref::<js_sys::Uint8ClampedArray>().map_or_else(
      || {
        value.dyn_ref::<js_sys::Uint8Array>().map_or(
          Err(Error::UnexpectedType { expected: "Uint8ClampedArray or Uint8Array" }),
          |arr| Ok(Self::from(arr.to_vec())),
        )
      },
      |arr| Ok(Self::from(arr.to_vec())),
    )
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_atomic(self, old, set);
  }
}

#[cfg(feature = "indexmap")]
impl<T: Typewire + Eq + core::hash::Hash> Typewire for indexmap::IndexSet<T> {
  type Ident = schema::coded::SeqIdent<T::Ident>;
  const IDENT: Self::Ident = schema::coded::SeqIdent::new(T::IDENT);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    array_ref(self.iter())
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;

    let arr: js_sys::Array =
      value.dyn_into().map_err(|_| Error::UnexpectedType { expected: "array" })?;
    let mut set = Self::with_capacity(arr.length() as usize);
    for i in 0..arr.length() {
      set.insert(T::from_js(arr.get(i))?);
    }
    Ok(set)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js_lenient(value: wasm_bindgen::JsValue, field: &str) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;
    let Some(arr) = value.dyn_ref::<js_sys::Array>() else {
      log::warn!("{field}: expected array, skipping");
      return Ok(Self::default());
    };
    let mut set = Self::with_capacity(arr.length() as usize);
    for i in 0..arr.length() {
      match T::from_js(arr.get(i)) {
        Ok(v) => {
          set.insert(v);
        }
        Err(e) => log::warn!("{field}[{i}]: skipping invalid element: {e}"),
      }
    }
    Ok(set)
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_slice(self.as_slice().iter(), old, set);
  }
}

#[cfg(feature = "indexmap")]
impl<K: Typewire + Eq + core::hash::Hash, V: Typewire> Typewire for indexmap::IndexMap<K, V> {
  type Ident = schema::coded::MapIdent<K::Ident, V::Ident>;
  const IDENT: Self::Ident = schema::coded::MapIdent::new(K::IDENT, V::IDENT);

  #[cfg(target_arch = "wasm32")]
  fn to_js(&self) -> wasm_bindgen::JsValue {
    let obj = js_sys::Object::new();
    for (k, v) in self {
      let _ = js_sys::Reflect::set(&obj, &k.to_js(), &v.to_js());
    }
    obj.into()
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js(value: wasm_bindgen::JsValue) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;
    let entries = js_sys::Object::entries(
      value.dyn_ref::<js_sys::Object>().ok_or(Error::UnexpectedType { expected: "object" })?,
    );
    let mut map = Self::with_capacity(entries.length() as usize);
    for i in 0..entries.length() {
      let pair: js_sys::Array =
        entries.get(i).dyn_into().map_err(|_| Error::UnexpectedType { expected: "array" })?;
      let key = K::from_js(pair.get(0))?;
      let val = V::from_js(pair.get(1))?;
      map.insert(key, val);
    }
    Ok(map)
  }

  #[cfg(target_arch = "wasm32")]
  fn from_js_lenient(value: wasm_bindgen::JsValue, field: &str) -> Result<Self, Error> {
    use wasm_bindgen::JsCast as _;
    let Some(obj) = value.dyn_ref::<js_sys::Object>() else {
      log::warn!("{field}: expected object, skipping");
      return Ok(Self::default());
    };
    let entries = js_sys::Object::entries(obj);
    let mut map = Self::with_capacity(entries.length() as usize);
    for i in 0..entries.length() {
      let pair: js_sys::Array = entries.get(i).into();
      match (K::from_js(pair.get(0)), V::from_js(pair.get(1))) {
        (Ok(k), Ok(v)) => {
          map.insert(k, v);
        }
        (Err(e), _) | (_, Err(e)) => {
          log::warn!("{field}: skipping entry {i}: {e}");
        }
      }
    }
    Ok(map)
  }

  #[cfg(target_arch = "wasm32")]
  fn patch_js(&self, old: &wasm_bindgen::JsValue, set: impl FnOnce(wasm_bindgen::JsValue)) {
    patch_js_map(
      self.iter().map(|(k, v)| (k.to_js(), v)),
      |js_key| K::from_js(js_key.clone()).ok().is_some_and(|k| self.contains_key(&k)),
      || self.to_js(),
      old,
      set,
    );
  }
}