@granite-js/screen 3.0.1 → 3.0.3

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,14 @@
1
1
  # @granite-js/screen
2
2
 
3
+ ## 3.0.3
4
+
5
+ ## 3.0.2
6
+
7
+ ### Patch Changes
8
+
9
+ - adf1840: Support React Native 0.87 factory delegate headers while preserving the explicit bridgeless opt-in on older versions. Use the supported default Proguard configuration with Android Gradle Plugin 9.
10
+ - 0a062dc: Fix Android host creation cancellation, native bundle evaluation errors and asset bundle loading.
11
+
3
12
  ## 3.0.1
4
13
 
5
14
  ### Patch Changes
@@ -11,6 +11,7 @@ Pod::Spec.new do |s|
11
11
  s.source = { :path => "." }
12
12
 
13
13
  s.source_files = "ios/**/*.{h,m,mm,swift}"
14
+ s.exclude_files = "ios/**/__tests__/**/*"
14
15
  s.public_header_files = "ios/**/*.h"
15
16
  s.private_header_files = "ios/**/*+*.h"
16
17
 
@@ -38,7 +38,7 @@ android {
38
38
  buildTypes {
39
39
  release {
40
40
  minifyEnabled false
41
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
41
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
42
42
  }
43
43
  }
44
44
 
@@ -0,0 +1,19 @@
1
+ #pragma once
2
+
3
+ #include <exception>
4
+ #include <utility>
5
+
6
+ namespace granite {
7
+
8
+ // JSI errors derive from std::exception. Translate them at the JNI boundary
9
+ // rather than allowing a JavaScript evaluation failure to escape into native code.
10
+ template <typename Evaluate, typename ReportError>
11
+ void WithEvaluationErrorHandler(Evaluate&& evaluate, ReportError&& reportError) {
12
+ try {
13
+ std::forward<Evaluate>(evaluate)();
14
+ } catch (const std::exception& error) {
15
+ std::forward<ReportError>(reportError)(error.what());
16
+ }
17
+ }
18
+
19
+ } // namespace granite
@@ -1,4 +1,5 @@
1
1
  #include "BundleEvaluator.h"
2
+ #include "BundleEvaluation.h"
2
3
  #include "FileReader.h"
3
4
  #include <fbjni/fbjni.h>
4
5
 
@@ -26,7 +27,17 @@ void BundleEvaluator::evaluateJavascriptSync(
26
27
  return;
27
28
  }
28
29
  auto rt = reinterpret_cast<jsi::Runtime *>(jsRuntime);
29
- rt->evaluateJavaScript(std::make_unique<jsi::StringBuffer>(std::move(source)), std::move(sourceUrl));
30
+ granite::WithEvaluationErrorHandler(
31
+ [&] {
32
+ rt->evaluateJavaScript(
33
+ std::make_unique<jsi::StringBuffer>(std::move(source)), sourceUrl);
34
+ },
35
+ [&](const char* message) {
36
+ jni::throwNewJavaException(
37
+ "java/lang/RuntimeException",
38
+ "Failed to evaluate JavaScript bundle (%s): %s",
39
+ sourceUrl.c_str(), message);
40
+ });
30
41
  };
31
42
 
32
43
  void BundleEvaluator::evaluateFileSync(
@@ -75,7 +86,15 @@ void BundleEvaluator::evaluateFileSync(
75
86
  }
76
87
 
77
88
  auto rt = reinterpret_cast<jsi::Runtime *>(jsRuntime);
78
- rt->evaluateJavaScript(
79
- std::make_unique<jsi::StringBuffer>(std::move(source)),
80
- std::move(sourceUrl));
89
+ granite::WithEvaluationErrorHandler(
90
+ [&] {
91
+ rt->evaluateJavaScript(
92
+ std::make_unique<jsi::StringBuffer>(std::move(source)), sourceUrl);
93
+ },
94
+ [&](const char* message) {
95
+ jni::throwNewJavaException(
96
+ "java/lang/RuntimeException",
97
+ "Failed to evaluate JavaScript bundle (%s): %s",
98
+ sourceUrl.c_str(), message);
99
+ });
81
100
  }
@@ -25,6 +25,9 @@ interface GraniteReactDelegate {
25
25
 
26
26
  fun onDestroy(activity: AppCompatActivity)
27
27
 
28
+ /** Cancel bundle loading and host creation when a screen leaves before it is ready. */
29
+ fun cancelPendingHostCreation() {}
30
+
28
31
  // Configuration methods - these should be provided by the activity
29
32
  fun setReactPackagesProvider(provider: () -> List<ReactPackage>)
30
33
 
@@ -5,6 +5,7 @@ import android.util.Log
5
5
  import android.view.View
6
6
  import android.widget.FrameLayout
7
7
  import androidx.appcompat.app.AppCompatActivity
8
+ import androidx.annotation.VisibleForTesting
8
9
  import androidx.core.view.ViewCompat
9
10
  import androidx.core.view.WindowInsetsCompat
10
11
  import androidx.lifecycle.lifecycleScope
@@ -17,7 +18,16 @@ import com.facebook.react.fabric.ComponentFactory
17
18
  import com.facebook.react.interfaces.fabric.ReactSurface
18
19
  import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler
19
20
  import com.facebook.react.runtime.ReactSurfaceView
21
+ import kotlinx.coroutines.CancellationException
22
+ import kotlinx.coroutines.CoroutineScope
23
+ import kotlinx.coroutines.CoroutineStart
24
+ import kotlinx.coroutines.Dispatchers
25
+ import kotlinx.coroutines.Job
26
+ import kotlinx.coroutines.NonCancellable
27
+ import kotlinx.coroutines.ensureActive
20
28
  import kotlinx.coroutines.launch
29
+ import kotlinx.coroutines.withContext
30
+ import kotlin.coroutines.coroutineContext
21
31
  import java.lang.ref.WeakReference
22
32
 
23
33
  /** Default implementation of GraniteReactDelegate. Manages ReactHost, ReactSurface */
@@ -61,6 +71,10 @@ class GraniteReactDelegateImpl : GraniteReactDelegate {
61
71
  private var surfaceViewConsumer: ((ReactSurfaceView) -> Unit)? = null
62
72
  private var errorViewConsumer: ((Throwable) -> Unit)? = null
63
73
 
74
+ private var pendingHostCreationJob: Job? = null
75
+ private var loadScopeForTest: CoroutineScope? = null
76
+ private var reactHostForTest: ((AppCompatActivity, BundleSource) -> ReactHost)? = null
77
+
64
78
  override fun onCreate(
65
79
  activity: AppCompatActivity,
66
80
  savedInstanceState: Bundle?,
@@ -132,6 +146,7 @@ class GraniteReactDelegateImpl : GraniteReactDelegate {
132
146
  // Track pending lifecycle state
133
147
  pendingLifecycleState = LifecycleState.DESTROYED
134
148
  pendingActivityRef = null
149
+ cancelPendingHostCreation()
135
150
 
136
151
  // Clean up ReactSurface
137
152
  // stop() is async (TaskInterface<Void>), but clear() and detach() can be called concurrently:
@@ -151,12 +166,10 @@ class GraniteReactDelegateImpl : GraniteReactDelegate {
151
166
  reactInstanceEventListener = null
152
167
 
153
168
  // Clean up ReactHost
154
- // invalidate() internally runs destroy() asynchronously on bgExecutor.
155
- // ReactHostImpl instance is kept alive by its own internal threading,
156
- // so nulling the delegate's reactHost field won't interrupt the async destroy.
169
+ // Destroy the runtime without permanently invalidating the host.
157
170
  reactHost?.let { host ->
158
171
  host.onHostDestroy(activity)
159
- host.invalidate()
172
+ host.destroy(TEARDOWN_REASON, null)
160
173
  }
161
174
  ?: Log.w(TAG, "ReactHost not ready, skipping onHostDestroy")
162
175
  reactHost = null
@@ -179,6 +192,23 @@ class GraniteReactDelegateImpl : GraniteReactDelegate {
179
192
  errorViewConsumer = null
180
193
  }
181
194
 
195
+ override fun cancelPendingHostCreation() {
196
+ pendingHostCreationJob?.cancel()
197
+ pendingHostCreationJob = null
198
+ }
199
+
200
+ /** Override the loading scope for deterministic lifecycle tests. */
201
+ @VisibleForTesting
202
+ fun setLoadScopeForTest(scope: CoroutineScope) {
203
+ loadScopeForTest = scope
204
+ }
205
+
206
+ /** Supply a host without starting a JavaScript runtime in lifecycle tests. */
207
+ @VisibleForTesting
208
+ fun setReactHostForTest(factory: (AppCompatActivity, BundleSource) -> ReactHost) {
209
+ reactHostForTest = factory
210
+ }
211
+
182
212
  override fun setReactPackagesProvider(provider: () -> List<ReactPackage>) {
183
213
  this.reactPackagesProvider = provider
184
214
  }
@@ -349,7 +379,7 @@ class GraniteReactDelegateImpl : GraniteReactDelegate {
349
379
  // Activity is being destroyed, clean up immediately
350
380
  surface.stop()
351
381
  pendingActivity?.let { act -> host.onHostDestroy(act) }
352
- host.invalidate()
382
+ host.destroy(TEARDOWN_REASON, null)
353
383
  Log.d(TAG, "Activity destroyed, cleaned up ReactHost")
354
384
  }
355
385
  else -> {
@@ -367,7 +397,11 @@ class GraniteReactDelegateImpl : GraniteReactDelegate {
367
397
  bundleLoader: BundleLoader,
368
398
  initialProps: Bundle,
369
399
  ) {
370
- activity.lifecycleScope.launch {
400
+ cancelPendingHostCreation()
401
+ val scope = loadScopeForTest ?: activity.lifecycleScope
402
+ // Assign before starting so reentrant cancellation during creation reaches this job.
403
+ val job = scope.launch(start = CoroutineStart.LAZY) {
404
+ var unattachedHost: ReactHost? = null
371
405
  try {
372
406
  Log.d(TAG, "loadBundleWithLoader started")
373
407
  Log.d(
@@ -404,24 +438,26 @@ class GraniteReactDelegateImpl : GraniteReactDelegate {
404
438
  }
405
439
  }
406
440
 
407
- // Create ReactHost with the loaded bundle (safe off main thread)
441
+ coroutineContext.ensureActive()
408
442
  val factoryResult = createReactHostWithBundle(activity, bundleSource)
443
+ unattachedHost = factoryResult.reactHost
444
+ coroutineContext.ensureActive()
409
445
 
410
- // Assign shared state and setup on UI thread to serialize with onDestroy
411
- activity.runOnUiThread {
446
+ // Await the handoff; a posted Runnable could attach an already-cancelled host.
447
+ withContext(Dispatchers.Main.immediate) {
412
448
  if (pendingLifecycleState != LifecycleState.DESTROYED) {
413
449
  currentBundleSource = bundleSource
414
450
  reactHost = factoryResult.reactHost
415
451
  componentFactory = factoryResult.componentFactory
452
+ unattachedHost = null
416
453
  setupReactHost(activity, initialProps)
417
- } else {
418
- // Activity already destroyed; clean up the host we just created
419
- factoryResult.reactHost.invalidate()
420
454
  }
421
455
  }
456
+ } catch (e: CancellationException) {
457
+ throw e
422
458
  } catch (e: Exception) {
423
459
  // Show error view on UI thread
424
- activity.runOnUiThread {
460
+ withContext(Dispatchers.Main.immediate) {
425
461
  if (pendingLifecycleState != LifecycleState.DESTROYED) {
426
462
  errorViewConsumer?.invoke(e)
427
463
  ?: run {
@@ -435,14 +471,27 @@ class GraniteReactDelegateImpl : GraniteReactDelegate {
435
471
  Log.e(TAG, "Failed to load bundle", e)
436
472
  }
437
473
  }
474
+ } finally {
475
+ val host = unattachedHost
476
+ if (host != null) {
477
+ withContext(NonCancellable + Dispatchers.Main.immediate) {
478
+ host.destroy(TEARDOWN_REASON, null)
479
+ }
480
+ }
481
+ if (pendingHostCreationJob === coroutineContext[Job]) {
482
+ pendingHostCreationJob = null
483
+ }
438
484
  }
439
485
  }
486
+ pendingHostCreationJob = job
487
+ job.start()
440
488
  }
441
489
 
442
490
  private fun createReactHostWithBundle(
443
491
  activity: AppCompatActivity,
444
492
  bundleSource: BundleSource,
445
493
  ): ReactHostFactory.Result {
494
+ reactHostForTest?.let { return ReactHostFactory.Result(it(activity, bundleSource), null) }
446
495
  val packages = reactPackagesProvider?.invoke() ?: emptyList()
447
496
  return ReactHostFactory.create(
448
497
  activity.applicationContext,
@@ -455,5 +504,6 @@ class GraniteReactDelegateImpl : GraniteReactDelegate {
455
504
  companion object {
456
505
  // Note: BuildConfig.DEBUG reflects this library's build variant, not the consuming app's.
457
506
  private const val TAG = "GraniteReactDelegate"
507
+ private const val TEARDOWN_REASON = "GraniteReactDelegate teardown"
458
508
  }
459
509
  }
@@ -26,7 +26,7 @@ internal object ReactHostFactory {
26
26
 
27
27
  data class Result(
28
28
  val reactHost: ReactHost,
29
- val componentFactory: ComponentFactory,
29
+ val componentFactory: ComponentFactory?,
30
30
  )
31
31
 
32
32
  fun create(
@@ -79,7 +79,7 @@ internal object ReactHostFactory {
79
79
  return Result(reactHostImpl, newComponentFactory)
80
80
  }
81
81
 
82
- private fun createBundleLoaderConfig(
82
+ internal fun createBundleLoaderConfig(
83
83
  context: Context,
84
84
  bundleSource: BundleSource,
85
85
  ): Pair<JSBundleLoader, Boolean> =
@@ -95,8 +95,11 @@ internal object ReactHostFactory {
95
95
  when (bundleSource.location) {
96
96
  is ProductionLocation.FileSystemBundle -> {
97
97
  val filePath = bundleSource.location.filePath
98
- Log.d(TAG, "Creating file loader with path: $filePath")
99
- JSBundleLoader.createFileLoader(filePath) to false
98
+ if (filePath.startsWith("assets://")) {
99
+ JSBundleLoader.createAssetLoader(context, filePath, false) to false
100
+ } else {
101
+ JSBundleLoader.createFileLoader(filePath) to false
102
+ }
100
103
  }
101
104
  is ProductionLocation.EmbeddedBundle -> {
102
105
  Log.d(TAG, "Creating asset loader for embedded bundle")
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ cd "$(dirname "$0")"
4
+ exec ../gradle-plugin/gradlew -p lifecycle-tests testDebugUnitTest "$@"
@@ -18,6 +18,12 @@
18
18
 
19
19
  @implementation GraniteNativeFactoryDelegate
20
20
 
21
+ // Keep the explicit opt-in for older RN versions. RN87 no longer exposes this
22
+ // selector to Swift, so implementing it here avoids a version-dependent override.
23
+ - (BOOL)bridgelessEnabled {
24
+ return YES;
25
+ }
26
+
21
27
  - (void)hostDidStart:(RCTHost *)host {
22
28
  [super hostDidStart:host];
23
29
  [self graniteHostDidStart];
@@ -26,10 +26,6 @@ public class ReactNativeFactoryDelegate: GraniteNativeFactoryDelegate {
26
26
  return bundleURL()
27
27
  }
28
28
 
29
- public override func bridgelessEnabled() -> Bool {
30
- return true
31
- }
32
-
33
29
  public override func graniteHostDidStart() {
34
30
  reactHost?.graniteHostDidStart()
35
31
  }
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ script_dir="$(cd "$(dirname "$0")" && pwd)"
5
+ source_dir="$script_dir/ReactNativeHosting"
6
+ fixture_dir="$script_dir/__tests__/factory-delegate"
7
+ build_dir="$(mktemp -d "${TMPDIR:-/tmp}/granite-factory-test.XXXXXX")"
8
+ trap 'rm -rf "$build_dir"' EXIT
9
+
10
+ # Exercise both RN's older public flag and RN87's header without that selector.
11
+ for legacy in 1 0; do
12
+ output_dir="$build_dir/$legacy"
13
+ mkdir -p "$output_dir"
14
+ for source in "$source_dir/GraniteNativeFactoryDelegate.m" "$fixture_dir/Fixture.m"; do
15
+ xcrun clang -fobjc-arc -fmodules -DGRANITE_TEST_LEGACY_DELEGATE="$legacy" \
16
+ -I "$source_dir" -I "$fixture_dir" \
17
+ -c "$source" -o "$output_dir/$(basename "$source").o"
18
+ done
19
+ xcrun swiftc -I "$fixture_dir" -import-objc-header "$fixture_dir/Fixture.h" \
20
+ -Xcc "-I$source_dir" -Xcc "-DGRANITE_TEST_LEGACY_DELEGATE=$legacy" \
21
+ -module-cache-path "$output_dir/module-cache" \
22
+ "$source_dir/GraniteNativeFactoryDelegateImpl.swift" "$fixture_dir/main.swift" \
23
+ "$output_dir/GraniteNativeFactoryDelegate.m.o" "$output_dir/Fixture.m.o" \
24
+ -framework Foundation -o "$output_dir/test"
25
+ "$output_dir/test"
26
+ done
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@granite-js/screen",
3
3
  "type": "module",
4
- "version": "3.0.1",
4
+ "version": "3.0.3",
5
5
  "description": "Brownfield Screen for React Native",
6
6
  "files": [
7
7
  "dist",
@@ -11,6 +11,8 @@
11
11
  "gradle-plugin",
12
12
  "react-native.config.js",
13
13
  "!ios/build",
14
+ "!android/lifecycle-tests",
15
+ "!android/src/test",
14
16
  "!android/build",
15
17
  "!android/gradle",
16
18
  "!android/gradlew",
@@ -26,7 +28,10 @@
26
28
  "scripts": {
27
29
  "build": "cd gradle-plugin && ./gradlew jar",
28
30
  "test:gradle-plugin": "cd gradle-plugin && ./gradlew test",
29
- "prepack": "cd gradle-plugin && ./gradlew jar"
31
+ "prepack": "cd gradle-plugin && ./gradlew jar",
32
+ "test:android": "android/test-lifecycle.sh",
33
+ "test:cpp": "android/test-cpp.sh",
34
+ "test:ios": "ios/test-factory-delegate.sh"
30
35
  },
31
36
  "nx": {
32
37
  "targets": {
@@ -1,38 +0,0 @@
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)
@@ -1,174 +0,0 @@
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
- }