Skip to main content

nsh_core/js/
mod.rs

1//! What the JS side is decoded with and typed from, so the two cannot
2//! drift apart: the animation graph's codes ([`protocol`]), the canvas
3//! operations and their decoding ([`canvas`], with [`ops`]'
4//! `#[derive(JsOps)]`), the style types ([`style`]), the host elements'
5//! props ([`host`]: their decoding and types, from `#[derive(HostProps)]`
6//! on [`crate::Prop`]) and the easings and layout animations ([`animation`]).
7//! The decoders in `nsh-js` match on the same constants and call the
8//! derived decoders, and their declarations go into the ones apps are
9//! checked against (`nsh-js` `declarations.rs`).
10
11use std::time::Duration;
12
13/// nsh's own native ES modules, which bundles compiled with nsh's JSX
14/// compiler import (served by `nsh-js`, left as imports by the bundler):
15/// `nsh`, the API apps write against; `nsh:rt`, the renderer compiled JSX
16/// calls; `nsh/device` and `nsh/accessibility`, the environment; the
17/// platforms' and host elements' modules. Registries add theirs
18/// (`Registry::specifier`: `nsh/ui/mobile`, ...) or the functions of
19/// nsh's own (`nsh/image`, `nsh/android`).
20pub const NATIVE_MODULES: &[&str] = &[
21    "nsh",
22    "nsh:rt",
23    "nsh/device",
24    "nsh/accessibility",
25    "nsh/android",
26    "nsh/ios",
27    "nsh/desktop",
28    "nsh/webview",
29    "nsh/video",
30    "nsh/native",
31    "nsh/gesture",
32    "nsh/animated",
33    "nsh/canvas",
34    "nsh/list",
35    "nsh/image",
36    "nsh/keymap",
37];
38
39/// The module name of an app's bundle (its entry chunk): stack traces show
40/// `bundle.js:LINE:COL`, and the chunks of a split bundle import it as
41/// `./bundle.js`.
42pub const ENTRY_CHUNK: &str = "bundle.js";
43
44/// The global function a split bundle's dynamic imports call (the bundler
45/// rewrites `import("./Screen.js")` into `__nsh_import("Screen.js",
46/// ["shared.js"])`): it makes the chunk and the chunks it imports
47/// statically available (on the web, fetched), then imports the first.
48pub const IMPORT_CHUNK: &str = "__nsh_import";
49
50/// Resource limits of one VM.
51#[derive(Debug, Clone, Copy, PartialEq)]
52pub struct Limits {
53    /// QuickJS heap, in bytes (0: no limit). Running out stops the VM.
54    pub memory_bytes: usize,
55    /// Interpreter stack, in bytes: deep recursion becomes a `RangeError`
56    /// rather than a native stack overflow. Must stay below the engine
57    /// thread's stack.
58    pub stack_bytes: usize,
59    /// Evaluating the bundle.
60    pub load_budget: Duration,
61    /// Any other call into JS: one event (with the rendering it causes), one
62    /// list bind, one timer, one frame's callbacks, the microtask drain.
63    pub call_budget: Duration,
64    /// Changes JS may make at once (the op queue's length): they are held in
65    /// Rust memory, which the heap limit does not cover.
66    pub max_op_values: usize,
67    /// Operations one canvas drawing may record.
68    pub max_canvas_ops: usize,
69    /// Nodes the core keeps (each may have a native view, whose memory the
70    /// heap limit does not cover either).
71    pub max_nodes: usize,
72}
73
74impl Limits {
75    /// The limits of an app nsh runs on its own on a desktop (the macOS,
76    /// Windows and Linux hosts and runners): a 1 GB heap, as a desktop app
77    /// may hold much more data than a module embedded in a host app.
78    pub fn standalone_desktop() -> Self {
79        Self {
80            memory_bytes: 1 << 30,
81            ..Self::default()
82        }
83    }
84
85    /// The limits of an app nsh runs on its own on a phone or tablet (the
86    /// iOS and Android hosts and runners): a 512 MB heap, well below where
87    /// the systems end apps for their memory.
88    pub fn standalone_mobile() -> Self {
89        Self {
90            memory_bytes: 512 << 20,
91            ..Self::default()
92        }
93    }
94}
95
96/// The limits of an app embedded in a host app (`NshAppView`, `NshView`,
97/// `AppView`): a 256 MB heap; the embedder may set others.
98impl Default for Limits {
99    fn default() -> Self {
100        Self {
101            memory_bytes: 256 << 20,
102            stack_bytes: 4 << 20,
103            load_budget: Duration::from_secs(10),
104            call_budget: Duration::from_secs(2),
105            max_op_values: 8_000_000,
106            max_canvas_ops: 1_000_000,
107            max_nodes: 200_000,
108        }
109    }
110}
111
112/// Constants of encoded operations and a table of them for the generators.
113macro_rules! codes {
114    ($table:ident: $($(#[doc = $doc:literal])* $name:ident = $value:literal),* $(,)?) => {
115        $(
116            #[doc = concat!("`", stringify!($name), "`.")]
117            $(#[doc = $doc])*
118            pub const $name: i32 = $value;
119        )*
120
121        /// The codes by name, with their documentation (the operands).
122        pub const $table: &[(&str, i32, &str)] = &[$((stringify!($name), $value, concat!($($doc),*))),*];
123    };
124}
125
126pub mod animation;
127pub mod canvas;
128pub mod host;
129pub(crate) mod host_values;
130pub mod ops;
131pub mod protocol;
132pub mod style;
133
134#[cfg(test)]
135mod tests {
136    #[test]
137    fn the_declarations_match_the_tables() {
138        let canvas = super::canvas::declarations();
139        assert!(
140            canvas.contains("  moveTo(x: CanvasNumber, y: CanvasNumber): void;"),
141            "{canvas}"
142        );
143        assert!(canvas.contains("counterclockwise?: boolean): void;"));
144        assert!(canvas.contains("  lineCap: LineCap;"));
145        assert!(canvas.contains("export type LineCap = \"butt\" | \"round\" | \"square\";"));
146        let style = super::style::declarations();
147        // Every property the core parses has a type, in its interface.
148        for (name, ts) in [
149            ("boxShadow", "string"),
150            ("gridTemplateColumns", "string"),
151            ("transform", "TransformStep[]"),
152            ("tintColor", "ColorValue"),
153            ("display", "\"flex\" | \"grid\" | \"block\" | \"none\""),
154        ] {
155            assert!(style.contains(&format!("  {name}?: {ts};")), "{name}");
156        }
157        let text = style.find("export interface TextStyle").unwrap();
158        assert!(style[text..].contains("  textDecorationStyle?:"));
159        // Each host prop and event in the interface of the elements it is for.
160        let elements = super::host::declarations();
161        for (interface, prop) in [
162            ("HostProps", "  pointerEvents?: PointerEvents;"),
163            ("HostProps", "  onPress?: () => void;"),
164            ("HostProps", "  onLayout?: (e: LayoutEvent) => void;"),
165            ("AndroidHostProps", "  elevation?: number;"),
166            ("InputHostProps", "  keyboardType?: KeyboardType;"),
167            ("InputHostProps", "  onChangeText?: (text: string) => void;"),
168            ("IOSInputHostProps", "  inputAccessoryViewID?: string;"),
169            (
170                "IOSInputHostProps",
171                "  keyboardAppearance?: KeyboardAppearance;",
172            ),
173            ("TextHostProps", "  selectionColor?: ColorValue;"),
174            ("InputHostProps", "  selectionColor?: ColorValue;"),
175            (
176                "ImageHostProps",
177                "  onLoad?: (e: { width: number; height: number }) => void;",
178            ),
179            (
180                "VideoHostProps",
181                "  onLoad?: (e: { duration: number; width: number; height: number }) => void;",
182            ),
183            (
184                "ScrollingHostProps",
185                "  decelerationRate?: \"normal\" | \"fast\" | number;",
186            ),
187            (
188                "ScrollingHostProps",
189                "  onScroll?: (e: ScrollEvent) => void;",
190            ),
191            (
192                "ListHostProps",
193                "  contentContainerStyle?: ListContentStyle;",
194            ),
195            (
196                "IOSModalHostProps",
197                "  presentationStyle?: ModalPresentation;",
198            ),
199            (
200                "DesktopModalHostProps",
201                "  presentationStyle?: ModalPresentation;",
202            ),
203            (
204                "WebModalHostProps",
205                "  presentationStyle?: ModalPresentation;",
206            ),
207            ("DesktopScreenHostProps", "  headerBackTitle?: string;"),
208            (
209                "DesktopWebViewHostProps",
210                "  allowsBackForwardNavigationGestures?: boolean;",
211            ),
212            ("ModalHostProps", "  onRequestClose?: () => void;"),
213        ] {
214            let at = elements
215                .find(&format!("export interface {interface} {{"))
216                .unwrap_or_else(|| panic!("{interface}"));
217            let end = at + elements[at..].find("\n}").unwrap();
218            assert!(elements[at..end].contains(prop), "{interface}: {prop}");
219        }
220        assert!(elements.contains(
221            "export type KeyboardType = \"default\" | \"number-pad\" | \"decimal-pad\" | \"numeric\" | \"numbers-and-punctuation\""
222        ));
223        assert!(
224            elements
225                .contains("export type KeyboardAppearance = \"default\" | \"light\" | \"dark\";")
226        );
227        let animation = super::animation::declarations();
228        assert!(animation.contains("  back(s?: number): EasingCurve;"));
229        assert!(
230            animation.contains("export type LayoutAnimationType = \"easeInEaseOut\" | \"spring\"")
231        );
232        assert!(animation.contains("  readonly scaleXY: \"scaleXY\";"));
233        // What the runtime sets itself is not part of the types.
234        for internal in ["splice?", "cellIndex?", "tailwindTheme?", "headerSlot?"] {
235            assert!(!elements.contains(internal), "{internal}");
236        }
237    }
238
239    #[test]
240    fn every_event_is_typed_or_internal() {
241        use super::host::{EVENTS, INTERNAL_EVENTS};
242        for kind in crate::EventKind::ALL {
243            let typed = EVENTS.iter().any(|e| e.0 == *kind);
244            let internal = INTERNAL_EVENTS.contains(kind);
245            assert!(
246                typed != internal,
247                "{}: give it a handler type in `EVENTS` or list it in `INTERNAL_EVENTS`",
248                kind.prop_name()
249            );
250        }
251    }
252}