@salve-software/react-native-nitro-jsdom 1.0.0

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.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/NitroJsdom.podspec +63 -0
  3. package/README.md +95 -0
  4. package/android/CMakeLists.txt +86 -0
  5. package/android/build.gradle +148 -0
  6. package/android/fix-prefab.gradle +51 -0
  7. package/android/gradle.properties +5 -0
  8. package/android/src/main/AndroidManifest.xml +2 -0
  9. package/android/src/main/cpp/cpp-adapter.cpp +9 -0
  10. package/android/src/main/java/com/nitrojsdom/NitroJsdomPackage.kt +20 -0
  11. package/cpp/HybridHtmlSandbox.cpp +171 -0
  12. package/cpp/HybridHtmlSandbox.hpp +47 -0
  13. package/cpp/lexbor/LexborDocument.cpp +365 -0
  14. package/cpp/lexbor/LexborDocument.hpp +71 -0
  15. package/cpp/quickjs/DOMBindings.cpp +57 -0
  16. package/cpp/quickjs/DOMBindings.hpp +21 -0
  17. package/cpp/quickjs/DOMBindingsInternal.cpp +157 -0
  18. package/cpp/quickjs/DOMBindingsInternal.hpp +83 -0
  19. package/cpp/quickjs/MutationObservers.cpp +546 -0
  20. package/cpp/quickjs/MutationObservers.hpp +127 -0
  21. package/cpp/quickjs/QuickJSRuntime.cpp +475 -0
  22. package/cpp/quickjs/QuickJSRuntime.hpp +110 -0
  23. package/cpp/quickjs/Storage.cpp +130 -0
  24. package/cpp/quickjs/Storage.hpp +40 -0
  25. package/cpp/quickjs/bindings/ClassListBindings.cpp +241 -0
  26. package/cpp/quickjs/bindings/ClassListBindings.hpp +29 -0
  27. package/cpp/quickjs/bindings/DatasetBindings.cpp +120 -0
  28. package/cpp/quickjs/bindings/DatasetBindings.hpp +20 -0
  29. package/cpp/quickjs/bindings/DocumentBindings.cpp +155 -0
  30. package/cpp/quickjs/bindings/DocumentBindings.hpp +19 -0
  31. package/cpp/quickjs/bindings/ElementBindings.cpp +1106 -0
  32. package/cpp/quickjs/bindings/ElementBindings.hpp +19 -0
  33. package/cpp/quickjs/bindings/EventBindings.cpp +352 -0
  34. package/cpp/quickjs/bindings/EventBindings.hpp +21 -0
  35. package/cpp/quickjs/bindings/FetchBindings.cpp +347 -0
  36. package/cpp/quickjs/bindings/FetchBindings.hpp +16 -0
  37. package/cpp/quickjs/bindings/StyleBindings.cpp +245 -0
  38. package/cpp/quickjs/bindings/StyleBindings.hpp +22 -0
  39. package/cpp/quickjs/bindings/TimerBindings.cpp +94 -0
  40. package/cpp/quickjs/bindings/TimerBindings.hpp +16 -0
  41. package/cpp/quickjs/bindings/WindowBindings.cpp +211 -0
  42. package/cpp/quickjs/bindings/WindowBindings.hpp +16 -0
  43. package/ios/Bridge.h +8 -0
  44. package/lib/commonjs/classes/JSDOM/JSDOM.class.js +138 -0
  45. package/lib/commonjs/classes/JSDOM/JSDOM.class.js.map +1 -0
  46. package/lib/commonjs/classes/JSDOM/index.js +17 -0
  47. package/lib/commonjs/classes/JSDOM/index.js.map +1 -0
  48. package/lib/commonjs/classes/JSDOM/types/IFetchOptions.js +2 -0
  49. package/lib/commonjs/classes/JSDOM/types/IFetchOptions.js.map +1 -0
  50. package/lib/commonjs/classes/JSDOM/types/IJSDOMOptions.js +6 -0
  51. package/lib/commonjs/classes/JSDOM/types/IJSDOMOptions.js.map +1 -0
  52. package/lib/commonjs/classes/JSDOM/types/index.js +2 -0
  53. package/lib/commonjs/classes/JSDOM/types/index.js.map +1 -0
  54. package/lib/commonjs/classes/index.js +17 -0
  55. package/lib/commonjs/classes/index.js.map +1 -0
  56. package/lib/commonjs/index.js +17 -0
  57. package/lib/commonjs/index.js.map +1 -0
  58. package/lib/commonjs/package.json +1 -0
  59. package/lib/commonjs/specs/HtmlSandbox.nitro.js +6 -0
  60. package/lib/commonjs/specs/HtmlSandbox.nitro.js.map +1 -0
  61. package/lib/module/classes/JSDOM/JSDOM.class.js +133 -0
  62. package/lib/module/classes/JSDOM/JSDOM.class.js.map +1 -0
  63. package/lib/module/classes/JSDOM/index.js +4 -0
  64. package/lib/module/classes/JSDOM/index.js.map +1 -0
  65. package/lib/module/classes/JSDOM/types/IFetchOptions.js +2 -0
  66. package/lib/module/classes/JSDOM/types/IFetchOptions.js.map +1 -0
  67. package/lib/module/classes/JSDOM/types/IJSDOMOptions.js +4 -0
  68. package/lib/module/classes/JSDOM/types/IJSDOMOptions.js.map +1 -0
  69. package/lib/module/classes/JSDOM/types/index.js +2 -0
  70. package/lib/module/classes/JSDOM/types/index.js.map +1 -0
  71. package/lib/module/classes/index.js +4 -0
  72. package/lib/module/classes/index.js.map +1 -0
  73. package/lib/module/index.js +4 -0
  74. package/lib/module/index.js.map +1 -0
  75. package/lib/module/specs/HtmlSandbox.nitro.js +4 -0
  76. package/lib/module/specs/HtmlSandbox.nitro.js.map +1 -0
  77. package/lib/typescript/src/classes/JSDOM/JSDOM.class.d.ts +74 -0
  78. package/lib/typescript/src/classes/JSDOM/JSDOM.class.d.ts.map +1 -0
  79. package/lib/typescript/src/classes/JSDOM/index.d.ts +3 -0
  80. package/lib/typescript/src/classes/JSDOM/index.d.ts.map +1 -0
  81. package/lib/typescript/src/classes/JSDOM/types/IFetchOptions.d.ts +14 -0
  82. package/lib/typescript/src/classes/JSDOM/types/IFetchOptions.d.ts.map +1 -0
  83. package/lib/typescript/src/classes/JSDOM/types/IJSDOMOptions.d.ts +57 -0
  84. package/lib/typescript/src/classes/JSDOM/types/IJSDOMOptions.d.ts.map +1 -0
  85. package/lib/typescript/src/classes/JSDOM/types/index.d.ts +3 -0
  86. package/lib/typescript/src/classes/JSDOM/types/index.d.ts.map +1 -0
  87. package/lib/typescript/src/classes/index.d.ts +2 -0
  88. package/lib/typescript/src/classes/index.d.ts.map +1 -0
  89. package/lib/typescript/src/index.d.ts +2 -0
  90. package/lib/typescript/src/index.d.ts.map +1 -0
  91. package/lib/typescript/src/specs/HtmlSandbox.nitro.d.ts +13 -0
  92. package/lib/typescript/src/specs/HtmlSandbox.nitro.d.ts.map +1 -0
  93. package/nitro.json +26 -0
  94. package/nitrogen/generated/.gitattributes +1 -0
  95. package/nitrogen/generated/android/NitroJsdom+autolinking.cmake +81 -0
  96. package/nitrogen/generated/android/NitroJsdom+autolinking.gradle +27 -0
  97. package/nitrogen/generated/android/NitroJsdomOnLoad.cpp +49 -0
  98. package/nitrogen/generated/android/NitroJsdomOnLoad.hpp +34 -0
  99. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrojsdom/NitroJsdomOnLoad.kt +35 -0
  100. package/nitrogen/generated/ios/NitroJsdom+autolinking.rb +62 -0
  101. package/nitrogen/generated/ios/NitroJsdom-Swift-Cxx-Bridge.cpp +17 -0
  102. package/nitrogen/generated/ios/NitroJsdom-Swift-Cxx-Bridge.hpp +27 -0
  103. package/nitrogen/generated/ios/NitroJsdom-Swift-Cxx-Umbrella.hpp +38 -0
  104. package/nitrogen/generated/ios/NitroJsdomAutolinking.mm +35 -0
  105. package/nitrogen/generated/ios/NitroJsdomAutolinking.swift +16 -0
  106. package/nitrogen/generated/shared/c++/HybridHtmlSandboxSpec.cpp +26 -0
  107. package/nitrogen/generated/shared/c++/HybridHtmlSandboxSpec.hpp +73 -0
  108. package/package.json +131 -0
  109. package/src/classes/JSDOM/JSDOM.class.ts +145 -0
  110. package/src/classes/JSDOM/index.ts +2 -0
  111. package/src/classes/JSDOM/types/IFetchOptions.ts +14 -0
  112. package/src/classes/JSDOM/types/IJSDOMOptions.ts +57 -0
  113. package/src/classes/JSDOM/types/index.ts +2 -0
  114. package/src/classes/index.ts +1 -0
  115. package/src/index.ts +1 -0
  116. package/src/specs/HtmlSandbox.nitro.ts +33 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 salvesoftware
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,63 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "NitroJsdom"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+
13
+ s.platforms = { :ios => min_ios_version_supported, :visionos => 1.0 }
14
+ s.source = { :git => "https://github.com/Salve-Software/react-native-nitro-jsdom.git", :tag => "#{s.version}" }
15
+
16
+ s.source_files = [
17
+ # Implementation (Swift)
18
+ "ios/**/*.{swift}",
19
+ # Autolinking/Registration (Objective-C++)
20
+ "ios/**/*.{m,mm}",
21
+ # Implementation (C++ objects)
22
+ "cpp/**/*.{hpp,cpp}",
23
+ # Third-party: QuickJS
24
+ "packages/quickjs/quickjs.{c,h}",
25
+ "packages/quickjs/libregexp.{c,h}",
26
+ "packages/quickjs/libunicode.{c,h}",
27
+ "packages/quickjs/cutils.{c,h}",
28
+ "packages/quickjs/dtoa.{c,h}",
29
+ "packages/quickjs/*.h",
30
+ # Third-party: Lexbor (explicit per-directory — omits ports/windows_nt)
31
+ "packages/lexbor/source/lexbor/core/*.{c,h}",
32
+ "packages/lexbor/source/lexbor/css/**/*.{c,h}",
33
+ "packages/lexbor/source/lexbor/dom/**/*.{c,h}",
34
+ "packages/lexbor/source/lexbor/encoding/*.{c,h}",
35
+ "packages/lexbor/source/lexbor/html/**/*.{c,h}",
36
+ "packages/lexbor/source/lexbor/ns/*.{c,h}",
37
+ "packages/lexbor/source/lexbor/ports/posix/**/*.{c,h}",
38
+ "packages/lexbor/source/lexbor/punycode/*.{c,h}",
39
+ "packages/lexbor/source/lexbor/selectors/*.{c,h}",
40
+ "packages/lexbor/source/lexbor/tag/*.{c,h}",
41
+ "packages/lexbor/source/lexbor/unicode/*.{c,h}",
42
+ "packages/lexbor/source/lexbor/url/*.{c,h}",
43
+ "packages/lexbor/source/lexbor/utils/*.{c,h}",
44
+ ]
45
+
46
+ s.preserve_paths = ["packages/lexbor/**", "packages/quickjs/**"]
47
+
48
+ s.pod_target_xcconfig = {
49
+ 'HEADER_SEARCH_PATHS' => '"$(PODS_TARGET_SRCROOT)/packages/lexbor/source"',
50
+ # QuickJS headers use -iquote so packages/quickjs/VERSION never shadows <version> (C++20)
51
+ 'USER_HEADER_SEARCH_PATHS' => '"$(PODS_TARGET_SRCROOT)/packages/quickjs"',
52
+ 'GCC_PREPROCESSOR_DEFINITIONS' => 'CONFIG_VERSION=\"2025-09-13\"',
53
+ }
54
+
55
+ s.compiler_flags = '-Wno-implicit-fallthrough -Wno-unused-variable -Wno-sign-compare -Wno-shorten-64-to-32'
56
+
57
+ load 'nitrogen/generated/ios/NitroJsdom+autolinking.rb'
58
+ add_nitrogen_files(s)
59
+
60
+ s.dependency 'React-jsi'
61
+ s.dependency 'React-callinvoker'
62
+ install_modules_dependencies(s)
63
+ end
package/README.md ADDED
@@ -0,0 +1,95 @@
1
+ <p align="center">
2
+ <img src="assets/banner.png" alt="react-native-nitro-jsdom Banner" width="1280" style="border-radius: 20px;">
3
+ </p>
4
+
5
+ <h1 align="center">react-native-nitro-jsdom</h1>
6
+
7
+ <p align="center">
8
+ <strong>A headless HTML/DOM environment for React Native</strong>
9
+ </p>
10
+
11
+ <p align="center">
12
+ <img src="https://img.shields.io/npm/v/@salve-software/react-native-nitro-jsdom.svg?style=flat-square" alt="Version">
13
+ <img src="https://img.shields.io/npm/dm/@salve-software/react-native-nitro-jsdom.svg?style=flat-square" alt="Downloads">
14
+ <img src="https://img.shields.io/badge/React%20Native-0.76+-61dafb?style=flat-square&logo=react" alt="React Native">
15
+ <img src="https://img.shields.io/badge/runtime-Node%2018+-339933?style=flat-square&logo=node.js" alt="Node">
16
+ <img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="License">
17
+ </p>
18
+
19
+ ---
20
+
21
+ React Native has no native equivalent of [jsdom](https://github.com/jsdom/jsdom). When you need to parse an HTML document, manipulate its DOM, or run arbitrary JavaScript inside it, without rendering anything on screen, your only option today is a `WebView`, a visual component that ties your business logic to the UI layer and drags in a full browser engine just to evaluate a script.
22
+
23
+ **react-native-nitro-jsdom** solves this by providing a real, isolated HTML + JS sandbox, powered by [Nitro Modules](https://nitro.margelo.com/), that runs entirely off-screen and off the React tree.
24
+
25
+ ```ts
26
+ import { JSDOM } from 'react-native-nitro-jsdom'
27
+
28
+ const dom = JSDOM.create(`
29
+ <html>
30
+ <body>
31
+ <div id="result">0</div>
32
+ </body>
33
+ </html>
34
+ `)
35
+
36
+ await dom.evaluate(`
37
+ document.getElementById('result').textContent = String(2 + 2)
38
+ `)
39
+
40
+ const value = await dom.evaluate(`document.getElementById('result').textContent`)
41
+ // → "4"
42
+
43
+ dom.dispose()
44
+ ```
45
+
46
+ ## Features
47
+
48
+ - **Headless & off-tree** - no React component, no screen, no UI tree. Parse, mutate, and evaluate HTML entirely off-screen.
49
+ - **Truly isolated runtime** - every `JSDOM.create()` spins up its own QuickJS runtime, not a shared Hermes instance. No leaking globals between sandboxes.
50
+ - **Native HTML parsing** - backed by [Lexbor](https://github.com/lexbor/lexbor), the fastest WHATWG-compliant HTML parser in C99, with zero dependencies.
51
+ - **jsdom-shaped DOM API** - `querySelector`, `textContent`, `dataset`, and more mirror jsdom's DOM shape, though usage differs: everything runs through the async `evaluate()`, not jsdom's synchronous object access.
52
+ - **Synchronous JSI bridge** - powered by Nitro Modules, with direct JSI calls, no bridge, no JSON serialization overhead.
53
+ - **Full memory control** - call `dispose()` to deterministically free the Lexbor document and QuickJS runtime, no waiting on GC.
54
+
55
+ ## Installation
56
+
57
+ ### Requirements
58
+
59
+ | Component | Requirement |
60
+ |-----------|-------------|
61
+ | React Native | 0.76.0 or higher, with the **New Architecture** (Fabric + TurboModules) enabled |
62
+ | Node.js | 18.0.0 or higher |
63
+ | `react-native-nitro-modules` | Required peer dependency |
64
+
65
+ ```bash
66
+ yarn add react-native-nitro-jsdom react-native-nitro-modules
67
+ ```
68
+
69
+ For iOS, install pods:
70
+
71
+ ```bash
72
+ cd ios && pod install && cd ..
73
+ ```
74
+
75
+ For Android, the package auto-links. Run a Gradle sync if needed.
76
+
77
+ See the [Compatibility page](https://salve-software.github.io/react-native-nitro-jsdom/docs/compatibility) for platform details (iOS, Android, visionOS) and Expo notes.
78
+
79
+ ## Usage
80
+
81
+ Full docs, architecture, and API reference: **[salve-software.github.io/react-native-nitro-jsdom](https://salve-software.github.io/react-native-nitro-jsdom)**
82
+
83
+ ## Contributing
84
+
85
+ We welcome contributions! See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup instructions, branch/commit conventions, and the PR process.
86
+
87
+ ## License
88
+
89
+ This project is licensed under the MIT License, see [LICENSE](./LICENSE) for details.
90
+
91
+ ---
92
+
93
+ <p align="center">
94
+ Made by Salve Software
95
+ </p>
@@ -0,0 +1,86 @@
1
+ project(NitroJsdom)
2
+ cmake_minimum_required(VERSION 3.9.0)
3
+
4
+ find_program(CCACHE_FOUND ccache)
5
+ if(CCACHE_FOUND)
6
+ set(CMAKE_C_COMPILER_LAUNCHER ccache)
7
+ set(CMAKE_CXX_COMPILER_LAUNCHER ccache)
8
+ endif()
9
+
10
+ set (PACKAGE_NAME NitroJsdom)
11
+ set (CMAKE_VERBOSE_MAKEFILE ON)
12
+ set (CMAKE_CXX_STANDARD 20)
13
+
14
+ # Enable Raw Props parsing in react-native (for Nitro Views)
15
+ add_compile_options(-DRN_SERIALIZABLE_STATE=1)
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Third-party: Lexbor
19
+ # ---------------------------------------------------------------------------
20
+ set(LEXBOR_BUILD_SHARED OFF CACHE BOOL "" FORCE)
21
+ set(LEXBOR_BUILD_TESTS OFF CACHE BOOL "" FORCE)
22
+ add_subdirectory(${CMAKE_SOURCE_DIR}/../packages/lexbor lexbor_build)
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Third-party: QuickJS
26
+ # ---------------------------------------------------------------------------
27
+ set(QUICKJS_SOURCES
28
+ ${CMAKE_SOURCE_DIR}/../packages/quickjs/quickjs.c
29
+ ${CMAKE_SOURCE_DIR}/../packages/quickjs/libregexp.c
30
+ ${CMAKE_SOURCE_DIR}/../packages/quickjs/libunicode.c
31
+ ${CMAKE_SOURCE_DIR}/../packages/quickjs/cutils.c
32
+ ${CMAKE_SOURCE_DIR}/../packages/quickjs/dtoa.c
33
+ )
34
+
35
+ set_source_files_properties(${QUICKJS_SOURCES} PROPERTIES
36
+ COMPILE_FLAGS "-Wno-implicit-fallthrough -Wno-unused-variable -Wno-sign-compare"
37
+ )
38
+
39
+ # Define C++ library and add all sources
40
+ add_library(${PACKAGE_NAME} SHARED
41
+ src/main/cpp/cpp-adapter.cpp
42
+ ../cpp/HybridHtmlSandbox.cpp
43
+ ../cpp/lexbor/LexborDocument.cpp
44
+ ../cpp/quickjs/QuickJSRuntime.cpp
45
+ ../cpp/quickjs/DOMBindings.cpp
46
+ ../cpp/quickjs/DOMBindingsInternal.cpp
47
+ ../cpp/quickjs/MutationObservers.cpp
48
+ ../cpp/quickjs/Storage.cpp
49
+ ../cpp/quickjs/bindings/ClassListBindings.cpp
50
+ ../cpp/quickjs/bindings/DatasetBindings.cpp
51
+ ../cpp/quickjs/bindings/StyleBindings.cpp
52
+ ../cpp/quickjs/bindings/ElementBindings.cpp
53
+ ../cpp/quickjs/bindings/DocumentBindings.cpp
54
+ ../cpp/quickjs/bindings/EventBindings.cpp
55
+ ../cpp/quickjs/bindings/TimerBindings.cpp
56
+ ../cpp/quickjs/bindings/WindowBindings.cpp
57
+ ../cpp/quickjs/bindings/FetchBindings.cpp
58
+ ${QUICKJS_SOURCES}
59
+ )
60
+
61
+ target_compile_definitions(${PACKAGE_NAME} PRIVATE CONFIG_VERSION="2025-09-13")
62
+
63
+ # Add Nitrogen specs :)
64
+ include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/NitroJsdom+autolinking.cmake)
65
+
66
+ # Set up local includes
67
+ include_directories(
68
+ "src/main/cpp"
69
+ "../cpp"
70
+ "${CMAKE_SOURCE_DIR}/../packages/lexbor/source"
71
+ )
72
+
73
+ # Use -iquote for QuickJS so packages/quickjs/VERSION never shadows <version> (C++20)
74
+ target_compile_options(${PACKAGE_NAME} PRIVATE
75
+ "-iquote${CMAKE_SOURCE_DIR}/../packages/quickjs"
76
+ )
77
+
78
+ find_library(LOG_LIB log)
79
+
80
+ # Link all libraries together
81
+ target_link_libraries(
82
+ ${PACKAGE_NAME}
83
+ ${LOG_LIB}
84
+ android # <-- Android core
85
+ lexbor_static
86
+ )
@@ -0,0 +1,148 @@
1
+ buildscript {
2
+ repositories {
3
+ google()
4
+ mavenCentral()
5
+ }
6
+
7
+ dependencies {
8
+ classpath "com.android.tools.build:gradle:8.8.0"
9
+ }
10
+ }
11
+
12
+ def reactNativeArchitectures() {
13
+ def value = rootProject.getProperties().get("reactNativeArchitectures")
14
+ return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
15
+ }
16
+
17
+ def isNewArchitectureEnabled() {
18
+ return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
19
+ }
20
+
21
+ apply plugin: "com.android.library"
22
+ apply plugin: 'org.jetbrains.kotlin.android'
23
+ apply from: '../nitrogen/generated/android/NitroJsdom+autolinking.gradle'
24
+ apply from: "./fix-prefab.gradle"
25
+
26
+ if (isNewArchitectureEnabled()) {
27
+ apply plugin: "com.facebook.react"
28
+ }
29
+
30
+ def getExtOrDefault(name) {
31
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["NitroJsdom_" + name]
32
+ }
33
+
34
+ def getExtOrIntegerDefault(name) {
35
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["NitroJsdom_" + name]).toInteger()
36
+ }
37
+
38
+ android {
39
+ namespace "com.nitrojsdom"
40
+
41
+ ndkVersion getExtOrDefault("ndkVersion")
42
+ compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
43
+
44
+ defaultConfig {
45
+ minSdkVersion getExtOrIntegerDefault("minSdkVersion")
46
+ targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
47
+ buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
48
+
49
+ externalNativeBuild {
50
+ cmake {
51
+ cppFlags "-frtti -fexceptions -Wall -Wextra -fstack-protector-all"
52
+ arguments "-DANDROID_STL=c++_shared", "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
53
+ abiFilters (*reactNativeArchitectures())
54
+
55
+ buildTypes {
56
+ debug {
57
+ cppFlags "-O1 -g"
58
+ }
59
+ release {
60
+ cppFlags "-O2"
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ externalNativeBuild {
68
+ cmake {
69
+ path "CMakeLists.txt"
70
+ }
71
+ }
72
+
73
+ packagingOptions {
74
+ excludes = [
75
+ "META-INF",
76
+ "META-INF/**",
77
+ "**/libc++_shared.so",
78
+ "**/libfbjni.so",
79
+ "**/libjsi.so",
80
+ "**/libfolly_json.so",
81
+ "**/libfolly_runtime.so",
82
+ "**/libglog.so",
83
+ "**/libhermes.so",
84
+ "**/libhermes-executor-debug.so",
85
+ "**/libhermes_executor.so",
86
+ "**/libreactnative.so",
87
+ "**/libreactnativejni.so",
88
+ "**/libturbomodulejsijni.so",
89
+ "**/libreact_nativemodule_core.so",
90
+ "**/libjscexecutor.so"
91
+ ]
92
+ }
93
+
94
+ buildFeatures {
95
+ buildConfig true
96
+ prefab true
97
+ }
98
+
99
+ buildTypes {
100
+ release {
101
+ minifyEnabled false
102
+ }
103
+ }
104
+
105
+ lintOptions {
106
+ disable "GradleCompatible"
107
+ }
108
+
109
+ compileOptions {
110
+ sourceCompatibility JavaVersion.VERSION_1_8
111
+ targetCompatibility JavaVersion.VERSION_1_8
112
+ }
113
+
114
+ sourceSets {
115
+ main {
116
+ if (isNewArchitectureEnabled()) {
117
+ java.srcDirs += [
118
+ // React Codegen files
119
+ "${project.buildDir}/generated/source/codegen/java"
120
+ ]
121
+ }
122
+ }
123
+ }
124
+ }
125
+
126
+ repositories {
127
+ mavenCentral()
128
+ google()
129
+ }
130
+
131
+
132
+ dependencies {
133
+ // For < 0.71, this will be from the local maven repo
134
+ // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin
135
+ //noinspection GradleDynamicVersion
136
+ implementation "com.facebook.react:react-native:+"
137
+
138
+ // Add a dependency on NitroModules
139
+ implementation project(":react-native-nitro-modules")
140
+ }
141
+
142
+ if (isNewArchitectureEnabled()) {
143
+ react {
144
+ jsRootDir = file("../src/")
145
+ libraryName = "NitroJsdom"
146
+ codegenJavaPackageName = "com.nitrojsdom"
147
+ }
148
+ }
@@ -0,0 +1,51 @@
1
+ tasks.configureEach { task ->
2
+ // Make sure that we generate our prefab publication file only after having built the native library
3
+ // so that not a header publication file, but a full configuration publication will be generated, which
4
+ // will include the .so file
5
+
6
+ def prefabConfigurePattern = ~/^prefab(.+)ConfigurePackage$/
7
+ def matcher = task.name =~ prefabConfigurePattern
8
+ if (matcher.matches()) {
9
+ def variantName = matcher[0][1]
10
+ task.outputs.upToDateWhen { false }
11
+ task.dependsOn("externalNativeBuild${variantName}")
12
+ }
13
+ }
14
+
15
+ afterEvaluate {
16
+ def abis = reactNativeArchitectures()
17
+ rootProject.allprojects.each { proj ->
18
+ if (proj === rootProject) return
19
+
20
+ def dependsOnThisLib = proj.configurations.findAll { it.canBeResolved }.any { config ->
21
+ config.dependencies.any { dep ->
22
+ dep.group == project.group && dep.name == project.name
23
+ }
24
+ }
25
+ if (!dependsOnThisLib && proj != project) return
26
+
27
+ if (!proj.plugins.hasPlugin('com.android.application') && !proj.plugins.hasPlugin('com.android.library')) {
28
+ return
29
+ }
30
+
31
+ def variants = proj.android.hasProperty('applicationVariants') ? proj.android.applicationVariants : proj.android.libraryVariants
32
+ // Touch the prefab_config.json files to ensure that in ExternalNativeJsonGenerator.kt we will re-trigger the prefab CLI to
33
+ // generate a libnameConfig.cmake file that will contain our native library (.so).
34
+ // See this condition: https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:build-system/gradle-core/src/main/java/com/android/build/gradle/tasks/ExternalNativeJsonGenerator.kt;l=207-219?q=createPrefabBuildSystemGlue
35
+ variants.all { variant ->
36
+ def variantName = variant.name
37
+ abis.each { abi ->
38
+ def searchDir = new File(proj.projectDir, ".cxx/${variantName}")
39
+ if (!searchDir.exists()) return
40
+ def matches = []
41
+ searchDir.eachDir { randomDir ->
42
+ def prefabFile = new File(randomDir, "${abi}/prefab_config.json")
43
+ if (prefabFile.exists()) matches << prefabFile
44
+ }
45
+ matches.each { prefabConfig ->
46
+ prefabConfig.setLastModified(System.currentTimeMillis())
47
+ }
48
+ }
49
+ }
50
+ }
51
+ }
@@ -0,0 +1,5 @@
1
+ NitroJsdom_kotlinVersion=2.1.20
2
+ NitroJsdom_minSdkVersion=23
3
+ NitroJsdom_targetSdkVersion=35
4
+ NitroJsdom_compileSdkVersion=34
5
+ NitroJsdom_ndkVersion=27.1.12297006
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,9 @@
1
+ #include <jni.h>
2
+ #include <fbjni/fbjni.h>
3
+ #include "NitroJsdomOnLoad.hpp"
4
+
5
+ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) {
6
+ return facebook::jni::initialize(vm, []() {
7
+ margelo::nitro::nitrojsdom::registerAllNatives();
8
+ });
9
+ }
@@ -0,0 +1,20 @@
1
+ package com.nitrojsdom;
2
+
3
+ import com.facebook.react.bridge.NativeModule;
4
+ import com.facebook.react.bridge.ReactApplicationContext;
5
+ import com.facebook.react.module.model.ReactModuleInfoProvider;
6
+ import com.facebook.react.BaseReactPackage;
7
+ import com.margelo.nitro.nitrojsdom.NitroJsdomOnLoad;
8
+
9
+
10
+ public class NitroJsdomPackage : BaseReactPackage() {
11
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? = null
12
+
13
+ override fun getReactModuleInfoProvider(): ReactModuleInfoProvider = ReactModuleInfoProvider { emptyMap() }
14
+
15
+ companion object {
16
+ init {
17
+ NitroJsdomOnLoad.initializeNative();
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,171 @@
1
+ #include "HybridHtmlSandbox.hpp"
2
+ #include <stdexcept>
3
+ #include <variant>
4
+ #include <optional>
5
+ #include <functional>
6
+ #include <vector>
7
+ #include <string>
8
+ #include <cstdio>
9
+
10
+ namespace margelo::nitro::nitrojsdom {
11
+
12
+ namespace {
13
+ std::string jsonQuote(const std::string& s) {
14
+ std::string out = "\"";
15
+ for (char c : s) {
16
+ switch (c) {
17
+ case '"': out += "\\\""; break;
18
+ case '\\': out += "\\\\"; break;
19
+ case '\n': out += "\\n"; break;
20
+ case '\r': out += "\\r"; break;
21
+ case '\t': out += "\\t"; break;
22
+ default:
23
+ if (static_cast<unsigned char>(c) < 0x20) {
24
+ char buf[8];
25
+ snprintf(buf, sizeof(buf), "\\u%04x", c);
26
+ out += buf;
27
+ } else {
28
+ out += c;
29
+ }
30
+ }
31
+ }
32
+ out += "\"";
33
+ return out;
34
+ }
35
+ } // namespace
36
+
37
+ void HybridHtmlSandbox::initialize(const std::string& html, bool runScripts, const std::string& url) {
38
+ _document = std::make_unique<LexborDocument>();
39
+ _document->parse(html);
40
+
41
+ _runtime = std::make_unique<QuickJSRuntime>();
42
+ _runtime->initialize(url);
43
+ _runtime->bindDocument(_document.get());
44
+
45
+ if (runScripts) {
46
+ for (const auto& script : _document->getScriptContents()) {
47
+ _runtime->evaluate(script);
48
+ }
49
+ }
50
+
51
+ _initialized = true;
52
+ }
53
+
54
+ std::shared_ptr<Promise<std::string>> HybridHtmlSandbox::evaluate(const std::string& script) {
55
+ if (!_initialized) {
56
+ return Promise<std::string>::rejected(
57
+ std::make_exception_ptr(std::runtime_error("HtmlSandbox: call initialize() before evaluate()"))
58
+ );
59
+ }
60
+ return Promise<std::string>::async([this, script]() {
61
+ return _runtime->evaluate(script);
62
+ });
63
+ }
64
+
65
+ std::string HybridHtmlSandbox::serialize() {
66
+ if (!_initialized) return "";
67
+ return _document->serialize();
68
+ }
69
+
70
+ void HybridHtmlSandbox::setConsoleCallback(
71
+ const std::optional<std::variant<nitro::NullType, std::function<void(const std::string& level, const std::vector<std::string>& args)>>>& callback) {
72
+ if (!_runtime) return;
73
+
74
+ if (!callback.has_value()) {
75
+ // No argument provided — clear the callback
76
+ _runtime->setConsoleCallback(nullptr);
77
+ return;
78
+ }
79
+
80
+ const auto& variant = callback.value();
81
+ if (std::holds_alternative<nitro::NullType>(variant)) {
82
+ // Explicit null passed — clear the callback
83
+ _runtime->setConsoleCallback(nullptr);
84
+ } else {
85
+ // A real function was provided
86
+ auto fn = std::get<std::function<void(const std::string&, const std::vector<std::string>&)>>(variant);
87
+ _runtime->setConsoleCallback(
88
+ [fn](std::string level, std::vector<std::string> args) {
89
+ fn(level, args);
90
+ }
91
+ );
92
+ }
93
+ }
94
+
95
+ void HybridHtmlSandbox::setDialogCallbacks(
96
+ const std::optional<std::variant<nitro::NullType, std::function<void(const std::string&)>>>& onAlert,
97
+ const std::optional<std::variant<nitro::NullType, std::function<std::shared_ptr<Promise<bool>>(const std::string&)>>>& onConfirm,
98
+ const std::optional<std::variant<nitro::NullType, std::function<std::shared_ptr<Promise<std::variant<nitro::NullType, std::string>>>(const std::string&, const std::optional<std::string>&)>>>& onPrompt) {
99
+ if (!_runtime) return;
100
+
101
+ // ── onAlert ──────────────────────────────────────────────────────────────────
102
+ if (!onAlert.has_value() || std::holds_alternative<nitro::NullType>(onAlert.value())) {
103
+ _runtime->setAlertCallback(nullptr);
104
+ } else {
105
+ auto fn = std::get<std::function<void(const std::string&)>>(onAlert.value());
106
+ _runtime->setAlertCallback([fn](const std::string& message) {
107
+ fn(message);
108
+ });
109
+ }
110
+
111
+ // ── onConfirm ────────────────────────────────────────────────────────────────
112
+ if (!onConfirm.has_value() || std::holds_alternative<nitro::NullType>(onConfirm.value())) {
113
+ _runtime->setConfirmCallback(nullptr);
114
+ } else {
115
+ auto fn = std::get<std::function<std::shared_ptr<Promise<bool>>(const std::string&)>>(onConfirm.value());
116
+ _runtime->setConfirmCallback([fn](const std::string& message) -> bool {
117
+ try {
118
+ return fn(message)->await().get();
119
+ } catch (...) {
120
+ return false;
121
+ }
122
+ });
123
+ }
124
+
125
+ // ── onPrompt ─────────────────────────────────────────────────────────────────
126
+ if (!onPrompt.has_value() || std::holds_alternative<nitro::NullType>(onPrompt.value())) {
127
+ _runtime->setPromptCallback(nullptr);
128
+ } else {
129
+ using RetType = std::variant<nitro::NullType, std::string>;
130
+ auto fn = std::get<std::function<std::shared_ptr<Promise<RetType>>(const std::string&, const std::optional<std::string>&)>>(onPrompt.value());
131
+ _runtime->setPromptCallback([fn](const std::string& message, const std::optional<std::string>& defaultValue) -> std::optional<std::string> {
132
+ try {
133
+ auto val = fn(message, defaultValue)->await().get();
134
+ if (std::holds_alternative<std::string>(val)) {
135
+ return std::get<std::string>(val);
136
+ }
137
+ return std::nullopt;
138
+ } catch (...) {
139
+ return std::nullopt;
140
+ }
141
+ });
142
+ }
143
+ }
144
+
145
+ void HybridHtmlSandbox::setFetchCallback(
146
+ const std::optional<std::variant<nitro::NullType, std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::string>>>>(const std::string&, const std::string&, const std::string&, const std::optional<std::string>&)>>>& callback) {
147
+ if (!_runtime) return;
148
+
149
+ if (!callback.has_value() || std::holds_alternative<nitro::NullType>(callback.value())) {
150
+ _runtime->setFetchCallback(nullptr);
151
+ return;
152
+ }
153
+
154
+ auto fn = std::get<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::string>>>>(const std::string&, const std::string&, const std::string&, const std::optional<std::string>&)>>(callback.value());
155
+ _runtime->setFetchCallback(
156
+ [fn](const std::string& url, const std::string& method, const std::string& headersJson, const std::optional<std::string>& body) -> std::string {
157
+ try {
158
+ // Outer await(): dispatches the JS callback call itself onto the JS thread and
159
+ // waits for it to return — resolves almost immediately with the inner Promise object.
160
+ // Inner await(): waits for that inner Promise (the real async onFetch() call) to settle.
161
+ return fn(url, method, headersJson, body)->await().get()->await().get();
162
+ } catch (const std::exception& e) {
163
+ return std::string("{\"error\":") + jsonQuote(e.what()) + "}";
164
+ } catch (...) {
165
+ return "{\"error\":\"fetch failed\"}";
166
+ }
167
+ }
168
+ );
169
+ }
170
+
171
+ } // namespace margelo::nitro::nitrojsdom