nsh-js 0.6.0

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
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
//! The TypeScript declarations of what apps import (`.nsh/types`), made
//! from what serves it: the declaration ([`Ts`]) next to each export of
//! nsh's modules (`modules.rs` and the tables it lists), the modules' own
//! types, the specs of the registries' components and modules
//! (`nsh_core::element::declarations`), and the core's tables (styles, host
//! props and events, easings, canvas operations: `nsh_core::js`). Nothing
//! is written twice: a test loads every module and checks that what it
//! exports is what its declarations say.
//!
//! Each file declares its own names; the `import type` lines between the
//! files are worked out from the names each one uses.

use std::{collections::BTreeMap, fmt::Write as _};

use nsh_core::element::{Registry, description::SetDescription};

use crate::modules::{Item, MODULES, NativeModule, Ts};

/// The banner of every file.
const BANNER: &str = "// Generated by nsh from its Rust sources: do not edit.\n\n";

/// The element and JSX types (`types.d.ts`, all exported by `nsh`) that do
/// not come from a table: how the tables' interfaces make up the props of
/// each element.
const ELEMENT_TYPES: &str = r#"/** A list of styles, possibly nested: `[base, props.style]` where
 * `props.style` is itself a list. */
export type RecursiveArray<T> = readonly (T | RecursiveArray<T>)[];

/** A style, or a list of styles (nested lists included) merged left to
 * right; falsy entries are skipped. */
export type StyleProp<T> = T | RecursiveArray<T | false | null | undefined> | false | null | undefined;

/** Props every host element accepts; `S`, the style its state styles
 * take (its `style`'s); `R`, its ref's type. */
export interface CommonProps<S = ViewStyle, R = ViewRef> extends TouchProps, HostProps, StateStyleProps<S> {
  ref?: R | ((node: R) => void);
  children?: JSX.Element;
  /** iOS-only props (ignored elsewhere). */
  ios?: IOSProps;
  /** Android-only props (ignored elsewhere). */
  android?: AndroidProps;
  /** macOS-only props (`macos={{…}}`; ignored elsewhere). */
  macos?: MacOSProps;
  /** Desktop-only props (macOS, Windows, Linux and desktop browsers;
   * ignored on mobile). */
  desktop?: DesktopProps;
  /** Web-only props (ignored elsewhere). */
  web?: WebProps;
}

/** Styles while the element is in a state, over its own `style` and
 * classes, applied natively (no JS runs): as the `<state>:` classes.
 * Later states win (checked, then hover, focus, active); `disabledStyle`
 * wins over all, and the others do not apply while disabled. */
export interface StateStyleProps<S = ViewStyle> {
  /** While pressed (`active:`). */
  activeStyle?: StyleProp<S>;
  /** While a pointer is over it (`hover:`). */
  hoverStyle?: StyleProp<S>;
  /** While it has focus (`focus:`). */
  focusStyle?: StyleProp<S>;
  /** While it or an element inside it has focus (`focus-within:`); the
   * content of an `Overlay` counts as inside the element it is in. */
  focusWithinStyle?: StyleProp<S>;
  /** While it has focus and shows it (`focus-visible:`): the keyboard
   * moved the focus there, or it is an input that edits. A press or a
   * tap that focuses it shows `focusStyle` alone. */
  focusVisibleStyle?: StyleProp<S>;
  /** While `disabled` (`disabled:`). */
  disabledStyle?: StyleProp<S>;
  /** While `accessibilityState.selected` is `true` (`selected:`): a
   * tab, a segment or a `Button` that is selected. */
  selectedStyle?: StyleProp<S>;
  /** While `accessibilityState.checked` is `true` (`checked:`; `"mixed"`
   * is not checked): a checkbox, a switch or a radio styled by its
   * value. */
  checkedStyle?: StyleProp<S>;
  /** While `accessibilityState.checked` is `"mixed"` (`indeterminate:`):
   * a checkbox that is neither checked nor unchecked. */
  indeterminateStyle?: StyleProp<S>;
  /** While `accessibilityState.expanded` is `true` (`aria-expanded:`): a
   * `Popover`'s or `Menu`'s trigger while its popup is open. */
  expandedStyle?: StyleProp<S>;
  /** While `accessibilityState.pressed` is `true` (`aria-pressed:`;
   * `"mixed"` is not pressed): a toggle button that is on. Not
   * `activeStyle`, a press in progress. */
  pressedStyle?: StyleProp<S>;
}

/** iOS-only props of every element (`ios={{…}}`); elements add their own. */
export interface IOSProps extends IOSHostProps {}

/** Desktop-only props of every element (`desktop={{…}}`); elements add their own. */
export interface DesktopProps extends DesktopHostProps {}

/** Web-only props of every element (`web={{…}}`). */
export interface WebProps extends WebHostProps {}

/** Android-only props of every element (`android={{…}}`). */
export interface AndroidProps extends AndroidHostProps {}

/** macOS-only props of every element (`macos={{…}}`); elements add their own. */
export interface MacOSProps extends MacOSHostProps {}

/** `<View>` */
export interface ViewProps extends CommonProps, ViewHostProps {
  style?: StyleProp<ViewStyle>;
}

/** `<Text>`: nested `<Text>` elements are spans of the same paragraph. */
export interface TextProps extends CommonProps<TextStyle>, TextHostProps {
  style?: StyleProp<TextStyle>;
}

/** An image asset (`import logo from "./logo.png"`), sized in points. */
export interface ImageAsset {
  url: string;
  /** Its size in points. */
  size: Size;
  /** The pixel densities it ships in, 1 being the imported file:
   * `[1, 2, 3]` when `logo@2x.png` and `logo@3x.png` sit next to
   * `logo.png`. The image loads the one for the screen's pixel ratio.
   * Absent when the imported file is the only one. */
  scales?: number[];
}

/** `<Image>` */
export interface ImageProps extends CommonProps<ImageStyle>, ImageHostProps {
  style?: StyleProp<ImageStyle>;
}

/** `<Shader>`: a view whose box a WGSL shader draws, under its children. */
export interface ShaderProps extends CommonProps, ViewHostProps, ShaderHostProps {
  /** The WGSL defining `fn shade(uv: vec2f) -> vec4f`. */
  source: string;
  style?: StyleProp<ViewStyle>;
}

/** `<ShaderEffect>`: a view whose children draw through a WGSL shader,
 * which reads what they draw with `sample_content(uv)`. */
export interface ShaderEffectProps
  extends CommonProps, ViewHostProps, ShaderHostProps, ShaderEffectHostProps {
  /** The WGSL defining `fn shade(uv: vec2f) -> vec4f`; without it the
   * children draw as they are. */
  source?: string;
  style?: StyleProp<ViewStyle>;
}

/** `<ShaderTransition>`: a view whose children change through a WGSL
 * shader when its `value` changes: `sample_from(uv)` is a picture of what
 * they drew, `sample_to(uv)` what they draw now, `nsh.progress` 0 to 1. */
export interface ShaderTransitionProps
  extends CommonProps, ViewHostProps, ShaderHostProps, ShaderTransitionHostProps {
  /** The WGSL defining `fn shade(uv: vec2f) -> vec4f`; without it the
   * transition runs its `fallback` (a cross-fade). */
  source?: string;
  style?: StyleProp<ViewStyle>;
}

/** `<ScreenEffect>`: the whole surface drawn through a WGSL shader, which
 * reads it with `sample_content(uv)`. It takes no space and has no
 * children. */
export interface ScreenEffectProps extends ShaderHostProps, ShaderEffectHostProps {
  /** The WGSL defining `fn shade(uv: vec2f) -> vec4f`. */
  source?: string;
}

/** `<ScreenTransition>`: the whole surface changing through a WGSL shader
 * when its `value` changes, as `ShaderTransition` does for its children. */
export interface ScreenTransitionProps extends ShaderHostProps, ShaderTransitionHostProps {
  /** The WGSL defining `fn shade(uv: vec2f) -> vec4f`; without it the
   * transition runs its `fallback`. */
  source?: string;
}

/** `<Scroll>` */
export interface ScrollProps extends CommonProps<ViewStyle, ScrollRef>, ScrollingHostProps, ScrollHostProps {
  style?: StyleProp<ViewStyle>;
  /** The style of a view around the content: it scrolls with the
   * content, `flexGrow: 1` makes it at least as tall as the viewport (a
   * centered empty state). Without it or `contentClass`, the children are
   * the scroll view's own. */
  contentStyle?: StyleProp<ViewStyle>;
  /** The classes of the content (`contentStyle`), e.g.
   * `"grow justify-center p-4"`. */
  contentClass?: string;
}

/** `<Overlay>`: its children shown on top of the root view it is in (the
 * surface, or the dialog around it), outside its parent's layout and
 * clipping; laid out as a `position: fixed` box of that root view, or
 * placed against `anchor`. */
export interface OverlayProps extends CommonProps, OverlayHostProps {
  style?: StyleProp<ViewStyle>;
}

/** What JS sets on a Rust component's host itself: the app's classes
 * (appended to the component's own), its inline and state styles, its test id, its
 * tooltip, layout events, desktop file drops on it, the mouse over it, a context menu
 * asked for over it and the ref
 * (`ref.command(name, args)`). */
export type ComponentHostProps = { [K in "class" | "classList" | "style" | "activeStyle" | "hoverStyle" | "focusStyle" | "focusWithinStyle" | "focusVisibleStyle" | "disabledStyle" | "testID" | "tooltip" | "onLayout" | "onFileDragEnter" | "onFileDragLeave" | "onFileDrop" | "onMouseEnter" | "onMouseMove" | "onMouseLeave" | "onMouseUp" | "onContextMenu" | "ref"]?: ViewProps[K] };

/** An operating system (`platform.os`). */
export type OS = "ios" | "android" | "macos" | "windows" | "linux" | "web";

export declare namespace JSX {
  /** What components return and children accept. */
  type Element = ViewRef | ArrayElement | (() => Element) | string | number | boolean | null | undefined;
  interface ArrayElement extends Array<Element> {}
  interface ElementChildrenAttribute {
    children: {};
  }
  /** None: every tag is a component in scope (`View` from "nsh", ...), or
   * the global `If` / `Each`. */
  interface IntrinsicElements {}
}
"#;

/// `/** doc */` for `doc` (plain text, possibly several lines).
fn doc_comment(out: &mut String, doc: &str, indent: &str) {
    if doc.is_empty() {
        return;
    }
    let lines: Vec<&str> = doc.lines().collect();
    if lines.len() == 1 {
        let _ = writeln!(out, "{indent}/** {doc} */");
        return;
    }
    let _ = writeln!(out, "{indent}/**");
    for line in lines {
        if line.is_empty() {
            let _ = writeln!(out, "{indent} *");
        } else {
            let _ = writeln!(out, "{indent} * {line}");
        }
    }
    let _ = writeln!(out, "{indent} */");
}

/// The declaration of export `name`.
fn export(out: &mut String, name: &str, ts: Ts) {
    match ts {
        Ts::Function(text, signatures) => {
            doc_comment(out, text, "");
            for signature in signatures {
                let _ = writeln!(out, "export declare function {name}{signature};");
            }
        }
        Ts::Const(text, ty) => {
            doc_comment(out, text, "");
            let _ = writeln!(out, "export declare const {name}: {ty};");
        }
        Ts::Class(text, body) => {
            doc_comment(out, text, "");
            let _ = writeln!(out, "export declare class {name}{body}");
        }
        Ts::Internal => return,
    }
    out.push('\n');
}

fn exports(out: &mut String, items: &[Item]) {
    for &(name, _, ts) in items {
        export(out, name, ts);
    }
}

/// The refs of the host elements: what `ref` receives, each element's
/// own type, so a method of one element is on no other's (`AGENTS.md`
/// "API shapes"). Name, base, documentation, the methods of
/// [`crate::dom::NODE_METHODS`] it adds. At run time every node has them
/// all; the types hold each element to its own.
pub(crate) const REFS: &[(&str, Option<&str>, &str, &[&str])] = &[
    (
        "ViewRef",
        None,
        "A native node: what `ref` receives, and what an element is. Its methods send commands to its\nview, in order with the changes before them.",
        &["focus", "blur", "measure", "reveal", "animateLayout"],
    ),
    (
        "InputRef",
        Some("ViewRef"),
        "An `<Input>`'s ref.",
        &["setSelection", "insertText"],
    ),
    (
        "ScrollRef",
        Some("ViewRef"),
        "A `<Scroll>`'s ref.",
        &["scrollTo", "zoomTo", "scrollToEnd"],
    ),
    (
        "ListRef",
        Some("ViewRef"),
        "A `List`'s ref.",
        &[
            "scrollTo",
            "scrollToOffset",
            "scrollToIndex",
            "scrollToEnd",
            "measureScrollPosition",
        ],
    ),
    (
        "WebViewRef",
        Some("ViewRef"),
        "A `<WebView>`'s ref.",
        &[
            "reload",
            "goBack",
            "goForward",
            "stopLoading",
            "injectJavaScript",
            "evaluate",
            "postMessage",
            "sendInput",
            "load",
        ],
    ),
    ("VideoRef", Some("ViewRef"), "A `<Video>`'s ref.", &["seek"]),
    (
        "NativeComponentRef",
        Some("ViewRef"),
        "The ref of a native component the embedding app registered (`nativeComponent`).",
        &["command"],
    ),
];

/// `types.d.ts`: the styles, the elements' props and events, the node and
/// JSX types.
fn element_types() -> String {
    let mut out = String::from(ELEMENT_TYPES);
    out.push('\n');
    out.push_str(&nsh_core::js::style::declarations());
    out.push('\n');
    out.push_str(&nsh_core::js::host::declarations());
    out.push('\n');
    out.push_str(crate::touch::TOUCH_TYPES);
    out.push_str("\n/** Raw touches and the gesture responder system (React Native semantics). */\nexport interface TouchProps {\n");
    for (name, handler, doc) in crate::touch::TOUCH_PROPS {
        doc_comment(&mut out, doc, "  ");
        let _ = writeln!(out, "  {name}?: {handler};");
    }
    out.push_str("}\n");
    for (name, extends, doc, methods) in REFS {
        out.push('\n');
        doc_comment(&mut out, doc, "");
        match extends {
            Some(base) => {
                let _ = writeln!(out, "export interface {name} extends {base} {{");
            }
            None => {
                let _ = writeln!(out, "export interface {name} {{");
            }
        }
        for method in *methods {
            let Some((_, _, signature, doc)) =
                crate::dom::NODE_METHODS.iter().find(|(n, ..)| n == method)
            else {
                continue;
            };
            doc_comment(&mut out, doc, "  ");
            let _ = writeln!(out, "  {method}{signature};");
        }
        out.push_str("}\n");
    }
    out
}

/// The file of module `specifier` (`nsh/base` -> `nsh/base.d.ts`).
fn path_of(specifier: &str) -> String {
    match specifier {
        "nsh" => "nsh/index.d.ts".to_owned(),
        s => format!("{s}.d.ts"),
    }
}

/// What the core's tables add to one of nsh's modules.
fn generated(module: &str) -> String {
    match module {
        "nsh/animated" => nsh_core::js::animation::declarations(),
        "nsh/canvas" => nsh_core::js::canvas::declarations(),
        "nsh/desktop" => nsh_core::desktop::window::declarations(),
        _ => String::new(),
    }
}

/// The declarations of a registry's exports, leaving out those `own`
/// declares.
fn registry_part(out: &mut String, registry: &Registry, own: &[Item]) {
    let omit: Vec<&str> = own.iter().map(|(n, ..)| *n).collect();
    out.push_str(&nsh_core::element::declarations(registry, &omit));
    let (values, types) = registry.reexports();
    reexports_part(out, values, types, registry.native_value_names());
}

/// The declarations of a described UI set's exports.
fn set_part(out: &mut String, set: &SetDescription) {
    out.push_str(&set.declarations);
    fn strs(names: &[String]) -> Vec<&str> {
        names.iter().map(String::as_str).collect()
    }
    reexports_part(
        out,
        &strs(&set.reexported_values),
        &strs(&set.reexported_types),
        &strs(&set.native_values),
    );
}

/// The props of `Input`, declared beside it (`nsh/base`).
const INPUT_TYPES: &str = r#"/** `<Input>` */
export interface InputProps extends CommonProps<InputStyle, InputRef>, InputHostProps {
  style?: StyleProp<InputStyle>;
  ios?: IOSInputProps;
}

/** iOS-only props of `<Input>`. */
export interface IOSInputProps extends IOSProps, IOSInputHostProps {}
"#;

/// The declarations of what a set exports as the runtime makes it: the
/// runtime's `values` and `types`, and the values nsh-js makes for it
/// (`natives`: `Input` and navigation's).
fn reexports_part(out: &mut String, values: &[&str], types: &[&str], natives: &[&str]) {
    let made = crate::env::REEXPORTS
        .iter()
        .chain(crate::env::ELEMENTS)
        .chain(crate::navigation::EXPORTS);
    let mut navigation = false;
    for item in made {
        if values.contains(&item.0) || natives.contains(&item.0) {
            navigation |= crate::navigation::EXPORTS.iter().any(|n| n.0 == item.0);
            export(out, item.0, item.2);
        }
    }
    if navigation {
        out.push_str(crate::navigation::TYPES);
        out.push('\n');
    }
    if natives.contains(&"Input") {
        out.push_str(INPUT_TYPES);
    }
    if !types.is_empty() {
        let _ = writeln!(out, "export type {{ {} }};", types.join(", "));
    }
}

/// The modules' files, before imports: (path, body).
fn bodies(ui_sets: &[SetDescription]) -> Vec<(String, String)> {
    let mut files = vec![("nsh/types.d.ts".to_owned(), element_types())];
    let registries = nsh_core::runtime::registries();
    let declared = |m: &&NativeModule| m.exports.iter().any(|e| !matches!(e.2, Ts::Internal));
    let body_of = |m: &NativeModule| {
        let mut body = String::from(m.types);
        if !body.is_empty() {
            body.push('\n');
        }
        body.push_str(&generated(m.name));
        // What nsh-js declares itself, the sources it serves included.
        let own: Vec<Item> = m
            .also
            .iter()
            .filter_map(|a| MODULES.iter().find(|o| o.name == *a))
            .flat_map(|o| o.exports.iter().copied())
            .chain(m.exports.iter().copied())
            .collect();
        for registry in registries.iter().filter(|r| r.specifier() == Some(m.name)) {
            registry_part(&mut body, registry, &own);
        }
        // A UI set is a module of its own (the command line refuses one
        // named as nsh's): nothing of nsh's to leave out.
        for set in ui_sets.iter().filter(|s| s.specifier == m.name) {
            set_part(&mut body, set);
        }
        exports(&mut body, m.exports);
        body
    };
    // A module `nsh` serves (`moved_to`) is declared in `nsh`'s file.
    for m in MODULES
        .iter()
        .filter(declared)
        .filter(|m| m.moved_to.is_none())
    {
        let mut body = body_of(m);
        for other in m
            .also
            .iter()
            .filter_map(|a| MODULES.iter().find(|o| o.name == *a))
        {
            body.push('\n');
            body.push_str(&body_of(other));
        }
        files.push((path_of(m.name), body));
    }
    // The registries that are modules of their own (`nsh/base`, `os`).
    for registry in registries {
        let Some(specifier) = registry.specifier() else {
            continue;
        };
        if MODULES.iter().any(|m| m.name == specifier) {
            continue;
        }
        let mut body = String::new();
        registry_part(&mut body, registry, &[]);
        files.push((path_of(specifier), body));
    }
    // The UI sets (`nsh/base`, an app's own).
    for set in ui_sets {
        if MODULES.iter().any(|m| m.name == set.specifier) {
            continue;
        }
        let mut body = String::new();
        set_part(&mut body, set);
        files.push((path_of(&set.specifier), body));
    }
    files
}

/// Removes comments and string literals (their words are not references).
fn code_only(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < bytes.len() {
        let rest = &text[i..];
        if rest.starts_with("/*") {
            i += rest.find("*/").map_or(rest.len(), |e| e + 2);
            out.push(' ');
        } else if rest.starts_with("//") {
            i += rest.find('\n').unwrap_or(rest.len());
        } else if bytes[i] == b'"' || bytes[i] == b'`' {
            let quote = bytes[i];
            i += 1;
            while i < bytes.len() && bytes[i] != quote {
                if bytes[i] == b'\\' {
                    i += 1;
                }
                i += 1;
            }
            i += 1;
            out.push_str("\"\"");
        } else {
            let c = rest.chars().next().unwrap_or(' ');
            out.push(c);
            i += c.len_utf8();
        }
    }
    out
}

fn is_ident_start(c: char) -> bool {
    c.is_ascii_alphabetic() || c == '_' || c == '$'
}

fn is_ident(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_' || c == '$'
}

/// The identifiers of `code`, with what precedes each (to tell member
/// names and declarations from references).
fn words(code: &str) -> Vec<(&str, &str)> {
    let mut out = Vec::new();
    let mut start = None;
    for (i, c) in code.char_indices() {
        match start {
            None if is_ident_start(c) => start = Some(i),
            Some(s) if !is_ident(c) => {
                out.push((&code[..s], &code[s..i]));
                start = None;
            }
            _ => {}
        }
    }
    if let Some(s) = start {
        out.push((&code[..s], &code[s..]));
    }
    out
}

/// The keywords that declare a name.
const DECLARING: &[&str] = &[
    "interface",
    "type",
    "class",
    "const",
    "function",
    "enum",
    "namespace",
    "let",
    "var",
];

/// The names `body` declares at its top level and exports (`export
/// [declare] interface X` ...).
pub(crate) fn exported_names(body: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in code_only(body).lines() {
        let Some(rest) = line.strip_prefix("export ") else {
            continue;
        };
        let rest = rest.trim_start_matches("declare ");
        let rest = rest.trim_start_matches("abstract ");
        let mut parts = rest.split_whitespace();
        let (Some(keyword), Some(name)) = (parts.next(), parts.next()) else {
            continue;
        };
        if DECLARING.contains(&keyword) {
            let name: String = name.chars().take_while(|c| is_ident(*c)).collect();
            if !name.is_empty() {
                out.push(name);
            }
        }
    }
    out
}

/// The values `body` declares as exports (what a module's namespace must
/// hold).
#[cfg(test)]
pub(crate) fn exported_values(body: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in code_only(body).lines() {
        let Some(rest) = line.strip_prefix("export ") else {
            continue;
        };
        // The local binding is not the exported name: `export default x`
        // creates the namespace value `default`, not a named export `x`.
        if rest.split_whitespace().next() == Some("default") {
            if !out.iter().any(|name| name == "default") {
                out.push("default".to_owned());
            }
            continue;
        }
        // A value re-exported: `export { Path2D } from "./canvas";`.
        if let Some(names) = rest.strip_prefix('{').and_then(|r| r.split_once('}')) {
            for name in names.0.split(',').map(str::trim).filter(|n| !n.is_empty()) {
                let name = name.rsplit(" as ").next().unwrap_or(name).to_owned();
                if !out.contains(&name) {
                    out.push(name);
                }
            }
            continue;
        }
        let Some(rest) = rest.strip_prefix("declare ") else {
            continue;
        };
        let rest = rest.trim_start_matches("abstract ");
        let mut parts = rest.split_whitespace();
        let (Some(keyword), Some(name)) = (parts.next(), parts.next()) else {
            continue;
        };
        if matches!(keyword, "const" | "function" | "class" | "let" | "var") {
            let name: String = name.chars().take_while(|c| is_ident(*c)).collect();
            if !out.contains(&name) {
                out.push(name);
            }
        }
    }
    out
}

/// The names `body` uses, declares itself (at any depth, and type
/// parameters) or imports.
fn references(body: &str) -> (Vec<String>, Vec<String>) {
    let code = code_only(body);
    let mut used = Vec::new();
    let mut local = Vec::new();
    for (before, word) in words(&code) {
        let prev = before.trim_end();
        let prev_word = prev
            .rsplit(|c: char| !is_ident(c))
            .next()
            .unwrap_or_default();
        let after = &code[before.len() + word.len()..];
        if DECLARING.contains(&prev_word) && prev.ends_with(prev_word) {
            local.push(word.to_owned());
        } else if prev.ends_with('.') {
            // A member (`JSX.Element`, `Symbol.iterator`).
        } else if after.trim_start_matches('?').starts_with([':', '(']) {
            // A field's, method's or parameter's name (`signal?: string`,
            // `connect(url: string)`), not a type.
        } else {
            used.push(word.to_owned());
        }
    }
    // Imported by the body itself (`nsh`'s `JSX`).
    for line in body.lines() {
        if let Some(rest) = line.strip_prefix("import type {")
            && let Some(names) = rest.split('}').next()
        {
            local.extend(names.split(',').map(|n| n.trim().to_owned()));
        }
    }
    (used, local)
}

/// `to` relative to the directory of `from` (both under `.nsh/types`),
/// without the extension: `./types`, `../types`.
fn relative(from: &str, to: &str) -> String {
    let from_dir: Vec<&str> =
        from.split('/').collect::<Vec<_>>()[..from.split('/').count() - 1].to_vec();
    let to_parts: Vec<&str> = to.split('/').collect();
    let common = from_dir
        .iter()
        .zip(&to_parts)
        .take_while(|(a, b)| a == b)
        .count();
    let mut path = String::new();
    if from_dir.len() == common {
        path.push_str("./");
    } else {
        for _ in common..from_dir.len() {
            path.push_str("../");
        }
    }
    path.push_str(&to_parts[common..].join("/"));
    path.trim_end_matches(".d.ts").to_owned()
}

/// The types TypeScript declares itself, which a body naming them means:
/// an import of a module's name would shadow them in that file.
const TS_GLOBALS: &[&str] = &[
    "Array",
    "ArrayBuffer",
    "ArrayLike",
    "Awaited",
    "Capitalize",
    "ConstructorParameters",
    "Date",
    "Error",
    "Exclude",
    "Extract",
    "Function",
    "InstanceType",
    "Iterable",
    "IterableIterator",
    "Lowercase",
    "Map",
    "NoInfer",
    "NonNullable",
    "Omit",
    "OmitThisParameter",
    "Parameters",
    "Partial",
    "Pick",
    "Promise",
    "PromiseLike",
    "Readonly",
    "ReadonlyArray",
    "ReadonlyMap",
    "ReadonlySet",
    "Record",
    "RegExp",
    "Required",
    "ReturnType",
    "Set",
    "ThisParameterType",
    "ThisType",
    "Uint8Array",
    "Uncapitalize",
    "Uppercase",
    "WeakMap",
    "WeakSet",
];

/// The files of `.nsh/types` for apps whose hosts serve `ui_sets`
/// (`nsh/base`, an app's own, as data: their declarations come with
/// them), as (path relative to it, contents): one per
/// module apps import, `nsh/types.d.ts` (the element types `nsh` exports),
/// `nsh/jsx-runtime.d.ts` (where TypeScript finds the JSX namespace:
/// `jsxImportSource: "nsh"`) and `nsh/globals.d.ts`.
pub fn type_definitions(ui_sets: &[SetDescription]) -> Vec<(String, String)> {
    let files = bodies(ui_sets);
    // Who declares each name.
    let mut owner: BTreeMap<String, &str> = BTreeMap::new();
    for (path, body) in &files {
        for name in exported_names(body) {
            owner.entry(name).or_insert(path);
        }
    }
    let mut out: Vec<(String, String)> = files
        .iter()
        .map(|(path, body)| {
            let (used, local) = references(body);
            let mut imports: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
            for name in &used {
                // TypeScript's own (`Pick<T, K>`): never another module's
                // name, whatever it exports.
                if local.contains(name) || TS_GLOBALS.contains(&name.as_str()) {
                    continue;
                }
                if let Some(&from) = owner.get(name)
                    && from != path
                {
                    let names = imports.entry(from).or_default();
                    if !names.contains(&name.as_str()) {
                        names.push(name);
                    }
                }
            }
            let mut text = String::from(BANNER);
            let any = !imports.is_empty();
            for (from, mut names) in imports {
                names.sort_unstable();
                let _ = writeln!(
                    text,
                    "import type {{ {} }} from \"{}\";",
                    names.join(", "),
                    relative(path, from)
                );
            }
            if any {
                text.push('\n');
            }
            text.push_str(body);
            (path.clone(), text)
        })
        .collect();
    out.push((
        "nsh/jsx-runtime.d.ts".to_owned(),
        format!("{BANNER}export type {{ JSX }} from \"./types\";\n"),
    ));
    out.push(("nsh/globals.d.ts".to_owned(), globals()));
    out.extend(standard_types().iter().cloned());
    out
}

/// Standard export discovery evaluates trusted builtins once, without running
/// application code, privileged operations, or asynchronous jobs.
fn standard_types() -> &'static Vec<(String, String)> {
    static FILES: std::sync::OnceLock<Vec<(String, String)>> = std::sync::OnceLock::new();
    FILES.get_or_init(|| {
        let host = crate::Host::new().expect("create standard declaration discovery VM");
        let exports = host
            .standard_exports()
            .expect("discover actual standard module exports");
        let names: Vec<Vec<&str>> = exports
            .iter()
            .map(|(_, values)| values.iter().map(String::as_str).collect())
            .collect();
        let borrowed: Vec<(&str, &[&str])> = exports
            .iter()
            .zip(&names)
            .map(|((name, _), values)| (name.as_str(), values.as_slice()))
            .collect();
        crate::standard::declarations::type_definitions(&borrowed)
    })
}

/// A constant's value as TypeScript (`2`, not `2.0`).
fn number(v: f64) -> String {
    if v.fract() == 0.0 && v.abs() < 1e15 {
        format!("{}", v as i64)
    } else {
        format!("{v}")
    }
}

/// `globals.d.ts`: what an app can use besides the ECMAScript library: the
/// host's globals, the web classes (from their specs) and functions.
fn globals() -> String {
    let mut out = String::from(BANNER);
    out.push_str("// The globals of nsh's JS environment besides the ECMAScript library\n// (there is no DOM).\n\n");
    out.push_str("/// <reference path=\"../standard/index.d.ts\" />\n");
    out.push_str(crate::host::GLOBALS);
    out.push_str(&crate::standard::declarations::globals());
    for types in crate::web::TYPES {
        out.push('\n');
        out.push_str(types);
    }
    for spec in crate::web::declared_specs() {
        let ts = &spec.ts;
        out.push('\n');
        doc_comment(&mut out, ts.doc, "");
        let name = spec.name.to_str().unwrap_or_default();
        let _ = writeln!(out, "declare class {name}{} {{", ts.head);
        for (constant, value) in spec.constants {
            let constant = constant.to_str().unwrap_or_default();
            let value = number(*value);
            let _ = writeln!(out, "  static readonly {constant}: {value};");
            let _ = writeln!(out, "  readonly {constant}: {value};");
        }
        for line in ts.members.lines() {
            let _ = writeln!(out, "  {line}");
        }
        out.push_str("}\n");
    }
    for f in crate::web::functions() {
        out.push('\n');
        doc_comment(&mut out, f.doc, "");
        let name = f.name.to_str().unwrap_or_default();
        let _ = writeln!(out, "declare function {name}{};", f.signature);
    }
    out
}

/// The names of a class body's members (`static`, accessors and symbols
/// as `[Symbol.iterator]`), one per declaration (overloads repeat).
#[cfg(test)]
fn member_names(members: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in members.lines() {
        if line.starts_with([' ', ')', '}', '/', '*']) || line.trim().is_empty() {
            continue;
        }
        let mut rest = line;
        for prefix in ["static ", "readonly ", "get ", "set "] {
            rest = rest.strip_prefix(prefix).unwrap_or(rest);
        }
        let name = if rest.starts_with('[') {
            rest[..rest.find(']').map_or(rest.len(), |e| e + 1)].to_owned()
        } else {
            rest.chars().take_while(|c| is_ident(*c)).collect()
        };
        if !name.is_empty() && name != "constructor" && !out.contains(&name) {
            out.push(name);
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every method a node has is declared on a ref, and each ref names
    /// only methods nodes have: no element's ref carries every method.
    #[test]
    fn each_node_method_is_on_a_ref() {
        for (name, ..) in crate::dom::NODE_METHODS {
            assert!(
                REFS.iter().any(|(.., methods)| methods.contains(name)),
                "`{name}` is on no ref of `REFS`"
            );
        }
        for (r, _, _, methods) in REFS {
            for m in *methods {
                assert!(
                    crate::dom::NODE_METHODS.iter().any(|(n, ..)| n == m),
                    "`{r}.{m}` is not a node method"
                );
            }
        }
        let ts = element_types();
        assert!(!ts.contains("YNode"));
        assert!(ts.contains("export interface InputRef extends ViewRef {"));
    }

    #[derive(Default, nsh_core::element::JsObject)]
    struct Pick {
        value: bool,
    }

    #[nsh_core::element::module]
    struct PickerTypes;

    #[nsh_core::element::module]
    impl PickerTypes {
        fn accept(_pick: Pick) {}
    }

    #[test]
    fn component_host_props_do_not_import_a_modules_pick_type() {
        PickerTypes::accept(Pick::default());
        let mut registry = nsh_core::element::Registry::ui_set("test/picker-types");
        registry.module::<PickerTypes>();
        let files = type_definitions(&[registry.into()]);
        let (_, fixture) = files
            .iter()
            .find(|(path, _)| path == "test/picker-types.d.ts")
            .unwrap();
        assert!(fixture.contains("interface Pick"), "{fixture}");
        let (_, types) = files
            .iter()
            .find(|(path, _)| path == "nsh/types.d.ts")
            .unwrap();
        assert!(!types.contains("picker-types"), "{types}");
    }

    #[test]
    fn variant_types_image_asset_lists_its_scales() {
        let files = type_definitions(&[]);
        let (_, types) = files
            .iter()
            .find(|(path, _)| path == "nsh/types.d.ts")
            .expect("nsh/types.d.ts");
        let at = types
            .find("export interface ImageAsset {")
            .expect("ImageAsset");
        let asset = &types[at..at + types[at..].find("\n}").unwrap()];
        assert!(asset.contains("  scales?: number[];"), "{asset}");
        assert!(asset.contains("The image loads the one for the screen's pixel ratio."));
    }

    #[test]
    fn default_export_statements_name_the_default_namespace_value() {
        assert_eq!(
            exported_values(
                r#"
declare const moduleValue: { value: number };
export default moduleValue;
export declare const EOL: string;
export interface Shape { default: string; }
// export default ignored;
declare const text: "export default ignored";
"#
            ),
            ["default", "EOL"]
        );
        for source in [
            "export default class Example {}",
            "export default function example(): void;",
            "export default\n  moduleValue;",
        ] {
            assert_eq!(exported_values(source), ["default"], "{source}");
        }
    }

    #[test]
    fn generated_os_declaration_really_exports_its_typed_default_object() {
        let files = bodies(&[]);
        let (_, os) = files.iter().find(|(path, _)| path == "os.d.ts").unwrap();
        assert!(os.contains("declare const defaultExport: {"), "{os}");
        assert!(os.contains("readonly EOL: string;"), "{os}");
        assert!(os.contains("export default defaultExport;"), "{os}");
        let mut values = exported_values(os);
        values.sort();
        assert_eq!(values, ["EOL", "arch", "default", "homedir", "platform"]);
    }

    #[test]
    fn paths_are_relative() {
        assert_eq!(relative("nsh/base.d.ts", "nsh/types.d.ts"), "./types");
        assert_eq!(relative("nsh/acme/ui.d.ts", "nsh/types.d.ts"), "../types");
        assert_eq!(relative("nsh/types.d.ts", "nsh/acme/ui.d.ts"), "./acme/ui");
    }

    #[test]
    fn references_skip_members_strings_and_declarations() {
        let (used, local) = references(
            "/** A `Foo` */\nexport interface Bar<T> { a: JSX.Element; b: \"Baz\"; c: Qux<T>; safeArea?: Quux }",
        );
        assert!(used.contains(&"Quux".to_owned()));
        assert!(!used.contains(&"safeArea".to_owned()));
        assert!(used.contains(&"JSX".to_owned()));
        assert!(used.contains(&"Qux".to_owned()));
        assert!(!used.contains(&"Element".to_owned()));
        assert!(!used.contains(&"Baz".to_owned()));
        assert!(!used.contains(&"Foo".to_owned()));
        assert!(local.contains(&"Bar".to_owned()));
    }

    /// Every host element's props reach an element or a component: a
    /// group of them declared but in no element's props (`IOSProps` once
    /// was `{}`, so `ios={{ anything }}` type-checked) is a typo nobody is
    /// told of.
    #[test]
    fn every_host_props_interface_is_used() {
        let files = bodies(&[nsh_base::registry().into()]);
        let all: String = files.iter().map(|(_, body)| body.as_str()).collect();
        let mut unused = Vec::new();
        for line in all.lines() {
            let Some(rest) = line.strip_prefix("export interface ") else {
                continue;
            };
            let name: String = rest.chars().take_while(|c| is_ident(*c)).collect();
            if !name.ends_with("HostProps") {
                continue;
            }
            let uses = all
                .match_indices(name.as_str())
                .filter(|(at, _)| {
                    let before = all[..*at].chars().next_back();
                    let after = all[at + name.len()..].chars().next();
                    !before.is_some_and(is_ident) && !after.is_some_and(is_ident)
                })
                .count();
            // Its declaration, and at least one use.
            if uses < 2 {
                unused.push(name);
            }
        }
        assert!(unused.is_empty(), "declared but used nowhere: {unused:?}");
        assert!(all.contains("export interface IOSProps extends IOSHostProps {}"));
        assert!(all.contains("export interface MacOSProps extends MacOSHostProps {}"));
        assert!(all.contains("export interface DesktopProps extends DesktopHostProps {}"));
    }

    /// A component's props leave out the host props it declares itself:
    /// one of another payload (`DataTable`'s `onContextMenu`) would not
    /// type-check, which apps' `skipLibCheck` hides.
    #[test]
    fn component_props_omit_the_host_props_they_declare() {
        let files = bodies(&[nsh_base::registry().into()]);
        let all: String = files.iter().map(|(_, body)| body.as_str()).collect();
        let keys = nsh_core::element::HOST_PROPS
            .iter()
            .chain(&["ref"])
            .map(|n| format!("\"{n}\""))
            .collect::<Vec<_>>()
            .join(" | ");
        assert!(
            all.contains(&format!(
                "export type ComponentHostProps = {{ [K in {keys}]?"
            )),
            "ComponentHostProps lists other keys than HOST_PROPS"
        );
        let mut checked = 0;
        let mut redeclared = Vec::new();
        for (at, _) in all.match_indices("export interface ") {
            let decl = &all[at..];
            let open = decl.find('{').unwrap();
            let head = &decl[..open];
            let Some(extends) = head.split(" extends ").nth(1) else {
                continue;
            };
            if !extends.contains("ComponentHostProps") {
                continue;
            }
            checked += 1;
            let omitted: Vec<&str> = match extends.strip_prefix("Omit<ComponentHostProps, ") {
                Some(rest) => rest[..rest.find('>').unwrap()]
                    .split(" | ")
                    .map(|n| n.trim_matches('"'))
                    .collect(),
                None => Vec::new(),
            };
            let body = &decl[open..decl.find("\n}").unwrap()];
            for line in body.lines() {
                let Some(member) = line.strip_prefix("  ") else {
                    continue;
                };
                let name: String = member.chars().take_while(|c| is_ident(*c)).collect();
                if nsh_core::element::HOST_PROPS.contains(&name.as_str())
                    && !omitted.contains(&name.as_str())
                {
                    redeclared.push(format!("{}: {name}", head.trim()));
                }
            }
        }
        assert!(checked > 30, "found {checked} components' props");
        assert!(
            redeclared.is_empty(),
            "host props redeclared: {redeclared:?}"
        );
        assert!(all.contains(
            "export interface DataTableProps<T = any> extends Omit<ComponentHostProps, \"ref\" | \"onContextMenu\">"
        ));
    }

    /// No module exports a name TypeScript declares itself (`Pick`): an
    /// app importing it would lose TypeScript's in that file.
    #[test]
    fn no_module_exports_a_typescript_global() {
        let files = bodies(&[nsh_base::registry().into()]);
        for (path, body) in &files {
            for name in exported_names(body) {
                assert!(
                    !TS_GLOBALS.contains(&name.as_str()),
                    "{path} exports `{name}`, TypeScript's own"
                );
            }
        }
    }

    /// Each file declares a type alias once, never as itself (`export type
    /// X = X;` is circular), and never beside an interface, class or enum of
    /// the same name: type aliases do not merge. Interfaces merging with a
    /// class, and a type beside a value of its name, stay allowed.
    #[test]
    fn no_module_declares_a_type_twice() {
        let files = bodies(&[nsh_base::registry().into()]);
        let mut problems = Vec::new();
        for (path, body) in &files {
            let mut aliases: BTreeMap<String, u32> = BTreeMap::new();
            let mut others = Vec::new();
            for line in code_only(body).lines() {
                let Some(rest) = line.strip_prefix("export ") else {
                    continue;
                };
                let rest = rest.trim_start_matches("declare ");
                let rest = rest.trim_start_matches("abstract ");
                let mut parts = rest.split_whitespace();
                let (Some(keyword), Some(name)) = (parts.next(), parts.next()) else {
                    continue;
                };
                let name: String = name.chars().take_while(|c| is_ident(*c)).collect();
                if name.is_empty() {
                    continue;
                }
                match keyword {
                    "type" => {
                        *aliases.entry(name.clone()).or_default() += 1;
                        let value = rest
                            .split_once('=')
                            .map(|(_, v)| v.trim().trim_end_matches(';').trim());
                        if value == Some(name.as_str()) {
                            problems.push(format!("{path}: `type {name} = {name}`"));
                        }
                    }
                    "interface" | "class" | "enum" => others.push(name),
                    _ => {}
                }
            }
            for (name, count) in &aliases {
                if *count > 1 {
                    problems.push(format!("{path}: type `{name}` declared {count} times"));
                }
                if others.contains(name) {
                    problems.push(format!(
                        "{path}: type `{name}` beside a declaration of its name"
                    ));
                }
            }
        }
        assert!(problems.is_empty(), "{problems:#?}");
    }

    /// A name a file imports is declared in one file only.
    #[test]
    fn imports_are_unambiguous() {
        let files = bodies(&[nsh_base::registry().into()]);
        let mut owners: BTreeMap<String, Vec<&str>> = BTreeMap::new();
        for (path, body) in &files {
            for name in exported_names(body) {
                let paths = owners.entry(name).or_default();
                if !paths.contains(&path.as_str()) {
                    paths.push(path);
                }
            }
        }
        for (path, body) in &files {
            let (used, local) = references(body);
            for name in used.iter().filter(|n| !local.contains(n)) {
                if let Some(paths) = owners.get(name) {
                    let others: Vec<_> = paths.iter().filter(|p| **p != path).collect();
                    assert!(
                        others.len() <= 1 || paths.contains(&path.as_str()),
                        "{path} uses `{name}`, declared in {others:?}"
                    );
                }
            }
        }
    }

    /// No module declares a value (a class, function or constant) named as
    /// a type `types.d.ts` declares: it would shadow the shared type
    /// everywhere in that module (an extension class `TextStyle` made
    /// `StyleProp<TextStyle>` mean the class). The same type alias
    /// generated in both is the same type.
    #[test]
    fn no_module_shadows_a_shared_type() {
        let files = bodies(&[nsh_base::registry().into()]);
        let (_, types) = files
            .iter()
            .find(|(path, _)| path == "nsh/types.d.ts")
            .expect("types.d.ts");
        let shared = exported_names(types);
        let mut clashes = Vec::new();
        for (path, body) in files.iter().filter(|(path, _)| path != "nsh/types.d.ts") {
            let (_, local) = references(body);
            let value = |name: &str| {
                ["class", "function", "const"].iter().any(|kind| {
                    body.contains(&format!("declare {kind} {name}<"))
                        || body.contains(&format!("declare {kind} {name} "))
                        || body.contains(&format!("declare {kind} {name}("))
                        || body.contains(&format!("declare {kind} {name}:"))
                })
            };
            clashes.extend(
                local
                    .iter()
                    .filter(|name| shared.contains(name) && value(name))
                    .map(|name| format!("{path}: {name}")),
            );
        }
        assert!(clashes.is_empty(), "{clashes:?}");
    }

    /// Each web class declares the members its spec defines, and no others.
    #[test]
    fn web_classes_declare_their_members() {
        use crate::web::Key;
        let mut wrong = Vec::new();
        for spec in crate::web::declared_specs() {
            let name = spec.name.to_str().unwrap();
            let mut declared = member_names(spec.ts.members);
            declared.sort();
            let mut defined: Vec<String> = spec
                .methods
                .iter()
                .map(|(key, ..)| match key {
                    Key::Name(n) => n.to_str().unwrap().to_owned(),
                    Key::Iterator => "[Symbol.iterator]".to_owned(),
                    Key::AsyncIterator => "[Symbol.asyncIterator]".to_owned(),
                })
                .chain(
                    spec.accessors
                        .iter()
                        .map(|(n, ..)| n.to_str().unwrap().to_owned()),
                )
                .chain(
                    spec.statics
                        .iter()
                        .map(|(n, ..)| n.to_str().unwrap().to_owned()),
                )
                .collect();
            defined.sort();
            defined.dedup();
            let missing: Vec<_> = defined.iter().filter(|n| !declared.contains(n)).collect();
            let extra: Vec<_> = declared.iter().filter(|n| !defined.contains(n)).collect();
            if !missing.is_empty() || !extra.is_empty() {
                wrong.push(format!(
                    "{name}: undeclared {missing:?}, not defined {extra:?}"
                ));
            }
            if let Some(parent) = spec.parent {
                let parent = crate::web::declared_specs()
                    .chain(crate::web::internal_specs())
                    .find(|s| s.class == parent)
                    .map(|s| s.name.to_str().unwrap())
                    .unwrap();
                if !spec.ts.head.contains(&format!("extends {parent}")) {
                    wrong.push(format!("{name} extends {parent}"));
                }
            }
        }
        assert!(wrong.is_empty(), "{}", wrong.join("\n"));
    }

    /// The declared globals exist, and every global the host adds is declared.
    #[test]
    fn globals_match_the_host() {
        let globals = globals();
        let mut declared: Vec<String> = Vec::new();
        for line in code_only(&globals).lines() {
            let Some(rest) = line.strip_prefix("declare ") else {
                continue;
            };
            let mut parts = rest.split_whitespace();
            if let (Some("var" | "function" | "class" | "const"), Some(name)) =
                (parts.next(), parts.next())
            {
                let name: String = name.chars().take_while(|c| is_ident(*c)).collect();
                if !declared.contains(&name) {
                    declared.push(name);
                }
            }
        }
        let names = |source: &str| -> Vec<String> {
            source
                .split(' ')
                .filter(|n| !n.is_empty())
                .map(str::to_owned)
                .collect()
        };
        let host = crate::Host::new().unwrap();
        host.eval_source(
            "import { text } from \"nsh:rt\";\ntext(Object.getOwnPropertyNames(globalThis).join(\" \"));",
        )
        .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        let on_host = ops
            .into_iter()
            .find_map(|op| match op {
                nsh_core::Op::CreateText { text, .. } => Some(names(&text)),
                _ => None,
            })
            .unwrap();
        let rt = rquickjs::Runtime::new().unwrap();
        let cx = rquickjs::Context::full(&rt).unwrap();
        let bare: Vec<String> = cx.with(|cx| {
            let list: String = cx
                .eval("Object.getOwnPropertyNames(globalThis).join(' ')")
                .unwrap();
            names(&list)
        });
        for name in &declared {
            assert!(
                on_host.contains(name),
                "`{name}` is declared but not a global"
            );
        }
        for name in on_host
            .iter()
            .filter(|n| !bare.contains(n) && !n.starts_with("__"))
            .filter(|n| !crate::web::ECMASCRIPT_GLOBALS.contains(&n.as_str()))
        {
            assert!(declared.contains(name), "global `{name}` is not declared");
        }
    }

    /// What each module exports at run time is what its declarations say
    /// (with a set of classes besides the UI sets).
    #[test]
    fn declarations_match_the_modules() {
        let sets = vec![nsh_base::registry(), crate::classes::tests::registry()];
        let host = crate::Host::with_options(crate::HostOptions {
            ui_sets: sets.clone(),
            ..crate::HostOptions::default()
        })
        .unwrap();
        let files = bodies(&sets.iter().cloned().map(Into::into).collect::<Vec<_>>());
        assert!(
            files.iter().any(|(path, body)| path == "test/classes.d.ts"
                && body.contains("export declare class Tally {")),
            "the classes are declared"
        );
        for (path, body) in files {
            if path == "nsh/types.d.ts" {
                continue;
            }
            let specifier = match path.trim_end_matches(".d.ts") {
                "nsh/index" => "nsh",
                s => s,
            }
            .to_owned();
            let mut declared = exported_values(&body);
            declared.sort();
            host.eval_source(&format!(
                "import {{ text }} from \"nsh:rt\";\nimport * as m from \"{specifier}\";\ntext(Object.keys(m).sort().join(\",\"));"
            ))
            .unwrap_or_else(|e| panic!("{specifier}: {e}"));
            let mut ops = Vec::new();
            host.take_ops(&mut ops);
            let actual = ops
                .into_iter()
                .find_map(|op| match op {
                    nsh_core::Op::CreateText { text, .. } => Some(text.to_string()),
                    _ => None,
                })
                .expect("the module's names");
            assert_eq!(actual, declared.join(","), "{specifier}");
        }
    }
}