@granite-js/screen 1.0.6 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @granite-js/screen
2
2
 
3
+ ## 1.0.7
4
+
5
+ ### Patch Changes
6
+
7
+ - 1cc53b9: fix(android): 16KB Page Size Support
8
+ - 5445e88: feat(android): add file-path based bundle evaluation to reduce memory usage
9
+ - 2b253fa: feat(android): Support additionalConfigurationSuffixes in GraniteRootExtension to extend React Native dependency substitution
10
+
3
11
  ## 1.0.6
4
12
 
5
13
  ## 1.0.5
@@ -11,6 +11,7 @@ add_library(
11
11
  SHARED
12
12
  src/main/cpp/onLoad.cpp
13
13
  src/main/cpp/BundleEvaluator.cpp
14
+ src/main/cpp/FileReader.cpp
14
15
  )
15
16
 
16
17
  # Configure C++ 17
@@ -1,9 +1,12 @@
1
1
  #include "BundleEvaluator.h"
2
+ #include "FileReader.h"
2
3
  #include <fbjni/fbjni.h>
3
4
 
4
5
  void BundleEvaluator::registerNatives() {
5
- registerHybrid(
6
- {makeNativeMethod("evaluateJavascriptSync", BundleEvaluator::evaluateJavascriptSync)});
6
+ registerHybrid({
7
+ makeNativeMethod("evaluateJavascriptSync", BundleEvaluator::evaluateJavascriptSync),
8
+ makeNativeMethod("evaluateFileSync", BundleEvaluator::evaluateFileSync)
9
+ });
7
10
  }
8
11
 
9
12
  void BundleEvaluator::evaluateJavascriptSync(
@@ -25,3 +28,54 @@ void BundleEvaluator::evaluateJavascriptSync(
25
28
  auto rt = reinterpret_cast<jsi::Runtime *>(jsRuntime);
26
29
  rt->evaluateJavaScript(std::make_unique<jsi::StringBuffer>(std::move(source)), std::move(sourceUrl));
27
30
  };
31
+
32
+ void BundleEvaluator::evaluateFileSync(
33
+ jni::alias_ref<jhybridobject> jThis,
34
+ jlong jsRuntime,
35
+ jni::alias_ref<JString> filePath,
36
+ jni::alias_ref<JString> url) {
37
+
38
+ if (jsRuntime == 0) {
39
+ jni::throwNewJavaException(
40
+ "java/lang/IllegalStateException",
41
+ "JS runtime is not available");
42
+ return;
43
+ }
44
+
45
+ std::string path = filePath->toStdString();
46
+ std::string sourceUrl = url->toStdString();
47
+
48
+ std::string source;
49
+ try {
50
+ source = granite::io::ReadFileToString(path);
51
+ } catch (const granite::io::FileReaderError& e) {
52
+ switch (e.kind()) {
53
+ case granite::io::ErrorKind::kNotFound:
54
+ jni::throwNewJavaException(
55
+ "java/io/FileNotFoundException", "%s", e.what());
56
+ break;
57
+ case granite::io::ErrorKind::kStatFailed:
58
+ case granite::io::ErrorKind::kReadFailed:
59
+ jni::throwNewJavaException(
60
+ "java/io/IOException", "%s", e.what());
61
+ break;
62
+ case granite::io::ErrorKind::kAllocationFailed:
63
+ jni::throwNewJavaException(
64
+ "java/lang/OutOfMemoryError", "%s", e.what());
65
+ break;
66
+ }
67
+ return;
68
+ }
69
+
70
+ if (source.empty()) {
71
+ jni::throwNewJavaException(
72
+ "java/io/IOException",
73
+ "Bundle file is empty: %s", path.c_str());
74
+ return;
75
+ }
76
+
77
+ auto rt = reinterpret_cast<jsi::Runtime *>(jsRuntime);
78
+ rt->evaluateJavaScript(
79
+ std::make_unique<jsi::StringBuffer>(std::move(source)),
80
+ std::move(sourceUrl));
81
+ }
@@ -4,14 +4,40 @@
4
4
  using namespace facebook;
5
5
  using namespace facebook::jni;
6
6
 
7
+ /**
8
+ * BundleEvaluator - JNI bridge for evaluating JavaScript bundles on the JSI runtime.
9
+ *
10
+ * Provides two evaluation methods:
11
+ * - evaluateJavascriptSync: Accepts a Java byte array (from Kotlin ByteArray).
12
+ * Peak memory: 2N (Java array + native std::string copy).
13
+ * - evaluateFileSync: Accepts a file path string, reads file via POSIX read() (not mmap).
14
+ * Peak memory: N (native std::string only, no Java heap allocation for bundle data).
15
+ *
16
+ * WARNING: Thread Safety
17
+ * Both methods execute JavaScript synchronously on the calling thread via a raw
18
+ * jsi::Runtime pointer. The caller must ensure they are on the JS thread.
19
+ * Unlike iOS (which uses callInvoker->invokeAsync), Android performs no automatic
20
+ * thread dispatch.
21
+ *
22
+ * Note: This class is for custom bundle evaluation outside the standard
23
+ * BundleLoader -> ReactHostFactory -> JSBundleLoader path.
24
+ */
7
25
  struct BundleEvaluator : public jni::HybridClass<BundleEvaluator> {
8
26
  static constexpr auto kJavaDescriptor = "Lrun/granite/BundleEvaluator;";
9
27
 
10
28
  static void registerNatives();
11
29
 
30
+ /** Evaluates JavaScript from a Java byte array. Pins the array, copies to std::string, then evaluates. */
12
31
  static void evaluateJavascriptSync(
13
32
  jni::alias_ref<jhybridobject> jThis,
14
33
  jlong jsRuntime,
15
34
  jni::alias_ref<JArrayByte> code,
16
35
  jni::alias_ref<JString> url);
36
+
37
+ /** Evaluates JavaScript from a file path. Reads file via POSIX open()/read() into native memory. */
38
+ static void evaluateFileSync(
39
+ jni::alias_ref<jhybridobject> jThis,
40
+ jlong jsRuntime,
41
+ jni::alias_ref<JString> filePath,
42
+ jni::alias_ref<JString> url);
17
43
  };
@@ -0,0 +1,84 @@
1
+ #include "FileReader.h"
2
+
3
+ #include <cerrno>
4
+ #include <cstring>
5
+ #include <fcntl.h>
6
+ #include <sys/stat.h>
7
+ #include <unistd.h>
8
+
9
+ namespace granite {
10
+ namespace io {
11
+
12
+ FdGuard::~FdGuard() {
13
+ if (fd >= 0) close(fd);
14
+ }
15
+
16
+ FileReaderError::FileReaderError(ErrorKind kind, const std::string& message,
17
+ int errno_value)
18
+ : std::runtime_error(message), kind_(kind), errno_value_(errno_value) {}
19
+
20
+ std::string ReadFileToString(const std::string& path) {
21
+ int fd = open(path.c_str(), O_RDONLY);
22
+ if (fd < 0) {
23
+ int saved_errno = errno;
24
+ throw FileReaderError(
25
+ ErrorKind::kNotFound,
26
+ "Cannot open file: " + path + " (errno: " +
27
+ std::to_string(saved_errno) + ", " + strerror(saved_errno) + ")",
28
+ saved_errno);
29
+ }
30
+ FdGuard guard{fd};
31
+
32
+ struct stat st;
33
+ if (fstat(fd, &st) < 0) {
34
+ int saved_errno = errno;
35
+ throw FileReaderError(
36
+ ErrorKind::kStatFailed,
37
+ "Cannot stat file: " + path + " (errno: " +
38
+ std::to_string(saved_errno) + ", " + strerror(saved_errno) + ")",
39
+ saved_errno);
40
+ }
41
+
42
+ size_t file_size = static_cast<size_t>(st.st_size);
43
+ if (file_size == 0) {
44
+ return std::string();
45
+ }
46
+
47
+ std::string source;
48
+ try {
49
+ source.resize(file_size);
50
+ } catch (const std::bad_alloc&) {
51
+ throw FileReaderError(
52
+ ErrorKind::kAllocationFailed,
53
+ "Cannot allocate " + std::to_string(file_size) +
54
+ " bytes for file: " + path);
55
+ }
56
+
57
+ size_t total_read = 0;
58
+ while (total_read < file_size) {
59
+ ssize_t bytes_read =
60
+ read(fd, &source[total_read], file_size - total_read);
61
+ if (bytes_read < 0) {
62
+ if (errno == EINTR) continue;
63
+ int saved_errno = errno;
64
+ throw FileReaderError(
65
+ ErrorKind::kReadFailed,
66
+ "Error reading file: " + path + " at offset " +
67
+ std::to_string(total_read) + " (errno: " +
68
+ std::to_string(saved_errno) + ", " +
69
+ strerror(saved_errno) + ")",
70
+ saved_errno);
71
+ }
72
+ if (bytes_read == 0) break;
73
+ total_read += static_cast<size_t>(bytes_read);
74
+ }
75
+
76
+ if (total_read < file_size) {
77
+ source.resize(total_read);
78
+ }
79
+
80
+ return source;
81
+ }
82
+
83
+ } // namespace io
84
+ } // namespace granite
@@ -0,0 +1,58 @@
1
+ #ifndef GRANITE_IO_FILE_READER_H_
2
+ #define GRANITE_IO_FILE_READER_H_
3
+
4
+ #include <string>
5
+ #include <stdexcept>
6
+
7
+ namespace granite {
8
+ namespace io {
9
+
10
+ // RAII guard for POSIX file descriptors.
11
+ // Closes the fd on destruction. Non-copyable, non-movable (stack-local usage only).
12
+ struct FdGuard {
13
+ int fd;
14
+ explicit FdGuard(int f) : fd(f) {}
15
+ ~FdGuard();
16
+ FdGuard(const FdGuard&) = delete;
17
+ FdGuard& operator=(const FdGuard&) = delete;
18
+ };
19
+
20
+ // Classification of file-reading errors.
21
+ enum class ErrorKind {
22
+ kNotFound, // open() failed (ENOENT, EACCES, etc.)
23
+ kStatFailed, // fstat() failed
24
+ kAllocationFailed, // std::bad_alloc during buffer allocation
25
+ kReadFailed // read() failed
26
+ };
27
+
28
+ // Error thrown by readFileToString() with a machine-readable ErrorKind
29
+ // and the originating errno value.
30
+ class FileReaderError : public std::runtime_error {
31
+ public:
32
+ FileReaderError(ErrorKind kind, const std::string& message,
33
+ int errno_value = 0);
34
+
35
+ ErrorKind kind() const { return kind_; }
36
+ int errno_value() const { return errno_value_; }
37
+
38
+ private:
39
+ ErrorKind kind_;
40
+ int errno_value_;
41
+ };
42
+
43
+ // Reads the entire contents of |path| into a std::string.
44
+ //
45
+ // Returns an empty string for zero-byte files (callers decide whether
46
+ // that is an error — e.g., BundleEvaluator treats it as IOException).
47
+ //
48
+ // Throws FileReaderError on failure:
49
+ // kNotFound — open() failed
50
+ // kStatFailed — fstat() failed
51
+ // kAllocationFailed — could not allocate buffer
52
+ // kReadFailed — read() failed (after EINTR retries)
53
+ std::string ReadFileToString(const std::string& path);
54
+
55
+ } // namespace io
56
+ } // namespace granite
57
+
58
+ #endif // GRANITE_IO_FILE_READER_H_
@@ -2,7 +2,25 @@ package run.granite
2
2
 
3
3
  import com.facebook.react.bridge.ReactContext
4
4
  import com.facebook.react.common.annotations.FrameworkAPI
5
+ import java.io.File
6
+ import java.io.FileNotFoundException
7
+ import java.io.IOException
5
8
 
9
+ /**
10
+ * Evaluates JavaScript bundles directly on the JSI runtime, outside the standard
11
+ * BundleLoader -> ReactHostFactory -> JSBundleLoader path.
12
+ *
13
+ * Two evaluation modes are provided:
14
+ * - [evaluate]: Accepts an in-memory [ByteArray]. Peak memory: 2N (Java heap + native heap copy).
15
+ * - [evaluateFile]: Accepts a file-system path. Peak memory: N (native heap only, no Java heap
16
+ * allocation for bundle data; file is read via POSIX read(), not mmap).
17
+ *
18
+ * **WARNING: Thread Safety**
19
+ * Both methods execute JavaScript synchronously on the calling thread via a raw JSI runtime
20
+ * pointer. The caller must ensure they are on the JS thread before invoking either method.
21
+ * Unlike iOS (which uses `callInvoker->invokeAsync`), Android performs no automatic thread
22
+ * dispatch.
23
+ */
6
24
  @OptIn(FrameworkAPI::class)
7
25
  class BundleEvaluator(
8
26
  private val reactContext: ReactContext,
@@ -13,6 +31,21 @@ class BundleEvaluator(
13
31
  url: String,
14
32
  )
15
33
 
34
+ private external fun evaluateFileSync(
35
+ jsRuntime: Long,
36
+ filePath: String,
37
+ url: String,
38
+ )
39
+
40
+ /**
41
+ * Evaluates JavaScript from an in-memory byte array.
42
+ *
43
+ * Peak memory usage: 2N — the Java [ByteArray] is pinned on the Java heap while a copy is
44
+ * made into a native `std::string`, resulting in two full-size allocations during evaluation.
45
+ *
46
+ * @param script The JavaScript source code as a byte array.
47
+ * @param url The source URL used for stack traces and error reporting.
48
+ */
16
49
  fun evaluate(
17
50
  script: ByteArray,
18
51
  url: String,
@@ -24,6 +57,32 @@ class BundleEvaluator(
24
57
  evaluateJavascriptSync(jsRuntime, script, url)
25
58
  }
26
59
 
60
+ /**
61
+ * Evaluates JavaScript from a file on the file system.
62
+ *
63
+ * Peak memory usage: N — the file is read directly into native memory via POSIX `read()`
64
+ * (not `mmap`), so no Java heap allocation is needed for the bundle data itself.
65
+ *
66
+ * @param filePath Absolute path to the JavaScript bundle file.
67
+ * @param url The source URL used for stack traces and error reporting.
68
+ * @throws FileNotFoundException if the file does not exist at [filePath].
69
+ * @throws IOException if the file exists but cannot be read (e.g., permission denied).
70
+ */
71
+ @Throws(FileNotFoundException::class, IOException::class)
72
+ fun evaluateFile(filePath: String, url: String) {
73
+ val file = File(filePath)
74
+ if (!file.exists()) {
75
+ throw FileNotFoundException("Bundle file not found: $filePath")
76
+ }
77
+ if (!file.canRead()) {
78
+ throw IOException("Bundle file not readable (permission denied): $filePath")
79
+ }
80
+ val jsRuntime =
81
+ reactContext.javaScriptContextHolder?.get()
82
+ ?: throw IllegalStateException("javaScriptContextHolder is null.")
83
+ evaluateFileSync(jsRuntime, filePath, url)
84
+ }
85
+
27
86
  companion object {
28
87
  init {
29
88
  // Loads the native granite-screen library containing the JNI evaluateJavascriptSync method.
@@ -34,10 +93,13 @@ class BundleEvaluator(
34
93
  }
35
94
 
36
95
  /**
37
- * Convenience method to evaluate JavaScript on the JSI runtime.
38
- * @param scriptData The JavaScript code as a byte array
39
- * @param url The source URL for error reporting
40
- * @param reactContext The React context containing the JSI runtime
96
+ * Convenience method to evaluate JavaScript from an in-memory byte array.
97
+ *
98
+ * Peak memory usage: 2N (Java heap + native heap copy). See [BundleEvaluator.evaluate].
99
+ *
100
+ * @param scriptData The JavaScript source code as a byte array.
101
+ * @param url The source URL used for stack traces and error reporting.
102
+ * @param reactContext The React context containing the JSI runtime.
41
103
  */
42
104
  fun evaluate(
43
105
  scriptData: ByteArray,
@@ -46,5 +108,22 @@ class BundleEvaluator(
46
108
  ) {
47
109
  BundleEvaluator(reactContext).evaluate(scriptData, url)
48
110
  }
111
+
112
+ /**
113
+ * Convenience method to evaluate JavaScript from a file on the file system.
114
+ *
115
+ * Peak memory usage: N (native heap only). See [BundleEvaluator.evaluateFile].
116
+ *
117
+ * @param filePath Absolute path to the JavaScript bundle file.
118
+ * @param url The source URL used for stack traces and error reporting.
119
+ * @param reactContext The React context containing the JSI runtime.
120
+ */
121
+ fun evaluateFile(
122
+ filePath: String,
123
+ url: String,
124
+ reactContext: ReactContext,
125
+ ) {
126
+ BundleEvaluator(reactContext).evaluateFile(filePath, url)
127
+ }
49
128
  }
50
129
  }
@@ -0,0 +1,38 @@
1
+ cmake_minimum_required(VERSION 3.14)
2
+ project(granite-screen-tests LANGUAGES CXX)
3
+
4
+ set(CMAKE_CXX_STANDARD 17)
5
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
6
+ set(CMAKE_CXX_EXTENSIONS OFF)
7
+
8
+ include(FetchContent)
9
+ FetchContent_Declare(
10
+ googletest
11
+ GIT_REPOSITORY https://github.com/google/googletest.git
12
+ GIT_TAG v1.14.0
13
+ )
14
+ FetchContent_MakeAvailable(googletest)
15
+
16
+ enable_testing()
17
+
18
+ set(MAIN_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../main/cpp")
19
+
20
+ add_executable(
21
+ FileReaderTest
22
+ FileReaderTest.cpp
23
+ ${MAIN_CPP_DIR}/FileReader.cpp
24
+ )
25
+
26
+ target_include_directories(
27
+ FileReaderTest
28
+ PRIVATE
29
+ "${CMAKE_CURRENT_SOURCE_DIR}/../../main/cpp"
30
+ )
31
+
32
+ target_link_libraries(
33
+ FileReaderTest
34
+ GTest::gtest_main
35
+ )
36
+
37
+ include(GoogleTest)
38
+ gtest_discover_tests(FileReaderTest)
@@ -0,0 +1,174 @@
1
+ #include <gtest/gtest.h>
2
+ #include "FileReader.h"
3
+
4
+ #include <fstream>
5
+ #include <filesystem>
6
+ #include <fcntl.h>
7
+ #include <sys/stat.h>
8
+ #include <unistd.h>
9
+
10
+ namespace fs = std::filesystem;
11
+ using namespace granite::io;
12
+
13
+ // Hermes Bytecode magic header: c6 1f bc 03
14
+ static const char kHermesMagic[] = {'\xc6', '\x1f', '\xbc', '\x03'};
15
+
16
+ class FileReaderTest : public ::testing::Test {
17
+ protected:
18
+ fs::path temp_dir_;
19
+
20
+ void SetUp() override {
21
+ temp_dir_ = fs::temp_directory_path() / "granite_file_reader_test";
22
+ fs::create_directories(temp_dir_);
23
+ }
24
+
25
+ void TearDown() override {
26
+ fs::remove_all(temp_dir_);
27
+ }
28
+
29
+ fs::path CreateTempFile(const std::string& name,
30
+ const std::string& content) {
31
+ auto path = temp_dir_ / name;
32
+ std::ofstream ofs(path, std::ios::binary);
33
+ ofs.write(content.data(), content.size());
34
+ ofs.close();
35
+ return path;
36
+ }
37
+
38
+ // Create a fake HBC file with magic header + payload.
39
+ fs::path CreateFakeHbcFile(const std::string& name,
40
+ size_t payload_size = 64) {
41
+ std::string content(kHermesMagic, sizeof(kHermesMagic));
42
+ for (size_t i = 0; i < payload_size; ++i) {
43
+ content.push_back(static_cast<char>(i & 0xFF));
44
+ }
45
+ return CreateTempFile(name, content);
46
+ }
47
+ };
48
+
49
+ // 1. Happy path: read HBC bundle with magic header.
50
+ TEST_F(FileReaderTest, ReadsHbcBundleCorrectly) {
51
+ auto path = CreateFakeHbcFile("bundle.hbc", 128);
52
+
53
+ std::string result = ReadFileToString(path.string());
54
+ EXPECT_EQ(result.size(), sizeof(kHermesMagic) + 128);
55
+ // Verify Hermes magic header is preserved.
56
+ EXPECT_EQ(result[0], '\xc6');
57
+ EXPECT_EQ(result[1], '\x1f');
58
+ EXPECT_EQ(result[2], '\xbc');
59
+ EXPECT_EQ(result[3], '\x03');
60
+ }
61
+
62
+ // 2. FdGuard RAII: fd is closed after destruction.
63
+ TEST_F(FileReaderTest, FdGuardClosesFileDescriptor) {
64
+ auto path = CreateFakeHbcFile("guard_test.hbc");
65
+ int fd = open(path.c_str(), O_RDONLY);
66
+ ASSERT_GE(fd, 0);
67
+
68
+ {
69
+ FdGuard guard{fd};
70
+ struct stat st;
71
+ EXPECT_EQ(fstat(fd, &st), 0);
72
+ }
73
+ // fd should be closed after FdGuard destruction.
74
+ struct stat st;
75
+ EXPECT_EQ(fstat(fd, &st), -1);
76
+ EXPECT_EQ(errno, EBADF);
77
+ }
78
+
79
+ // 3. Bundle file not found.
80
+ TEST_F(FileReaderTest, ThrowsNotFoundForMissingBundle) {
81
+ std::string missing_path = (temp_dir_ / "nonexistent.hbc").string();
82
+
83
+ try {
84
+ ReadFileToString(missing_path);
85
+ FAIL() << "Expected FileReaderError";
86
+ } catch (const FileReaderError& e) {
87
+ EXPECT_EQ(e.kind(), ErrorKind::kNotFound);
88
+ EXPECT_EQ(e.errno_value(), ENOENT);
89
+ EXPECT_NE(std::string(e.what()).find(missing_path), std::string::npos)
90
+ << "Error message should contain file path";
91
+ }
92
+ }
93
+
94
+ // 4. Bundle file permission denied.
95
+ TEST_F(FileReaderTest, ThrowsNotFoundForPermissionDenied) {
96
+ if (getuid() == 0) {
97
+ GTEST_SKIP() << "Skipping permission test when running as root";
98
+ }
99
+
100
+ auto path = CreateFakeHbcFile("no_access.hbc");
101
+ chmod(path.c_str(), 0000);
102
+
103
+ try {
104
+ ReadFileToString(path.string());
105
+ FAIL() << "Expected FileReaderError";
106
+ } catch (const FileReaderError& e) {
107
+ EXPECT_EQ(e.kind(), ErrorKind::kNotFound);
108
+ EXPECT_EQ(e.errno_value(), EACCES);
109
+ }
110
+
111
+ // Restore permissions for cleanup.
112
+ chmod(path.c_str(), 0644);
113
+ }
114
+
115
+ // 5. Empty bundle returns empty string (domain policy handled by caller).
116
+ TEST_F(FileReaderTest, ReturnsEmptyStringForEmptyBundle) {
117
+ auto path = CreateTempFile("empty.hbc", "");
118
+
119
+ std::string result = ReadFileToString(path.string());
120
+ EXPECT_TRUE(result.empty());
121
+ }
122
+
123
+ // 6. Large HBC bundle (> 4KB, multi-read territory).
124
+ TEST_F(FileReaderTest, ReadsLargeHbcBundleCorrectly) {
125
+ // Simulate a realistic HBC bundle: magic header + 8KB bytecode payload.
126
+ std::string content(kHermesMagic, sizeof(kHermesMagic));
127
+ for (size_t i = 0; i < 8192; ++i) {
128
+ content.push_back(static_cast<char>(i & 0xFF));
129
+ }
130
+ auto path = CreateTempFile("large_bundle.hbc", content);
131
+
132
+ std::string result = ReadFileToString(path.string());
133
+ EXPECT_EQ(result.size(), content.size());
134
+ EXPECT_EQ(result, content);
135
+ // Verify magic header survived the read.
136
+ EXPECT_EQ(result.substr(0, 4),
137
+ std::string(kHermesMagic, sizeof(kHermesMagic)));
138
+ }
139
+
140
+ // 7. Binary content with null bytes (common in HBC bytecode).
141
+ TEST_F(FileReaderTest, ReadsBinaryBytecodeWithNullBytes) {
142
+ std::string bytecode(kHermesMagic, sizeof(kHermesMagic));
143
+ bytecode += std::string("\x00\x00\x00\x00", 4); // null-filled section
144
+ bytecode += std::string("\x01\x02\x00\x04", 4); // mixed with nulls
145
+ bytecode += std::string(32, '\0'); // zero-padding block
146
+ auto path = CreateTempFile("nullbytes.hbc", bytecode);
147
+
148
+ std::string result = ReadFileToString(path.string());
149
+ EXPECT_EQ(result.size(), bytecode.size());
150
+ EXPECT_EQ(result, bytecode);
151
+ }
152
+
153
+ // 8. Error message contains bundle file path for diagnostics.
154
+ TEST_F(FileReaderTest, ErrorMessageContainsBundlePath) {
155
+ std::string missing_path = (temp_dir_ / "missing_bundle.hbc").string();
156
+
157
+ try {
158
+ ReadFileToString(missing_path);
159
+ FAIL() << "Expected FileReaderError";
160
+ } catch (const FileReaderError& e) {
161
+ std::string msg = e.what();
162
+ EXPECT_NE(msg.find("missing_bundle.hbc"), std::string::npos)
163
+ << "Error message should contain the bundle file name. Got: " << msg;
164
+ EXPECT_NE(msg.find("errno"), std::string::npos)
165
+ << "Error message should contain errno info. Got: " << msg;
166
+ }
167
+ }
168
+
169
+ // 9. FdGuard with invalid fd does not crash.
170
+ TEST_F(FileReaderTest, FdGuardHandlesInvalidFd) {
171
+ { FdGuard guard{-1}; }
172
+ // Should not crash or throw — just a no-op close.
173
+ SUCCEED();
174
+ }
@@ -0,0 +1,30 @@
1
+ #!/bin/bash
2
+ # Build and run host-side C++ unit tests for granite-screen FileReader.
3
+ #
4
+ # Prerequisites:
5
+ # - CMake >= 3.14
6
+ # - C++17 compiler (clang or gcc)
7
+ # - Internet access (gtest is fetched via CMake FetchContent on first build)
8
+ #
9
+ # Usage:
10
+ # ./packages/granite-screen/android/test-cpp.sh
11
+ #
12
+ # The test binary is built in /tmp/granite-screen-test-build.
13
+ # Re-running the script will rebuild only changed files.
14
+
15
+ set -euo pipefail
16
+
17
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
18
+ SRC_DIR="${SCRIPT_DIR}/src/test/cpp"
19
+ BUILD_DIR="/tmp/granite-screen-test-build"
20
+
21
+ echo "==> Configuring (${SRC_DIR})"
22
+ cmake -S "${SRC_DIR}" -B "${BUILD_DIR}" -DCMAKE_BUILD_TYPE=Release 2>&1
23
+
24
+ echo ""
25
+ echo "==> Building"
26
+ cmake --build "${BUILD_DIR}" --parallel 2>&1
27
+
28
+ echo ""
29
+ echo "==> Running tests"
30
+ ctest --test-dir "${BUILD_DIR}" --output-on-failure -V 2>&1
@@ -2,6 +2,7 @@ package run.granite.gradle
2
2
 
3
3
  import org.gradle.api.Project
4
4
  import org.gradle.api.provider.Property
5
+ import org.gradle.api.provider.SetProperty
5
6
  import run.granite.gradle.config.DependencyCoordinates
6
7
  import run.granite.gradle.utils.ReactNativeVersionReader
7
8
  import java.io.File
@@ -19,6 +20,9 @@ import java.io.File
19
20
  * // Optional: Override Maven group (for custom Maven repositories)
20
21
  * // reactGroup.set("com.facebook.react")
21
22
  * // hermesGroup.set("com.facebook.hermes")
23
+ *
24
+ * // Optional: Apply dependency substitution to additional configuration suffixes
25
+ * // additionalConfigurationSuffixes.add("DexGuardConsumerRuleBuildDependencies")
22
26
  * }
23
27
  * ```
24
28
  */
@@ -52,11 +56,18 @@ abstract class GraniteRootExtension(private val project: Project) {
52
56
  */
53
57
  abstract val nodeModulesDir: Property<File>
54
58
 
59
+ /**
60
+ * Additional configuration name suffixes for dependency substitution.
61
+ * Default: empty set (only CompileClasspath and RuntimeClasspath are matched)
62
+ */
63
+ abstract val additionalConfigurationSuffixes: SetProperty<String>
64
+
55
65
  init {
56
66
  // Set default conventions
57
67
  reactGroup.convention(DependencyCoordinates.DEFAULT_REACT_GROUP)
58
68
  hermesGroup.convention(DependencyCoordinates.DEFAULT_HERMES_GROUP)
59
69
  nodeModulesDir.convention(project.file("node_modules"))
70
+ additionalConfigurationSuffixes.convention(emptySet())
60
71
  // reactNativeVersion and hermesVersion are intentionally left without conventions
61
72
  // They will be auto-detected if not explicitly set
62
73
  }
@@ -5,6 +5,7 @@ import com.android.build.api.variant.LibraryAndroidComponentsExtension
5
5
  import org.gradle.api.JavaVersion
6
6
  import org.gradle.api.Plugin
7
7
  import org.gradle.api.Project
8
+ import org.gradle.api.UnknownDomainObjectException
8
9
  import org.gradle.api.artifacts.Configuration
9
10
  import run.granite.gradle.config.DependencyConfigurator
10
11
 
@@ -98,18 +99,26 @@ class GraniteRootProjectPlugin : Plugin<Project> {
98
99
  val coordinates = extension.getCoordinates()
99
100
  val substitutions = DependencyConfigurator.getDependencySubstitutions(coordinates)
100
101
  val hermesVersion = coordinates.getEffectiveHermesVersion()
102
+ val additionalSuffixes = extension.additionalConfigurationSuffixes.get()
101
103
 
102
104
  project.logger.lifecycle(
103
105
  "Granite: Configuring dependency substitution " +
104
106
  "(react: ${coordinates.reactVersion}, hermes: $hermesVersion)",
105
107
  )
106
108
 
109
+ if (additionalSuffixes.isNotEmpty()) {
110
+ project.logger.lifecycle(
111
+ "Granite: Additional configuration suffixes registered: $additionalSuffixes"
112
+ )
113
+ }
107
114
  project.allprojects {
108
115
  val targetProject = this
109
116
 
110
117
  targetProject.configurations.all configBlock@{
111
118
  // Filter: only Classpath configurations
112
- if (!name.endsWith("CompileClasspath") && !name.endsWith("RuntimeClasspath")) {
119
+ val matchesDefault = name.endsWith("CompileClasspath") || name.endsWith("RuntimeClasspath")
120
+ val matchesAdditional = additionalSuffixes.any { suffix -> name.endsWith(suffix) }
121
+ if (!matchesDefault && !matchesAdditional) {
113
122
  return@configBlock
114
123
  }
115
124
  // Filter: skip AGP internal metadata configurations
@@ -105,6 +105,7 @@ class NdkConfigurator(
105
105
  "-DPROJECT_BUILD_DIR=$projectBuildDir",
106
106
  "-DPROJECT_ROOT_DIR=$projectRootDir",
107
107
  "-DANDROID_STL=c++_shared",
108
+ "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
108
109
  )
109
110
 
110
111
  project.logger.debug("CMake configured with React Native arguments")
@@ -62,6 +62,36 @@ class GraniteRootProjectPluginTest {
62
62
  assertTrue(!extension.hermesVersion.isPresent)
63
63
  }
64
64
 
65
+ @Test
66
+ fun `additionalConfigurationSuffixes defaults to empty set`() {
67
+ // Given
68
+ val project = ProjectBuilder.builder().build()
69
+ project.pluginManager.apply(GraniteRootProjectPlugin::class.java)
70
+
71
+ // When
72
+ val extension = project.extensions.getByType(GraniteRootExtension::class.java)
73
+
74
+ // Then
75
+ assertTrue(extension.additionalConfigurationSuffixes.get().isEmpty())
76
+ }
77
+
78
+ @Test
79
+ fun `additionalConfigurationSuffixes can be configured`() {
80
+ // Given
81
+ val project = ProjectBuilder.builder().build()
82
+ project.pluginManager.apply(GraniteRootProjectPlugin::class.java)
83
+ val extension = project.extensions.getByType(GraniteRootExtension::class.java)
84
+
85
+ // When
86
+ extension.additionalConfigurationSuffixes.add("DexGuardConsumerRuleBuildDependencies")
87
+
88
+ // Then
89
+ assertEquals(
90
+ setOf("DexGuardConsumerRuleBuildDependencies"),
91
+ extension.additionalConfigurationSuffixes.get()
92
+ )
93
+ }
94
+
65
95
  @Test
66
96
  fun `plugin fails when applied to non-root project`() {
67
97
  // Given
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@granite-js/screen",
3
3
  "type": "module",
4
- "version": "1.0.6",
4
+ "version": "1.0.7",
5
5
  "description": "Brownfield Screen for React Native",
6
6
  "files": [
7
7
  "dist",