nsh-js 0.7.2

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
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
//! The native ES modules apps import: nsh's own (`nsh`,
//! `nsh:rt`, `nsh/device`, `nsh/accessibility`, `nsh/keymap`, ...;
//! [`nsh_core::js::NATIVE_MODULES`])
//! and those of registries (`Registry::specifier`): the UI sets a host
//! serves (`nsh/base`, an app's own) and the runtime's (`nsh/android`, ...), whose
//! components, modules and re-exports become exports (`components.rs`).
//! A module of both kinds (`nsh/accessibility`) has the exports of both.
//!
//! The exports are made when a bundle first imports the module. QuickJS-NG
//! resolves imports when it compiles a module, so the bytecode compiler
//! installs the same loader (a module then only declares its export names;
//! nothing runs).
//!
//! The loader also compiles the chunks of a split bundle (`chunks.rs`): the
//! code the host gave for a name that is not a native module.

use std::{
    cell::RefCell,
    collections::{HashMap, HashSet},
    ffi::{CStr, CString, c_char, c_int, c_void},
    sync::Arc,
};

use nsh_core::{
    decl,
    element::{ComponentSpec, DECLARATIONS, ModuleSpec, Registry, description::SetDescription},
    host_channel::ModuleFake,
};
use rquickjs::{Ctx, JsLifetime, Module, qjs};

use crate::{
    animated, canvas, components, desktop, dom, env, keymap, list, platform_modules,
    reactive::{self, Native},
    touch,
};

type JsValue = qjs::JSValue;
type JsContext = qjs::JSContext;

/// A value nsh's own modules export.
#[derive(Clone, Copy)]
pub(crate) enum Export {
    /// A native function and its `length`.
    Function(Native, c_int),
    /// A value made when the module is first imported (owned).
    Value(fn(*mut JsContext) -> JsValue),
}

/// The TypeScript declaration of an export (`.nsh/types`, assembled by
/// `declarations.rs`): documentation as plain text, the rest as it follows
/// the export's name.
#[derive(Clone, Copy)]
pub(crate) enum Ts {
    /// A function and its signatures (overloads): `<T>(value: T): Signal<T>`.
    Function(&'static str, &'static [&'static str]),
    /// A value and its type.
    Const(&'static str, &'static str),
    /// A class: ` extends Base { ... }` or ` { ... }`.
    Class(&'static str, &'static str),
    /// Not declared: what only compiled code or development bundles import.
    Internal,
}

impl Ts {
    // Constructors for the tables: the text is left out of builds without
    // declarations (`nsh_core::element::DECLARATIONS`).

    /// [`Ts::Function`].
    pub(crate) const fn function(doc: &'static str, signatures: &'static [&'static str]) -> Ts {
        if DECLARATIONS {
            Ts::Function(doc, signatures)
        } else {
            Ts::Internal
        }
    }

    /// [`Ts::Const`].
    pub(crate) const fn value(doc: &'static str, ty: &'static str) -> Ts {
        if DECLARATIONS {
            Ts::Const(doc, ty)
        } else {
            Ts::Internal
        }
    }

    /// [`Ts::Class`].
    pub(crate) const fn class(doc: &'static str, body: &'static str) -> Ts {
        if DECLARATIONS {
            Ts::Class(doc, body)
        } else {
            Ts::Internal
        }
    }
}

/// An export: its name, how it is made and its declaration.
pub(crate) type Item = (&'static str, Export, Ts);

/// One of nsh's own modules.
pub(crate) struct NativeModule {
    pub(crate) name: &'static str,
    pub(crate) exports: &'static [Item],
    /// The sources whose exports this one serves too (`moved_to`), kept by
    /// area: `nsh` serves the primitives (`nsh/list`, `nsh/image`, ...), the
    /// environment (`nsh/device`), ...; no app imports a source.
    pub(crate) also: &'static [&'static str],
    /// The module that serves this one's exports (`nsh`): it is no module
    /// apps import, only the source of those exports and their types.
    pub(crate) moved_to: Option<&'static str>,
    /// The module's own TypeScript types (interfaces, type aliases), next to
    /// the declarations of its exports.
    pub(crate) types: &'static str,
}

/// `nsh`: the API apps write against.
const NSH: &[Item] = &[
    crate::env::TOKEN_EXPORT,
    crate::env::SET_THEME_EXPORT,
    crate::env::APP_INFO_EXPORT,
    (
        "signal",
        Export::Function(reactive::signal, 2),
        Ts::function(
            "A signal holding `value`.",
            &[
                "<T>(value: T, options?: SignalOptions<T>): Signal<T>",
                "<T = undefined>(): Signal<T | undefined>",
            ],
        ),
    ),
    (
        "computed",
        Export::Function(reactive::computed, 2),
        Ts::function(
            "A value derived from signals, computed again when they change (and read).",
            &["<T>(fn: (previous: T | undefined) => T, options?: SignalOptions<T>): Accessor<T>"],
        ),
    ),
    (
        "effect",
        Export::Function(reactive::effect, 1),
        Ts::function(
            "Runs `fn` after rendering, and again when what it read changes. A function `fn`\nreturns is its cleanup (`cleanup(f)`): it runs before `fn` runs again, or when the\neffect goes away.",
            &["(fn: () => void | (() => void)): void"],
        ),
    ),
    (
        "batch",
        Export::Function(reactive::batch, 1),
        Ts::function(
            "Runs `fn`, applying its writes together at the end.",
            &["<T>(fn: () => T): T"],
        ),
    ),
    (
        "untracked",
        Export::Function(reactive::untrack, 1),
        Ts::function(
            "Runs `fn` without tracking what it reads.",
            &["<T>(fn: () => T): T"],
        ),
    ),
    (
        "cleanup",
        Export::Function(reactive::on_cleanup, 1),
        Ts::function(
            "Runs `fn` before the current effect or component runs again or goes away.",
            &["(fn: () => void): void"],
        ),
    ),
    (
        "resource",
        Export::Function(crate::resource::resource, 3),
        Ts::function(
            "A value loaded asynchronously by `fetcher`, again whenever `source` (an accessor) gives a\nnew value that is set (not `undefined`, `null` or `false`) and on `refetch()`. Only the\nlatest load counts: the one it supersedes is aborted (`info.signal`), and so is the running\none when its owner goes away. The value stays while loading again and after a failure.",
            &[
                "<T>(fetcher: (info: ResourceInfo) => T | Promise<T>, options: ResourceOptions<T> & { initialValue: T }): InitializedResource<T>",
                "<T>(fetcher: (info: ResourceInfo) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>",
                "<S, T>(source: ResourceSource<S>, fetcher: (source: S, info: ResourceInfo) => T | Promise<T>, options: ResourceOptions<T> & { initialValue: T }): InitializedResource<T>",
                "<S, T>(source: ResourceSource<S>, fetcher: (source: S, info: ResourceInfo) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>",
            ],
        ),
    ),
    (
        "context",
        Export::Function(dom::context, 1),
        Ts::function(
            "A context with a default value.",
            &["<T>(defaultValue: T): Context<T>"],
        ),
    ),
    (
        "mount",
        Export::Function(dom::mount, 2),
        Ts::function(
            "Renders `app` as the app root. On the desktops `app` declares its windows with\n`<Window>` (a plain root or no window is an error); off them it renders the app's one\nsurface. Returns a function that removes it.",
            &["<P extends object>(app: Component<P>, props?: P): () => void"],
        ),
    ),
    (
        "split",
        Export::Function(dom::split, 2),
        Ts::function(
            "`[picked, rest]`: the props named in `keys` and the others, both still\nfollowing what they read (a component passing the rest on: `<Input {...rest} />`).",
            &[
                "<T extends object, K extends readonly (keyof T)[]>(props: T, keys: K): [Pick<T, K[number]>, Omit<T, K[number]>]",
            ],
        ),
    ),
    (
        "ErrorBoundary",
        Export::Function(dom::error_boundary, 1),
        Ts::function(
            "Its children, or `fallback` once something under them threw (a component's body, a\nbinding, an effect, a listener): what failed goes, and `fallback(error, reset)` shows the\nthrown value; `reset()` renders the children again. A function fallback is always\ncalled so; an element is shown as is. What throws in the fallback goes to\nthe boundary above.",
            &[
                "(props: { fallback: JSX.Element | ((error: unknown, reset: () => void) => JSX.Element); children?: JSX.Element }): JSX.Element",
            ],
        ),
    ),
    (
        "View",
        Export::Value(|cx| dom::host_component(cx, "view", true)),
        Ts::function(
            "A view: the box layout, styles, touches and accessibility work on\n(UIView / ViewGroup).",
            &["(props: ViewProps): JSX.Element"],
        ),
    ),
    (
        "Text",
        Export::Value(|cx| dom::host_component(cx, "text", true)),
        Ts::function(
            "A paragraph of text; a `<Text>` in it is a span of the same paragraph, other\nelements are inline attachments.",
            &["(props: TextProps): JSX.Element"],
        ),
    ),
    (
        "Scroll",
        Export::Value(|cx| dom::host_component(cx, "scroll", true)),
        Ts::function(
            "A native scroll view (UIScrollView / ScrollView), zoomable; for long\nlists, `List`.",
            &["(props: ScrollProps): JSX.Element"],
        ),
    ),
    (
        "Overlay",
        Export::Value(|cx| dom::host_component(cx, "overlay", true)),
        Ts::function(
            "Its children on top of the root view it is in (the surface, or the dialog\naround it), outside its parent's layout and clipping, while it stays its\nparent's child for everything else (context, events, lifetime): popovers,\nmenus, tooltips. Without `anchor` it is a `position: fixed` box of that\nroot view; with one it goes on the `placement` side of the anchor, on the\nother when only that one has room, kept inside the safe area, and follows\nthe anchor as it moves. `onPressOutside` and `onCancel` (Escape, Android\nback) report what closes it; closing is the app's.",
            &["(props: OverlayProps): JSX.Element"],
        ),
    ),
    (
        "Shader",
        Export::Value(|cx| dom::host_component(cx, "shader", true)),
        Ts::function(
            "A view whose box a GPU shader draws, under its children: `source` is WGSL\ndefining `fn shade(uv: vec2f) -> vec4f`, the straight sRGB color of each\npoint (`uv` 0..1 from the top left), which reads `nsh.size` (points),\n`nsh.time` (seconds; reading it animates the shader, unless `paused`),\n`nsh.scale` and the members of its `struct Uniforms` as `uniforms.name`, set by\n`uniforms={{ name: value }}`: numbers, colors, lists and animated values,\nwhich move it natively. It takes every prop of a `View`.",
            &["(props: ShaderProps): JSX.Element"],
        ),
    ),
    (
        "ShaderEffect",
        Export::Value(|cx| dom::host_component(cx, "shadereffect", true)),
        Ts::function(
            "A view whose children draw through a GPU shader: its WGSL `shade` reads\nwhat they draw with `sample_content(uv)` (and what is behind the view with\n`sample_backdrop(uv)`), `nsh.progress` from `progress` (a number or an\nanimated value), and draws `maxSampleOffset` points beyond the box. The\nchildren keep their presses. Without `source` they draw as they are.",
            &["(props: ShaderEffectProps): JSX.Element"],
        ),
    ),
    (
        "ShaderTransition",
        Export::Value(|cx| dom::host_component(cx, "shadertransition", true)),
        Ts::function(
            "A view whose children change through a GPU shader: when `value` changes\n(not the first one) its WGSL `shade` draws, for `duration` ms (300),\n`sample_from(uv)` (a picture of what they drew) changing into\n`sample_to(uv)` (what they draw now) as `nsh.progress` goes from 0 to 1.\nWithout `source` it runs `fallback`: `\"fade\"` (a cross-fade) or `\"none\"`.",
            &["(props: ShaderTransitionProps): JSX.Element"],
        ),
    ),
    (
        "ScreenEffect",
        Export::Value(|cx| dom::host_component(cx, "screeneffect", false)),
        Ts::function(
            "The whole surface (its pages, dialogs and overlays) drawn through a GPU\nshader, which reads it with `sample_content(uv)`. It takes no space and\nhas no children; the last one mounted with a `source` draws.",
            &["(props: ScreenEffectProps): JSX.Element"],
        ),
    ),
    (
        "ScreenTransition",
        Export::Value(|cx| dom::host_component(cx, "screentransition", false)),
        Ts::function(
            "The whole surface changing through a GPU shader when `value` changes,\nas `ShaderTransition` does for its children.",
            &["(props: ScreenTransitionProps): JSX.Element"],
        ),
    ),
];

/// `nsh`'s types; its element and style types and `JSX` are `types.d.ts`'s.
const NSH_TYPES: &str = r#"export type * from "./types";

/** A value that changes over time, read by calling it (tracked). */
export interface Accessor<T> {
  (): T;
}

/** A signal: `count()` reads it, `count.set(1)` and `count.update((n) => n + 1)` write it (both bound: `count.set` can be passed on its own). */
export interface Signal<T> extends Accessor<T> {
  set(value: T): void;
  update(fn: (value: T) => T): void;
}

export interface SignalOptions<T> {
  /** When a new value counts as a change (default `===`); `false`: always. */
  equals?: false | ((previous: T, next: T) => boolean);
}

/** Where a resource is: nothing to load, loading the first value, loaded, loading again, failed. */
export type ResourceState = "unresolved" | "pending" | "ready" | "refreshing" | "errored";

/** What a resource loads from: an accessor (tracked) or a value; `undefined`, `null` and `false` load nothing. */
export type ResourceSource<S> = S | false | null | undefined | (() => S | false | null | undefined);

/** What a load is given besides the source. */
export interface ResourceInfo {
  /** Aborted when the load no longer counts (another load, or the owner went away): pass it to `fetch`. */
  signal: AbortSignal;
  /** Started by `refetch()`, the source unchanged. */
  refetching: boolean;
}

export interface ResourceOptions<T> {
  /** The value until the first load ends, which is then a refresh. */
  initialValue?: T;
}

/** What a resource does besides giving its value. */
export interface ResourceControls<T> {
  /** Whether a load runs. */
  loading(): boolean;
  /** The last load's error; `undefined` once a load gives a value. */
  error(): unknown;
  state(): ResourceState;
  /** Loads again from the same source, keeping the value meanwhile (a retry, a pull to refresh). */
  refetch(): void;
  /** Sets the value here, with no load (an optimistic update), clearing the error. */
  mutate(value: T): T;
}

/** A value loaded asynchronously: `user()` reads the latest one, `undefined` before the first. */
export interface Resource<T> extends Accessor<T | undefined>, ResourceControls<T> {}

/** A resource with an `initialValue`: it always has a value. */
export interface InitializedResource<T> extends Accessor<T>, ResourceControls<T> {}

/** A value components provide to what they render: `Theme()` reads the nearest one. */
export interface Context<T> extends Accessor<T> {
  Provider: (props: { value: T; children?: JSX.Element }) => JSX.Element;
}

/** A component: a function of its props rendering elements. */
export type Component<P = {}> = (props: P) => JSX.Element;

/**
 * The design tokens of the app's theme by name, and what `token()` gives
 * for each: a color or a font family as a string, a number. nsh declares
 * the app's (`.nsh/types/nsh/tokens.d.ts`, from `nsh.json` `"theme"`).
 */
export interface Tokens {}

/**
 * A theme, as `nsh.json`'s `"theme"` writes it: shadcn/ui's `cssVars`, the
 * values as CSS writes them (colors, `var(--name)`, `color-mix()`, lengths in
 * `px` or `rem`, font family lists for `font-*`). `theme`'s apply in both
 * appearances, `light`'s in the light one and in the dark one where `dark`
 * leaves them out, `dark`'s in the dark one.
 */
export interface Theme {
  cssVars: {
    theme?: Record<string, string | number>;
    light?: Record<string, string | number>;
    dark?: Record<string, string | number>;
  };
}

/** The app as it was built (`appInfo()`). */
export interface AppInfo {
  /** `nsh.json`'s `"id"`; `null` without one. */
  readonly id: string | null;
  /** `nsh.json`'s `"name"`; `null` without one. */
  readonly name: string | null;
  /** The version the code was built as: `nsh.json`'s `"version"`, or the
   * one `nsh package` / `nsh publish` was given (`--version`); `null`
   * without one. */
  readonly version: string | null;
  /** The build number the code was built as: `nsh.json`'s `"build"`, or the
   * one `nsh package` / `nsh publish` was given (`--build`); `null`
   * without one. */
  readonly build: number | null;
  /** A development build: `nsh run`, `nsh dev`, `nsh test` and `nsh build`
   * without `--release`. `false` for release builds: `nsh package`,
   * `nsh publish`, `nsh build --release`. */
  readonly development: boolean;
}
"#;

/// The sources of what `nsh` serves (`NativeModule::moved_to`), kept by
/// area.
const NSH_SOURCES: &[&str] = &[
    "nsh/image",
    "nsh/list",
    "nsh/canvas",
    "nsh/webview",
    "nsh/video",
    "nsh/device",
    "nsh/accessibility",
    "nsh/native",
    "nsh/gesture",
    "nsh/animated",
    "nsh/host",
    "nsh/keymap",
];

/// The sources of what `nsh/mobile` serves, by platform.
const MOBILE_SOURCES: &[&str] = &["nsh/ios", "nsh/android"];

pub(crate) const MODULES: &[NativeModule] = &[
    NativeModule {
        name: "nsh",
        exports: NSH,
        also: NSH_SOURCES,
        moved_to: None,
        types: decl!(NSH_TYPES),
    },
    NativeModule {
        name: "nsh:rt",
        exports: dom::RT_EXPORTS,
        also: &[],
        moved_to: None,
        types: "",
    },
    NativeModule {
        name: "nsh/device",
        exports: env::DEVICE_EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: decl!(env::DEVICE_TYPES),
    },
    NativeModule {
        name: "nsh/accessibility",
        exports: env::ACCESSIBILITY_EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: "",
    },
    NativeModule {
        name: "nsh/android",
        exports: platform_modules::ANDROID_EXPORTS,
        also: &[],
        moved_to: Some("nsh/mobile"),
        types: decl!(platform_modules::ANDROID_TYPES),
    },
    NativeModule {
        name: "nsh/ios",
        exports: platform_modules::IOS_EXPORTS,
        also: &[],
        moved_to: Some("nsh/mobile"),
        types: decl!(platform_modules::IOS_TYPES),
    },
    NativeModule {
        name: "nsh/desktop",
        exports: desktop::EXPORTS,
        also: &[],
        moved_to: None,
        types: decl!(desktop::TYPES),
    },
    NativeModule {
        name: "nsh/i18n",
        exports: crate::i18n::EXPORTS,
        also: &[],
        moved_to: None,
        types: "",
    },
    NativeModule {
        name: "nsh/mobile",
        exports: platform_modules::MOBILE_EXPORTS,
        also: MOBILE_SOURCES,
        moved_to: None,
        types: "",
    },
    NativeModule {
        name: "nsh/web",
        exports: crate::web_page::EXPORTS,
        also: &[],
        moved_to: None,
        types: decl!(crate::web_page::TYPES),
    },
    NativeModule {
        name: "nsh/webview",
        exports: platform_modules::WEBVIEW_EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: decl!(platform_modules::WEBVIEW_TYPES),
    },
    NativeModule {
        name: "nsh/video",
        exports: platform_modules::VIDEO_EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: decl!(platform_modules::VIDEO_TYPES),
    },
    NativeModule {
        name: "nsh/native",
        exports: platform_modules::NATIVE_EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: decl!(platform_modules::NATIVE_TYPES),
    },
    NativeModule {
        name: "nsh/gesture",
        exports: touch::GESTURE_EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: decl!(touch::GESTURE_TYPES),
    },
    NativeModule {
        name: "nsh/animated",
        exports: animated::EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: decl!(animated::TYPES),
    },
    NativeModule {
        name: "nsh/canvas",
        exports: canvas::EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: decl!(canvas::TYPES),
    },
    NativeModule {
        name: "nsh/list",
        exports: list::EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: decl!(list::TYPES),
    },
    NativeModule {
        name: "nsh/image",
        exports: IMAGE_EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: "",
    },
    NativeModule {
        name: "nsh/host",
        exports: platform_modules::HOST_EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: decl!(crate::host_channel::TYPES),
    },
    NativeModule {
        name: "nsh/keymap",
        exports: keymap::EXPORTS,
        also: &[],
        moved_to: Some("nsh"),
        types: decl!(keymap::TYPES),
    },
];

/// `nsh`'s `Image`: the image element as a component carrying the
/// functions of the runtime's module (`getSize`, `prefetch`).
const IMAGE_EXPORTS: &[Item] = &[(
    "Image",
    Export::Value(|cx| {
        let image = dom::host_component(cx, "image", true);
        components::add_runtime_functions(cx, image, "nsh", "Image");
        image
    }),
    Ts::value(
        "An image (a URL or `import logo from \"./logo.png\"`), decoded and cached\nnatively; `Image.getSize(src)` and `Image.prefetch(src)` ask about one\nwithout showing it.",
        "((props: ImageProps) => JSX.Element) & ImageModule",
    ),
)];

/// One export of a module, as it is made.
enum Made {
    Own(Export),
    /// An export of source `.0` a module serves (`nsh`'s `Image` is the
    /// source `nsh/image`'s): one value per VM, whichever module serving it
    /// is imported first making it.
    Shared(&'static str, Export),
    /// A Rust component, with the functions of a module of the same name.
    Component(Arc<ComponentSpec>, Option<Arc<ModuleSpec>>),
    /// A module object.
    Module(Arc<ModuleSpec>),
    /// One function of a flat module, with the functions of a module of
    /// its name.
    Function(Arc<ModuleSpec>, &'static str, Option<Arc<ModuleSpec>>),
    /// A constant projected from the same generated module object.
    Constant(Arc<ModuleSpec>, &'static str),
    /// The generated module object itself.
    Default(Arc<ModuleSpec>),
    /// A Rust class (`#[class]`).
    Class(&'static nsh_core::element::ClassDef),
    /// A runtime value a registry exports as it is (`safeArea`).
    Reexport(&'static str),
}

/// The modules a VM (or the bytecode compiler) serves: nsh's own, the
/// runtime's registries and the host's UI sets, and the chunks of a split
/// bundle.
pub(crate) struct ModuleTable {
    registries: Vec<Registry>,
    /// Where the host's UI sets start in `registries` (after the
    /// runtime's).
    host: usize,
    /// UI sets known by their exports' names only (the bytecode compiler's:
    /// it links imports by name and never runs the modules).
    declared: Vec<SetDescription>,
    pub(crate) chunks: RefCell<ChunkCodes>,
    /// The objects of typed modules made so far, by specifier and module:
    /// one per VM, so a module's default export, its flat exports and a
    /// global made from it (`process`) are the same values.
    objects: RefCell<HashMap<(String, &'static str), crate::web::js::V>>,
    /// The values of [`Made::Shared`] exports made so far, by (module,
    /// export).
    shared: RefCell<HashMap<(&'static str, String), crate::web::js::V>>,
}

/// The code of a chunk.
pub(crate) enum ChunkCode {
    Source(String),
    /// From `compile_bytecode`, trusted (as `Host::eval_bytecode`'s).
    Bytecode(Vec<u8>),
}

/// The chunks of a split bundle a VM knows of, by id (module name).
#[derive(Default)]
pub(crate) struct ChunkCodes {
    /// Given, not imported yet: the loader compiles them (and drops the
    /// code).
    pub(crate) code: HashMap<String, ChunkCode>,
    /// Compiled (QuickJS has the modules).
    pub(crate) loaded: HashSet<String>,
}

impl ChunkCodes {
    /// Whether chunk `id` can be imported now.
    pub(crate) fn has(&self, id: &str) -> bool {
        id == nsh_core::js::ENTRY_CHUNK || self.loaded.contains(id) || self.code.contains_key(id)
    }
}

impl ModuleTable {
    pub(crate) fn new(ui_sets: &[Registry]) -> ModuleTable {
        let mut registries: Vec<Registry> = nsh_core::runtime::registries().to_vec();
        let host = registries.len();
        registries.extend(
            ui_sets
                .iter()
                .flat_map(Registry::sets)
                .filter(|r| r.specifier().is_some())
                .cloned(),
        );
        ModuleTable {
            registries,
            host,
            declared: Vec::new(),
            chunks: RefCell::default(),
            objects: RefCell::default(),
            shared: RefCell::default(),
        }
    }

    /// Frees the module objects (the VM is going).
    pub(crate) fn free_objects(&self) {
        let objects = std::mem::take(&mut *self.objects.borrow_mut());
        drop(objects);
        let shared = std::mem::take(&mut *self.shared.borrow_mut());
        drop(shared);
    }

    /// The values `nsh-js` makes for the registries of module `name`.
    fn natives(&self, name: &str) -> Vec<&'static str> {
        self.registries
            .iter()
            .filter(|r| r.specifier() == Some(name))
            .flat_map(|r| r.native_value_names().iter().copied())
            .collect()
    }

    /// The default object of the typed module `name` (its flat default
    /// module's), made once per VM; `None`: it has none.
    pub(crate) fn default_object(&self, cx: *mut JsContext, name: &str) -> Option<JsValue> {
        let spec = self
            .registries
            .iter()
            .filter(|r| r.specifier() == Some(name))
            .flat_map(|r| r.module_specs())
            .find(|m| m.flat && m.default)?;
        Some(self.object(cx, name, &spec))
    }

    /// Module `spec`'s object (owned), made once per VM: its functions,
    /// getters and constants, and on a flat default module the registry's
    /// native values too.
    fn object(&self, cx: *mut JsContext, name: &str, spec: &ModuleSpec) -> JsValue {
        let key = (name.to_owned(), spec.name);
        if let Some(object) = self.objects.borrow().get(&key) {
            // SAFETY: a live value the table holds.
            return unsafe { qjs::JS_DupValue(cx, object.raw()) };
        }
        let object = components::module(cx, spec);
        // SAFETY: inline tag check.
        if unsafe { qjs::JS_IsException(object) } {
            return object;
        }
        if spec.flat {
            for f in spec.functions.iter().filter(|f| !f.getter) {
                let Some(members) = self
                    .registries
                    .iter()
                    .filter(|r| r.specifier() == Some(name))
                    .find_map(|r| r.function_members(f.name))
                else {
                    continue;
                };
                let cname = CString::new(f.name).unwrap_or_default();
                // SAFETY: a property of the object we own; the reference
                // it returns is ours to free.
                unsafe {
                    let function = qjs::JS_GetPropertyStr(cx, object, cname.as_ptr());
                    components::add_functions(cx, function, &members);
                    qjs::JS_FreeValue(cx, function);
                }
            }
        }
        if spec.flat && spec.default {
            for native in self.natives(name) {
                let value = env::reexport(cx, native);
                // SAFETY: inline tag check.
                if unsafe { qjs::JS_IsException(value) } {
                    // SAFETY: ours.
                    unsafe { qjs::JS_FreeValue(cx, object) };
                    return value;
                }
                let cname = CString::new(native).unwrap_or_default();
                // SAFETY: the object takes the value.
                unsafe { qjs::JS_SetPropertyStr(cx, object, cname.as_ptr(), value) };
            }
        }
        // SAFETY: the table keeps one reference, the caller gets another.
        let kept = unsafe { qjs::JS_DupValue(cx, object) };
        self.objects
            .borrow_mut()
            .insert(key, crate::web::js::V::own(cx, kept));
        object
    }

    /// The value of export `export` of nsh's module `module` that another
    /// module serves too (owned), made once per VM.
    fn shared(&self, cx: *mut JsContext, module: &'static str, export: &str, e: Export) -> JsValue {
        let key = (module, export.to_owned());
        if let Some(value) = self.shared.borrow().get(&key) {
            // SAFETY: a live value the table holds.
            return unsafe { qjs::JS_DupValue(cx, value.raw()) };
        }
        let value = make_own(cx, export, e);
        // SAFETY: inline tag check.
        if unsafe { qjs::JS_IsException(value) } {
            return value;
        }
        // SAFETY: the table keeps one reference, the caller gets another.
        let kept = unsafe { qjs::JS_DupValue(cx, value) };
        self.shared
            .borrow_mut()
            .insert(key, crate::web::js::V::own(cx, kept));
        value
    }

    /// The table the bytecode compiler links against: nsh's own modules,
    /// the runtime's registries and `ui_sets` by their exports' names.
    pub(crate) fn compiling(ui_sets: &[SetDescription]) -> ModuleTable {
        let registries = nsh_core::runtime::registries().to_vec();
        ModuleTable {
            // No host sets: `nativeModule` is a run-time call, never an
            // import the compiler links.
            host: registries.len(),
            registries,
            declared: ui_sets.to_vec(),
            chunks: RefCell::default(),
            objects: RefCell::default(),
            shared: RefCell::default(),
        }
    }

    /// The names module `name` exports, if it is one: what the loader
    /// declares (the values are made when it is evaluated, [`init`]).
    pub(crate) fn export_names(&self, name: &str) -> Option<Vec<String>> {
        let own = self.exports(name);
        let mut found = own.is_some();
        let mut names: Vec<String> = own.into_iter().flatten().map(|(name, _)| name).collect();
        for set in self.declared.iter().filter(|s| s.specifier == name) {
            found = true;
            for export in &set.exports {
                if !names.contains(&export.name) {
                    names.push(export.name.clone());
                }
            }
        }
        found.then_some(names)
    }

    /// The exports of module `name`, if it is one.
    fn exports(&self, name: &str) -> Option<Vec<(String, Made)>> {
        let mut out: Vec<(String, Made)> = Vec::new();
        let mut found = false;
        if name == crate::hot::SPECIFIER {
            let own = crate::hot::EXPORTS.iter();
            return Some(own.map(|&(n, e, _)| (n.to_owned(), Made::Own(e))).collect());
        }
        if let Some(m) = MODULES
            .iter()
            .find(|m| m.name == name && m.moved_to.is_none())
        {
            found = true;
            let shared = m.moved_to.is_some();
            out.extend(m.exports.iter().map(|&(n, e, _)| {
                let made = if shared {
                    Made::Shared(m.name, e)
                } else {
                    Made::Own(e)
                };
                (n.to_owned(), made)
            }));
            for other in m
                .also
                .iter()
                .filter_map(|a| MODULES.iter().find(|o| o.name == *a))
            {
                out.extend(
                    other
                        .exports
                        .iter()
                        .map(|&(n, e, _)| (n.to_owned(), Made::Shared(other.name, e))),
                );
            }
        }
        for registry in self
            .registries
            .iter()
            .filter(|r| r.specifier() == Some(name))
        {
            found = true;
            registry_exports(registry, &mut out);
        }
        // nsh's own export wins over a registry's of the same name (it
        // builds on it: `BackHandler`).
        let mut seen = std::collections::HashSet::new();
        out.retain(|(name, _)| seen.insert(name.clone()));
        found.then_some(out)
    }

    /// The exports of the UI set the host registered under `specifier`
    /// (`nativeModule`): only the host's sets, never nsh's own modules or
    /// the runtime's.
    fn host_exports(&self, specifier: &str) -> Option<Vec<(String, Made)>> {
        if MODULES.iter().any(|m| m.name == specifier) {
            return None;
        }
        let mut out = Vec::new();
        let mut found = false;
        for registry in self.registries[self.host..]
            .iter()
            .filter(|r| r.specifier() == Some(specifier))
        {
            found = true;
            registry_exports(registry, &mut out);
        }
        let mut seen = std::collections::HashSet::new();
        out.retain(|(name, _)| seen.insert(name.clone()));
        found.then_some(out)
    }
}

/// The exports of `registry`: its components, modules, classes and
/// re-exports.
fn registry_exports(registry: &Registry, out: &mut Vec<(String, Made)>) {
    let modules = registry.module_specs();
    let specs = registry.specs();
    for spec in &specs {
        let module = modules.iter().find(|m| m.name == spec.export).cloned();
        out.push((spec.export.clone(), Made::Component(spec.clone(), module)));
    }
    for m in &modules {
        if specs.iter().any(|s| s.export == m.name)
            || (!m.flat && registry.function_members(m.name).is_some())
        {
            continue;
        }
        if m.flat {
            // A getter reads the object's property; it is no export.
            for f in m.functions.iter().filter(|f| !f.getter) {
                let members = registry.function_members(f.name);
                out.push((
                    f.name.to_owned(),
                    Made::Function(m.clone(), f.name, members),
                ));
            }
            for constant in &m.constants {
                out.push((
                    constant.name.to_owned(),
                    Made::Constant(m.clone(), constant.name),
                ));
            }
        } else {
            out.push((m.name.to_owned(), Made::Module(m.clone())));
        }
        if m.default {
            out.push(("default".to_owned(), Made::Default(m.clone())));
        }
    }
    // An interface's objects come from members only: no value.
    for class in registry
        .class_specs()
        .into_iter()
        .filter(|c| !c.def.interface)
    {
        out.push((class.name.to_owned(), Made::Class(class.def)));
    }
    for &value in registry
        .reexports()
        .0
        .iter()
        .chain(registry.native_value_names())
    {
        out.push((value.to_owned(), Made::Reexport(value)));
    }
}

/// The table is owned by State (or the bytecode compiler), and outlives
/// every module load. No JS values are kept in this context-local handle.
#[derive(Clone, Copy, JsLifetime)]
struct ModuleTablePtr(*const ModuleTable);

pub(crate) fn install(cx: &Ctx<'_>, table: *const ModuleTable) {
    assert!(cx.store_userdata(ModuleTablePtr(table)).is_ok());
}

pub(crate) struct Resolver;
impl rquickjs::loader::Resolver for Resolver {
    fn resolve<'js>(
        &mut self,
        _ctx: &Ctx<'js>,
        base: &str,
        name: &str,
        _attributes: Option<rquickjs::loader::ImportAttributes<'js>>,
    ) -> rquickjs::Result<String> {
        if let Some(name) = crate::standard::normalize(name) {
            return Ok(name.to_owned());
        }
        Ok(normalize_chunk(base, name))
    }
}

// Match QuickJS's default normalization: preserve bare names and only
// consume leading ./ and ../ relative to the importing module's directory.
fn normalize_chunk(base: &str, name: &str) -> String {
    if !name.starts_with('.') {
        return name.to_owned();
    }
    let mut directory = base.rsplit_once('/').map_or("", |(dir, _)| dir);
    let mut rest = name;
    loop {
        if let Some(next) = rest.strip_prefix("./") {
            rest = next;
        } else if let Some(next) = rest.strip_prefix("../") {
            let last = directory.rsplit('/').next().unwrap_or("");
            if directory.is_empty() || matches!(last, "." | "..") {
                break;
            }
            directory = directory.rsplit_once('/').map_or("", |(dir, _)| dir);
            rest = next;
        } else {
            break;
        }
    }
    if directory.is_empty() {
        rest.to_owned()
    } else {
        format!("{directory}/{rest}")
    }
}

pub(crate) struct Loader;
impl rquickjs::loader::Loader for Loader {
    fn load<'js>(
        &mut self,
        cx: &Ctx<'js>,
        name: &str,
        _attributes: Option<rquickjs::loader::ImportAttributes<'js>>,
    ) -> rquickjs::Result<Module<'js>> {
        // Framework typed registries own their native exports, including
        // standard names migrated from handwritten adapters. LLRT providers
        // remain on their original ModuleDef path in this same VM.
        let registered = cx
            .userdata::<ModuleTablePtr>()
            // SAFETY: `install`'s owner (the VM state or the bytecode
            // compiler) keeps the table alive while the context loads.
            .is_some_and(|table| unsafe { (&*table.0).exports(name).is_some() });
        if !registered && let Some(name) = crate::standard::normalize(name) {
            return crate::standard::load(cx, name);
        }
        // SAFETY: the thunk uses this live context's registered table and
        // returns exactly the module created by the existing native loader.
        unsafe { Module::from_load_fn(cx.clone(), name, load_native) }
    }
}

/// Resolve an already-canonical native specifier through the same provider
/// selection used by the runtime loader (also used by type discovery).
pub(crate) fn load_module<'js>(cx: &Ctx<'js>, name: &str) -> rquickjs::Result<Module<'js>> {
    rquickjs::loader::Loader::load(&mut Loader, cx, name, None)
}

unsafe extern "C" fn load_native(
    raw: *mut JsContext,
    name: *const c_char,
) -> *mut qjs::JSModuleDef {
    // SAFETY: called by Module::from_load_fn while its runtime is locked;
    // the temporary Ctx never escapes this callback.
    let cx = unsafe { Ctx::from_raw(std::ptr::NonNull::new_unchecked(raw)) };
    let table = cx.userdata::<ModuleTablePtr>().map(|table| table.0);
    match table {
        // SAFETY: install's owner keeps the table alive through this load.
        Some(table) => unsafe { load(raw, name, table as *mut c_void) },
        None => {
            // SAFETY: throws on the live context of this callback; the
            // message is a literal without format directives.
            unsafe {
                qjs::JS_ThrowInternalError(raw, c"native module table is not installed".as_ptr());
            }
            std::ptr::null_mut()
        }
    }
}

unsafe extern "C" fn load(
    cx: *mut JsContext,
    name: *const c_char,
    opaque: *mut c_void,
) -> *mut qjs::JSModuleDef {
    // SAFETY: QuickJS passes a NUL-terminated module name; the table is the
    // one `install` registered for this context.
    let (cname, table) = unsafe { (CStr::from_ptr(name), &*(opaque as *const ModuleTable)) };
    let exports = cname.to_str().ok().and_then(|n| table.export_names(n));
    // Taken first: compiling it loads its imports, here again.
    let chunk = match (&exports, cname.to_str()) {
        (None, Ok(id)) => table.chunks.borrow_mut().code.remove(id).map(|c| (id, c)),
        _ => None,
    };
    if let Some((id, code)) = chunk {
        // SAFETY: a live context; `code` is trusted as the host's API
        // requires.
        let m = unsafe { compile_chunk(cx, name, code) };
        if !m.is_null() {
            table.chunks.borrow_mut().loaded.insert(id.to_owned());
        }
        return m;
    }
    let Some(exports) = exports else {
        // SAFETY: throws on a live context; `%s` keeps the name literal.
        unsafe {
            qjs::JS_ThrowReferenceError(
                cx,
                c"could not load module '%s' (only registered native modules and bundle chunks can be imported at run time)"
                    .as_ptr(),
                name,
            )
        };
        return std::ptr::null_mut();
    };
    // SAFETY: a new C module declaring its exports (set by `init`).
    unsafe {
        let m = qjs::JS_NewCModule(cx, name, Some(init));
        if m.is_null() {
            return m;
        }
        for export in &exports {
            let export = CString::new(export.as_str()).unwrap_or_default();
            qjs::JS_AddModuleExport(cx, m, export.as_ptr());
        }
        m
    }
}

/// Compiles chunk `name` (its imports resolved by the loader, recursively);
/// null with the exception pending when it does not compile.
///
/// # Safety
///
/// `cx` is live; bytecode is trusted.
unsafe fn compile_chunk(
    cx: *mut JsContext,
    name: *const c_char,
    code: ChunkCode,
) -> *mut qjs::JSModuleDef {
    // SAFETY: per the contract; QuickJS reads source up to the NUL it
    // requires after it.
    let module = unsafe {
        match code {
            ChunkCode::Source(mut source) => {
                let len = source.len();
                source.push('\0');
                qjs::JS_Eval(
                    cx,
                    source.as_ptr() as *const c_char,
                    len as _,
                    name,
                    (qjs::JS_EVAL_TYPE_MODULE | qjs::JS_EVAL_FLAG_COMPILE_ONLY) as c_int,
                )
            }
            ChunkCode::Bytecode(bytes) => qjs::JS_ReadObject(
                cx,
                bytes.as_ptr(),
                bytes.len() as _,
                qjs::JS_READ_OBJ_BYTECODE as c_int,
            ),
        }
    };
    // SAFETY: inspecting and freeing the value just made.
    unsafe {
        if qjs::JS_IsException(module) {
            return std::ptr::null_mut();
        }
        if qjs::JS_VALUE_GET_TAG(module) != qjs::JS_TAG_MODULE {
            qjs::JS_FreeValue(cx, module);
            qjs::JS_ThrowTypeError(cx, c"chunk '%s' is not a module".as_ptr(), name);
            return std::ptr::null_mut();
        }
        let m = qjs::JS_VALUE_GET_PTR(module) as *mut qjs::JSModuleDef;
        // The context keeps the module: the value is one more reference.
        qjs::JS_FreeValue(cx, module);
        m
    }
}

unsafe extern "C" fn init(cx: *mut JsContext, m: *mut qjs::JSModuleDef) -> c_int {
    // SAFETY: the module's name atom, freed below; exports are new values
    // the module takes; the state's table lives as long as the context.
    unsafe {
        let atom = qjs::JS_GetModuleName(cx, m);
        let name = qjs::JS_AtomToCStringLen(cx, std::ptr::null_mut(), atom);
        qjs::JS_FreeAtom(cx, atom);
        if name.is_null() {
            return -1;
        }
        let state = crate::state::state(cx);
        let module_name = CStr::from_ptr(name).to_string_lossy().into_owned();
        qjs::JS_FreeCString(cx, name);
        let Some(exports) = (*state).modules.exports(&module_name) else {
            return -1;
        };
        let name = module_name;
        // One object per typed module in the VM: default and flat named
        // exports share its functions and values, as a global made from it
        // does.
        let table = &(*state).modules;
        let default_spec = exports.iter().find_map(|(_, made)| match made {
            Made::Default(spec) if spec.flat => Some(spec.clone()),
            _ => None,
        });
        let fakes = crate::host_channel::module_fakes(cx, &name);
        if !fakes.is_empty() {
            let names: Vec<&str> = exports.iter().map(|(n, _)| n.as_str()).collect();
            warn_unknown_fakes(&name, &names, &fakes);
            if let Some(spec) = &default_spec
                && fake_members(cx, table.object(cx, &name, spec), &name, "", &fakes).is_err()
            {
                return -1;
            }
        }
        for (export, made) in exports {
            let value = make(cx, table, &name, default_spec.as_ref(), &export, made);
            let value = with_fakes(cx, &name, &export, value, &fakes);
            if qjs::JS_IsException(value) {
                return -1;
            }
            let cname = CString::new(export.as_str()).unwrap_or_default();
            if qjs::JS_SetModuleExport(cx, m, cname.as_ptr(), value) != 0 {
                return -1;
            }
        }
    }
    0
}

/// The value of export `export` of module `name` (owned; an exception when
/// making it threw). A typed module's object is the VM's one (`table`), and
/// a value of a flat default module (`default_spec`) is that object's.
fn make(
    cx: *mut JsContext,
    table: &ModuleTable,
    name: &str,
    default_spec: Option<&Arc<ModuleSpec>>,
    export: &str,
    made: Made,
) -> JsValue {
    let member = |spec: &ModuleSpec, member: &str| {
        let object = crate::web::js::V::own(cx, table.object(cx, name, spec));
        // SAFETY: inline tag check; a property read of the live object.
        unsafe {
            if qjs::JS_IsException(object.raw()) {
                return qjs::JS_EXCEPTION;
            }
            let member = CString::new(member).unwrap_or_default();
            qjs::JS_GetPropertyStr(cx, object.raw(), member.as_ptr())
        }
    };
    match made {
        Made::Own(e) => make_own(cx, export, e),
        Made::Shared(module, e) => table.shared(cx, module, export, e),
        Made::Component(spec, module) => components::component(cx, spec, module),
        Made::Module(spec) | Made::Default(spec) => table.object(cx, name, &spec),
        Made::Function(spec, f, members) if !spec.default => {
            let function = components::module_function(cx, &spec, f);
            if let Some(members) = members {
                components::add_functions(cx, function, &members);
            }
            function
        }
        // The object's function, which has its members already.
        Made::Function(spec, f, _) | Made::Constant(spec, f) => member(&spec, f),
        Made::Class(def) => match crate::classes::constructor(cx, def) {
            Ok(ctor) => ctor.take(),
            Err(_) => qjs::JS_EXCEPTION,
        },
        Made::Reexport(value) => match default_spec {
            Some(spec) => member(spec, value),
            None => env::reexport(cx, value),
        },
    }
}

/// `value` (owned), export `export` of module `specifier`, with the
/// stand-ins `fakes` give it or its members (owned; an exception when
/// making one threw).
fn with_fakes(
    cx: *mut JsContext,
    specifier: &str,
    export: &str,
    value: JsValue,
    fakes: &[(String, ModuleFake)],
) -> JsValue {
    // SAFETY: inline tag check.
    if fakes.is_empty() || unsafe { qjs::JS_IsException(value) } {
        return value;
    }
    let mut value = crate::web::js::V::own(cx, value);
    if let Some((_, fake)) = fakes.iter().find(|(path, _)| path == export) {
        match crate::host_channel::stand_in(cx, value.raw(), fake) {
            Ok(fake) => value = fake,
            Err(_) => return qjs::JS_EXCEPTION,
        }
    }
    let prefix = format!("{export}.");
    // SAFETY: a new reference for the members' object, freed by its owner.
    let object = unsafe { qjs::JS_DupValue(cx, value.raw()) };
    match fake_members(cx, object, specifier, &prefix, fakes) {
        Ok(()) => value.take(),
        Err(_) => qjs::JS_EXCEPTION,
    }
}

/// Puts the stand-ins of `fakes` whose path is `prefix` and a member's name
/// on `object` (owned, freed here), as data properties; warns of those
/// naming no member of it (a test's typo) and leaves them out. `prefix` is
/// `"Export."`, or empty for a flat default module's object.
fn fake_members(
    cx: *mut JsContext,
    object: JsValue,
    specifier: &str,
    prefix: &str,
    fakes: &[(String, ModuleFake)],
) -> crate::web::js::R<()> {
    use crate::web::js;
    let object = js::V::own(cx, object);
    // SAFETY: inline tag check.
    let is_object = unsafe { qjs::JS_IsObject(object.raw()) };
    for (path, fake) in fakes {
        let Some(member) = path.strip_prefix(prefix) else {
            continue;
        };
        // The default object takes stand-ins of its own members only: the
        // others are exports, faked with theirs.
        if prefix.is_empty() && (member.contains('.') || !is_object) {
            continue;
        }
        if member.is_empty() || member.contains('.') {
            log::warn!(
                target: "js",
                "nsh/test: open's `modules` fakes an export or one of its members, not `{specifier}`'s `{path}`"
            );
            continue;
        }
        let real = if is_object {
            js::get(cx, object.raw(), member)?
        } else {
            js::V::undefined()
        };
        if js::is_undefined(real.raw()) {
            if !prefix.is_empty() {
                log::warn!(
                    target: "js",
                    "nsh/test: `{specifier}`'s `{path}` is no member for open's `modules` to fake"
                );
            }
            continue;
        }
        let fake = crate::host_channel::stand_in(cx, real.raw(), fake)?;
        js::define(cx, object.raw(), member, fake, true)?;
    }
    Ok(())
}

/// Warns of the stand-ins of `fakes` that name no export of module
/// `specifier` (whose exports are `names`): a test's typo.
fn warn_unknown_fakes(specifier: &str, names: &[&str], fakes: &[(String, ModuleFake)]) {
    for (path, _) in fakes {
        let export = path.split_once('.').map_or(path.as_str(), |(e, _)| e);
        if !names.contains(&export) {
            log::warn!(
                target: "js",
                "nsh/test: `{specifier}` has no export `{export}` for open's `modules` to fake"
            );
        }
    }
}

/// The value of nsh's own export `export` (owned).
fn make_own(cx: *mut JsContext, export: &str, e: Export) -> JsValue {
    match e {
        Export::Function(f, length) => {
            let cname = CString::new(export).unwrap_or_default();
            reactive::new_function(cx, &cname, f, length)
        }
        Export::Value(make) => make(cx),
    }
}

/// The exports of the UI set the host registered under `specifier`, as one
/// object (`nativeModule`; owned): `None` when the host registered none,
/// an exception when making an export threw.
pub(crate) fn host_module(cx: *mut JsContext, specifier: &str) -> Option<JsValue> {
    // SAFETY: the state's table, by shared reference; it lives as long as
    // the context.
    let table = unsafe { &(*crate::state::state(cx)).modules };
    let exports = table.host_exports(specifier)?;
    let default_spec = exports.iter().find_map(|(_, made)| match made {
        Made::Default(spec) if spec.flat => Some(spec.clone()),
        _ => None,
    });
    let fakes = crate::host_channel::module_fakes(cx, specifier);
    if !fakes.is_empty() {
        let names: Vec<&str> = exports.iter().map(|(n, _)| n.as_str()).collect();
        warn_unknown_fakes(specifier, &names, &fakes);
    }
    // SAFETY: a new object taking each new value; freed when one throws.
    unsafe {
        let object = qjs::JS_NewObject(cx);
        for (export, made) in exports {
            let value = make(cx, table, specifier, default_spec.as_ref(), &export, made);
            let value = with_fakes(cx, specifier, &export, value, &fakes);
            if qjs::JS_IsException(value) {
                qjs::JS_FreeValue(cx, object);
                return Some(value);
            }
            let cname = CString::new(export.as_str()).unwrap_or_default();
            qjs::JS_SetPropertyStr(cx, object, cname.as_ptr(), value);
        }
        Some(object)
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn nshs_own_modules_are_the_ones_the_bundler_knows() {
        let names: Vec<&str> = super::MODULES
            .iter()
            .filter(|m| m.moved_to.is_none())
            .map(|m| m.name)
            .collect();
        assert_eq!(names, nsh_core::js::NATIVE_MODULES);
    }

    /// `Image` carries its functions; the sources the primitives come from
    /// are no modules apps import (bundles never import them: the bundler
    /// refuses them).
    #[test]
    fn nsh_serves_the_primitives() {
        let source = r#"
            import * as nsh from "nsh";
            if (typeof nsh.Image.getSize !== "function" || typeof nsh.Image.prefetch !== "function") {
                throw Error("Image carries its functions");
            }
            if (!(new nsh.Path2D("M0 0 L1 1") instanceof nsh.Path2D)) throw Error("Path2D");
        "#;
        crate::Host::new().unwrap().eval_source(source).unwrap();
        for old in [
            "nsh/image",
            "nsh/list",
            "nsh/canvas",
            "nsh/webview",
            "nsh/video",
        ] {
            let source = format!("import * as old from \"{old}\";");
            assert!(
                crate::Host::new().unwrap().eval_source(&source).is_err(),
                "{old}"
            );
        }
    }

    /// The bytecode compiler, which knows a UI set by its description,
    /// links against the names a VM serving the set exports.
    #[test]
    fn a_described_set_exports_what_its_registry_does() {
        for registry in [nsh_base::registry(), crate::classes::tests::registry()] {
            let specifier = registry.specifier().unwrap();
            let served = super::ModuleTable::new(std::slice::from_ref(&registry));
            let compiled = super::ModuleTable::compiling(&[(&registry).into()]);
            let mut served: Vec<String> = served
                .exports(specifier)
                .unwrap()
                .into_iter()
                .map(|(name, _)| name)
                .collect();
            let mut compiled = compiled.export_names(specifier).unwrap();
            assert!(!served.is_empty(), "{specifier}");
            served.sort();
            compiled.sort();
            assert_eq!(compiled, served, "{specifier}");
        }
        let compiling = super::ModuleTable::compiling(&[]);
        assert!(compiling.export_names("nsh/base").is_none());
        assert!(compiling.export_names("nsh").is_some());
    }
}

#[cfg(test)]
mod loader_tests {
    use super::normalize_chunk;

    #[test]
    fn typed_os_uses_one_object_in_source_bytecode_and_generated_types() {
        let source = r#"
            import os, {EOL,platform,arch,homedir} from 'os';
            import {Buffer} from 'buffer';
            import {Text} from 'nsh';
            if (Object.keys(os).sort().join(',') !== 'EOL,arch,homedir,platform') throw Error('shape');
            if (os.platform !== platform || os.arch !== arch || os.homedir !== homedir || os.EOL !== EOL) throw Error('identity');
            if (typeof platform() !== 'string' || typeof arch() !== 'string') throw Error('sync result');
            if (Buffer.from('os').toString() !== 'os' || typeof Text !== 'function') throw Error('mixed provider');
        "#;
        crate::Host::new().unwrap().eval_source(source).unwrap();
        let bytecode = crate::compile_bytecode(source, false).unwrap();
        crate::Host::new()
            .unwrap()
            .eval_bytecode(&bytecode)
            .unwrap();
        let declarations = crate::type_definitions(&[]);
        let (_, generated) = declarations
            .iter()
            .find(|(path, _)| path == "os.d.ts")
            .expect("registry declaration file");
        assert!(generated.contains("export declare function platform(): string;"));
        assert!(generated.contains("export declare const EOL: string;"));
        assert!(generated.contains("export default defaultExport;"));
        assert!(generated.contains("readonly EOL: string;"));
    }

    #[test]
    fn relative_chunks_keep_quickjs_default_resolution() {
        assert_eq!(normalize_chunk("bundle.js", "./chunk.js"), "chunk.js");
        assert_eq!(normalize_chunk("a/b/main.js", "../chunk.js"), "a/chunk.js");
        assert_eq!(
            normalize_chunk("a/main.js", "../../chunk.js"),
            "../chunk.js"
        );
        assert_eq!(normalize_chunk("a/main.js", "nsh/device"), "nsh/device");
        assert_eq!(
            normalize_chunk("a/main.js", "./x/../chunk.js"),
            "a/x/../chunk.js"
        );
    }
}