nativeview-codegen 0.1.0-rc.1

Multi-language ABI, policy, flat-op codec, and hybrid Direct-FFI code generator for Native View Engine.
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
mod common;

use common::specs::{assert_balanced_delimiters, counter_card_hybrid_spec};
use nativeview_codegen::{
    export_all_targets, export_compose, export_flutter, export_nitro_ui, export_rn, export_swiftui,
    export_target, export_web_component, parse_hybrid_rust_spec, ExportTarget,
};

#[test]
fn multi_target_export_emits_valid_wrappers_for_all_six_frameworks() {
    let file = counter_card_hybrid_spec();
    let view = &file.views[0];

    // 1. Flutter
    let fl = export_flutter(&file, view).expect("export_flutter");
    assert_eq!(fl.dart_widget.relative_path, "nv_counter_card.generated.dart");
    let dart_s = &fl.dart_widget.content;
    assert!(dart_s.contains("import 'dart:ffi' as ffi;"));
    assert!(dart_s.contains("import 'package:nativeview_flutter/nativeview_flutter.dart';"));
    assert!(dart_s.contains("enum CounterVariant {"));
    assert!(dart_s.contains("class CounterBadge {"));
    assert!(dart_s.contains("class NvCounterCard extends StatefulWidget"));
    assert!(dart_s.contains("static const String vtableSymbol = 'nv_get_interface_counter_card';"));
    assert!(dart_s.contains("_canvas?.sendCommand('set_count'"));
    assert_balanced_delimiters("nv_counter_card.generated.dart", dart_s);

    // 2. SwiftUI (matches live NvSurfaceRepresentable: zero stale `backend:` arg)
    let sw = export_swiftui(&file, view).expect("export_swiftui");
    assert_eq!(sw.swift_view.relative_path, "NvCounterCardView.generated.swift");
    let swift = &sw.swift_view.content;
    assert!(swift.contains("import SwiftUI"));
    assert!(swift.contains("import NativeViewSwiftUI"));
    assert!(swift.contains("public enum CounterVariant: UInt32"));
    assert!(swift.contains("public struct CounterBadge: NvDirectEncodable, Sendable, Equatable"));
    assert!(swift.contains("public struct NvCounterCardDirectProps: NvDirectEncodable, Equatable, Sendable"));
    assert!(swift.contains("public struct NvCounterCardView: View"));
    assert!(swift.contains("NvSurfaceRepresentable("));
    assert!(!swift.contains("backend:"));
    assert!(swift.contains("vtableSymbol: \"nv_get_interface_counter_card\""));
    assert_balanced_delimiters("NvCounterCardView.generated.swift", swift);

    // 3. Jetpack Compose
    let cmp = export_compose(&file, view).expect("export_compose");
    assert_eq!(cmp.compose_kt.relative_path, "NvCounterCardComposable.generated.kt");
    let compose = &cmp.compose_kt.content;
    assert!(compose.contains("package io.github.nativeview.components"));
    assert!(compose.contains("enum class CounterVariant(val rawValue: Int)"));
    assert!(compose.contains("data class CounterBadge("));
    assert!(compose.contains("object NvCounterCardDirectPropsWriter"));
    assert!(compose.contains("class NvCounterCardController"));
    assert!(compose.contains("@Composable\nfun NvCounterCard("));
    assert!(compose.contains("NvSurface("));
    assert_balanced_delimiters("NvCounterCardComposable.generated.kt", compose);

    // 4. Web Component (Light DOM, ZERO attachShadow, + React TSX!)
    let web = export_web_component(&file, view).expect("export_web_component");
    assert_eq!(web.tag_name, "nv-counter-card");
    assert_eq!(web.element_js.relative_path, "nv-counter-card.generated.js");
    assert_eq!(web.types_dts.relative_path, "nv-counter-card.generated.d.ts");
    assert_eq!(web.react_tsx.relative_path, "NvCounterCard.generated.tsx");
    assert_eq!(web.files().len(), 3);
    assert!(
        !web.element_js.content.contains("attachShadow"),
        "web component must mount in Light DOM so WebBackend's document stylesheet cascade applies"
    );
    assert!(web.element_js.content.contains("this.appendChild(this._mountRoot)"));
    assert!(web.element_js.content.contains("BinWriter"));
    assert!(web.element_js.content.contains("BinReader"));
    assert!(web.element_js.content.contains("'pair-url'"));
    assert!(web.types_dts.content.contains("export type CounterVariant = 0 | 1 | 2;"));
    assert!(web.types_dts.content.contains("export interface CounterBadge {"));
    assert!(web.react_tsx.content.contains("React.forwardRef<NvCounterCardHandle, NvCounterCardReactProps>"));
    assert!(web.react_tsx.content.contains("React.createElement('nv-counter-card'"));
    assert_balanced_delimiters("nv-counter-card.generated.js", &web.element_js.content);
    assert_balanced_delimiters("nv-counter-card.generated.d.ts", &web.types_dts.content);
    assert_balanced_delimiters("NvCounterCard.generated.tsx", &web.react_tsx.content);

    // 5. Nitro UI (`margelo/nitro-ui` 0.3.0 bare module)
    let nitro = export_nitro_ui(&file, view).expect("export_nitro_ui");
    assert_eq!(nitro.files().len(), 5);
    assert_eq!(nitro.nitro_spec_ts.relative_path, "src/specs/NativeNvCounterCard.nitro.ts");
    assert_eq!(nitro.view_ts.relative_path, "src/NvCounterCard.ts");
    assert_eq!(nitro.ios_hybrid_swift.relative_path, "ios/HybridNativeNvCounterCard.swift");
    assert_eq!(
        nitro.android_hybrid_kt.relative_path,
        "android/src/main/java/com/margelo/nitro/io/github/nativeview/components/HybridNativeNvCounterCard.kt"
    );
    assert_eq!(nitro.nitro_json.relative_path, "nitro.json");

    let nspec = &nitro.nitro_spec_ts.content;
    assert!(nspec.contains("import { Android, iOS } from 'nitro-core';"));
    assert!(nspec.contains("import type { View } from 'nitro-ui-renderer/hybrids';"));
    assert!(nspec.contains("export * from '#nitro/NativeNvCounterCard';"));
    assert!(nspec.contains("export enum CounterVariant {"));
    assert!(nspec.contains("export interface CounterBadge {"));
    assert!(nspec.contains("export declare class NativeNvCounterCard extends View"));
    assert!(nspec.contains("pairUrl: string | undefined;"));

    let nview = &nitro.view_ts.content;
    assert!(nview.contains("import { registerView, viewPropsSetters, type SharedViewProps } from 'nitro-ui-renderer';"));
    assert!(nview.contains("declare module 'nitro-ui-renderer'"));
    assert!(nview.contains("export const NvCounterCard = registerView('NvCounterCard', () => new NativeNvCounterCard()"));
    assert!(!nview.contains("| undefined | undefined"), "optional props must not duplicate `| undefined`");
    assert!(!nview.contains("export { NativeNvCounterCard }"), "index.ts re-exports Native* from .nitro.ts; avoid TS2308");

    let nswift = &nitro.ios_hybrid_swift.content;
    assert!(nswift.contains("final class HybridNativeNvCounterCard: HybridNativeNvCounterCardSpec"));
    assert!(nswift.contains("typealias AllowedChildrenType = Never"));
    assert!(nswift.contains("let view: UIView"));
    assert!(nswift.contains("let layoutNode = LayoutNode()"));
    assert!(nswift.contains("weak var parentReference: (any HybridViewSpec)?"));
    assert!(nswift.contains("func dispose() {"));
    assert!(nswift.contains("var gestureRecognizers: [any HybridGestureRecognizerSpec] = []"));
    assert!(nswift.contains("internal import NitroLayout"));
    assert!(nswift.contains("internal import NitroUIRenderer"));
    assert!(nswift.contains("internal import NativeViewAppleHost"));
    assert!(nswift.contains("override init() throws"));
    assert!(nswift.contains("try super.init()"));
    assert!(nswift.contains("NLMarkDirty(self.layoutNode.ref)"));
    assert!(!nswift.contains("layoutNode.markDirty()"));
    assert!(nswift.contains("(any Callback<"));
    assert!(nswift.contains(".callAndForget("));
    assert!(nswift.contains("attachNvInterface(nv_export_interface_nv_counter_card(), surfaceId: surface.nvSurfaceId)"));
    assert!(nswift.contains("applyNvPropsBytes(Data(propsWriter.bytes))"));
    assert!(nswift.contains("onNvEventBytes = { [weak self] eventName, payloadBytes in"));
    assert!(nswift.contains("dispatchNvCustomEvent(\"set_count\", payloadBytes: Data(propsWriter.bytes))"));
    assert!(nswift.contains("measureNvSurface(withMaxWidth: maxWidth, maxHeight: maxHeight)"));
    assert!(nswift.contains("teardownNvSession()"));
    assert!(!nswift.contains("NV_WITH_RN_FABRIC"));

    let nkt = &nitro.android_hybrid_kt.content;
    assert!(nkt.contains("package com.margelo.nitro.io.github.nativeview.components"));
    assert!(nkt.contains("import com.margelo.nitro.renderer.AndroidHost"));
    assert!(!nkt.contains("import com.margelo.nitro.ui."));
    assert!(nkt.contains("import com.margelo.nitro.core.Callback"));
    assert!(nkt.contains("import com.margelo.nitro.core.callAndForget"));
    assert!(nkt.contains("class HybridNativeNvCounterCard private constructor("));
    assert!(nkt.contains("override val nativeState: ViewState"));
    assert!(nkt.contains("ViewOperations by nativeState"));
    assert!(nkt.contains("nativeState.bind(this)"));
    assert!(nkt.contains("nativeState.layoutNode.markDirty()"));
    assert!(nkt.contains("CounterVariant.SOLID"));
    assert!(nkt.contains("Callback<(payload: "));
    assert!(nkt.contains(".callAndForget("));
    assert!(nkt.contains("NvAndroidViewSurface(AndroidHost.context)"));
    assert!(nkt.contains("surfaceView.attachAppSymbol(_libPath, VTABLE_SYMBOL, false)"));
    assert!(nkt.contains("surfaceView.dispatchCustomEvent(\"set_count\""));
    assert!(nkt.contains("surfaceView.setPropsBytes("));
    assert!(nkt.contains("surfaceView.setOnEmittedEvent"));
    assert!(nkt.contains("surfaceView.destroy()"));
    assert!(nkt.contains("super.dispose()"));

    let njson = &nitro.nitro_json.content;
    assert!(njson.contains("\"environment\": \"bare\""));
    assert!(njson.contains("\"cxxNamespace\""));
    assert!(njson.contains("\"moduleName\": \"NvComponents\""));
    assert!(njson.contains("\"cxxLibName\": \"NvComponents\""));
    assert!(!njson.contains("\"autolinking\""), "Nitrogen v1 rejects legacy nitro.json autolinking key");
    for f in nitro.files() {
        assert_balanced_delimiters(&f.relative_path, &f.content);
    }

    // 6. Unified `export_all_targets` + ExportTarget::from_name
    assert_eq!(ExportTarget::from_name("nitro-ui").unwrap(), ExportTarget::NitroUi);
    assert_eq!(ExportTarget::from_name("rn").unwrap(), ExportTarget::ReactNative);
    assert_eq!(ExportTarget::from_name("web").unwrap(), ExportTarget::WebComponent);
    assert!(ExportTarget::from_name("unknown").is_err());

    let bundles = export_all_targets(&file, ExportTarget::ALL).expect("export_all_targets");
    assert_eq!(bundles.len(), 6);
    for bundle in &bundles {
        assert!(!bundle.files.is_empty());
        for f in &bundle.files {
            assert!(
                !f.content.contains("serde_json"),
                "{} must not reference serde_json",
                f.relative_path
            );
        }
    }
}

#[test]
fn multi_view_spec_generates_collision_free_symbols_and_merges_nitro_json() {
    let multi = parse_hybrid_rust_spec(
        r#"
#[nativeview_hybrid_spec(namespace = "com.acme.widgets")]
pub mod widgets {
    #[nv_hybrid_view(name = "SparkChart")]
    pub trait SparkChartSpec {
        #[prop]
        fn points(&self) -> Vec<f64>;
    }

    #[nv_hybrid_view(name = "MetricTile")]
    pub trait MetricTileSpec {
        #[prop(default = "")]
        fn label(&self) -> String;
    }
}
"#,
    )
    .expect("parse multi-view spec");

    assert_eq!(multi.views[0].vtable_symbol(&multi), "nv_get_interface_spark_chart");
    assert_eq!(multi.views[1].vtable_symbol(&multi), "nv_get_interface_metric_tile");

    let nitro_bundle = export_target(&multi, ExportTarget::NitroUi).expect("multi nitro export");
    let json_files: Vec<_> = nitro_bundle
        .files
        .iter()
        .filter(|f| f.relative_path == "nitro.json")
        .collect();
    assert_eq!(json_files.len(), 1, "multi-view nitro export emits one merged nitro.json");
    assert!(json_files[0].content.contains("\"environment\": \"bare\""));
    assert!(json_files[0].content.contains("\"moduleName\": \"NvWidgets\""));
    assert!(json_files[0].content.contains("\"cxxLibName\": \"NvWidgets\""));
    assert!(json_files[0].content.contains("\"namespace\": [\"com\", \"acme\", \"widgets\"]"));
    assert!(!json_files[0].content.contains("\"autolinking\""));

    let rn_bundle = export_target(&multi, ExportTarget::ReactNative).expect("multi rn export");
    assert_eq!(
        rn_bundle.files.len(),
        9,
        "4 per-view files * 2 views + 1 combined ReactPackage"
    );
    let combined_pkg = rn_bundle
        .files
        .iter()
        .find(|f| f.relative_path == "WidgetsReactPackage.generated.kt")
        .expect("combined WidgetsReactPackage.generated.kt for multi-view RN spec");
    assert!(combined_pkg.content.contains("SparkChartViewManager()"));
    assert!(combined_pkg.content.contains("MetricTileViewManager()"));
    assert!(
        !rn_bundle
            .files
            .iter()
            .any(|f| f.relative_path == "SparkChartReactPackage.generated.kt"),
        "multi-view RN export must emit one combined ReactPackage instead of per-view packages"
    );

    // Spec with zero views is refused cleanly
    let module_only = parse_hybrid_rust_spec(
        r#"
#[nativeview_hybrid_spec]
pub mod mods {
    #[nv_hybrid_module(name = "OnlyMod")]
    pub trait OnlyModSpec {
        fn ping(&self) -> bool;
    }
}
"#,
    )
    .expect("parse module-only spec");
    assert!(export_target(&module_only, ExportTarget::ReactNative).is_err());

    // Non-conforming symbols (outside `nv_get_interface` / `nv_get_interface_*`) are refused
    assert!(parse_hybrid_rust_spec(
        r#"
#[nativeview_hybrid_spec]
pub mod bad_sym {
    #[nv_hybrid_view(name = "ViewA", symbol = "custom_vtable")]
    pub trait ViewASpec {}
}
"#,
    )
    .is_err());

    // Duplicate explicit symbols across views are refused by validation
    let dup_sym = parse_hybrid_rust_spec(
        r#"
#[nativeview_hybrid_spec]
pub mod dup {
    #[nv_hybrid_view(name = "ViewA", symbol = "nv_get_interface_same")]
    pub trait ViewASpec {}
    #[nv_hybrid_view(name = "ViewB", symbol = "nv_get_interface_same")]
    pub trait ViewBSpec {}
}
"#,
    );
    assert!(dup_sym.is_err());

    // Single view without explicit symbol defaults to `nv_get_interface`
    let single = parse_hybrid_rust_spec(
        r#"
#[nativeview_hybrid_spec]
pub mod single {
    #[nv_hybrid_view(name = "EmptyCanvas")]
    pub trait EmptyCanvasSpec {}
}
"#,
    )
    .expect("parse single view");
    assert_eq!(single.views[0].vtable_symbol(&single), "nv_get_interface");
    let rn_empty = export_rn(&single, &single.views[0]).expect("rn empty");
    assert!(
        rn_empty
            .ios_component_view_mm
            .content
            .contains("dlopen(\"@rpath/NvEmptyCanvasCore.framework/NvEmptyCanvasCore\", RTLD_NOW | RTLD_LOCAL)")
    );
    assert!(
        rn_empty
            .ios_component_view_mm
            .content
            .contains("dlsym(handle, \"nv_get_interface\")")
    );
    assert!(
        rn_empty
            .ios_component_view_mm
            .content
            .contains("return nvResolveEmptyCanvasInterface();")
    );
}

#[test]
fn android_package_preserves_underscores_and_escapes_kotlin_keywords() {
    let spec = parse_hybrid_rust_spec(
        r#"
#[nativeview_hybrid_spec(namespace = "dev.in.embed_card")]
pub mod embed_card_spec {
    #[nv_hybrid_view(name = "EmbedCard")]
    pub trait EmbedCardSpec {
        #[prop(default = 0)]
        fn count(&self) -> i32;
        #[event]
        fn on_increment(&self, new_count: i32);
    }
}
"#,
    )
    .expect("parse snake_case namespace spec");

    let rn = export_rn(&spec, &spec.views[0]).expect("export_rn");
    assert!(
        rn.android_view_manager_kt.content.contains("package dev.`in`.embed_card\n"),
        "expected underscores preserved and keyword escaped, got:\n{}",
        &rn.android_view_manager_kt.content[..200]
    );
    assert!(rn.android_react_package_kt.content.contains("package dev.`in`.embed_card\n"));
    assert!(
        rn.android_react_package_kt.content.contains(": BaseReactPackage()"),
        "RN ReactPackage should extend BaseReactPackage for RN 0.88+ Kotlin warning-free compilation"
    );
    assert!(
        !rn.android_view_manager_kt.content.contains("MapBuilder"),
        "RN Fabric ViewManager should avoid deprecated MapBuilder"
    );
    assert!(
        rn.android_view_manager_kt.content.contains("UIManagerHelper.getEventDispatcher(_reactContext)"),
        "RN Fabric ViewManager should use non-deprecated UIManagerHelper.getEventDispatcher"
    );
    assert!(
        !rn.android_view_manager_kt.content.contains("getEventDispatcherForReactTag"),
        "RN Fabric ViewManager should not use deprecated getEventDispatcherForReactTag"
    );
    assert!(
        !rn.native_component_ts.content.contains("react-native/Libraries/"),
        "RN 0.87+ strict TS spec must import CodegenTypes/codegenNativeComponent/codegenNativeCommands from 'react-native'"
    );
    assert!(rn.native_component_ts.content.contains("CodegenTypes.WithDefault<"));
    assert!(rn.native_component_ts.content.contains("CodegenTypes.DirectEventHandler<"));

    let nitro = export_nitro_ui(&spec, &spec.views[0]).expect("export_nitro_ui");
    assert!(
        nitro
            .android_hybrid_kt
            .content
            .contains("package com.margelo.nitro.dev.`in`.embed_card\n"),
        "expected NitroUI package prefix with preserved underscores and escaped keyword, got:\n{}",
        &nitro.android_hybrid_kt.content[..220]
    );
    assert_eq!(
        nitro.android_hybrid_kt.relative_path,
        "android/src/main/java/com/margelo/nitro/dev/in/embed_card/HybridNativeEmbedCard.kt"
    );

    let compose = export_compose(&spec, &spec.views[0]).expect("export_compose");
    assert!(compose.compose_kt.content.contains("package dev.`in`.embed_card\n"));
}

#[test]
fn nitro_ui_escapes_keyword_event_params_and_struct_fields_without_double_prefix() {
    let spec = parse_hybrid_rust_spec(
        r#"
#[nativeview_hybrid_spec(namespace = "io.github.nativeview.widgets")]
pub mod nativeview_widgets {
    #[nv_hybrid_struct]
    pub struct KeywordPayload {
        pub var: i32,
        pub default: String,
        pub class: bool,
    }

    #[nv_hybrid_view(name = "NvDemoCard")]
    pub trait NvDemoCardSpec {
        #[prop(default = 0)]
        fn count(&self) -> i32;

        #[event]
        fn on_select(&self, var: i32, default: String, class: KeywordPayload);
    }
}
"#,
    )
    .expect("parse keyword spec");

    let nitro = export_nitro_ui(&spec, &spec.views[0]).expect("export_nitro_ui");
    let swift = &nitro.ios_hybrid_swift.content;
    assert!(!swift.contains("_f_`"), "Swift local names must never embed backticks:\n{swift}");
    assert!(swift.contains("var _f_var:"));
    assert!(swift.contains("var _f_default:"));
    assert!(swift.contains("var _f_class:"));
    assert!(swift.contains("`var`: _f_var"));
    assert!(swift.contains("`default`: _f_default"));
    assert!(swift.contains("`class`: _f_class"));
    assert!(swift.contains("weak var parentReference: (any HybridViewSpec)?"));
    assert!(swift.contains("func dispose() {"));

    let kt = &nitro.android_hybrid_kt.content;
    assert!(!kt.contains("_f_`"), "Kotlin local names must never embed backticks:\n{kt}");
    assert!(kt.contains("var _f_var:"));
    assert!(kt.contains("var _f_default:"));
    assert!(kt.contains("var _f_class:"));
    assert!(kt.contains("`var` = _f_var"));
    assert!(kt.contains("`class` = _f_class"));

    let json = &nitro.nitro_json.content;
    assert!(
        json.contains("\"moduleName\": \"NvWidgets\""),
        "must not double-prefix NvNvWidgets:\n{json}"
    );
    assert!(!json.contains("NvNv"));
}