Repository navigation
RFC: ns proguard and --optimize-native — TypeScript-aware R8 keep rules for NativeScript Android
#64
NathanWalker
started this conversation in
1. Ideas & Discussions
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
RFC:
ns proguardand--optimize-native— TypeScript-aware R8 keep rules for NativeScript AndroidnativescriptCLI,@nativescript/vite(with Webpack/Rspack bundle fallback),@nativescript/androidnative-api-usage.json),@nativescript/vitemodule graph, Static Binding Generator (SBG), andMetadataClosure/ProguardRulesWriterin NativeScript/runtimesns metadata trim), rfcs#58 (ns:nativemodule imports)Summary
Android's R8 compiler shrinks, optimizes, and obfuscates Java and Kotlin bytecode in release builds, but it cannot see native Android APIs accessed dynamically from JavaScript/TypeScript through the NativeScript runtime. Today, developers either leave R8 disabled (shipping larger binaries and triggering Google Play Console optimization warnings) or maintain
proguard-rules.proby trial and error.This RFC proposes a TypeScript- and bundler-aware R8 keep-rule generator exposed both as an integrated release build flag and as an inspectable CLI command:
@nativescript/core, installed plugins, lazy-loaded routes, workers, and secondary Android entrypoints while ignoring dead tree-shaken branches.proguard-android-optimize.txtwith narrow app-specificproguard-rules.prorules. It never generates a replacement for Android's standard R8 optimization configuration or library consumer rules (consumer-rules.pro); it generates only the rules needed to make JS-originated native interop visible to R8.android.jar) are not shrunk by R8 and are omitted unless subclassed or implemented. Third-party library, plugin, and app-owned native classes receive member-level rules (constructors, methods, fields) when usage is statically bounded, widening to class-level ({ *; }) only when instances escape or use dynamic property lookups.native-api-usage.json(app and plugins), plugin-suppliedproguard-rules.profiles, library AAR consumer rules,AndroidManifest.xml, Android XML resources, Static Binding Generator (com.tns.gen.**) bindings, and hand-written developer rules inApp_Resources/Android/proguard-rules.proall merge deterministically.eval, or unresolved classpath references emit conservative scoped fallbacks where possible and printfile:linediagnostics — or fail the build under--strict.--optimize-native(orandroid.optimizeNativeinnativescript.config.ts) automatesns build android --release, whilens proguardwrites auditable rules with source-provenance comments intoApp_Resources/Android/proguard-rules.profor version control and standalone Gradle builds.Motivation
Why NativeScript is different under R8
Consider ordinary NativeScript TypeScript code calling native Android APIs:
At runtime, NativeScript resolves these references through its Android metadata tree and JNI bridge. R8, however, operates purely on Java/Kotlin bytecode and resource files. Unless a Java class in the Static Binding Generator (
com.tns.gen.*) or a library's consumer keep rules happens to referenceandroidx.appcompat.app.AlertDialog$Builderdirectly, R8 sees zero bytecode callers:minifyReleaseWithR8and does not observe JS-originated references.TypeErrororNoSuchMethodErrorcrashes exclusively in--releasebuilds.Important
Framework classes vs. program classes: Android platform classes in
android.jar(such asandroid.content.Intentorandroid.view.View) sit on R8's library classpath (-libraryjars) and are never removed or renamed by an app's R8 pass. The real shrinking and obfuscation hazards involve program classes packaged into the app's DEX: third-party Android libraries (androidx.*,com.google.android.material.*, Maven SDKs), NativeScript plugin.aar/.jarcode, Kotlin file-facade (*Kt) and metadata classes, application-defined Java/Kotlin sources underApp_Resources/Android, SBG-generated bindings (com.tns.gen.**), and D8/R8 synthetic interface companions (**$-CC,**$$CC).Two configuration files, two distinct jobs
Android's official R8 optimization guidance and Google Play Vitals code optimization requirements favor Android's standard optimizing base configuration paired with narrowly targeted keep rules:
proguard-android-optimize.txtproguard-android.txt)getDefaultProguardFile(...).consumer-rules.pro(proguard.txt)com.tns.*runtime entrypointsApp_Resources/Android/proguard-rules.proPain points in NativeScript today
Today in
@nativescript/android,minifyEnabledis off by default inreleasebuilds. Developers who enable R8 inApp_Resources/Android/app.gradlehit three recurring problems:-keep class ** { *; }or-keep class androidx.** { *; }, neutralizing most of R8's DEX size, startup, and memory wins.@nativescript/vitealready resolves the exact ESM module graph during bundling, and@nativescript/android's metadata pipeline (collectAllJars,MDG,SBG) already inspects every JAR, AAR, and compiled class in the project. Yet neither informsproguard-rules.pro.Guide-level explanation
1. Zero-config optimized release builds (
--optimize-native)Pass
--optimize-nativetons build android --release(orns run android --release):During the build, the CLI:
@nativescript/core, plugins, lazy chunks, workers, and Android component entrypoints).AndroidManifest.xml, XML resources, SBG bindings, andnative-api-usage.json.platforms/android/app/build/nativescript/proguard-generated.pro.releasebuild type withminifyEnabled true,getDefaultProguardFile('proguard-android-optimize.txt'), the generated rules, plugin-suppliedproguard-rules.profiles, andApp_Resources/Android/proguard-rules.pro.To make
--optimize-nativethe default for every Android release build in a project, setandroid.optimizeNativeinnativescript.config.ts(use--no-optimize-nativeon the CLI to opt out for a single build):2. Generating and maintaining
proguard-rules.pro(ns proguard)Teams that build release artifacts in Android Studio, Fastlane, or standalone Gradle CI — or developers who want to review and commit their exact ProGuard configuration — can run
ns proguard:ns proguardruns the production bundler analysis, resolves rules against the Android classpath (preparingplatforms/androidif needed), and updates a clearly delimited managed block insideApp_Resources/Android/proguard-rules.prowhile leaving every developer-authored rule outside the markers untouched:If
App_Resources/Android/app.gradledoes not yet enable R8 for release builds,ns proguardprints (or with--write-gradle, adds) the standardbuildTypes.releaseconfiguration referencingproguard-android-optimize.txtandproguard-rules.pro.3. Auditing in CI (
ns proguard check) and inspecting (--dry-run)Running
ns proguard checkin pull-request CI ensures that when a developer imports a new plugin or calls a newandroidx.*or third-party SDK API from TypeScript,App_Resources/Android/proguard-rules.prostays in sync before release QA.4. Escape hatches: dynamic interop, plugins, and overrides
Static analysis cannot infer every native API used at runtime (for example,
java.lang.Class.forName(dynamicName), reflection inside a plugin helper, or dynamicglobalThis[pkg]lookups). Three layers cover those cases:App_Resources/Android/proguard-rules.pro. Anything written outside the# BEGIN NATIVESCRIPT GENERATED RULESblock is preserved verbatim and passed to R8.<plugin>/platforms/android/proguard-rules.pro. Plugins that wrap reflective or dynamically constructed Java/Kotlin calls can ship aproguard-rules.proalongsideinclude.gradleandnative-api-usage.json(in addition to standard AARconsumer-rules.pro). Bothns proguardand--optimize-nativemerge rules from installed production plugins automatically.native-api-usage.jsonandnativescript.config.tskeepentries. Existingwhitelist/usespatterns innative-api-usage.jsonandandroid.optimizeNative.keeppatterns are fed into the class/member resolver before rules are emitted.Relationship to Metadata Filtering and RFC #62 (
ns metadata trim)NativeScript Android has two distinct build artifacts that depend on knowing which native APIs JavaScript reaches:
assets/metadata/*.dat) — the lookup tables NativeScript's C++/JNI runtime uses to resolve Java packages, classes, and signatures from JS.classes*.dex) — the compiled Java/Kotlin classes shrunk and optimized by R8.RFC #62 (
ns metadata trim) and the experimental-PnsFilterMetadatapipeline inNativeScript/runtimesintroducedharvest.js,seed.js,MetadataClosure, and an internalProguardRulesWriter. This RFC builds directly on lessons from that work while addressing a different primary goal and developer workflow:native-api-usage.jsonns metadata trim(rfcs#62)ns proguard/--optimize-native(this RFC)assets/metadataacross iOS, macOS, Androidproguard-rules.pro& shrinking Android DEXandroid.jarSDK classesandroid.jar)pkg:Class)-keep class X { *; })<init>, methods, fields) when bounded; class-level fallbackproguard-android.txt+ global-dontobfuscateproguard-android-optimize.txt+ targeted-keepundefinedif missedfile:linewarning (or fails under--strict)whitelist.mdg/blacklist.mdgwhitelist.mdg+ internalmetadata-keep-rules.proApp_Resources/Android/proguard-rules.pro+--optimize-nativebuildWhen an Android build enables both metadata filtering and
--optimize-native, both pipelines share the same front-end usage analysis so that metadata and DEX remain strictly consistent without parsing the bundle twice. Conversely, apps that keep full SDK metadata (for example, to preserve full Android framework flexibility or OTA bundle compatibility forandroid.*APIs) can still use--optimize-nativeandns proguardto shrink heavy third-party Android dependencies with R8.Reference-level details
Architecture and pipeline
Stage 1: Bundler module-graph analysis
@nativescript/viteintegration (primary path)In Vite builds, a dedicated Rollup/Vite plugin hook runs during
moduleParsedandgenerateBundle:import()lazy chunks, worker bundles, and secondary Android entrypoints such as customApplication,Activity, orServicemodules) contribute references. Unreferenced plugin exports and iOS-only branches eliminated by__ANDROID__/__IOS__constant folding are excluded automatically.ns:nativecompatibility (rfcs#58): Static imports fromns:native/android/<package>map directly to resolved JVM package and class bindings with zero heuristic ambiguity, while global accesses (androidx.appcompat.app.AlertDialog,global.androidx...,globalThis.com...) are tracked through scope-aware AST binding analysis.const/let(const builder = new androidx.appcompat.app.AlertDialog.Builder(ctx)), the analyzer tracks member reads, calls (builder.setTitle(...)), chained fluent calls (new Builder(ctx).setTitle(...).show()), and whether the binding escapes (passed as an untyped argument to non-native JS functions, stored on an untyped object property, returned from a module export without narrowing, or accessed via computed bracketsbuilder[key]).Emitted bundle fallback (Webpack, Rspack, and external hosts)
When
bundleriswebpackorrspack, or whenns proguard --bundle <dir|file>is invoked against prebuilt JS bundles (such asnshor brownfield hosts), the analyzer runs the same AST pass (via Oxc/Babel parser + source-map lookup for original TypeScriptfile:linediagnostics) over all emitted.jsand.mjschunks in the target directory.Stage 2: Non-JS and plugin native inputs
JavaScript is not the only place dynamic class references originate in a NativeScript Android app. The merger collects:
AndroidManifest.xml(app and plugins): Every class named inandroid:nameon<application>,<activity>,<service>,<receiver>,<provider>, and<meta-data>entries.res/layout/**/*.xml,res/xml/**/*.xml,res/navigation/**/*.xml): Custom view tags (<com.airbnb.lottie.LottieAnimationView .../>),<fragment android:name="..."/>,<view class="..."/>, andapp:layout_behaviorattributes (thoughaapt2generates view keep rules for standard layouts, custom XML attributes and plugin resource merges are included explicitly for completeness).SBG) outputs: Classes extended via@NativeClass/.extend()and interfaces implemented vianew android.content.DialogInterface.OnClickListener({ ... })produce generated Java proxies undercom.tns.gen.**alongsidesbg-bindings.txtandsbg-interface-names.txt.<plugin>/platforms/android/proguard-rules.pro— included verbatim with# Added from <plugin>provenance headers.<plugin>/platforms/android/native-api-usage.json(uses) andApp_Resources/Android/native-api-usage.json(whitelist/blacklist).META-INF/proguard/*/proguard.txtconsumer rules — left to AGP's native consumer-rule merger rather than duplicated.Stage 3: Classpath and hierarchy resolution
Syntactic JS analysis alone cannot produce sound member-level ProGuard rules because Java/Kotlin bytecode dispatch involves inheritance, bridge methods, inner-class
$binary names, and Kotlin companion/file-facade classes.The resolver inspects the project's compiled classpath (
mdg-java-dependencies.txtJARs/exploded AARs +mdg-java-out.txtcompiled app Java/Kotlin classes) alongsideandroid.jar:android.jar(e.g.,android.content.Intent,java.util.ArrayList) and is not subclassed/implemented by JS, no-keeprule is emitted.androidx.appcompat.app.AlertDialog$Builder,com.google.android.material.snackbar.Snackbar,com.mycompany.CustomHelper), it enters rule synthesis.androidx.appcompat.app.AlertDialog.Builderlooks identical syntactically to package traversal. Against the bytecode repository,AlertDialogis identified as a class andBuilderas its nested classandroidx.appcompat.app.AlertDialog$Builder(plus outer/inner attributes).widget.setSomething(arg)on a program subclassSubwheresetSomethingis declared on program superclassBase(or overridden inSub), the resolver retains both the receiver classSuband the declaring/overridingsetSomethingmethod(s) in the hierarchy so R8 neither devirtualizes nor strips the metadata-dispatched target.N(e.g.,builder.setTitle(x)with 1 argument:setTitle(CharSequence)andsetTitle(int)), if the argument type is statically known (e.g., string literal →CharSequence), only compatible overloads are kept; otherwise all public/protected overloads of arityN(or...varargs) on that class hierarchy are kept.*Ktfile classes. When referenced, the declaring*Ktclass andkotlin.Metadataannotation (when Kotlin reflection/metadata inspection is involved) are retained.com.vendor.missing.Client) that matches neitherandroid.jarnor any program JAR/class, the tool warns with the source location (Referenced native class 'com.vendor.missing.Client' not found on Android compile classpath).Stage 4: Narrow keep-rule synthesis & obfuscation semantics
Each reachable program class falls into one of three precision tiers:
-keep class <BinaryName> { <matched <init>, methods, fields>; }obj[prop]), is subclassed/implemented, or comes fromnative-api-usage.jsonClasswildcard-keep class <BinaryName> { *; }androidx.recyclerview.widget[viewName])-keep class <pkg>.** { *; }+ build warning namingfile:lineWhy targeted
-keepavoids global-dontobfuscateNativeScript's JNI bridge resolves classes and members by exact JVM string name from metadata. In R8:
-keep class Foo { void bar(); }already prevents both shrinking and renaming ofFooandbar(), preserving exact JNI compatibility for everything JS touches.-dontobfuscatedirective (which disables identifier minification across the entire APK, including thousands of internal SDK classes JS never sees), targeted-keeplets R8 shrink, inline, and obfuscate purely internal library implementation classes while keeping every JS-facing boundary intact.minSdk < 24): Below API 24, D8/R8 moves static interface method bodies onto synthetic companion classes ($-CC/$$CC), which R8 will rename unless protected. WhenminSdkVersion < 24, the generator automatically emits:android.optimizeNative: { obfuscate: false }to emit-dontobfuscate.Runtime baseline rules
Every generated configuration includes the minimal NativeScript runtime invariants (deduplicated safely with runtime AAR consumer rules):
Stage 5: Gradle / R8 integration & post-build validation
In
@nativescript/android'sapp/build.gradle:-PnsOptimizeNative): When--optimize-native(orandroid.optimizeNativeinnativescript.config.ts) is active on a release build,GradleBuildArgsServicepasses-PnsOptimizeNative=true(and optional-PnsShrinkResources=true).buildTypes.releasewiring:AndroidProjectServicecopiesApp_Resources/Android/proguard-rules.pro(when present) intoplatforms/android/app/proguard-rules.produringprepareso standard Android Studio / Gradle builds referencing'proguard-rules.pro'pick it up automatically.minify*WithR8explicitlydependsOnbothbuildMetadataandgenerateNativeScriptProguardRules, preventing R8 from running against stale or missing rules and avoiding circular task dependencies withcompile*ArtProfileandoptimize*Resources(previously encountered in android#1887 and android#1910).mapping.txt,usage.txt,seeds.txt, andconfiguration.txtunderplatforms/android/app/build/outputs/mapping/release/.seeds.txt(catching accidental rule syntax mismatches or conflicting-assumenosideeffectsrules) and surfaces R8 missing-class warnings in CLI output.CLI and configuration surface
ns build android/ns run androidflags--optimize-nativebooleanfalse(ornativescript.config.ts)minifyEnabledwithproguard-android-optimize.txton--releasebuilds.--no-optimize-nativebooleanandroid.optimizeNative: trueinnativescript.config.tsfor a single build.ns proguardcommandns proguard [generate|check] [options]generate(default)App_Resources/Android/proguard-rules.pro.checkApp_Resources/Android/proguard-rules.promatches current reachable native API usage; exits with code1if stale.--out <path><path>instead of updatingApp_Resources/Android/proguard-rules.pro.--dry-runstdoutwithout writing files.--precision <member|class>memberdefault;classemits{ *; }for all matched program classes).--stricteval,globalThis[x], dynamicClass.forName) lacks an explicit keep rule.--write-gradleApp_Resources/Android/app.gradleconfiguresminifyEnabled truewithproguard-android-optimize.txtandproguard-rules.pro.--bundle <path...>nshor brownfield hosts).--jsonnativescript.config.tsschemaDrawbacks
Class.forName(variable)), computed bracket lookups, JNI calls inside native C/C++ libraries without consumer rules, and over-the-air (OTA / AppSync) bundles shipping new native API calls after the binary was built cannot be inferred from the build-time JS graph alone. Thorough testing of actual--releasebuilds remains mandatory.Subwithout keeping an inherited method onBase(or vice versa when overridden through an interface) can break R8 virtual dispatch if computed purely from AST names. Implementing Stage 3 against the compiled bytecode graph adds engineering complexity compared to class-wide{ *; }rules.ns proguardrequires resolved Android dependencies. On a fresh clone beforeplatforms/androidexists, resolving program vs.android.jarclasses requires preparing the Android project and running Gradle'scollectAllJars+ Java/Kotlin compilation tasks once.mapping.txt. Withproguard-android-optimize.txtenabled and global-dontobfuscateomitted, internal non-JS-facing library frames are obfuscated. Android App Bundles (.aab) bundlemapping.txtautomatically for Google Play Console deobfuscation, whereas raw.apkdistributions require uploadingmapping.txtto crash reporters (Sentry, Crashlytics).Alternatives considered
proguard-rules.proonly-keep class ** { *; }rules. Kept as an override layer, not the sole mechanism.src/**/*.ts)@nativescript/coreandnode_modulesplugins, includes dead code from unused exports or iOS branches, and misses generated framework template code. Analyzing the bundler's resolved graph solves all three.{ *; }for the entire metadata closure (ProguardRulesWriteras-is)android.jarclasses R8 doesn't shrink anyway, keeps every method on largeandroidx.*/ Material / SDK classes when only one method is used, relies on legacyproguard-android.txt+ global-dontobfuscate, and produces no user-inspectableApp_Resources/Android/proguard-rules.pro.consumer-rules.proand layering JS-interop rules on top aligns with Google's R8 design.ns proguardcommand)--optimize-nativeflag)ns build android --release. Supporting both on top of one shared engine serves both workflows cleanly.Adoption plan
@nativescript/vite+ AST chunk fallback): ImplementNativeUsageGraphextraction covering multi-entry apps, lazyimport()chunks, workers,@NativeClass/ interface proxies, and escape tracking, tested against@nativescript/coreand community plugins.ns proguardCLI command: Landns proguard(generate,check,--dry-run,--precision) innativescript-cli. Developers can immediately generate, inspect, and testApp_Resources/Android/proguard-rules.proin existing apps with zero breaking changes.@nativescript/androidGradle integration &--optimize-native: Land-PnsOptimizeNative, task-ordering guarantees (minify*WithR8afterbuildMetadataand rule generation),App_Resources/Android/proguard-rules.propreparation copying, and pluginplatforms/android/proguard-rules.prodiscovery.platforms/android/proguard-rules.proscaffolding and documentation to@nativescript/plugin-seedand official plugins that use reflective Java/Kotlin helpers.ns:nativestatic specifier fast-path (rfcs#58): Wirens:native/android/<package>imports directly intoNativeUsageGraphas RFC RFC: `ns:native` — native APIs as modules, one namespace per platform, every language behind it #58 lands.android.optimizeNative: truein new starter templates.Unresolved questions
ns proguard(generate/check) withns build android --release --optimize-nativethe clearest UX, or should both share one word (for example,ns android proguardor--proguard/--r8onns build android)?-includefile. Shouldns proguardwrite a# BEGIN NATIVESCRIPT GENERATED RULESsection directly insideApp_Resources/Android/proguard-rules.pro, or write a siblingApp_Resources/Android/proguard-nativescript.proand add-include proguard-nativescript.protoproguard-rules.pro?membervs.class). Should--optimize-nativelaunch withprecision: 'member'by default (smaller binaries, relies on escape analysis + hierarchy closure) or start withprecision: 'class'on program-only classes and promote'member'to default after preview feedback?shrinkResources). Should--optimize-nativeleave AGP'sshrinkResourcesoff by default (since NativeScript apps and@nativescript/coresometimes look up drawables/layouts dynamically viagetIdentifier), or generate a complementaryres/raw/keep.xmlfrom resource references and enableshrinkResources true?--strictto fail CI) the right default whenevalorglobalThis[dynamic]appears in a dependency, or should--optimize-nativerefuse to run R8 unless--allow-dynamicor an explicit keep rule is present (matchingns metadata trimin rfcs#62)?--optimize-nativestay purely focused on R8 / DEX optimization by default, or also enable Android metadata trimming (-PnsFilterMetadata) unless opted out?All reactions