From 99bb72929f1669e84fe0dc906f8cb4583bb5ec62 Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:32:05 +0800 Subject: [PATCH 1/5] refactor(nitro): generate HybridObject specs with Nitrogen The method table, pure virtual interface, and iOS registration duplicated the TypeScript API, and a missed registerHybridMethod only showed up at runtime. Generate them from the specs so a missing override fails to compile. Result payloads stay handwritten: one task's result type varies, and SmbFileInfo is recursive. - add src/specs and nitrogen/generated; register ReactNativeSmb from the generated autolinking +load instead of OnLoad.mm - move domain structs to SmbModels and take SmbTask off HybridObject; HybridSMB and HybridSmbTask implement the generated specs - keep getResultValue and drainEntries as raw methods, and keep the SmbFileInfo JSIConverter - depend on Nitro 0.37.2, make react-native-nitro-modules an optional peer, and set FOLLY_CFG_NO_COROUTINES while excluding generated Swift from the pod - rerun nitrogen in CI and fail when nitrogen/ drifts --- .github/workflows/ci.yml | 8 + README.md | 2 +- ReactNativeSmb.podspec | 24 +- cpp/ios/OnLoad.mm | 24 - cpp/shared/HybridSMB.cpp | 434 ------------------ cpp/shared/HybridSMB.hpp | 127 ----- cpp/shared/bridge/BridgeMapping.hpp | 12 + cpp/shared/bridge/HybridSMB.cpp | 376 +++++++++++++++ cpp/shared/bridge/HybridSMB.hpp | 114 +++++ cpp/shared/bridge/HybridSmbTask.cpp | 56 +++ cpp/shared/bridge/HybridSmbTask.hpp | 45 ++ cpp/shared/connection/SmbConnection.hpp | 2 +- cpp/shared/core/EntryStream.hpp | 2 +- .../SmbModels.hpp} | 163 +++---- cpp/shared/core/SmbTask.cpp | 34 +- cpp/shared/core/SmbTask.hpp | 10 +- cpp/shared/io/SmbCopyTree.hpp | 2 +- cpp/shared/io/SmbPathUtil.hpp | 2 +- cpp/shared/io/SmbSecurity.hpp | 2 +- cpp/shared/io/SmbSecurityQuery.hpp | 2 +- cpp/shared/io/SmbTreeOps.hpp | 2 +- cpp/shared/io/listing/DirectoryLister.hpp | 2 +- cpp/shared/operators/Operator.hpp | 2 +- .../operators/connection/ConnectOperator.hpp | 2 +- .../connection/ConnectShareOperator.hpp | 2 +- .../connection/InitializeOperator.hpp | 2 +- .../connection/ListSharesOperator.hpp | 2 +- .../operators/listing/GetPathInfoOperator.hpp | 2 +- .../listing/GetSecurityDescriptorOperator.hpp | 2 +- .../listing/ListDirectoryOperator.cpp | 2 +- .../operators/mutate/DeleteItemOperator.cpp | 2 +- example/package-lock.json | 28 +- example/package.json | 2 +- nitro.json | 20 + nitrogen/generated/.gitattributes | 1 + .../android/ReactNativeSmb+autolinking.cmake | 82 ++++ .../android/ReactNativeSmb+autolinking.gradle | 27 ++ .../android/ReactNativeSmbOnLoad.cpp | 49 ++ .../android/ReactNativeSmbOnLoad.hpp | 34 ++ .../margelo/nitro/smb/ReactNativeSmbOnLoad.kt | 35 ++ .../ios/ReactNativeSmb+autolinking.rb | 62 +++ .../ios/ReactNativeSmb-Swift-Cxx-Bridge.cpp | 17 + .../ios/ReactNativeSmb-Swift-Cxx-Bridge.hpp | 27 ++ .../ios/ReactNativeSmb-Swift-Cxx-Umbrella.hpp | 38 ++ .../ios/ReactNativeSmbAutolinking.mm | 35 ++ .../ios/ReactNativeSmbAutolinking.swift | 16 + .../shared/c++/HybridNativeSmbTaskSpec.cpp | 26 ++ .../shared/c++/HybridNativeSmbTaskSpec.hpp | 69 +++ .../shared/c++/HybridReactNativeSmbSpec.cpp | 52 +++ .../shared/c++/HybridReactNativeSmbSpec.hpp | 103 +++++ .../generated/shared/c++/SmbCredentials.hpp | 87 ++++ package-lock.json | 312 ++++++++++++- package.json | 15 +- src/ReactNativeSmb.ts | 270 +---------- src/core/SmbClient.ts | 12 +- src/specs/NativeSmbTask.nitro.ts | 17 + src/specs/ReactNativeSmb.nitro.ts | 55 +++ src/specs/types.ts | 44 ++ src/types.ts | 160 +++---- 59 files changed, 2018 insertions(+), 1140 deletions(-) delete mode 100644 cpp/ios/OnLoad.mm delete mode 100644 cpp/shared/HybridSMB.cpp delete mode 100644 cpp/shared/HybridSMB.hpp create mode 100644 cpp/shared/bridge/BridgeMapping.hpp create mode 100644 cpp/shared/bridge/HybridSMB.cpp create mode 100644 cpp/shared/bridge/HybridSMB.hpp create mode 100644 cpp/shared/bridge/HybridSmbTask.cpp create mode 100644 cpp/shared/bridge/HybridSmbTask.hpp rename cpp/shared/{ReactNativeSmb.hpp => core/SmbModels.hpp} (71%) create mode 100644 nitro.json create mode 100644 nitrogen/generated/.gitattributes create mode 100644 nitrogen/generated/android/ReactNativeSmb+autolinking.cmake create mode 100644 nitrogen/generated/android/ReactNativeSmb+autolinking.gradle create mode 100644 nitrogen/generated/android/ReactNativeSmbOnLoad.cpp create mode 100644 nitrogen/generated/android/ReactNativeSmbOnLoad.hpp create mode 100644 nitrogen/generated/android/kotlin/com/margelo/nitro/smb/ReactNativeSmbOnLoad.kt create mode 100644 nitrogen/generated/ios/ReactNativeSmb+autolinking.rb create mode 100644 nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Bridge.cpp create mode 100644 nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Bridge.hpp create mode 100644 nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Umbrella.hpp create mode 100644 nitrogen/generated/ios/ReactNativeSmbAutolinking.mm create mode 100644 nitrogen/generated/ios/ReactNativeSmbAutolinking.swift create mode 100644 nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.cpp create mode 100644 nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp create mode 100644 nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.cpp create mode 100644 nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp create mode 100644 nitrogen/generated/shared/c++/SmbCredentials.hpp create mode 100644 src/specs/NativeSmbTask.nitro.ts create mode 100644 src/specs/ReactNativeSmb.nitro.ts create mode 100644 src/specs/types.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3882b1..f10cf69 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,6 +40,14 @@ jobs: - name: Install dependencies run: npm ci + - name: Regenerate Nitrogen specs and check committed output + run: | + npx nitrogen + git diff --exit-code nitrogen/ || { + echo "nitrogen/generated is out of date — run npm run specs and commit" + exit 1 + } + - name: Run unit tests run: npm test diff --git a/README.md b/README.md index 703a3a3..c112908 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ SMB client for React Native via [libsmb2](https://github.com/sahlberg/libsmb2) a | -------------------------- | -------------- | | React Native | >= 0.76 | | React | >= 19 | -| react-native-nitro-modules | >= 0.22, < 1.0 | +| react-native-nitro-modules | * (peer; developed against 0.37.2) | | iOS | 12+ | | Android | not yet | diff --git a/ReactNativeSmb.podspec b/ReactNativeSmb.podspec index ebecdfd..e686e8a 100644 --- a/ReactNativeSmb.podspec +++ b/ReactNativeSmb.podspec @@ -16,12 +16,10 @@ Pod::Spec.new do |s| s.source = { :git => "https://github.com/cetapod/react-native-smb.git", :tag => "v#{s.version}" } s.source_files = [ - "cpp/shared/**/*.{cpp,hpp}", - "cpp/ios/**/*.{cpp,hpp,mm,m,h}" + "cpp/shared/**/*.{cpp,hpp}" ] s.header_mappings_dir = "cpp" - # React Native dependencies s.dependency "React" s.dependency "React-Core" s.dependency "NitroModules" @@ -32,18 +30,23 @@ Pod::Spec.new do |s| header == "cpp/shared/io/SmbCopyTree.hpp" || header == "cpp/shared/io/SmbTreeOps.hpp" end - # Compiler settings s.requires_arc = true + # FOLLY_NO_CONFIG skips folly-config.h; under C++20 that turns FOLLY_HAS_COROUTINES + # on unless FOLLY_CFG_NO_COROUTINES is set. ReactNativeDependencies prebuilts omit + # folly/coro headers, so libraries that set FOLLY_NO_CONFIG must also disable coroutines. s.pod_target_xcconfig = { - 'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) FOLLY_NO_CONFIG FOLLY_MOBILE=1 FOLLY_USE_LIBCPP=1', + 'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) FOLLY_NO_CONFIG FOLLY_MOBILE=1 FOLLY_USE_LIBCPP=1 FOLLY_CFG_NO_COROUTINES=1', 'HEADER_SEARCH_PATHS' => [ '$(inherited)', '$(PODS_TARGET_SRCROOT)/cpp', + '$(PODS_TARGET_SRCROOT)/cpp/shared/bridge', + '$(PODS_TARGET_SRCROOT)/nitrogen/generated/shared/c++', + '$(PODS_TARGET_SRCROOT)/nitrogen/generated/ios', '$(PODS_TARGET_SRCROOT)/libsmb2/include', '$(PODS_ROOT)/NitroModules', '$(PODS_ROOT)/Headers/Private/NitroModules' ].join(' '), - 'OTHER_CPLUSPLUSFLAGS' => '$(inherited) -std=c++20 -Wall' + 'OTHER_CPLUSPLUSFLAGS' => '$(inherited) -std=c++20 -Wall -DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -DFOLLY_CFG_NO_COROUTINES=1' } s.user_target_xcconfig = { @@ -55,7 +58,14 @@ Pod::Spec.new do |s| ].join(' ') } - # Modern XCFramework approach - automatically selects correct library s.vendored_frameworks = "ios/libs/libsmb2.xcframework" + # Nitrogen-generated sources + iOS autolinking registration + load 'nitrogen/generated/ios/ReactNativeSmb+autolinking.rb' + add_nitrogen_files(s) + + # HybridObjects are C++-only. Nitrogen still emits Swift scaffolding that + # `import NitroModules`; building that Swift module against RN prebuilt Folly + # fails with missing folly/coro headers. Registration lives in the .mm +load. + s.exclude_files = 'nitrogen/generated/**/*.swift' end diff --git a/cpp/ios/OnLoad.mm b/cpp/ios/OnLoad.mm deleted file mode 100644 index 571fd17..0000000 --- a/cpp/ios/OnLoad.mm +++ /dev/null @@ -1,24 +0,0 @@ -#import -#include -#include - -@interface ReactNativeSmbModuleLoader : NSObject -@end - -@implementation ReactNativeSmbModuleLoader - -+ (void)load { - using namespace react_native_smb; - using namespace margelo::nitro; - - HybridObjectRegistry::registerHybridObjectConstructor( - "ReactNativeSmb", - []() -> std::shared_ptr { - return std::make_shared(); - } - ); - - NSLog(@"ReactNativeSmb module registered"); -} - -@end diff --git a/cpp/shared/HybridSMB.cpp b/cpp/shared/HybridSMB.cpp deleted file mode 100644 index 42c7371..0000000 --- a/cpp/shared/HybridSMB.cpp +++ /dev/null @@ -1,434 +0,0 @@ -#include "HybridSMB.hpp" - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "connection/PoolTypes.hpp" -#include "util/SmbErrorMapper.hpp" -#include "util/SmbException.hpp" -#include "util/SmbLog.hpp" -#include "core/TaskSnapshotCodec.hpp" -#include "operators/connection/ConnectOperator.hpp" -#include "operators/connection/ConnectShareOperator.hpp" -#include "operators/connection/DisconnectOperator.hpp" -#include "operators/connection/InitializeOperator.hpp" -#include "operators/connection/ListSharesOperator.hpp" -#include "operators/listing/GetPathInfoOperator.hpp" -#include "operators/listing/GetSecurityDescriptorOperator.hpp" -#include "operators/listing/ListDirectoryOperator.hpp" -#include "operators/mutate/CopyItemOperator.hpp" -#include "operators/mutate/CreateDirectoryOperator.hpp" -#include "operators/mutate/DeleteItemOperator.hpp" -#include "operators/mutate/DuplicateItemOperator.hpp" -#include "operators/mutate/MoveItemOperator.hpp" -#include "operators/mutate/RenameItemOperator.hpp" -#include "operators/transfer/DownloadFileOperator.hpp" -#include "operators/transfer/UploadFileOperator.hpp" - -namespace react_native_smb { -using namespace margelo::nitro; - -void HybridSMB::releaseTaskRun(const std::shared_ptr& state) { - { - std::lock_guard lock(state->mutex); - --state->active; - } - state->cv.notify_all(); -} - -template -std::shared_ptr HybridSMB::createTask(const std::string& taskId, std::unique_ptr seedOp, ExecutionLane lane) { - std::lock_guard shutdownLock(shutdownMutex_); - if (disposed_.load(std::memory_order_acquire)) { - SmbException::raise(SmbErrorCode::NotConnected, "SMB client has been destroyed"); - } - - auto task = std::make_shared(taskId, std::move(seedOp), pool_); - if (observer_) { - observer_->track(task); - } - { - std::lock_guard lk(tasksMutex_); - tasks_[taskId] = task; - } - - auto taskRuns = taskRuns_; - { - std::lock_guard lock(taskRuns->mutex); - ++taskRuns->active; - } - - auto* self = this; - auto runBody = [self, task, taskId, taskRuns] { - struct RunCompletionGuard { - std::shared_ptr state; - ~RunCompletionGuard() { HybridSMB::releaseTaskRun(state); } - } guard{taskRuns}; - task->start(); - // Drop the live strong ref once the task is terminal so cancel scans stay O(active). - self->forgetTask(taskId); - }; - - try { - if (lane == ExecutionLane::Lifecycle) { - lifecycleExecutor_.post(std::move(runBody)); - } else { - (void)Promise::async(std::move(runBody)); - } - } catch (...) { - releaseTaskRun(taskRuns); - forgetTask(taskId); - throw; - } - - return task; -} - -HybridSMB::HybridSMB() : HybridObject(NAME) { - // 4 parallel SMB connections — each slot is an independent TCP/SMB2 session - // to the same server/user/share. The pool reserves one slot for Interactive - // callers (UI ops) so long Metadata fan-outs (parallel copy/delete/list) cannot - // freeze the UI; see AcquireMode in PoolTypes.hpp. - pool_ = std::make_shared(4, [this](const std::string& taskId) { cancelAllTasksExcept(taskId); }); - observer_ = std::make_unique(); -} - -HybridSMB::~HybridSMB() { - shutdownImpl(); -} - -void HybridSMB::shutdownImpl() { - std::lock_guard shutdownLock(shutdownMutex_); - if (disposed_.exchange(true, std::memory_order_acq_rel)) { - std::unique_lock lock(taskRuns_->mutex); - taskRuns_->cv.wait(lock, [&] { return taskRuns_->active == 0; }); - return; - } - - try { - cancelAllTasksExcept("__destroy__"); - } catch (...) { - } - try { - if (pool_) pool_->disconnect(); - } catch (...) { - } - { - std::unique_lock lock(taskRuns_->mutex); - taskRuns_->cv.wait(lock, [&] { return taskRuns_->active == 0; }); - } - lifecycleExecutor_.shutdown(); -} - -std::shared_ptr> HybridSMB::destroy() { - auto self = shared_cast(); - return Promise::async([self]() { self->shutdownImpl(); }); -} - -void HybridSMB::forgetTask(const std::string& taskId) { - { - std::lock_guard lk(tasksMutex_); - tasks_.erase(taskId); - } - if (observer_) observer_->untrack(taskId); -} - -void HybridSMB::cancelTasksMatching(const std::function&)>& pred) { - std::vector> toCancel; - { - std::lock_guard lock(tasksMutex_); - toCancel.reserve(tasks_.size()); - for (const auto& [id, task] : tasks_) { - if (!task || task->isSettled()) continue; - if (!pred(task)) continue; - toCancel.push_back(task); - } - } - if (!toCancel.empty()) SMB_LOG_INFO("Cancelling %zu pending task(s)", toCancel.size()); - for (const auto& task : toCancel) task->cancel(); -} - -void HybridSMB::cancelAllTasksExcept(const std::string& taskId) { - cancelTasksMatching([&](const std::shared_ptr& task) { return task->getId() != taskId; }); -} - -// --- State Checks --- - -bool HybridSMB::isConnected() { return pool_->isConnected(); } - -bool HybridSMB::isInitialized() { return pool_->isInitialized(); } - -// --- Connection Management --- - -std::shared_ptr HybridSMB::initialize(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) { - return createTask(taskId, std::make_unique(url, credentials), ExecutionLane::Lifecycle); -} - -std::shared_ptr HybridSMB::connect(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) { - return createTask(taskId, std::make_unique(url, credentials), ExecutionLane::Lifecycle); -} - -std::shared_ptr HybridSMB::disconnect(const std::string& taskId) { - return createTask(taskId, std::make_unique(), ExecutionLane::Lifecycle); -} - -std::shared_ptr HybridSMB::listShares(const std::string& taskId) { - return createTask(taskId, std::make_unique()); -} - -std::shared_ptr HybridSMB::connectShare(const std::string& taskId, const std::string& share) { - return createTask(taskId, std::make_unique(share), ExecutionLane::Lifecycle); -} - -// --- Listing & Info --- - -std::shared_ptr HybridSMB::listDirectory(const std::string& taskId, const std::string& path, int maxDepth, bool includeSecurityDescriptor, int batchSize) { - return createTask(taskId, std::make_unique(path, maxDepth, includeSecurityDescriptor, batchSize)); -} - -std::shared_ptr HybridSMB::getPathInfo(const std::string& taskId, const std::string& path) { - return createTask(taskId, std::make_unique(path)); -} - -std::shared_ptr HybridSMB::getSecurityDescriptor(const std::string& taskId, const std::string& path) { - return createTask(taskId, std::make_unique(path)); -} - -// --- File Transfers --- - -std::shared_ptr HybridSMB::downloadFile(const std::string& taskId, const std::string& remotePath, const std::string& localPath) { - return createTask(taskId, std::make_unique(remotePath, localPath)); -} - -std::shared_ptr HybridSMB::uploadFile(const std::string& taskId, const std::string& localPath, const std::string& remotePath) { - return createTask(taskId, std::make_unique(localPath, remotePath)); -} - -// --- Mutating File Operations --- - -std::shared_ptr HybridSMB::createDirectory(const std::string& taskId, const std::string& path) { - return createTask(taskId, std::make_unique(path)); -} - -std::shared_ptr HybridSMB::deleteItem(const std::string& taskId, const std::string& path) { - return createTask(taskId, std::make_unique(path)); -} - -std::shared_ptr HybridSMB::moveItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath) { - return createTask(taskId, std::make_unique(fromPath, toPath)); -} - -std::shared_ptr HybridSMB::renameItem(const std::string& taskId, const std::string& currentPath, const std::string& newName) { - return createTask(taskId, std::make_unique(currentPath, newName)); -} - -std::shared_ptr HybridSMB::copyItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath, bool recursive) { - return createTask(taskId, std::make_unique(fromPath, toPath, recursive)); -} - -std::shared_ptr HybridSMB::duplicateItem(const std::string& taskId, const std::string& path) { - return createTask(taskId, std::make_unique(path)); -} - -void HybridSMB::cancelTask(const std::string& taskId) { - std::shared_ptr task; - { - std::lock_guard lk(tasksMutex_); - auto it = tasks_.find(taskId); - if (it != tasks_.end()) task = it->second; - } - if (task) task->cancel(); -} - -void HybridSMB::cancelTransferTasks() { - cancelTasksMatching([](const std::shared_ptr& task) { return isTransferKind(task->getKind()); }); -} - -void HybridSMB::resetPool() { - if (pool_) pool_->resetPool(); -} - -namespace { - -std::unordered_map encodePoolSlot(const PoolSlotInfo& s) { - std::unordered_map m; - m["poolSize"] = std::to_string(s.poolSize); - m["index"] = std::to_string(s.index); - m["interactiveOnly"] = s.interactiveOnly ? "1" : "0"; - m["state"] = std::to_string(static_cast(s.state)); - m["kind"] = std::to_string(static_cast(s.kind)); - m["isConnected"] = s.isConnected ? "1" : "0"; - m["shareName"] = s.shareName; - m["taskId"] = s.taskId; - return m; -} - -} // namespace - -std::vector> HybridSMB::getPoolInfo() { - std::vector> out; - if (!pool_) return out; - for (const auto& s : pool_->getPoolStatus()) out.push_back(encodePoolSlot(s)); - return out; -} - -std::string HybridSMB::subscribePoolInfo(const std::function>&)>& listener) { - std::string key = std::to_string(poolListenerToken_.fetch_add(1)); - { - std::lock_guard lock(poolListenersMutex_); - poolListeners_.emplace(key, listener); - } - if (pool_) { - size_t obsId = pool_->addObserver([this, key](const std::vector& status) { - std::vector> out; - for (const auto& s : status) out.push_back(encodePoolSlot(s)); - PoolListener cb; - { - std::lock_guard lock(poolListenersMutex_); - auto it = poolListeners_.find(key); - if (it != poolListeners_.end()) cb = it->second; - } - if (cb) { - try { - cb(out); - } catch (...) { - } - } - }); - std::lock_guard lock(poolListenersMutex_); - poolObserverIds_[key] = obsId; - } - return key; -} - -void HybridSMB::unsubscribePoolInfo(const std::string& subscriptionId) { - size_t obsId = 0; - { - std::lock_guard lock(poolListenersMutex_); - auto it = poolObserverIds_.find(subscriptionId); - if (it != poolObserverIds_.end()) { - obsId = it->second; - poolObserverIds_.erase(it); - } - poolListeners_.erase(subscriptionId); - } - if (obsId && pool_) { - pool_->removeObserver(obsId); - } -} - -// --- Task observer APIs --- - -std::string HybridSMB::subscribeTaskEvents(const std::function&)>& listener) { - if (!observer_) return ""; - // The hub forwards snapshots - auto eventId = std::make_shared>(1); - return observer_->subscribeAll([listener, eventId](const SmbTaskState& s) { - std::unordered_map m = TaskSnapshotCodec::encode(s); - m["eventId"] = std::to_string(eventId->fetch_add(1)); - m["type"] = std::to_string(static_cast(s.status)); // status drives event type - m["ts"] = std::to_string(s.updatedAt); - listener(m); - }); -} - -void HybridSMB::unsubscribeTaskEvents(const std::string& subscriptionId) { - if (observer_) observer_->unsubscribe(subscriptionId); -} - -std::unordered_map HybridSMB::getTask(const std::string& taskId) { - if (!observer_) return TaskSnapshotCodec::notFound(); - auto snapshot = observer_->getTask(taskId); - if (!snapshot) return TaskSnapshotCodec::notFound(); - return TaskSnapshotCodec::encode(*snapshot); -} - -std::vector> HybridSMB::getActiveTasks() { - std::vector> out; - if (!observer_) return out; - for (const auto& snapshot : observer_->getActive()) out.push_back(TaskSnapshotCodec::encode(snapshot)); - return out; -} - -std::vector> HybridSMB::getTransferTasks() { - std::vector> out; - if (!observer_) return out; - for (const auto& snapshot : observer_->getTransfers()) out.push_back(TaskSnapshotCodec::encode(snapshot)); - return out; -} - -std::vector> HybridSMB::getTaskHistory(int limit, int offset) { - std::vector> out; - if (!observer_) return out; - const size_t safeLimit = limit < 0 ? 0 : static_cast(limit); - const size_t safeOffset = offset < 0 ? 0 : static_cast(offset); - for (const auto& snapshot : observer_->getHistory(safeLimit, safeOffset)) out.push_back(TaskSnapshotCodec::encode(snapshot)); - return out; -} - -void HybridSMB::clearTaskHistory(int64_t beforeTs) { - if (observer_) observer_->clearHistory(beforeTs); -} - -void HybridSMB::loadHybridMethods() { - // Call parent implementation - HybridObject::loadHybridMethods(); - - // Register methods - registerHybrids(this, [](Prototype& prototype) { - // --- State Checks --- - prototype.registerHybridMethod("isConnected", &HybridSMB::isConnected); - prototype.registerHybridMethod("isInitialized", &HybridSMB::isInitialized); - - // --- Connection Management --- - prototype.registerHybridMethod("initialize", &HybridSMB::initialize); - prototype.registerHybridMethod("connect", &HybridSMB::connect); - prototype.registerHybridMethod("connectShare", &HybridSMB::connectShare); - prototype.registerHybridMethod("disconnect", &HybridSMB::disconnect); - prototype.registerHybridMethod("listShares", &HybridSMB::listShares); - prototype.registerHybridMethod("destroy", &HybridSMB::destroy); - - // --- Listing & Info --- - prototype.registerHybridMethod("listDirectory", &HybridSMB::listDirectory); - prototype.registerHybridMethod("getPathInfo", &HybridSMB::getPathInfo); - prototype.registerHybridMethod("getSecurityDescriptor", &HybridSMB::getSecurityDescriptor); - - // --- File Transfers --- - prototype.registerHybridMethod("downloadFile", &HybridSMB::downloadFile); - prototype.registerHybridMethod("uploadFile", &HybridSMB::uploadFile); - - // --- Mutating File Operations --- - prototype.registerHybridMethod("createDirectory", &HybridSMB::createDirectory); - prototype.registerHybridMethod("deleteItem", &HybridSMB::deleteItem); - prototype.registerHybridMethod("moveItem", &HybridSMB::moveItem); - prototype.registerHybridMethod("renameItem", &HybridSMB::renameItem); - prototype.registerHybridMethod("copyItem", &HybridSMB::copyItem); - prototype.registerHybridMethod("duplicateItem", &HybridSMB::duplicateItem); - - // Task control - prototype.registerHybridMethod("subscribeTaskEvents", &HybridSMB::subscribeTaskEvents); - prototype.registerHybridMethod("unsubscribeTaskEvents", &HybridSMB::unsubscribeTaskEvents); - prototype.registerHybridMethod("getTask", &HybridSMB::getTask); - prototype.registerHybridMethod("getActiveTasks", &HybridSMB::getActiveTasks); - prototype.registerHybridMethod("getTransferTasks", &HybridSMB::getTransferTasks); - prototype.registerHybridMethod("getTaskHistory", &HybridSMB::getTaskHistory); - prototype.registerHybridMethod("cancelTask", &HybridSMB::cancelTask); - prototype.registerHybridMethod("cancelTransferTasks", &HybridSMB::cancelTransferTasks); - prototype.registerHybridMethod("clearTaskHistory", &HybridSMB::clearTaskHistory); - - // Debug / instrumentation - prototype.registerHybridMethod("subscribePoolInfo", &HybridSMB::subscribePoolInfo); - prototype.registerHybridMethod("unsubscribePoolInfo", &HybridSMB::unsubscribePoolInfo); - prototype.registerHybridMethod("getPoolInfo", &HybridSMB::getPoolInfo); - prototype.registerHybridMethod("resetPool", &HybridSMB::resetPool); - }); -} - -} // namespace react_native_smb diff --git a/cpp/shared/HybridSMB.hpp b/cpp/shared/HybridSMB.hpp deleted file mode 100644 index cfa62a6..0000000 --- a/cpp/shared/HybridSMB.hpp +++ /dev/null @@ -1,127 +0,0 @@ -#pragma once - -#include "ReactNativeSmb.hpp" -#include "connection/SmbConnectionPool.hpp" -#include "core/LifecycleSerialExecutor.hpp" -#include "core/SmbTask.hpp" -#include "core/TaskObserverHub.hpp" -#include "operators/OperatorBase.hpp" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace react_native_smb { -using namespace margelo::nitro; - -class HybridSMB : public ReactNativeSmb { - private: - std::shared_ptr pool_; - // Optional observer; tracks every task this instance creates. - std::unique_ptr observer_; - - // Live tasks, kept only so cancelTask/getTask can locate them. - std::map> tasks_; - std::mutex tasksMutex_; - struct TaskRunState { - std::mutex mutex; - std::condition_variable cv; - size_t active{0}; - }; - std::shared_ptr taskRuns_{std::make_shared()}; - LifecycleSerialExecutor lifecycleExecutor_; - std::atomic disposed_{false}; - std::mutex shutdownMutex_; - - void cancelAllTasksExcept(const std::string& taskId); - void cancelTasksMatching(const std::function&)>& pred); - void forgetTask(const std::string& taskId); - void shutdownImpl(); - static void releaseTaskRun(const std::shared_ptr& state); - - using PoolListener = std::function>&)>; - std::map poolListeners_; - std::map poolObserverIds_; - std::mutex poolListenersMutex_; - std::atomic poolListenerToken_{1}; - - // Shared = Nitro Promise::async (general tasks). Lifecycle = dedicated FIFO worker - // for connection transitions so logout/reconnect is not queued behind bulk work. - enum class ExecutionLane { Shared, Lifecycle }; - - // SmbTask factory - template - std::shared_ptr createTask(const std::string& taskId, std::unique_ptr seedOp, ExecutionLane lane = ExecutionLane::Shared); - - - public: - HybridSMB(); - virtual ~HybridSMB(); - - // Implement ReactNativeSmb interface - - // --- State Checks --- - bool isConnected() override; - bool isInitialized() override; - - // --- Connection Management --- - std::shared_ptr initialize(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) override; - std::shared_ptr connect(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) override; - std::shared_ptr connectShare(const std::string& taskId, const std::string& share) override; - std::shared_ptr disconnect(const std::string& taskId) override; - std::shared_ptr listShares(const std::string& taskId) override; - - // --- Listing & Info --- - std::shared_ptr listDirectory(const std::string& taskId, const std::string& path, int maxDepth, bool includeSecurityDescriptor, int batchSize) override; - std::shared_ptr getPathInfo(const std::string& taskId, const std::string& path) override; - std::shared_ptr getSecurityDescriptor(const std::string& taskId, const std::string& path) override; - - // --- File Transfers --- - std::shared_ptr downloadFile(const std::string& taskId, const std::string& remotePath, const std::string& localPath) override; - std::shared_ptr uploadFile(const std::string& taskId, const std::string& localPath, const std::string& remotePath) override; - - // --- Mutating File Operations --- - std::shared_ptr createDirectory(const std::string& taskId, const std::string& path) override; - std::shared_ptr deleteItem(const std::string& taskId, const std::string& path) override; - std::shared_ptr moveItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath) override; - std::shared_ptr renameItem(const std::string& taskId, const std::string& currentPath, const std::string& newName) override; - std::shared_ptr copyItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath, bool recursive) override; - std::shared_ptr duplicateItem(const std::string& taskId, const std::string& path) override; - - // Task control - std::string subscribeTaskEvents(const std::function&)>& listener) override; - void unsubscribeTaskEvents(const std::string& subscriptionId) override; - std::unordered_map getTask(const std::string& taskId) override; - std::vector> getActiveTasks() override; - std::vector> getTransferTasks() override; - std::vector> getTaskHistory(int limit, int offset) override; - void cancelTask(const std::string& taskId) override; - void cancelTransferTasks() override; - void clearTaskHistory(int64_t beforeTs) override; - - std::shared_ptr> destroy() override; - - // Debug / instrumentation - std::string subscribePoolInfo(const std::function>&)>& listener) override; - void unsubscribePoolInfo(const std::string& subscriptionId) override; - std::vector> getPoolInfo() override; - void resetPool() override; - - protected: - void loadHybridMethods() override; -}; - -} // namespace react_native_smb diff --git a/cpp/shared/bridge/BridgeMapping.hpp b/cpp/shared/bridge/BridgeMapping.hpp new file mode 100644 index 0000000..4e0dec0 --- /dev/null +++ b/cpp/shared/bridge/BridgeMapping.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "../core/SmbModels.hpp" +#include "SmbCredentials.hpp" + +namespace margelo::nitro::smb { + +inline react_native_smb::SmbCredentials fromBridge(const SmbCredentials& credentials) { + return react_native_smb::SmbCredentials{credentials.username, credentials.password}; +} + +} // namespace margelo::nitro::smb diff --git a/cpp/shared/bridge/HybridSMB.cpp b/cpp/shared/bridge/HybridSMB.cpp new file mode 100644 index 0000000..6048c62 --- /dev/null +++ b/cpp/shared/bridge/HybridSMB.cpp @@ -0,0 +1,376 @@ +#include "HybridSMB.hpp" + +#include "BridgeMapping.hpp" + +#include +#include +#include + +#include "../connection/PoolTypes.hpp" +#include "../core/TaskSnapshotCodec.hpp" +#include "../operators/connection/ConnectOperator.hpp" +#include "../operators/connection/ConnectShareOperator.hpp" +#include "../operators/connection/DisconnectOperator.hpp" +#include "../operators/connection/InitializeOperator.hpp" +#include "../operators/connection/ListSharesOperator.hpp" +#include "../operators/listing/GetPathInfoOperator.hpp" +#include "../operators/listing/GetSecurityDescriptorOperator.hpp" +#include "../operators/listing/ListDirectoryOperator.hpp" +#include "../operators/mutate/CopyItemOperator.hpp" +#include "../operators/mutate/CreateDirectoryOperator.hpp" +#include "../operators/mutate/DeleteItemOperator.hpp" +#include "../operators/mutate/DuplicateItemOperator.hpp" +#include "../operators/mutate/MoveItemOperator.hpp" +#include "../operators/mutate/RenameItemOperator.hpp" +#include "../operators/transfer/DownloadFileOperator.hpp" +#include "../operators/transfer/UploadFileOperator.hpp" +#include "../util/SmbException.hpp" +#include "../util/SmbLog.hpp" + +namespace margelo::nitro::smb { + +using react_native_smb::SmbTask; +using react_native_smb::SmbTaskState; +using react_native_smb::TaskSnapshotCodec; +using react_native_smb::isTransferKind; +using react_native_smb::PoolSlotInfo; +using react_native_smb::SmbErrorCode; +using react_native_smb::SmbException; + +void HybridSMB::releaseTaskRun(const std::shared_ptr& state) { + { + std::lock_guard lock(state->mutex); + --state->active; + } + state->cv.notify_all(); +} + +template +std::shared_ptr HybridSMB::createTask(const std::string& taskId, std::unique_ptr seedOp, + ExecutionLane lane) { + std::lock_guard shutdownLock(shutdownMutex_); + if (disposed_.load(std::memory_order_acquire)) { + SmbException::raise(SmbErrorCode::NotConnected, "SMB client has been destroyed"); + } + + auto task = std::make_shared(taskId, std::move(seedOp), pool_); + if (observer_) { + observer_->track(task); + } + { + std::lock_guard lk(tasksMutex_); + tasks_[taskId] = task; + } + + auto taskRuns = taskRuns_; + { + std::lock_guard lock(taskRuns->mutex); + ++taskRuns->active; + } + + auto* self = this; + auto runBody = [self, task, taskId, taskRuns] { + struct RunCompletionGuard { + std::shared_ptr state; + ~RunCompletionGuard() { HybridSMB::releaseTaskRun(state); } + } guard{taskRuns}; + task->start(); + self->forgetTask(taskId); + }; + + try { + if (lane == ExecutionLane::Lifecycle) { + lifecycleExecutor_.post(std::move(runBody)); + } else { + (void)Promise::async(std::move(runBody)); + } + } catch (...) { + releaseTaskRun(taskRuns); + forgetTask(taskId); + throw; + } + + return std::make_shared(std::move(task)); +} + +HybridSMB::HybridSMB() : HybridObject(TAG) { + pool_ = std::make_shared(4, [this](const std::string& taskId) { cancelAllTasksExcept(taskId); }); + observer_ = std::make_unique(); +} + +HybridSMB::~HybridSMB() { + shutdownImpl(); +} + +void HybridSMB::shutdownImpl() { + std::lock_guard shutdownLock(shutdownMutex_); + if (disposed_.exchange(true, std::memory_order_acq_rel)) { + std::unique_lock lock(taskRuns_->mutex); + taskRuns_->cv.wait(lock, [&] { return taskRuns_->active == 0; }); + return; + } + + try { + cancelAllTasksExcept("__destroy__"); + } catch (...) { + } + try { + if (pool_) pool_->disconnect(); + } catch (...) { + } + { + std::unique_lock lock(taskRuns_->mutex); + taskRuns_->cv.wait(lock, [&] { return taskRuns_->active == 0; }); + } + lifecycleExecutor_.shutdown(); +} + +// --- lifecycle --- +std::shared_ptr> HybridSMB::destroy() { + auto self = shared_cast(); + return Promise::async([self]() { self->shutdownImpl(); }); +} + +void HybridSMB::forgetTask(const std::string& taskId) { + { + std::lock_guard lk(tasksMutex_); + tasks_.erase(taskId); + } + if (observer_) observer_->untrack(taskId); +} + +void HybridSMB::cancelTasksMatching(const std::function&)>& pred) { + std::vector> toCancel; + { + std::lock_guard lock(tasksMutex_); + toCancel.reserve(tasks_.size()); + for (const auto& [id, task] : tasks_) { + if (!task || task->isSettled()) continue; + if (!pred(task)) continue; + toCancel.push_back(task); + } + } + if (!toCancel.empty()) SMB_LOG_INFO("Cancelling %zu pending task(s)", toCancel.size()); + for (const auto& task : toCancel) task->cancel(); +} + +void HybridSMB::cancelAllTasksExcept(const std::string& taskId) { + cancelTasksMatching([&](const std::shared_ptr& task) { return task->getId() != taskId; }); +} + +// --- state --- +bool HybridSMB::isConnected() { return pool_->isConnected(); } + +bool HybridSMB::isInitialized() { return pool_->isInitialized(); } + +// --- connection --- +std::shared_ptr HybridSMB::initialize(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) { + return createTask(taskId, std::make_unique(url, fromBridge(credentials)), ExecutionLane::Lifecycle); +} + +std::shared_ptr HybridSMB::connect(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) { + return createTask(taskId, std::make_unique(url, fromBridge(credentials)), ExecutionLane::Lifecycle); +} + +std::shared_ptr HybridSMB::disconnect(const std::string& taskId) { + return createTask(taskId, std::make_unique(), ExecutionLane::Lifecycle); +} + +std::shared_ptr HybridSMB::listShares(const std::string& taskId) { + return createTask(taskId, std::make_unique()); +} + +std::shared_ptr HybridSMB::connectShare(const std::string& taskId, const std::string& share) { + return createTask(taskId, std::make_unique(share), ExecutionLane::Lifecycle); +} + +// --- listing --- +std::shared_ptr HybridSMB::listDirectory(const std::string& taskId, const std::string& path, double maxDepth, bool includeSecurityDescriptor, double batchSize) { + return createTask(taskId, std::make_unique(path, static_cast(maxDepth), includeSecurityDescriptor, static_cast(batchSize))); +} + +std::shared_ptr HybridSMB::getPathInfo(const std::string& taskId, const std::string& path) { + return createTask(taskId, std::make_unique(path)); +} + +std::shared_ptr HybridSMB::getSecurityDescriptor(const std::string& taskId, const std::string& path) { + return createTask(taskId, std::make_unique(path)); +} + +// --- transfer --- +std::shared_ptr HybridSMB::downloadFile(const std::string& taskId, const std::string& remotePath, const std::string& localPath) { + return createTask(taskId, std::make_unique(remotePath, localPath)); +} + +std::shared_ptr HybridSMB::uploadFile(const std::string& taskId, const std::string& localPath, const std::string& remotePath) { + return createTask(taskId, std::make_unique(localPath, remotePath)); +} + +// --- mutate --- +std::shared_ptr HybridSMB::createDirectory(const std::string& taskId, const std::string& path) { + return createTask(taskId, std::make_unique(path)); +} + +std::shared_ptr HybridSMB::deleteItem(const std::string& taskId, const std::string& path) { + return createTask(taskId, std::make_unique(path)); +} + +std::shared_ptr HybridSMB::moveItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath) { + return createTask(taskId, std::make_unique(fromPath, toPath)); +} + +std::shared_ptr HybridSMB::renameItem(const std::string& taskId, const std::string& currentPath, const std::string& newName) { + return createTask(taskId, std::make_unique(currentPath, newName)); +} + +std::shared_ptr HybridSMB::copyItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath, bool recursive) { + return createTask(taskId, std::make_unique(fromPath, toPath, recursive)); +} + +std::shared_ptr HybridSMB::duplicateItem(const std::string& taskId, const std::string& path) { + return createTask(taskId, std::make_unique(path)); +} + +// --- tasks --- +void HybridSMB::cancelTask(const std::string& taskId) { + std::shared_ptr task; + { + std::lock_guard lk(tasksMutex_); + auto it = tasks_.find(taskId); + if (it != tasks_.end()) task = it->second; + } + if (task) task->cancel(); +} + +void HybridSMB::cancelTransferTasks() { + cancelTasksMatching([](const std::shared_ptr& task) { return isTransferKind(task->getKind()); }); +} + +// --- pool --- +void HybridSMB::resetPool() { + if (pool_) pool_->resetPool(); +} + +namespace { + +std::unordered_map encodePoolSlot(const PoolSlotInfo& s) { + std::unordered_map m; + m["poolSize"] = std::to_string(s.poolSize); + m["index"] = std::to_string(s.index); + m["interactiveOnly"] = s.interactiveOnly ? "1" : "0"; + m["state"] = std::to_string(static_cast(s.state)); + m["kind"] = std::to_string(static_cast(s.kind)); + m["isConnected"] = s.isConnected ? "1" : "0"; + m["shareName"] = s.shareName; + m["taskId"] = s.taskId; + return m; +} + +} // namespace + +std::vector> HybridSMB::getPoolInfo() { + std::vector> out; + if (!pool_) return out; + for (const auto& s : pool_->getPoolStatus()) out.push_back(encodePoolSlot(s)); + return out; +} + +std::string HybridSMB::subscribePoolInfo(const std::function>&)>& listener) { + std::string key = std::to_string(poolListenerToken_.fetch_add(1)); + { + std::lock_guard lock(poolListenersMutex_); + poolListeners_.emplace(key, listener); + } + if (pool_) { + size_t obsId = pool_->addObserver([this, key](const std::vector& status) { + std::vector> out; + for (const auto& s : status) out.push_back(encodePoolSlot(s)); + PoolListener cb; + { + std::lock_guard lock(poolListenersMutex_); + auto it = poolListeners_.find(key); + if (it != poolListeners_.end()) cb = it->second; + } + if (cb) { + try { + cb(out); + } catch (...) { + } + } + }); + std::lock_guard lock(poolListenersMutex_); + poolObserverIds_[key] = obsId; + } + return key; +} + +void HybridSMB::unsubscribePoolInfo(const std::string& subscriptionId) { + size_t obsId = 0; + { + std::lock_guard lock(poolListenersMutex_); + auto it = poolObserverIds_.find(subscriptionId); + if (it != poolObserverIds_.end()) { + obsId = it->second; + poolObserverIds_.erase(it); + } + poolListeners_.erase(subscriptionId); + } + if (obsId && pool_) { + pool_->removeObserver(obsId); + } +} + +// --- tasks --- +std::string HybridSMB::subscribeTaskEvents(const std::function&)>& listener) { + if (!observer_) return ""; + auto eventId = std::make_shared>(1); + return observer_->subscribeAll([listener, eventId](const SmbTaskState& s) { + std::unordered_map m = TaskSnapshotCodec::encode(s); + m["eventId"] = std::to_string(eventId->fetch_add(1)); + m["type"] = std::to_string(static_cast(s.status)); + m["ts"] = std::to_string(s.updatedAt); + listener(m); + }); +} + +void HybridSMB::unsubscribeTaskEvents(const std::string& subscriptionId) { + if (observer_) observer_->unsubscribe(subscriptionId); +} + +std::unordered_map HybridSMB::getTask(const std::string& taskId) { + if (!observer_) return TaskSnapshotCodec::notFound(); + auto snapshot = observer_->getTask(taskId); + if (!snapshot) return TaskSnapshotCodec::notFound(); + return TaskSnapshotCodec::encode(*snapshot); +} + +std::vector> HybridSMB::getActiveTasks() { + std::vector> out; + if (!observer_) return out; + for (const auto& snapshot : observer_->getActive()) out.push_back(TaskSnapshotCodec::encode(snapshot)); + return out; +} + +std::vector> HybridSMB::getTransferTasks() { + std::vector> out; + if (!observer_) return out; + for (const auto& snapshot : observer_->getTransfers()) out.push_back(TaskSnapshotCodec::encode(snapshot)); + return out; +} + +std::vector> HybridSMB::getTaskHistory(double limit, double offset) { + std::vector> out; + if (!observer_) return out; + const int limitInt = static_cast(limit); + const int offsetInt = static_cast(offset); + const size_t safeLimit = limitInt < 0 ? 0 : static_cast(limitInt); + const size_t safeOffset = offsetInt < 0 ? 0 : static_cast(offsetInt); + for (const auto& snapshot : observer_->getHistory(safeLimit, safeOffset)) out.push_back(TaskSnapshotCodec::encode(snapshot)); + return out; +} + +void HybridSMB::clearTaskHistory(int64_t beforeTs) { + if (observer_) observer_->clearHistory(beforeTs); +} + +} // namespace margelo::nitro::smb diff --git a/cpp/shared/bridge/HybridSMB.hpp b/cpp/shared/bridge/HybridSMB.hpp new file mode 100644 index 0000000..ed22547 --- /dev/null +++ b/cpp/shared/bridge/HybridSMB.hpp @@ -0,0 +1,114 @@ +#pragma once + +#include "HybridReactNativeSmbSpec.hpp" +#include "HybridSmbTask.hpp" + +#include "../connection/SmbConnectionPool.hpp" +#include "../core/LifecycleSerialExecutor.hpp" +#include "../core/SmbTask.hpp" +#include "../core/TaskObserverHub.hpp" +#include "../operators/OperatorBase.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace margelo::nitro::smb { + +class HybridSMB : public HybridReactNativeSmbSpec { + private: + std::shared_ptr pool_; + std::unique_ptr observer_; + + std::map> tasks_; + std::mutex tasksMutex_; + struct TaskRunState { + std::mutex mutex; + std::condition_variable cv; + size_t active{0}; + }; + std::shared_ptr taskRuns_{std::make_shared()}; + react_native_smb::LifecycleSerialExecutor lifecycleExecutor_; + std::atomic disposed_{false}; + std::mutex shutdownMutex_; + + void cancelAllTasksExcept(const std::string& taskId); + void cancelTasksMatching(const std::function&)>& pred); + void forgetTask(const std::string& taskId); + void shutdownImpl(); + static void releaseTaskRun(const std::shared_ptr& state); + + using PoolListener = std::function>&)>; + std::map poolListeners_; + std::map poolObserverIds_; + std::mutex poolListenersMutex_; + std::atomic poolListenerToken_{1}; + + enum class ExecutionLane { Shared, Lifecycle }; + + template + std::shared_ptr createTask(const std::string& taskId, std::unique_ptr seedOp, + ExecutionLane lane = ExecutionLane::Shared); + + public: + HybridSMB(); + ~HybridSMB() override; + + // --- state --- + bool isConnected() override; + bool isInitialized() override; + + // --- connection --- + std::shared_ptr initialize(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) override; + std::shared_ptr connect(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) override; + std::shared_ptr connectShare(const std::string& taskId, const std::string& share) override; + std::shared_ptr disconnect(const std::string& taskId) override; + std::shared_ptr listShares(const std::string& taskId) override; + + // --- listing --- + std::shared_ptr listDirectory(const std::string& taskId, const std::string& path, double maxDepth, bool includeSecurityDescriptor, double batchSize) override; + std::shared_ptr getPathInfo(const std::string& taskId, const std::string& path) override; + std::shared_ptr getSecurityDescriptor(const std::string& taskId, const std::string& path) override; + + // --- transfer --- + std::shared_ptr downloadFile(const std::string& taskId, const std::string& remotePath, const std::string& localPath) override; + std::shared_ptr uploadFile(const std::string& taskId, const std::string& localPath, const std::string& remotePath) override; + + // --- mutate --- + std::shared_ptr createDirectory(const std::string& taskId, const std::string& path) override; + std::shared_ptr deleteItem(const std::string& taskId, const std::string& path) override; + std::shared_ptr moveItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath) override; + std::shared_ptr renameItem(const std::string& taskId, const std::string& currentPath, const std::string& newName) override; + std::shared_ptr copyItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath, bool recursive) override; + std::shared_ptr duplicateItem(const std::string& taskId, const std::string& path) override; + + // --- tasks --- + std::string subscribeTaskEvents(const std::function&)>& listener) override; + void unsubscribeTaskEvents(const std::string& subscriptionId) override; + std::unordered_map getTask(const std::string& taskId) override; + std::vector> getActiveTasks() override; + std::vector> getTransferTasks() override; + std::vector> getTaskHistory(double limit, double offset) override; + void cancelTask(const std::string& taskId) override; + void cancelTransferTasks() override; + void clearTaskHistory(int64_t beforeTs) override; + + // --- lifecycle --- + std::shared_ptr> destroy() override; + + // --- pool --- + std::string subscribePoolInfo(const std::function>&)>& listener) override; + void unsubscribePoolInfo(const std::string& subscriptionId) override; + std::vector> getPoolInfo() override; + void resetPool() override; +}; + +} // namespace margelo::nitro::smb diff --git a/cpp/shared/bridge/HybridSmbTask.cpp b/cpp/shared/bridge/HybridSmbTask.cpp new file mode 100644 index 0000000..b7dbe78 --- /dev/null +++ b/cpp/shared/bridge/HybridSmbTask.cpp @@ -0,0 +1,56 @@ +#include "HybridSmbTask.hpp" + +#include + +#include "../core/SmbModels.hpp" +#include "../core/SmbTask.hpp" + +namespace margelo::nitro::smb { + +HybridSmbTask::HybridSmbTask(std::shared_ptr task) + : HybridObject(TAG), task_(std::move(task)) { + if (!task_) { + throw std::invalid_argument("HybridSmbTask requires a non-null SmbTask"); + } +} + +void HybridSmbTask::cancel() { task_->cancel(); } + +std::unordered_map HybridSmbTask::get() { return task_->get(); } + +std::string HybridSmbTask::subscribe(const std::function&)>& listener) { + return task_->subscribeMap(listener); +} + +void HybridSmbTask::unsubscribe(const std::string& subscriptionId) { task_->unsubscribe(subscriptionId); } + +std::string HybridSmbTask::subscribeEntries(const std::function& listener) { + return task_->subscribeEntries(listener); +} + +void HybridSmbTask::unsubscribeEntries(const std::string& subscriptionId) { task_->unsubscribeEntries(subscriptionId); } + +facebook::jsi::Value HybridSmbTask::getResultValueRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& /*thisValue*/, + const facebook::jsi::Value* /*args*/, size_t /*count*/) { + return task_->getResultValue(runtime); +} + +facebook::jsi::Value HybridSmbTask::drainEntriesRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& /*thisValue*/, + const facebook::jsi::Value* args, size_t count) { + if (count < 1 || !args[0].isString()) { + throw facebook::jsi::JSError(runtime, "drainEntries(subscriptionId: string) requires a string argument"); + } + const std::string subscriptionId = args[0].asString(runtime).utf8(runtime); + auto entries = task_->drainEntries(subscriptionId); + return JSIConverter>::toJSI(runtime, entries); +} + +void HybridSmbTask::loadHybridMethods() { + HybridNativeSmbTaskSpec::loadHybridMethods(); + registerHybrids(this, [](Prototype& prototype) { + prototype.registerRawHybridMethod("getResultValue", 0, &HybridSmbTask::getResultValueRaw); + prototype.registerRawHybridMethod("drainEntries", 1, &HybridSmbTask::drainEntriesRaw); + }); +} + +} // namespace margelo::nitro::smb diff --git a/cpp/shared/bridge/HybridSmbTask.hpp b/cpp/shared/bridge/HybridSmbTask.hpp new file mode 100644 index 0000000..a464877 --- /dev/null +++ b/cpp/shared/bridge/HybridSmbTask.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include "HybridNativeSmbTaskSpec.hpp" + +#include +#include +#include +#include + +namespace react_native_smb { +class SmbTask; +} + +namespace margelo::nitro::smb { + +/** + * Nitro adapter around domain SmbTask. + * Typed Hybrid methods come from HybridNativeSmbTaskSpec. + * getResultValue / drainEntries are registered as raw JSI methods. + */ +class HybridSmbTask : public HybridNativeSmbTaskSpec { + public: + explicit HybridSmbTask(std::shared_ptr task); + ~HybridSmbTask() override = default; + + void cancel() override; + std::unordered_map get() override; + std::string subscribe(const std::function&)>& listener) override; + void unsubscribe(const std::string& subscriptionId) override; + std::string subscribeEntries(const std::function& listener) override; + void unsubscribeEntries(const std::string& subscriptionId) override; + + protected: + void loadHybridMethods() override; + + private: + std::shared_ptr task_; + + facebook::jsi::Value getResultValueRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& thisValue, + const facebook::jsi::Value* args, size_t count); + facebook::jsi::Value drainEntriesRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& thisValue, + const facebook::jsi::Value* args, size_t count); +}; + +} // namespace margelo::nitro::smb diff --git a/cpp/shared/connection/SmbConnection.hpp b/cpp/shared/connection/SmbConnection.hpp index 7d53034..df1f5c6 100644 --- a/cpp/shared/connection/SmbConnection.hpp +++ b/cpp/shared/connection/SmbConnection.hpp @@ -1,6 +1,6 @@ #pragma once -#include "../ReactNativeSmb.hpp" +#include "../core/SmbModels.hpp" #include "../util/SmbErrorMapper.hpp" #include "ServerCapabilities.hpp" diff --git a/cpp/shared/core/EntryStream.hpp b/cpp/shared/core/EntryStream.hpp index 62f0307..c0c5bd1 100644 --- a/cpp/shared/core/EntryStream.hpp +++ b/cpp/shared/core/EntryStream.hpp @@ -7,7 +7,7 @@ #include #include -#include "../ReactNativeSmb.hpp" // SmbFileInfo +#include "../core/SmbModels.hpp" namespace react_native_smb { diff --git a/cpp/shared/ReactNativeSmb.hpp b/cpp/shared/core/SmbModels.hpp similarity index 71% rename from cpp/shared/ReactNativeSmb.hpp rename to cpp/shared/core/SmbModels.hpp index 7aa56f9..b2cffd8 100644 --- a/cpp/shared/ReactNativeSmb.hpp +++ b/cpp/shared/core/SmbModels.hpp @@ -1,21 +1,12 @@ -#include #pragma once -#include #include -#include -#include +#include #include #include #include -#include "core/SmbTask.hpp" - namespace react_native_smb { -using namespace margelo::nitro; - -using SmbStatusCallback = std::function; -using SmbProgressCallback = std::function; struct SmbCredentials { std::string username; @@ -35,12 +26,10 @@ struct SmbConnectionInfo { }; struct SmbAce { - std::string aceType; // Type of ACE (e.g., "ACCESS_ALLOWED_ACE", - // "ACCESS_DENIED_ACE") - std::vector aceFlags; // Flags for the ACE (e.g., - // "INHERIT_ONLY", "NO_PROPAGATE_INHERIT") - std::vector mask; // Access mask (e.g., "READ", "WRITE", "EXECUTE") - std::string sid; // Security Identifier + std::string aceType; + std::vector aceFlags; + std::vector mask; + std::string sid; }; struct SmbAcl { @@ -62,73 +51,20 @@ struct SmbFileInfo { std::string path; int64_t size; bool isDirectory; - int64_t modifiedAt; // Content modification time (smb2_mtime) - int64_t accessedAt; // Last access time (smb2_atime) - int64_t createdAt; // Creation time (smb2_btime) - int64_t changedAt; // Attribute change time (smb2_ctime) - int64_t childCount; // Directories: number of immediate children; -1 if unknown / not a directory - std::vector children; // Nested children for directories (when maxDepth != 0) + int64_t modifiedAt; + int64_t accessedAt; + int64_t createdAt; + int64_t changedAt; + int64_t childCount; // -1 if unknown / not a directory + std::vector children; std::optional securityDescriptor; }; -class ReactNativeSmb : public virtual HybridObject { - public: - virtual ~ReactNativeSmb() = default; - - virtual bool isConnected() = 0; - virtual bool isInitialized() = 0; - - // --- Connection Management --- - virtual std::shared_ptr initialize(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) = 0; - virtual std::shared_ptr connect(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) = 0; - virtual std::shared_ptr connectShare(const std::string& taskId, const std::string& share) = 0; - virtual std::shared_ptr disconnect(const std::string& taskId) = 0; - virtual std::shared_ptr listShares(const std::string& taskId) = 0; - - // --- Listing & Info --- - virtual std::shared_ptr listDirectory(const std::string& taskId, const std::string& path, int maxDepth, bool includeSecurityDescriptor, int batchSize) = 0; - virtual std::shared_ptr getPathInfo(const std::string& taskId, const std::string& path) = 0; - virtual std::shared_ptr getSecurityDescriptor(const std::string& taskId, const std::string& path) = 0; - - // --- File Transfers --- - virtual std::shared_ptr downloadFile(const std::string& taskId, const std::string& remotePath, const std::string& localPath) = 0; - virtual std::shared_ptr uploadFile(const std::string& taskId, const std::string& localPath, const std::string& remotePath) = 0; - - // --- Mutating File Operations --- - virtual std::shared_ptr createDirectory(const std::string& taskId, const std::string& path) = 0; - virtual std::shared_ptr deleteItem(const std::string& taskId, const std::string& path) = 0; - virtual std::shared_ptr moveItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath) = 0; - virtual std::shared_ptr renameItem(const std::string& taskId, const std::string& currentPath, const std::string& newName) = 0; - virtual std::shared_ptr copyItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath, bool recursive) = 0; - virtual std::shared_ptr duplicateItem(const std::string& taskId, const std::string& path) = 0; - - // --- Task control & Task Center APIs --- - virtual std::string subscribeTaskEvents(const std::function&)>& listener) = 0; - virtual void unsubscribeTaskEvents(const std::string& subscriptionId) = 0; - virtual std::unordered_map getTask(const std::string& taskId) = 0; - virtual std::vector> getActiveTasks() = 0; - virtual std::vector> getTransferTasks() = 0; - virtual std::vector> getTaskHistory(int limit, int offset) = 0; - virtual void cancelTask(const std::string& taskId) = 0; - // Cancels unsettled download/upload/copy/duplicate tasks only. - virtual void cancelTransferTasks() = 0; - virtual void clearTaskHistory(int64_t beforeTs) = 0; - - // Tear down the client (cancel tasks, disconnect pool, wait workers). Not reusable. - virtual std::shared_ptr> destroy() = 0; - - // Debug / instrumentation - virtual std::string subscribePoolInfo(const std::function>&)>& listener) = 0; - virtual void unsubscribePoolInfo(const std::string& subscriptionId) = 0; - virtual std::vector> getPoolInfo() = 0; - virtual void resetPool() = 0; - - protected: - static constexpr auto NAME = "ReactNativeSmb"; -}; - } // namespace react_native_smb +// Hand-written JSIConverters for domain result types. +// SmbFileInfo is recursive — Nitrogen 0.37.2 cannot generate it. +// Other result structs are returned via raw getResultValue, not Nitrogen method tables. namespace margelo::nitro { using namespace react_native_smb; @@ -150,17 +86,17 @@ struct JSIConverter { if (!value.isObject()) { throw std::invalid_argument("SmbCredentials must be an object"); } - jsi::Object obj = value.asObject(runtime); SmbCredentials credentials; - credentials.username = obj.getProperty(runtime, "username").asString(runtime).utf8(runtime); credentials.password = obj.getProperty(runtime, "password").asString(runtime).utf8(runtime); - return credentials; } - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { return value.isObject(); } + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } }; template <> @@ -178,13 +114,17 @@ struct JSIConverter { if (!value.isObject()) { throw std::invalid_argument("SmbConnectionInfo must be an object"); } - jsi::Object obj = value.asObject(runtime); - return SmbConnectionInfo{obj.getProperty(runtime, "url").asString(runtime).utf8(runtime), obj.getProperty(runtime, "server").asString(runtime).utf8(runtime), - obj.getProperty(runtime, "share").asString(runtime).utf8(runtime), obj.getProperty(runtime, "isConnected").asBool()}; + return SmbConnectionInfo{obj.getProperty(runtime, "url").asString(runtime).utf8(runtime), + obj.getProperty(runtime, "server").asString(runtime).utf8(runtime), + obj.getProperty(runtime, "share").asString(runtime).utf8(runtime), + obj.getProperty(runtime, "isConnected").asBool()}; } - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { return value.isObject(); } + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } }; template <> @@ -229,10 +169,8 @@ struct JSIConverter { jsi::Array childrenArray = childrenValue.asObject(runtime).asArray(runtime); size_t childrenCount = childrenArray.size(runtime); children.reserve(childrenCount); - for (size_t i = 0; i < childrenCount; i++) { - jsi::Value childValue = childrenArray.getValueAtIndex(runtime, i); - children.push_back(fromJSI(runtime, childValue)); + children.push_back(fromJSI(runtime, childrenArray.getValueAtIndex(runtime, i))); } } } @@ -253,12 +191,15 @@ struct JSIConverter { static_cast(obj.hasProperty(runtime, "accessedAt") ? obj.getProperty(runtime, "accessedAt").asNumber() : 0), static_cast(obj.hasProperty(runtime, "createdAt") ? obj.getProperty(runtime, "createdAt").asNumber() : 0), static_cast(obj.hasProperty(runtime, "changedAt") ? obj.getProperty(runtime, "changedAt").asNumber() : 0), - static_cast(obj.hasProperty(runtime, "childCount") ? obj.getProperty(runtime, "childCount").asNumber() : -1), - children, - securityDescriptor}; + static_cast(obj.hasProperty(runtime, "childCount") ? obj.getProperty(runtime, "childCount").asNumber() : -1), + children, + securityDescriptor}; } - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { return value.isObject(); } + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } }; template <> @@ -274,12 +215,15 @@ struct JSIConverter { if (!value.isObject()) { throw std::invalid_argument("SmbShare must be an object"); } - jsi::Object obj = value.asObject(runtime); - return SmbShare{obj.getProperty(runtime, "name").asString(runtime).utf8(runtime), obj.getProperty(runtime, "comment").asString(runtime).utf8(runtime)}; + return SmbShare{obj.getProperty(runtime, "name").asString(runtime).utf8(runtime), + obj.getProperty(runtime, "comment").asString(runtime).utf8(runtime)}; } - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { return value.isObject(); } + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } }; template <> @@ -311,7 +255,6 @@ struct JSIConverter { jsi::Object obj = value.asObject(runtime); SmbAce ace; - ace.aceType = obj.getProperty(runtime, "aceType").asString(runtime).utf8(runtime); if (obj.hasProperty(runtime, "aceFlags")) { @@ -320,7 +263,6 @@ struct JSIConverter { jsi::Array aceFlagsArray = aceFlagsValue.asObject(runtime).asArray(runtime); size_t flagsCount = aceFlagsArray.size(runtime); ace.aceFlags.reserve(flagsCount); - for (size_t i = 0; i < flagsCount; i++) { jsi::Value flagItem = aceFlagsArray.getValueAtIndex(runtime, i); if (flagItem.isString()) { @@ -336,7 +278,6 @@ struct JSIConverter { jsi::Array maskArray = maskValue.asObject(runtime).asArray(runtime); size_t maskCount = maskArray.size(runtime); ace.mask.reserve(maskCount); - for (size_t i = 0; i < maskCount; i++) { jsi::Value maskItem = maskArray.getValueAtIndex(runtime, i); if (maskItem.isString()) { @@ -347,11 +288,13 @@ struct JSIConverter { } ace.sid = obj.getProperty(runtime, "sid").asString(runtime).utf8(runtime); - return ace; } - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { return value.isObject(); } + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } }; template <> @@ -366,7 +309,6 @@ struct JSIConverter { aces.setValueAtIndex(runtime, i, JSIConverter::toJSI(runtime, acl.aces[i])); } obj.setProperty(runtime, "aces", aces); - return obj; } @@ -384,17 +326,18 @@ struct JSIConverter { jsi::Array aces = obj.getProperty(runtime, "aces").asObject(runtime).asArray(runtime); size_t aceCount = aces.size(runtime); acl.aces.reserve(aceCount); - for (size_t i = 0; i < aceCount; i++) { - jsi::Value aceValue = aces.getValueAtIndex(runtime, i); - acl.aces.push_back(JSIConverter::fromJSI(runtime, aceValue)); + acl.aces.push_back(JSIConverter::fromJSI(runtime, aces.getValueAtIndex(runtime, i))); } } return acl; } - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { return value.isObject(); } + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } }; template <> @@ -422,7 +365,6 @@ struct JSIConverter { jsi::Object obj = value.asObject(runtime); SmbSecurityDescriptor sd; - sd.revision = static_cast(obj.getProperty(runtime, "revision").asNumber()); if (obj.hasProperty(runtime, "control")) { @@ -431,7 +373,6 @@ struct JSIConverter { jsi::Array controlArray = controlValue.asObject(runtime).asArray(runtime); size_t controlCount = controlArray.size(runtime); sd.control.reserve(controlCount); - for (size_t i = 0; i < controlCount; i++) { jsi::Value controlItem = controlArray.getValueAtIndex(runtime, i); if (controlItem.isString()) { @@ -444,11 +385,13 @@ struct JSIConverter { sd.ownerSid = obj.getProperty(runtime, "ownerSid").asString(runtime).utf8(runtime); sd.groupSid = obj.getProperty(runtime, "groupSid").asString(runtime).utf8(runtime); sd.dacl = JSIConverter::fromJSI(runtime, obj.getProperty(runtime, "dacl")); - return sd; } - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { return value.isObject(); } + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } }; namespace react_native_smb_detail { diff --git a/cpp/shared/core/SmbTask.cpp b/cpp/shared/core/SmbTask.cpp index 63f2455..f0075d6 100644 --- a/cpp/shared/core/SmbTask.cpp +++ b/cpp/shared/core/SmbTask.cpp @@ -1,29 +1,23 @@ #include "SmbTask.hpp" -#include #include -#include "../ReactNativeSmb.hpp" // JSIConverter #include "../connection/SmbConnectionPool.hpp" #include "../operators/OperatorBase.hpp" #include "../util/SmbErrorMapper.hpp" #include "../util/SmbException.hpp" #include "EntryStream.hpp" +#include "SmbModels.hpp" #include "TaskSnapshotCodec.hpp" namespace react_native_smb { -namespace jsi = facebook::jsi; -using namespace margelo::nitro; - SmbTask::SmbTask(std::string id, std::unique_ptr seedOp, std::shared_ptr pool) - : HybridObject("SmbTask"), - SmbTaskCore(std::move(id), seedOp->kind()), + : SmbTaskCore(std::move(id), seedOp->kind()), pool_(pool), entries_(std::make_shared()) { ops_.push_back(std::move(seedOp)); opProgress_.resize(1); - loadHybridMethods(); } SmbTask::~SmbTask() = default; @@ -31,8 +25,6 @@ SmbTask::~SmbTask() = default; void SmbTask::cancel() { if (isSettled()) return; // Trip the shared flag first so in-flight poll loops see cancel immediately. - // Pool queue cancellation can wake a waiting op with SmbException::Cancelled - // on the worker thread; the flag must already be set to avoid settling Error. SmbTaskCore::cancel(); if (auto pool = pool_.lock()) pool->cancelRequestsForTask(getId()); } @@ -49,7 +41,7 @@ void SmbTask::start() { } void SmbTask::launchOp(size_t opIndex) { - auto self = std::static_pointer_cast(shared()); + auto self = shared_from_this(); std::thread([self, opIndex] { if (self->cancel_.cancelled()) { self->onOpFinished(); @@ -116,11 +108,6 @@ std::unordered_map SmbTask::get() { return TaskSnapshotCodec::encode(getState()); } -jsi::Value SmbTask::getResultValueRaw(jsi::Runtime& runtime, const jsi::Value& /*thisValue*/, const jsi::Value* /*args*/, - size_t /*count*/) { - return SmbTaskCore::getResultValue(runtime); -} - std::string SmbTask::subscribeMap(const std::function&)>& listener) { return SmbTaskCore::subscribe([listener](const SmbTaskState& s) { if (listener) { @@ -140,19 +127,4 @@ void SmbTask::unsubscribeEntries(const std::string& id) { entries_->unsubscribe( std::vector SmbTask::drainEntries(const std::string& id) { return entries_->drain(id); } -void SmbTask::loadHybridMethods() { - HybridObject::loadHybridMethods(); - registerHybrids(this, [](Prototype& prototype) { - prototype.registerHybridMethod("id", &SmbTask::getId); - prototype.registerHybridMethod("cancel", &SmbTask::cancel); - prototype.registerHybridMethod("get", &SmbTask::get); - prototype.registerHybridMethod("subscribe", &SmbTask::subscribeMap); - prototype.registerHybridMethod("unsubscribe", &SmbTask::unsubscribe); - prototype.registerHybridMethod("subscribeEntries", &SmbTask::subscribeEntries); - prototype.registerHybridMethod("unsubscribeEntries", &SmbTask::unsubscribeEntries); - prototype.registerHybridMethod("drainEntries", &SmbTask::drainEntries); - prototype.registerRawHybridMethod("getResultValue", 0, &SmbTask::getResultValueRaw); - }); -} - } // namespace react_native_smb diff --git a/cpp/shared/core/SmbTask.hpp b/cpp/shared/core/SmbTask.hpp index 7ee7b87..2e819db 100644 --- a/cpp/shared/core/SmbTask.hpp +++ b/cpp/shared/core/SmbTask.hpp @@ -8,7 +8,6 @@ #include #include -#include #include #include "SmbTaskCore.hpp" @@ -21,9 +20,8 @@ class EntryStream; struct SmbFileInfo; namespace jsi = facebook::jsi; -using namespace margelo::nitro; -class SmbTask : public HybridObject, public SmbTaskCore { +class SmbTask : public SmbTaskCore, public std::enable_shared_from_this { public: using EntriesListener = std::function; @@ -41,7 +39,6 @@ class SmbTask : public HybridObject, public SmbTaskCore { std::string subscribeMap(const std::function&)>& listener); void unsubscribe(const std::string& id) { SmbTaskCore::unsubscribe(id); } - // Incremental listing entries via notify-and-drain (coalesced while JS is busy). std::string subscribeEntries(const EntriesListener& listener); void unsubscribeEntries(const std::string& id); std::vector drainEntries(const std::string& id); @@ -49,15 +46,14 @@ class SmbTask : public HybridObject, public SmbTaskCore { std::future result() { return completionFuture(); } + jsi::Value getResultValue(jsi::Runtime& runtime) const { return SmbTaskCore::getResultValue(runtime); } + private: - jsi::Value getResultValueRaw(jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* args, size_t count); std::weak_ptr pool_; std::shared_ptr entries_; void launchOp(size_t opIndex); size_t appendOps(std::vector>& more); - - void loadHybridMethods() override; }; } // namespace react_native_smb diff --git a/cpp/shared/io/SmbCopyTree.hpp b/cpp/shared/io/SmbCopyTree.hpp index b6dd80f..d28fa9a 100644 --- a/cpp/shared/io/SmbCopyTree.hpp +++ b/cpp/shared/io/SmbCopyTree.hpp @@ -10,7 +10,7 @@ #include #include -#include "../ReactNativeSmb.hpp" +#include "../core/SmbModels.hpp" #include "../connection/MetadataContextLease.hpp" #include "../connection/SmbConnectionPool.hpp" #include "../core/CancellationToken.hpp" diff --git a/cpp/shared/io/SmbPathUtil.hpp b/cpp/shared/io/SmbPathUtil.hpp index 7804cc5..98c1139 100644 --- a/cpp/shared/io/SmbPathUtil.hpp +++ b/cpp/shared/io/SmbPathUtil.hpp @@ -9,7 +9,7 @@ #include #include -#include "../ReactNativeSmb.hpp" // SmbFileInfo +#include "../core/SmbModels.hpp" #include "../util/SmbException.hpp" namespace react_native_smb { diff --git a/cpp/shared/io/SmbSecurity.hpp b/cpp/shared/io/SmbSecurity.hpp index f8b2570..96d28b7 100644 --- a/cpp/shared/io/SmbSecurity.hpp +++ b/cpp/shared/io/SmbSecurity.hpp @@ -1,6 +1,6 @@ #pragma once -#include "../ReactNativeSmb.hpp" +#include "../core/SmbModels.hpp" #include #include #include diff --git a/cpp/shared/io/SmbSecurityQuery.hpp b/cpp/shared/io/SmbSecurityQuery.hpp index 8de3155..0a1c08a 100644 --- a/cpp/shared/io/SmbSecurityQuery.hpp +++ b/cpp/shared/io/SmbSecurityQuery.hpp @@ -3,7 +3,7 @@ #include #include -#include "../ReactNativeSmb.hpp" +#include "../core/SmbModels.hpp" #include "../util/SmbErrorMapper.hpp" struct smb2_context; diff --git a/cpp/shared/io/SmbTreeOps.hpp b/cpp/shared/io/SmbTreeOps.hpp index e8bc359..c607eba 100644 --- a/cpp/shared/io/SmbTreeOps.hpp +++ b/cpp/shared/io/SmbTreeOps.hpp @@ -7,7 +7,7 @@ #include #include -#include "../ReactNativeSmb.hpp" // SmbFileInfo +#include "../core/SmbModels.hpp" #include "../core/CancellationToken.hpp" #include "../util/SmbException.hpp" #include "SmbPathUtil.hpp" diff --git a/cpp/shared/io/listing/DirectoryLister.hpp b/cpp/shared/io/listing/DirectoryLister.hpp index b135238..eb3f0d2 100644 --- a/cpp/shared/io/listing/DirectoryLister.hpp +++ b/cpp/shared/io/listing/DirectoryLister.hpp @@ -12,7 +12,7 @@ #include #include -#include "../../ReactNativeSmb.hpp" // SmbFileInfo +#include "../../core/SmbModels.hpp" #include "../../core/CancellationToken.hpp" #include "../../util/SmbErrorMapper.hpp" #include "../SmbSecurityQuery.hpp" diff --git a/cpp/shared/operators/Operator.hpp b/cpp/shared/operators/Operator.hpp index 3c62270..e3d4ee2 100644 --- a/cpp/shared/operators/Operator.hpp +++ b/cpp/shared/operators/Operator.hpp @@ -3,7 +3,7 @@ #include "OperatorBase.hpp" // For JSIConverter in publishThisResult convenience. -#include "../ReactNativeSmb.hpp" // brings the JSIConverter specializations in margelo::nitro namespace +#include "../core/SmbModels.hpp" namespace jsi = facebook::jsi; diff --git a/cpp/shared/operators/connection/ConnectOperator.hpp b/cpp/shared/operators/connection/ConnectOperator.hpp index 60fa9de..021c53f 100644 --- a/cpp/shared/operators/connection/ConnectOperator.hpp +++ b/cpp/shared/operators/connection/ConnectOperator.hpp @@ -2,7 +2,7 @@ #include -#include "../../ReactNativeSmb.hpp" // SmbCredentials, SmbConnectionInfo +#include "../../core/SmbModels.hpp" #include "../Operator.hpp" namespace react_native_smb { diff --git a/cpp/shared/operators/connection/ConnectShareOperator.hpp b/cpp/shared/operators/connection/ConnectShareOperator.hpp index 2f7860d..c66ea71 100644 --- a/cpp/shared/operators/connection/ConnectShareOperator.hpp +++ b/cpp/shared/operators/connection/ConnectShareOperator.hpp @@ -2,7 +2,7 @@ #include -#include "../../ReactNativeSmb.hpp" // SmbConnectionInfo +#include "../../core/SmbModels.hpp" #include "../Operator.hpp" namespace react_native_smb { diff --git a/cpp/shared/operators/connection/InitializeOperator.hpp b/cpp/shared/operators/connection/InitializeOperator.hpp index ddb94f6..0598fbe 100644 --- a/cpp/shared/operators/connection/InitializeOperator.hpp +++ b/cpp/shared/operators/connection/InitializeOperator.hpp @@ -2,7 +2,7 @@ #include -#include "../../ReactNativeSmb.hpp" // SmbCredentials +#include "../../core/SmbModels.hpp" #include "../OperatorBase.hpp" namespace react_native_smb { diff --git a/cpp/shared/operators/connection/ListSharesOperator.hpp b/cpp/shared/operators/connection/ListSharesOperator.hpp index 8ceb49c..d43f936 100644 --- a/cpp/shared/operators/connection/ListSharesOperator.hpp +++ b/cpp/shared/operators/connection/ListSharesOperator.hpp @@ -2,7 +2,7 @@ #include -#include "../../ReactNativeSmb.hpp" // SmbShare +#include "../../core/SmbModels.hpp" #include "../Operator.hpp" namespace react_native_smb { diff --git a/cpp/shared/operators/listing/GetPathInfoOperator.hpp b/cpp/shared/operators/listing/GetPathInfoOperator.hpp index 8a541ac..24d47bf 100644 --- a/cpp/shared/operators/listing/GetPathInfoOperator.hpp +++ b/cpp/shared/operators/listing/GetPathInfoOperator.hpp @@ -2,7 +2,7 @@ #include -#include "../../ReactNativeSmb.hpp" // SmbFileInfo +#include "../../core/SmbModels.hpp" #include "../Operator.hpp" namespace react_native_smb { diff --git a/cpp/shared/operators/listing/GetSecurityDescriptorOperator.hpp b/cpp/shared/operators/listing/GetSecurityDescriptorOperator.hpp index e1707f0..88df6dd 100644 --- a/cpp/shared/operators/listing/GetSecurityDescriptorOperator.hpp +++ b/cpp/shared/operators/listing/GetSecurityDescriptorOperator.hpp @@ -2,7 +2,7 @@ #include -#include "../../ReactNativeSmb.hpp" // SmbSecurityDescriptor +#include "../../core/SmbModels.hpp" #include "../Operator.hpp" namespace react_native_smb { diff --git a/cpp/shared/operators/listing/ListDirectoryOperator.cpp b/cpp/shared/operators/listing/ListDirectoryOperator.cpp index 5fb3892..aebdc72 100644 --- a/cpp/shared/operators/listing/ListDirectoryOperator.cpp +++ b/cpp/shared/operators/listing/ListDirectoryOperator.cpp @@ -4,7 +4,7 @@ #include #include -#include "../../ReactNativeSmb.hpp" // SmbFileInfo + JSIConverter +#include "../../core/SmbModels.hpp" #include "../../connection/SmbConnectionPool.hpp" #include "../../core/EntryStream.hpp" #include "../../io/listing/DirectoryLister.hpp" diff --git a/cpp/shared/operators/mutate/DeleteItemOperator.cpp b/cpp/shared/operators/mutate/DeleteItemOperator.cpp index d96d28c..8ef91ff 100644 --- a/cpp/shared/operators/mutate/DeleteItemOperator.cpp +++ b/cpp/shared/operators/mutate/DeleteItemOperator.cpp @@ -7,7 +7,7 @@ #include #include -#include "../../ReactNativeSmb.hpp" +#include "../../core/SmbModels.hpp" #include "../../io/PipelinedOps.hpp" #include "../../io/SmbPathUtil.hpp" #include "../../io/listing/DirectoryLister.hpp" diff --git a/example/package-lock.json b/example/package-lock.json index 9dfd0af..b6c5097 100644 --- a/example/package-lock.json +++ b/example/package-lock.json @@ -21,7 +21,7 @@ "react": "19.2.0", "react-native": "0.83.4", "react-native-linear-gradient": "^2.8.3", - "react-native-nitro-modules": "~0.31.9", + "react-native-nitro-modules": "0.37.2", "react-native-safe-area-context": "~5.6.2", "react-native-screens": "~4.23.0", "webidl-conversions": "^5.0.0" @@ -33,15 +33,21 @@ "license": "LGPL-2.1", "devDependencies": { "@types/react": "^19.1.1", + "nitrogen": "0.37.2", "react-native": "0.83.4", - "react-native-nitro-modules": "~0.31.9", + "react-native-nitro-modules": "0.37.2", "typescript": "^5.0.0", "vitest": "^4.1.11" }, "peerDependencies": { "react": ">=19.0.0", "react-native": ">=0.76.0", - "react-native-nitro-modules": ">=0.22.0 <1.0.0" + "react-native-nitro-modules": "*" + }, + "peerDependenciesMeta": { + "react-native-nitro-modules": { + "optional": true + } } }, "node_modules/@babel/code-frame": { @@ -6037,6 +6043,12 @@ "node": ">= 0.6" } }, + "node_modules/nitro-core": { + "version": "0.37.2", + "resolved": "https://registry.npmjs.org/nitro-core/-/nitro-core-0.37.2.tgz", + "integrity": "sha512-dhagikz9VXXzfidRH/vPNJfYWPmTBArDOo9wE/wEqeERU9C8uRWz9YccOyNUOvADccPAZq319yzhDMoJ9excSQ==", + "license": "MIT" + }, "node_modules/node-forge": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.0.tgz", @@ -6696,11 +6708,13 @@ } }, "node_modules/react-native-nitro-modules": { - "version": "0.31.10", - "resolved": "https://registry.npmjs.org/react-native-nitro-modules/-/react-native-nitro-modules-0.31.10.tgz", - "integrity": "sha512-hcvjTu9YJE9fMmnAUvhG8CxvYLpOuMQ/2eyi/S6GyrecezF6Rmk/uRQEL6v09BRFWA/xRVZNQVulQPS+2HS3mQ==", - "hasInstallScript": true, + "version": "0.37.2", + "resolved": "https://registry.npmjs.org/react-native-nitro-modules/-/react-native-nitro-modules-0.37.2.tgz", + "integrity": "sha512-Odnrq/p6/q0R01qZlkqeXu9VHHMuGEnZZmyxMvehEu6QiACNHhBCmAHgyBDqOSo9Lb3G0TscFAT+HG0uxsR/GA==", "license": "MIT", + "dependencies": { + "nitro-core": "0.37.2" + }, "peerDependencies": { "react": "*", "react-native": "*" diff --git a/example/package.json b/example/package.json index a4a2109..2c297da 100644 --- a/example/package.json +++ b/example/package.json @@ -28,7 +28,7 @@ "react": "19.2.0", "react-native": "0.83.4", "react-native-linear-gradient": "^2.8.3", - "react-native-nitro-modules": "~0.31.9", + "react-native-nitro-modules": "0.37.2", "react-native-safe-area-context": "~5.6.2", "react-native-screens": "~4.23.0", "webidl-conversions": "^5.0.0" diff --git a/nitro.json b/nitro.json new file mode 100644 index 0000000..1c1525b --- /dev/null +++ b/nitro.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://nitro.margelo.com/nitro.schema.json", + "cxxNamespace": ["smb"], + "ios": { + "iosModuleName": "ReactNativeSmb" + }, + "android": { + "androidNamespace": ["smb"], + "androidCxxLibName": "ReactNativeSmb" + }, + "autolinking": { + "ReactNativeSmb": { + "all": { + "language": "c++", + "implementationClassName": "HybridSMB" + } + } + }, + "ignorePaths": ["**/node_modules", "lib", "example"] +} diff --git a/nitrogen/generated/.gitattributes b/nitrogen/generated/.gitattributes new file mode 100644 index 0000000..fb7a0d5 --- /dev/null +++ b/nitrogen/generated/.gitattributes @@ -0,0 +1 @@ +** linguist-generated=true diff --git a/nitrogen/generated/android/ReactNativeSmb+autolinking.cmake b/nitrogen/generated/android/ReactNativeSmb+autolinking.cmake new file mode 100644 index 0000000..5130e48 --- /dev/null +++ b/nitrogen/generated/android/ReactNativeSmb+autolinking.cmake @@ -0,0 +1,82 @@ +# +# ReactNativeSmb+autolinking.cmake +# This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +# https://github.com/margelo/nitro +# Copyright © Marc Rousavy @ Margelo +# + +# This is a CMake file that adds all files generated by Nitrogen +# to the current CMake project. +# +# To use it, add this to your CMakeLists.txt: +# ```cmake +# include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/ReactNativeSmb+autolinking.cmake) +# ``` + +# Define a flag to check if we are building properly +add_definitions(-DBUILDING_REACTNATIVESMB_WITH_GENERATED_CMAKE_PROJECT) + +# Enable Raw Props parsing in react-native (for Nitro Views) +add_definitions(-DRN_SERIALIZABLE_STATE) + +# Add all headers that were generated by Nitrogen +include_directories( + "../nitrogen/generated/shared/c++" + "../nitrogen/generated/android/c++" + "../nitrogen/generated/android/" +) + +# Add all .cpp sources that were generated by Nitrogen +target_sources( + # CMake project name (Android C++ library name) + ReactNativeSmb PRIVATE + # Autolinking Setup + ../nitrogen/generated/android/ReactNativeSmbOnLoad.cpp + # Shared Nitrogen C++ sources + ../nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.cpp + ../nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.cpp + # Android-specific Nitrogen C++ sources + +) + +# From node_modules/react-native/ReactAndroid/cmake-utils/folly-flags.cmake +# Used in node_modules/react-native/ReactAndroid/cmake-utils/ReactNative-application.cmake +target_compile_definitions( + ReactNativeSmb PRIVATE + -DFOLLY_NO_CONFIG=1 + -DFOLLY_HAVE_CLOCK_GETTIME=1 + -DFOLLY_USE_LIBCPP=1 + -DFOLLY_CFG_NO_COROUTINES=1 + -DFOLLY_MOBILE=1 + -DFOLLY_HAVE_RECVMMSG=1 + -DFOLLY_HAVE_PTHREAD=1 + # Once we target android-23 above, we can comment + # the following line. NDK uses GNU style stderror_r() after API 23. + -DFOLLY_HAVE_XSI_STRERROR_R=1 +) + +# Add all libraries required by the generated specs +find_package(fbjni REQUIRED) # <-- Used for communication between Java <-> C++ +find_package(ReactAndroid REQUIRED) # <-- Used to set up React Native bindings (e.g. CallInvoker/TurboModule) +find_package(react-native-nitro-modules REQUIRED) # <-- Used to create all HybridObjects and use the Nitro core library + +# Link all libraries together +target_link_libraries( + ReactNativeSmb + fbjni::fbjni # <-- Facebook C++ JNI helpers + ReactAndroid::jsi # <-- RN: JSI + react-native-nitro-modules::NitroModules # <-- NitroModules Core :) +) + +# Link react-native (different prefab between RN 0.75 and RN 0.76) +if(ReactAndroid_VERSION_MINOR GREATER_EQUAL 76) + target_link_libraries( + ReactNativeSmb + ReactAndroid::reactnative # <-- RN: Native Modules umbrella prefab + ) +else() + target_link_libraries( + ReactNativeSmb + ReactAndroid::react_nativemodule_core # <-- RN: TurboModules Core + ) +endif() diff --git a/nitrogen/generated/android/ReactNativeSmb+autolinking.gradle b/nitrogen/generated/android/ReactNativeSmb+autolinking.gradle new file mode 100644 index 0000000..b3acb18 --- /dev/null +++ b/nitrogen/generated/android/ReactNativeSmb+autolinking.gradle @@ -0,0 +1,27 @@ +/// +/// ReactNativeSmb+autolinking.gradle +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +/// This is a Gradle file that adds all files generated by Nitrogen +/// to the current Gradle project. +/// +/// To use it, add this to your build.gradle: +/// ```gradle +/// apply from: '../nitrogen/generated/android/ReactNativeSmb+autolinking.gradle' +/// ``` + +logger.warn("[NitroModules] 🔥 ReactNativeSmb is boosted by nitro!") + +android { + sourceSets { + main { + java.srcDirs += [ + // Nitrogen files + "${project.projectDir}/../nitrogen/generated/android/kotlin" + ] + } + } +} diff --git a/nitrogen/generated/android/ReactNativeSmbOnLoad.cpp b/nitrogen/generated/android/ReactNativeSmbOnLoad.cpp new file mode 100644 index 0000000..692b4af --- /dev/null +++ b/nitrogen/generated/android/ReactNativeSmbOnLoad.cpp @@ -0,0 +1,49 @@ +/// +/// ReactNativeSmbOnLoad.cpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#ifndef BUILDING_REACTNATIVESMB_WITH_GENERATED_CMAKE_PROJECT +#error ReactNativeSmbOnLoad.cpp is not being built with the autogenerated CMakeLists.txt project. Is a different CMakeLists.txt building this? +#endif + +#include "ReactNativeSmbOnLoad.hpp" + +#include +#include +#include + +#include "HybridSMB.hpp" + +namespace margelo::nitro::smb { + +int initialize(JavaVM* vm) { + return facebook::jni::initialize(vm, []() { + ::margelo::nitro::smb::registerAllNatives(); + }); +} + + + +void registerAllNatives() { + using namespace margelo::nitro; + using namespace margelo::nitro::smb; + + // Register native JNI methods + + + // Register Nitro Hybrid Objects + HybridObjectRegistry::registerHybridObjectConstructor( + "ReactNativeSmb", + []() -> std::shared_ptr { + static_assert(std::is_default_constructible_v, + "The HybridObject \"HybridSMB\" is not default-constructible! " + "Create a public constructor that takes zero arguments to be able to autolink this HybridObject."); + return std::make_shared(); + } + ); +} + +} // namespace margelo::nitro::smb diff --git a/nitrogen/generated/android/ReactNativeSmbOnLoad.hpp b/nitrogen/generated/android/ReactNativeSmbOnLoad.hpp new file mode 100644 index 0000000..fbdeb63 --- /dev/null +++ b/nitrogen/generated/android/ReactNativeSmbOnLoad.hpp @@ -0,0 +1,34 @@ +/// +/// ReactNativeSmbOnLoad.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#include +#include +#include + +namespace margelo::nitro::smb { + + [[deprecated("Use registerNatives() instead.")]] + int initialize(JavaVM* vm); + + /** + * Register the native (C++) part of ReactNativeSmb, and autolinks all Hybrid Objects. + * Call this in your `JNI_OnLoad` function (probably inside `cpp-adapter.cpp`), + * inside a `facebook::jni::initialize(vm, ...)` call. + * Example: + * ```cpp (cpp-adapter.cpp) + * JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) { + * return facebook::jni::initialize(vm, []() { + * // register all ReactNativeSmb HybridObjects + * margelo::nitro::smb::registerNatives(); + * // any other custom registrations go here. + * }); + * } + * ``` + */ + void registerAllNatives(); + +} // namespace margelo::nitro::smb diff --git a/nitrogen/generated/android/kotlin/com/margelo/nitro/smb/ReactNativeSmbOnLoad.kt b/nitrogen/generated/android/kotlin/com/margelo/nitro/smb/ReactNativeSmbOnLoad.kt new file mode 100644 index 0000000..1ff7f6b --- /dev/null +++ b/nitrogen/generated/android/kotlin/com/margelo/nitro/smb/ReactNativeSmbOnLoad.kt @@ -0,0 +1,35 @@ +/// +/// ReactNativeSmbOnLoad.kt +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +package com.margelo.nitro.smb + +import android.util.Log + +internal class ReactNativeSmbOnLoad { + companion object { + private const val TAG = "ReactNativeSmbOnLoad" + private var didLoad = false + /** + * Initializes the native part of "ReactNativeSmb". + * This method is idempotent and can be called more than once. + */ + @JvmStatic + fun initializeNative() { + if (didLoad) return + try { + Log.i(TAG, "Loading ReactNativeSmb C++ library...") + System.loadLibrary("ReactNativeSmb") + Log.i(TAG, "Successfully loaded ReactNativeSmb C++ library!") + didLoad = true + } catch (e: Error) { + Log.e(TAG, "Failed to load ReactNativeSmb C++ library! Is it properly installed and linked? " + + "Is the name correct? (see `CMakeLists.txt`, at `add_library(...)`)", e) + throw e + } + } + } +} diff --git a/nitrogen/generated/ios/ReactNativeSmb+autolinking.rb b/nitrogen/generated/ios/ReactNativeSmb+autolinking.rb new file mode 100644 index 0000000..aad6f4c --- /dev/null +++ b/nitrogen/generated/ios/ReactNativeSmb+autolinking.rb @@ -0,0 +1,62 @@ +# +# ReactNativeSmb+autolinking.rb +# This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +# https://github.com/margelo/nitro +# Copyright © Marc Rousavy @ Margelo +# + +# This is a Ruby script that adds all files generated by Nitrogen +# to the given podspec. +# +# To use it, add this to your .podspec: +# ```ruby +# Pod::Spec.new do |spec| +# # ... +# +# # Add all files generated by Nitrogen +# load 'nitrogen/generated/ios/ReactNativeSmb+autolinking.rb' +# add_nitrogen_files(spec) +# end +# ``` + +def add_nitrogen_files(spec) + Pod::UI.puts "[NitroModules] 🔥 ReactNativeSmb is boosted by nitro!" + + spec.dependency "NitroModules" + + current_source_files = Array(spec.attributes_hash['source_files']) + spec.source_files = current_source_files + [ + # Generated cross-platform specs + "nitrogen/generated/shared/**/*.{h,hpp,c,cpp,swift}", + # Generated bridges for the cross-platform specs + "nitrogen/generated/ios/**/*.{h,hpp,c,cpp,mm,swift}", + ] + + current_public_header_files = Array(spec.attributes_hash['public_header_files']) + spec.public_header_files = current_public_header_files + [ + # Generated specs + "nitrogen/generated/shared/**/*.{h,hpp}", + # Swift to C++ bridging helpers + "nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Bridge.hpp" + ] + + current_private_header_files = Array(spec.attributes_hash['private_header_files']) + spec.private_header_files = current_private_header_files + [ + # iOS specific specs + "nitrogen/generated/ios/c++/**/*.{h,hpp}", + # Views are framework-specific and should be private + "nitrogen/generated/shared/**/views/**/*" + ] + + current_pod_target_xcconfig = spec.attributes_hash['pod_target_xcconfig'] || {} + spec.pod_target_xcconfig = current_pod_target_xcconfig.merge({ + # Use C++ 20 + "CLANG_CXX_LANGUAGE_STANDARD" => "c++20", + # Enables C++ <-> Swift interop (by default it's only ObjC) + "SWIFT_OBJC_INTEROP_MODE" => "objcxx", + # Enables stricter modular headers + "DEFINES_MODULE" => "YES", + # Disable auto-generated ObjC header for Swift (Static linkage on Xcode 26.4 breaks here) + "SWIFT_INSTALL_OBJC_HEADER" => "NO", + }) +end diff --git a/nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Bridge.cpp b/nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Bridge.cpp new file mode 100644 index 0000000..ee2c839 --- /dev/null +++ b/nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Bridge.cpp @@ -0,0 +1,17 @@ +/// +/// ReactNativeSmb-Swift-Cxx-Bridge.cpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#include "ReactNativeSmb-Swift-Cxx-Bridge.hpp" + +// Include C++ implementation defined types + + +namespace margelo::nitro::smb::bridge::swift { + + + +} // namespace margelo::nitro::smb::bridge::swift diff --git a/nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Bridge.hpp b/nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Bridge.hpp new file mode 100644 index 0000000..be9729d --- /dev/null +++ b/nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Bridge.hpp @@ -0,0 +1,27 @@ +/// +/// ReactNativeSmb-Swift-Cxx-Bridge.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +// Forward declarations of C++ defined types + + +// Forward declarations of Swift defined types + + +// Include C++ defined types + + +/** + * Contains specialized versions of C++ templated types so they can be accessed from Swift, + * as well as helper functions to interact with those C++ types from Swift. + */ +namespace margelo::nitro::smb::bridge::swift { + + + +} // namespace margelo::nitro::smb::bridge::swift diff --git a/nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Umbrella.hpp b/nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Umbrella.hpp new file mode 100644 index 0000000..972b118 --- /dev/null +++ b/nitrogen/generated/ios/ReactNativeSmb-Swift-Cxx-Umbrella.hpp @@ -0,0 +1,38 @@ +/// +/// ReactNativeSmb-Swift-Cxx-Umbrella.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +// Forward declarations of C++ defined types + + +// Include C++ defined types + + +// C++ helpers for Swift +#include "ReactNativeSmb-Swift-Cxx-Bridge.hpp" + +// Common C++ types used in Swift +#include +#include +#include +#include + +// Forward declarations of Swift defined types + + +// Include Swift defined types +#if __has_include("ReactNativeSmb-Swift.h") +// This header is generated by Xcode/Swift on every app build. +// If it cannot be found, make sure the Swift module's name (= podspec name) is actually "ReactNativeSmb". +#include "ReactNativeSmb-Swift.h" +// Same as above, but used when building with frameworks (`use_frameworks`) +#elif __has_include() +#include +#else +#error ReactNativeSmb's autogenerated Swift header cannot be found! Make sure the Swift module's name (= podspec name) is actually "ReactNativeSmb", and try building the app first. +#endif diff --git a/nitrogen/generated/ios/ReactNativeSmbAutolinking.mm b/nitrogen/generated/ios/ReactNativeSmbAutolinking.mm new file mode 100644 index 0000000..4839da9 --- /dev/null +++ b/nitrogen/generated/ios/ReactNativeSmbAutolinking.mm @@ -0,0 +1,35 @@ +/// +/// ReactNativeSmbAutolinking.mm +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#import +#import + +#import + +#include "HybridSMB.hpp" + +@interface ReactNativeSmbAutolinking : NSObject +@end + +@implementation ReactNativeSmbAutolinking + ++ (void) load { + using namespace margelo::nitro; + using namespace margelo::nitro::smb; + + HybridObjectRegistry::registerHybridObjectConstructor( + "ReactNativeSmb", + []() -> std::shared_ptr { + static_assert(std::is_default_constructible_v, + "The HybridObject \"HybridSMB\" is not default-constructible! " + "Create a public constructor that takes zero arguments to be able to autolink this HybridObject."); + return std::make_shared(); + } + ); +} + +@end diff --git a/nitrogen/generated/ios/ReactNativeSmbAutolinking.swift b/nitrogen/generated/ios/ReactNativeSmbAutolinking.swift new file mode 100644 index 0000000..ed934d2 --- /dev/null +++ b/nitrogen/generated/ios/ReactNativeSmbAutolinking.swift @@ -0,0 +1,16 @@ +/// +/// ReactNativeSmbAutolinking.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +import NitroModules + +// TODO: Use empty enums once Swift supports exporting them as namespaces +// See: https://github.com/swiftlang/swift/pull/83616 +public final class ReactNativeSmbAutolinking { + public typealias bridge = margelo.nitro.smb.bridge.swift + + +} diff --git a/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.cpp b/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.cpp new file mode 100644 index 0000000..5a25825 --- /dev/null +++ b/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.cpp @@ -0,0 +1,26 @@ +/// +/// HybridNativeSmbTaskSpec.cpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#include "HybridNativeSmbTaskSpec.hpp" + +namespace margelo::nitro::smb { + + void HybridNativeSmbTaskSpec::loadHybridMethods() { + // load base methods/properties + HybridObject::loadHybridMethods(); + // load custom methods/properties + registerHybrids(this, [](Prototype& prototype) { + prototype.registerHybridMethod("cancel", &HybridNativeSmbTaskSpec::cancel); + prototype.registerHybridMethod("get", &HybridNativeSmbTaskSpec::get); + prototype.registerHybridMethod("subscribe", &HybridNativeSmbTaskSpec::subscribe); + prototype.registerHybridMethod("unsubscribe", &HybridNativeSmbTaskSpec::unsubscribe); + prototype.registerHybridMethod("subscribeEntries", &HybridNativeSmbTaskSpec::subscribeEntries); + prototype.registerHybridMethod("unsubscribeEntries", &HybridNativeSmbTaskSpec::unsubscribeEntries); + }); + } + +} // namespace margelo::nitro::smb diff --git a/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp b/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp new file mode 100644 index 0000000..d0cdf35 --- /dev/null +++ b/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp @@ -0,0 +1,69 @@ +/// +/// HybridNativeSmbTaskSpec.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + + + +#include +#include +#include + +namespace margelo::nitro::smb { + + using namespace margelo::nitro; + + /** + * An abstract base class for `NativeSmbTask` + * Inherit this class to create instances of `HybridNativeSmbTaskSpec` in C++. + * You must explicitly call `HybridObject`'s constructor yourself, because it is virtual. + * @example + * ```cpp + * class HybridNativeSmbTask: public HybridNativeSmbTaskSpec { + * public: + * HybridNativeSmbTask(...): HybridObject(TAG) { ... } + * // ... + * }; + * ``` + */ + class HybridNativeSmbTaskSpec: public virtual HybridObject { + public: + // Constructor + explicit HybridNativeSmbTaskSpec(): HybridObject(TAG) { } + + // Destructor + ~HybridNativeSmbTaskSpec() override = default; + + public: + // Properties + + + public: + // Methods + virtual void cancel() = 0; + virtual std::unordered_map get() = 0; + virtual std::string subscribe(const std::function& /* snapshot */)>& listener) = 0; + virtual void unsubscribe(const std::string& subscriptionId) = 0; + virtual std::string subscribeEntries(const std::function& listener) = 0; + virtual void unsubscribeEntries(const std::string& subscriptionId) = 0; + + protected: + // Hybrid Setup + void loadHybridMethods() override; + + protected: + // Tag for logging + static constexpr auto TAG = "NativeSmbTask"; + }; + +} // namespace margelo::nitro::smb diff --git a/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.cpp b/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.cpp new file mode 100644 index 0000000..e14e9d3 --- /dev/null +++ b/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.cpp @@ -0,0 +1,52 @@ +/// +/// HybridReactNativeSmbSpec.cpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#include "HybridReactNativeSmbSpec.hpp" + +namespace margelo::nitro::smb { + + void HybridReactNativeSmbSpec::loadHybridMethods() { + // load base methods/properties + HybridObject::loadHybridMethods(); + // load custom methods/properties + registerHybrids(this, [](Prototype& prototype) { + prototype.registerHybridMethod("isConnected", &HybridReactNativeSmbSpec::isConnected); + prototype.registerHybridMethod("isInitialized", &HybridReactNativeSmbSpec::isInitialized); + prototype.registerHybridMethod("initialize", &HybridReactNativeSmbSpec::initialize); + prototype.registerHybridMethod("connect", &HybridReactNativeSmbSpec::connect); + prototype.registerHybridMethod("connectShare", &HybridReactNativeSmbSpec::connectShare); + prototype.registerHybridMethod("disconnect", &HybridReactNativeSmbSpec::disconnect); + prototype.registerHybridMethod("listShares", &HybridReactNativeSmbSpec::listShares); + prototype.registerHybridMethod("listDirectory", &HybridReactNativeSmbSpec::listDirectory); + prototype.registerHybridMethod("getPathInfo", &HybridReactNativeSmbSpec::getPathInfo); + prototype.registerHybridMethod("getSecurityDescriptor", &HybridReactNativeSmbSpec::getSecurityDescriptor); + prototype.registerHybridMethod("downloadFile", &HybridReactNativeSmbSpec::downloadFile); + prototype.registerHybridMethod("uploadFile", &HybridReactNativeSmbSpec::uploadFile); + prototype.registerHybridMethod("createDirectory", &HybridReactNativeSmbSpec::createDirectory); + prototype.registerHybridMethod("deleteItem", &HybridReactNativeSmbSpec::deleteItem); + prototype.registerHybridMethod("moveItem", &HybridReactNativeSmbSpec::moveItem); + prototype.registerHybridMethod("renameItem", &HybridReactNativeSmbSpec::renameItem); + prototype.registerHybridMethod("copyItem", &HybridReactNativeSmbSpec::copyItem); + prototype.registerHybridMethod("duplicateItem", &HybridReactNativeSmbSpec::duplicateItem); + prototype.registerHybridMethod("subscribeTaskEvents", &HybridReactNativeSmbSpec::subscribeTaskEvents); + prototype.registerHybridMethod("unsubscribeTaskEvents", &HybridReactNativeSmbSpec::unsubscribeTaskEvents); + prototype.registerHybridMethod("getTask", &HybridReactNativeSmbSpec::getTask); + prototype.registerHybridMethod("getActiveTasks", &HybridReactNativeSmbSpec::getActiveTasks); + prototype.registerHybridMethod("getTransferTasks", &HybridReactNativeSmbSpec::getTransferTasks); + prototype.registerHybridMethod("getTaskHistory", &HybridReactNativeSmbSpec::getTaskHistory); + prototype.registerHybridMethod("cancelTask", &HybridReactNativeSmbSpec::cancelTask); + prototype.registerHybridMethod("cancelTransferTasks", &HybridReactNativeSmbSpec::cancelTransferTasks); + prototype.registerHybridMethod("clearTaskHistory", &HybridReactNativeSmbSpec::clearTaskHistory); + prototype.registerHybridMethod("destroy", &HybridReactNativeSmbSpec::destroy); + prototype.registerHybridMethod("subscribePoolInfo", &HybridReactNativeSmbSpec::subscribePoolInfo); + prototype.registerHybridMethod("unsubscribePoolInfo", &HybridReactNativeSmbSpec::unsubscribePoolInfo); + prototype.registerHybridMethod("getPoolInfo", &HybridReactNativeSmbSpec::getPoolInfo); + prototype.registerHybridMethod("resetPool", &HybridReactNativeSmbSpec::resetPool); + }); + } + +} // namespace margelo::nitro::smb diff --git a/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp b/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp new file mode 100644 index 0000000..1a90e50 --- /dev/null +++ b/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp @@ -0,0 +1,103 @@ +/// +/// HybridReactNativeSmbSpec.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +// Forward declaration of `HybridNativeSmbTaskSpec` to properly resolve imports. +namespace margelo::nitro::smb { class HybridNativeSmbTaskSpec; } +// Forward declaration of `SmbCredentials` to properly resolve imports. +namespace margelo::nitro::smb { struct SmbCredentials; } + +#include +#include "HybridNativeSmbTaskSpec.hpp" +#include +#include "SmbCredentials.hpp" +#include +#include +#include +#include + +namespace margelo::nitro::smb { + + using namespace margelo::nitro; + + /** + * An abstract base class for `ReactNativeSmb` + * Inherit this class to create instances of `HybridReactNativeSmbSpec` in C++. + * You must explicitly call `HybridObject`'s constructor yourself, because it is virtual. + * @example + * ```cpp + * class HybridReactNativeSmb: public HybridReactNativeSmbSpec { + * public: + * HybridReactNativeSmb(...): HybridObject(TAG) { ... } + * // ... + * }; + * ``` + */ + class HybridReactNativeSmbSpec: public virtual HybridObject { + public: + // Constructor + explicit HybridReactNativeSmbSpec(): HybridObject(TAG) { } + + // Destructor + ~HybridReactNativeSmbSpec() override = default; + + public: + // Properties + + + public: + // Methods + virtual bool isConnected() = 0; + virtual bool isInitialized() = 0; + virtual std::shared_ptr initialize(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) = 0; + virtual std::shared_ptr connect(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) = 0; + virtual std::shared_ptr connectShare(const std::string& taskId, const std::string& share) = 0; + virtual std::shared_ptr disconnect(const std::string& taskId) = 0; + virtual std::shared_ptr listShares(const std::string& taskId) = 0; + virtual std::shared_ptr listDirectory(const std::string& taskId, const std::string& path, double maxDepth, bool includeSecurityDescriptor, double batchSize) = 0; + virtual std::shared_ptr getPathInfo(const std::string& taskId, const std::string& path) = 0; + virtual std::shared_ptr getSecurityDescriptor(const std::string& taskId, const std::string& path) = 0; + virtual std::shared_ptr downloadFile(const std::string& taskId, const std::string& remotePath, const std::string& localPath) = 0; + virtual std::shared_ptr uploadFile(const std::string& taskId, const std::string& localPath, const std::string& remotePath) = 0; + virtual std::shared_ptr createDirectory(const std::string& taskId, const std::string& path) = 0; + virtual std::shared_ptr deleteItem(const std::string& taskId, const std::string& path) = 0; + virtual std::shared_ptr moveItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath) = 0; + virtual std::shared_ptr renameItem(const std::string& taskId, const std::string& currentPath, const std::string& newName) = 0; + virtual std::shared_ptr copyItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath, bool recursive) = 0; + virtual std::shared_ptr duplicateItem(const std::string& taskId, const std::string& path) = 0; + virtual std::string subscribeTaskEvents(const std::function& /* event */)>& listener) = 0; + virtual void unsubscribeTaskEvents(const std::string& subscriptionId) = 0; + virtual std::unordered_map getTask(const std::string& taskId) = 0; + virtual std::vector> getActiveTasks() = 0; + virtual std::vector> getTransferTasks() = 0; + virtual std::vector> getTaskHistory(double limit, double offset) = 0; + virtual void cancelTask(const std::string& taskId) = 0; + virtual void cancelTransferTasks() = 0; + virtual void clearTaskHistory(int64_t beforeTs) = 0; + virtual std::shared_ptr> destroy() = 0; + virtual std::string subscribePoolInfo(const std::function>& /* snapshot */)>& listener) = 0; + virtual void unsubscribePoolInfo(const std::string& subscriptionId) = 0; + virtual std::vector> getPoolInfo() = 0; + virtual void resetPool() = 0; + + protected: + // Hybrid Setup + void loadHybridMethods() override; + + protected: + // Tag for logging + static constexpr auto TAG = "ReactNativeSmb"; + }; + +} // namespace margelo::nitro::smb diff --git a/nitrogen/generated/shared/c++/SmbCredentials.hpp b/nitrogen/generated/shared/c++/SmbCredentials.hpp new file mode 100644 index 0000000..c63e636 --- /dev/null +++ b/nitrogen/generated/shared/c++/SmbCredentials.hpp @@ -0,0 +1,87 @@ +/// +/// SmbCredentials.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + + + +#include + +namespace margelo::nitro::smb { + + /** + * A struct which can be represented as a JavaScript object (SmbCredentials). + */ + struct SmbCredentials final { + public: + std::string username SWIFT_PRIVATE; + std::string password SWIFT_PRIVATE; + + public: + SmbCredentials() = default; + explicit SmbCredentials(std::string username, std::string password): username(username), password(password) {} + + public: + friend bool operator==(const SmbCredentials& lhs, const SmbCredentials& rhs) = default; + }; + +} // namespace margelo::nitro::smb + +namespace margelo::nitro { + + // C++ SmbCredentials <> JS SmbCredentials (object) + template <> + struct JSIConverter final { + static inline margelo::nitro::smb::SmbCredentials fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + jsi::Object obj = arg.asObject(runtime); + return margelo::nitro::smb::SmbCredentials( + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "username"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "password"))) + ); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::smb::SmbCredentials& arg) { + jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "username"), JSIConverter::toJSI(runtime, arg.username)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "password"), JSIConverter::toJSI(runtime, arg.password)); + return obj; + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + return false; + } + jsi::Object obj = value.getObject(runtime); + if (!nitro::isPlainObject(runtime, obj)) { + return false; + } + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "username")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "password")))) return false; + return true; + } + }; + +} // namespace margelo::nitro diff --git a/package-lock.json b/package-lock.json index cf942f1..b615675 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,8 +10,9 @@ "license": "LGPL-2.1", "devDependencies": { "@types/react": "^19.1.1", + "nitrogen": "^0.37.2", "react-native": "0.83.4", - "react-native-nitro-modules": "~0.31.9", + "react-native-nitro-modules": "^0.37.2", "typescript": "^5.0.0", "vitest": "^4.1.11" }, @@ -1176,6 +1177,57 @@ "dev": true, "license": "MIT" }, + "node_modules/@ts-morph/common": { + "version": "0.29.0", + "resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.29.0.tgz", + "integrity": "sha512-35oUmphHbJvQ/+UTwFNme/t2p3FoKiGJ5auTjjpNTop2dyREspirjMy82PLSC1pnDJ8ah1GU98hwpVt64YXQsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "minimatch": "^10.0.1", + "path-browserify": "^1.0.1", + "tinyglobby": "^0.2.14" + } + }, + "node_modules/@ts-morph/common/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@ts-morph/common/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@ts-morph/common/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -1898,6 +1950,13 @@ "node": ">=12" } }, + "node_modules/code-block-writer": { + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-13.0.3.tgz", + "integrity": "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg==", + "dev": true, + "license": "MIT" + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -2337,6 +2396,19 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-package-type": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", @@ -3673,6 +3745,206 @@ "node": ">= 0.6" } }, + "node_modules/nitro-core": { + "version": "0.37.2", + "resolved": "https://registry.npmjs.org/nitro-core/-/nitro-core-0.37.2.tgz", + "integrity": "sha512-dhagikz9VXXzfidRH/vPNJfYWPmTBArDOo9wE/wEqeERU9C8uRWz9YccOyNUOvADccPAZq319yzhDMoJ9excSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/nitrogen": { + "version": "0.37.2", + "resolved": "https://registry.npmjs.org/nitrogen/-/nitrogen-0.37.2.tgz", + "integrity": "sha512-dqQIrtU9EmFgUa+FLnUeITQRjQGsq3K1rH+fvgRflA64Xmy04oJGXl6arerzsKIocg8nZoWZiq7z803iw+4gNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^5.3.0", + "nitro-core": "0.37.2", + "ts-morph": "^28.0.0", + "yargs": "^18.0.0", + "zod": "^4.4.3" + }, + "bin": { + "nitrogen": "lib/index.js" + } + }, + "node_modules/nitrogen/node_modules/ansi-regex": { + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz", + "integrity": "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/nitrogen/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/nitrogen/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/nitrogen/node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/nitrogen/node_modules/cliui/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/nitrogen/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" + }, + "node_modules/nitrogen/node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/nitrogen/node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/nitrogen/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/nitrogen/node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/nitrogen/node_modules/yargs": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz", + "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^8.2.1", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/nitrogen/node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, "node_modules/node-int64": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", @@ -3820,6 +4092,13 @@ "node": ">= 0.8" } }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -4062,12 +4341,14 @@ } }, "node_modules/react-native-nitro-modules": { - "version": "0.31.10", - "resolved": "https://registry.npmjs.org/react-native-nitro-modules/-/react-native-nitro-modules-0.31.10.tgz", - "integrity": "sha512-hcvjTu9YJE9fMmnAUvhG8CxvYLpOuMQ/2eyi/S6GyrecezF6Rmk/uRQEL6v09BRFWA/xRVZNQVulQPS+2HS3mQ==", + "version": "0.37.2", + "resolved": "https://registry.npmjs.org/react-native-nitro-modules/-/react-native-nitro-modules-0.37.2.tgz", + "integrity": "sha512-Odnrq/p6/q0R01qZlkqeXu9VHHMuGEnZZmyxMvehEu6QiACNHhBCmAHgyBDqOSo9Lb3G0TscFAT+HG0uxsR/GA==", "dev": true, - "hasInstallScript": true, "license": "MIT", + "dependencies": { + "nitro-core": "0.37.2" + }, "peerDependencies": { "react": "*", "react-native": "*" @@ -4692,6 +4973,17 @@ "node": ">=0.6" } }, + "node_modules/ts-morph": { + "version": "28.0.0", + "resolved": "https://registry.npmjs.org/ts-morph/-/ts-morph-28.0.0.tgz", + "integrity": "sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ts-morph/common": "~0.29.0", + "code-block-writer": "^13.0.3" + } + }, "node_modules/type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", @@ -5157,6 +5449,16 @@ "engines": { "node": ">=12" } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/package.json b/package.json index b2d2b38..3be0bbc 100644 --- a/package.json +++ b/package.json @@ -5,11 +5,12 @@ "main": "lib/index.js", "types": "lib/index.d.ts", "scripts": { + "specs": "nitrogen", "build": "tsc", "build:libsmb2": "chmod +x scripts/build-libsmb2.sh && scripts/build-libsmb2.sh", "build:xcframework": "chmod +x scripts/create-xcframework.sh && scripts/create-xcframework.sh", "build:ios": "npm run build:libsmb2 && npm run build:xcframework", - "build:full": "npm run build && npm run build:ios", + "build:full": "npm run specs && npm run build && npm run build:ios", "prepare": "npm run build", "prepack": "npm run clean && npm run build:full", "postpack": "npm run clean:build", @@ -45,12 +46,18 @@ "peerDependencies": { "react": ">=19.0.0", "react-native": ">=0.76.0", - "react-native-nitro-modules": ">=0.22.0 <1.0.0" + "react-native-nitro-modules": "*" + }, + "peerDependenciesMeta": { + "react-native-nitro-modules": { + "optional": true + } }, "devDependencies": { "@types/react": "^19.1.1", + "nitrogen": "0.37.2", "react-native": "0.83.4", - "react-native-nitro-modules": "~0.31.9", + "react-native-nitro-modules": "0.37.2", "typescript": "^5.0.0", "vitest": "^4.1.11" }, @@ -59,6 +66,8 @@ "cpp/", "ios/", "docs/", + "nitrogen/", + "nitro.json", "ReactNativeSmb.podspec" ] } diff --git a/src/ReactNativeSmb.ts b/src/ReactNativeSmb.ts index 15f0c0e..1db266d 100644 --- a/src/ReactNativeSmb.ts +++ b/src/ReactNativeSmb.ts @@ -1,269 +1 @@ -import type { HybridObject } from 'react-native-nitro-modules'; -import type { SmbCredentials, NativeSmbListTask, NativeSmbTask } from './types'; - -/** - * A Nitro module that provides SMB client functionality using libsmb2 - * - * This interface provides low-level access to SMB operations with proper - * TypeScript typing for React Native applications. - */ -export interface ReactNativeSmb extends HybridObject<{ ios: 'c++'; android: 'c++' }> { - // State Checks - // ---------------------------------------------- - - /** - * Checks connection status - * @returns True if currently connected to an SMB server - */ - isConnected(): boolean; - - /** - * Checks if the SMB client is initialized - * @returns True if initialized, false otherwise - */ - isInitialized(): boolean; - - // Connection Management - // ---------------------------------------------- - - /** - * Configures an SMB server (without connecting to a specific share) - * @param url Server URL (`smb://host[:port]`) - * @param credentials Authentication credentials - * @returns SmbTask that resolves when initialized - */ - initialize(taskId: string, url: string, credentials: SmbCredentials): NativeSmbTask; - - /** - * Establishes a connection to an SMB share - * @param url The SMB server URL (`smb://host[:port]/share`) - * @param credentials Authentication credentials - * @returns SmbTask with connection information - * @throws {Error} When connection fails - * - * @example - * await smb.connect('smb://192.168.1.100/Media', { - * username: 'admin', - * password: 'secret' - * }); - */ - connect(taskId: string, url: string, credentials: SmbCredentials): NativeSmbTask; - - /** - * Connects to a specific share - * @param share Name of the share to connect to - * @returns SmbTask that resolves when connected - * @throws {Error} If not initialized or share doesn't exist - */ - connectShare(taskId: string, share: string): NativeSmbTask; - - /** - * Cancels active work and disconnects from the current SMB server. The client can be reused. - * @returns SmbTask that resolves when disconnected - */ - disconnect(taskId: string): NativeSmbTask; - - - /** - * Lists available shares on the server - * @returns SmbTask resolving to array of share information - * @throws {Error} If not initialized - * - * @example - * const shares = await smb.listShares(); - * shares.forEach(share => console.log(share.name)); - */ - listShares(taskId: string): NativeSmbTask; - - - // Listing & Info - // ---------------------------------------------- - - /** - * Lists contents of a directory - * @param taskId Unique ID for the task - * @param path Directory path (use "/" for root) - * @param maxDepth Nested levels to include as children (0 = this level only, -1 = unlimited) - * @param includeSecurityDescriptor Whether to fetch each item's security descriptor - * @param batchSize Top-level entries per streamed batch (batches also flush every 100 ms) - * @returns SmbTask resolving to array of file/directory info; top-level entries also stream - */ - listDirectory( - taskId: string, - path: string, - maxDepth: number, - includeSecurityDescriptor: boolean, - batchSize: number, - ): NativeSmbListTask; - - - /** - * Gets information about a path (file or directory) from the item itself. - * @param taskId Unique ID for the task - * @param path Path to the item ("/" is the share root) - * @returns SmbTask resolving to file information with a security descriptor when available; - * folders include `childCount` but not `children` - */ - getPathInfo(taskId: string, path: string): NativeSmbTask; - - - /** - * Retrieves security descriptor for a file/directory - * @param taskId Unique ID for the task - * @param path Path to the item - * @returns SmbTask resolving to security descriptor - * - * @example - * const security = await smb.getSecurityDescriptor('/important.txt'); - * console.log('Owner:', security.ownerSid); - */ - getSecurityDescriptor(taskId: string, path: string): NativeSmbTask; - - - // File Transfers - // ---------------------------------------------- - - downloadFile(taskId: string, remotePath: string, localPath: string): NativeSmbTask; - - - /** - * Uploads a file from local storage to the SMB server - * @param localPath Local path to the file - * @param remotePath Destination path on the server - * @returns SmbTask that resolves when upload completes; subscribe for progress - */ - uploadFile(taskId: string, localPath: string, remotePath: string): NativeSmbTask; - - - // Mutating File Operations - // ---------------------------------------------- - - /** - * Creates a new directory - * @param path Path of the directory to create - * @returns SmbTask that resolves when directory is created - */ - createDirectory(taskId: string, path: string): NativeSmbTask; - - - /** - * Deletes a file or directory (automatically handles recursive deletion) - * @param path Path to the item to delete - * @returns SmbTask that resolves when deletion completes - */ - deleteItem(taskId: string, path: string): NativeSmbTask; - - - /** - * Moves or renames a file/directory - * @param fromPath Current path - * @param toPath New path - * @returns SmbTask that resolves when move completes - */ - moveItem(taskId: string, fromPath: string, toPath: string): NativeSmbTask; - - - /** - * Renames a file/directory (in the same directory) - * @param currentPath Current path - * @param newName New name (without path) - * @returns SmbTask that resolves when rename completes - */ - renameItem(taskId: string, currentPath: string, newName: string): NativeSmbTask; - - - /** - * Copies a file or directory on the SMB server - * @param taskId Unique ID for the task - * @param fromPath Source path - * @param toPath Destination path - * @param recursive Whether to copy recursively - * @returns SmbTask that resolves when the copy completes; subscribe for progress - */ - copyItem(taskId: string, fromPath: string, toPath: string, recursive: boolean): NativeSmbTask; - - - /** - * Duplicates an item giving it a unique name - * @param path Path to the item - * @returns SmbTask resolving to the new path - */ - duplicateItem(taskId: string, path: string): NativeSmbTask; - - // Task control - - /** - * Subscribe to task events (created, status, progress, settled, removed) - * @param listener Callback that receives task events - * @returns Subscription ID for unsubscribing - */ - subscribeTaskEvents(listener: (event: Record) => void): string; - - /** - * Unsubscribe from task events - * @param subscriptionId The subscription ID returned from subscribeTaskEvents - */ - unsubscribeTaskEvents(subscriptionId: string): void; - - /** - * Get a specific task snapshot by ID - * @param taskId The task ID to retrieve - * @returns Task snapshot as string-keyed map, or {exists: '0'} if not found - */ - getTask(taskId: string): Record; - - /** - * Get all currently active (pending/running) tasks - * @returns Array of task snapshots - */ - getActiveTasks(): Array>; - - /** Get the latest snapshot for every transfer task observed by this client. */ - getTransferTasks(): Array>; - - /** - * Get task history (settled tasks) - * @param limit Maximum number of tasks to return - * @param offset Number of tasks to skip - * @returns Array of task snapshots - */ - getTaskHistory(limit: number, offset: number): Array>; - - /** - * Cancels a specific task by ID - */ - cancelTask(taskId: string): void; - - /** - * Cancels unsettled transfer tasks (download/upload/copy/duplicate), including queued pool waiters. - * Does not cancel connection, listing, or mutation tasks. - */ - cancelTransferTasks(): void; - - /** - * Clear task history - * @param beforeTs Clear tasks that ended before this timestamp (0 = clear all) - */ - clearTaskHistory(beforeTs: bigint): void; - - /** - * Tear down this SMB client: cancel tasks, disconnect the pool, wait for workers. - * The instance is not reusable afterwards — call `SMB()` for a new client. - */ - destroy(): Promise; - - // Debug / instrumentation - - subscribePoolInfo(listener: (snapshot: Array<{ [key: string]: string }>) => void): string; - - unsubscribePoolInfo(subscriptionId: string): void; - - getPoolInfo(): Array<{ [key: string]: string }>; - - /** - * Force-disconnects every connection-pool slot and forgets cached config. - * Use for recovery when slots become stuck (`isConnected:false` but - * `inUse:true`). Subsequent operations must re-connect from scratch. - */ - resetPool(): void; -} +export type { ReactNativeSmb } from './specs/ReactNativeSmb.nitro' diff --git a/src/core/SmbClient.ts b/src/core/SmbClient.ts index 9dae541..0bd2874 100644 --- a/src/core/SmbClient.ts +++ b/src/core/SmbClient.ts @@ -3,6 +3,7 @@ import { shapePoolInfo } from '../bridge/decode'; import type { ReactNativeSmb } from '../ReactNativeSmb'; import type { ListDirectoryOptions, + NativeSmbListTask, NativeSmbTask, PoolInfo, SmbConnectionInfo, @@ -27,9 +28,10 @@ export class SmbClient { native ?? NitroModules.createHybridObject('ReactNativeSmb'); } - private op(call: (taskId: string) => NativeSmbTask): SmbTask { + private op(call: (taskId: string) => import('../specs/NativeSmbTask.nitro').NativeSmbTask): SmbTask { const id = generateTaskId(); - return new SmbTask(id, call(id)); + // getResultValue is a raw JSI method on HybridSmbTask, not in the Nitrogen spec. + return new SmbTask(id, call(id) as NativeSmbTask); } transferStore(): TransferStore { @@ -87,7 +89,11 @@ export class SmbClient { listDirectory(path: string, options: ListDirectoryOptions = {}): SmbListTask { const { maxDepth = 0, includeSecurityDescriptor = false, batchSize = DEFAULT_LIST_BATCH_SIZE } = options; const id = generateTaskId(); - return new SmbListTask(id, this.native.listDirectory(id, path, maxDepth, includeSecurityDescriptor, batchSize)); + // drainEntries is a raw JSI method on every HybridSmbTask; list ops use NativeSmbListTask. + return new SmbListTask( + id, + this.native.listDirectory(id, path, maxDepth, includeSecurityDescriptor, batchSize) as NativeSmbListTask, + ); } getPathInfo(path: string): SmbTask { diff --git a/src/specs/NativeSmbTask.nitro.ts b/src/specs/NativeSmbTask.nitro.ts new file mode 100644 index 0000000..298c09f --- /dev/null +++ b/src/specs/NativeSmbTask.nitro.ts @@ -0,0 +1,17 @@ +import type { HybridObject } from 'react-native-nitro-modules' + +/** + * Nitro HybridObject for one native SMB operation. + * + * `getResultValue` and `drainEntries` are registered as raw JSI methods in + * HybridSmbTask (result type varies; SmbFileInfo is recursive and cannot be + * Nitrogen-generated). + */ +export interface NativeSmbTask extends HybridObject<{ ios: 'c++'; android: 'c++' }> { + cancel(): void + get(): Record + subscribe(listener: (snapshot: Record) => void): string + unsubscribe(subscriptionId: string): void + subscribeEntries(listener: () => void): string + unsubscribeEntries(subscriptionId: string): void +} diff --git a/src/specs/ReactNativeSmb.nitro.ts b/src/specs/ReactNativeSmb.nitro.ts new file mode 100644 index 0000000..a1ee89a --- /dev/null +++ b/src/specs/ReactNativeSmb.nitro.ts @@ -0,0 +1,55 @@ +import type { HybridObject, Int64 } from 'react-native-nitro-modules' +import type { NativeSmbTask } from './NativeSmbTask.nitro' +import type { SmbCredentials } from './types' + +/** + * Nitro HybridObject for the SMB client. + * Method table and struct converters are generated by Nitrogen. + */ +export interface ReactNativeSmb extends HybridObject<{ ios: 'c++'; android: 'c++' }> { + isConnected(): boolean + isInitialized(): boolean + + initialize(taskId: string, url: string, credentials: SmbCredentials): NativeSmbTask + connect(taskId: string, url: string, credentials: SmbCredentials): NativeSmbTask + connectShare(taskId: string, share: string): NativeSmbTask + disconnect(taskId: string): NativeSmbTask + listShares(taskId: string): NativeSmbTask + + listDirectory( + taskId: string, + path: string, + maxDepth: number, + includeSecurityDescriptor: boolean, + batchSize: number, + ): NativeSmbTask + getPathInfo(taskId: string, path: string): NativeSmbTask + getSecurityDescriptor(taskId: string, path: string): NativeSmbTask + + downloadFile(taskId: string, remotePath: string, localPath: string): NativeSmbTask + uploadFile(taskId: string, localPath: string, remotePath: string): NativeSmbTask + + createDirectory(taskId: string, path: string): NativeSmbTask + deleteItem(taskId: string, path: string): NativeSmbTask + moveItem(taskId: string, fromPath: string, toPath: string): NativeSmbTask + renameItem(taskId: string, currentPath: string, newName: string): NativeSmbTask + copyItem(taskId: string, fromPath: string, toPath: string, recursive: boolean): NativeSmbTask + duplicateItem(taskId: string, path: string): NativeSmbTask + + subscribeTaskEvents(listener: (event: Record) => void): string + unsubscribeTaskEvents(subscriptionId: string): void + getTask(taskId: string): Record + getActiveTasks(): Record[] + getTransferTasks(): Record[] + getTaskHistory(limit: number, offset: number): Record[] + cancelTask(taskId: string): void + cancelTransferTasks(): void + clearTaskHistory(beforeTs: Int64): void + + destroy(): Promise + + subscribePoolInfo(listener: (snapshot: Record[]) => void): string + unsubscribePoolInfo(subscriptionId: string): void + getPoolInfo(): Record[] + resetPool(): void +} diff --git a/src/specs/types.ts b/src/specs/types.ts new file mode 100644 index 0000000..3951959 --- /dev/null +++ b/src/specs/types.ts @@ -0,0 +1,44 @@ +/** + * Structs shared by Nitrogen HybridObject specs. + * Domain C++ keeps its own SmbModels with int64_t; bridge maps between them. + * SmbFileInfo is intentionally absent — Nitrogen 0.37.2 cannot generate + * recursive structs; it stays hand-converted via JSIConverter. + */ + +export interface SmbCredentials { + username: string + password: string +} + +export interface SmbShare { + name: string + comment: string +} + +export interface SmbConnectionInfo { + url: string + server: string + share: string + isConnected: boolean +} + +export interface SmbAce { + aceType: string + aceFlags: string[] + mask: string[] + sid: string +} + +export interface SmbAcl { + revision: number + aceCount: number + aces: SmbAce[] +} + +export interface SmbSecurityDescriptor { + revision: number + control: string[] + ownerSid: string + groupSid: string + dacl: SmbAcl +} diff --git a/src/types.ts b/src/types.ts index 4efefe0..5dc3d91 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,19 +1,13 @@ -export interface SmbCredentials { - readonly username: string; - readonly password: string; -} +import type { NativeSmbTask as NitroNativeSmbTask } from './specs/NativeSmbTask.nitro' -export interface SmbShare { - readonly name: string; - readonly comment: string; -} - -export interface SmbConnectionInfo { - readonly url: string; - readonly server: string; - readonly share: string; - readonly isConnected: boolean; -} +export type { + SmbCredentials, + SmbShare, + SmbConnectionInfo, + SmbAce, + SmbAcl, + SmbSecurityDescriptor, +} from './specs/types' export enum SmbError { Unknown = 0, @@ -35,65 +29,44 @@ export enum SmbError { } export class SmbTaskError extends Error { - readonly code: SmbError; - readonly taskId?: string; + readonly code: SmbError + readonly taskId?: string constructor(message: string, code: SmbError = SmbError.Unknown, taskId?: string) { - super(message); - this.code = code; - this.taskId = taskId; + super(message) + this.code = code + this.taskId = taskId } } export interface SmbFileInfo { - readonly name: string; - readonly path: string; - readonly size: number; - readonly isDirectory: boolean; - readonly modifiedAt: number; - readonly accessedAt: number; - readonly createdAt: number; - readonly changedAt: number; - readonly childCount?: number; - readonly children?: SmbFileInfo[]; - readonly securityDescriptor?: SmbSecurityDescriptor; + readonly name: string + readonly path: string + readonly size: number + readonly isDirectory: boolean + readonly modifiedAt: number + readonly accessedAt: number + readonly createdAt: number + readonly changedAt: number + readonly childCount?: number + readonly children?: SmbFileInfo[] + readonly securityDescriptor?: import('./specs/types').SmbSecurityDescriptor } export interface ListDirectoryOptions { /** Nested levels to include as `children`: 0 = this level only (default), -1 = unlimited. */ - readonly maxDepth?: number; + readonly maxDepth?: number /** Fetch each item's security descriptor (default `false`). */ - readonly includeSecurityDescriptor?: boolean; + readonly includeSecurityDescriptor?: boolean /** Top-level entries per streamed batch (default 10). */ - readonly batchSize?: number; -} - -export interface SmbAce { - readonly aceType: string; - readonly aceFlags: string[]; - readonly mask: string[]; - readonly sid: string; -} - -export interface SmbAcl { - readonly revision: number; - readonly aceCount: number; - readonly aces: SmbAce[]; -} - -export interface SmbSecurityDescriptor { - readonly revision: number; - readonly control: string[]; - readonly ownerSid: string; - readonly groupSid: string; - readonly dacl: SmbAcl; + readonly batchSize?: number } export interface PathComponents { - readonly parentDirectory: string; - readonly baseFileName: string; - readonly extension: string; - readonly fullFileName: string; + readonly parentDirectory: string + readonly baseFileName: string + readonly extension: string + readonly fullFileName: string } export enum TaskStatus { @@ -131,53 +104,52 @@ export enum SlotState { } export interface SmbTaskState { - readonly taskId: string; - readonly kind: SmbOperatorKind; - readonly status: TaskStatus; - readonly determinate: boolean; - readonly progress: number; - readonly bytesDone: number; - readonly totalBytes: number; - readonly bytesPerSecond: number; - readonly etaSeconds: number; - readonly sourcePath: string; - readonly destinationPath: string; - readonly errorCode: number; - readonly errorMessage: string; - readonly startedAt: number; - readonly updatedAt: number; - readonly endedAt: number; + readonly taskId: string + readonly kind: SmbOperatorKind + readonly status: TaskStatus + readonly determinate: boolean + readonly progress: number + readonly bytesDone: number + readonly totalBytes: number + readonly bytesPerSecond: number + readonly etaSeconds: number + readonly sourcePath: string + readonly destinationPath: string + readonly errorCode: number + readonly errorMessage: string + readonly startedAt: number + readonly updatedAt: number + readonly endedAt: number } export interface PoolSlotInfo { - readonly index: number; - readonly interactiveOnly: boolean; - readonly state: SlotState; - readonly isConnected: boolean; - readonly shareName: string; - readonly taskId: string; - readonly kind: SmbOperatorKind; + readonly index: number + readonly interactiveOnly: boolean + readonly state: SlotState + readonly isConnected: boolean + readonly shareName: string + readonly taskId: string + readonly kind: SmbOperatorKind } export interface PoolInfo { - readonly poolSize: number; - readonly slots: PoolSlotInfo[]; + readonly poolSize: number + readonly slots: PoolSlotInfo[] } -export interface NativeSmbTask { - cancel(): void; - get(): Record; - subscribe(listener: (snapshot: Record) => void): string; - unsubscribe(subscriptionId: string): void; - getResultValue(): unknown; +/** + * Native HybridObject for one SMB task. + * Nitrogen generates cancel/get/subscribe/…; getResultValue and drainEntries + * are registered as raw JSI methods on HybridSmbTask. + */ +export type NativeSmbTask = NitroNativeSmbTask & { + getResultValue(): unknown } -export interface NativeSmbListTask extends NativeSmbTask { +export type NativeSmbListTask = NativeSmbTask & { /** * Payload-free wake for new entries. Call {@link drainEntries} to pull every * entry appended since the last drain (including a late-subscribe replay). */ - subscribeEntries(listener: () => void): string; - unsubscribeEntries(subscriptionId: string): void; - drainEntries(subscriptionId: string): SmbFileInfo[]; + drainEntries(subscriptionId: string): SmbFileInfo[] } From 67d6d158c75044ec73d88fe5a5f987504b6cf43f Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:26:06 +0800 Subject: [PATCH 2/5] fix(deps): require nitro-modules 0.37.2 or newer Generated Nitrogen headers target 0.37.2, so an older peer would compile against the wrong APIs. Keep the peer optional for non-RN consumers of the TypeScript surface. - set peerDependencies.react-native-nitro-modules to >=0.37.2 --- package-lock.json | 11 ++++++++--- package.json | 2 +- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index b615675..ad32ed6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,16 +10,21 @@ "license": "LGPL-2.1", "devDependencies": { "@types/react": "^19.1.1", - "nitrogen": "^0.37.2", + "nitrogen": "0.37.2", "react-native": "0.83.4", - "react-native-nitro-modules": "^0.37.2", + "react-native-nitro-modules": "0.37.2", "typescript": "^5.0.0", "vitest": "^4.1.11" }, "peerDependencies": { "react": ">=19.0.0", "react-native": ">=0.76.0", - "react-native-nitro-modules": ">=0.22.0 <1.0.0" + "react-native-nitro-modules": ">=0.37.2" + }, + "peerDependenciesMeta": { + "react-native-nitro-modules": { + "optional": true + } } }, "node_modules/@ampproject/remapping": { diff --git a/package.json b/package.json index 3be0bbc..3d09763 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "peerDependencies": { "react": ">=19.0.0", "react-native": ">=0.76.0", - "react-native-nitro-modules": "*" + "react-native-nitro-modules": ">=0.37.2" }, "peerDependenciesMeta": { "react-native-nitro-modules": { From f3d05341ec872e19555044d230c7a0e62223f97d Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:30:54 +0800 Subject: [PATCH 3/5] refactor(bridge): keep JSI out of the SMB domain layer Domain tasks stored results as any plus a jsi::Runtime converter, so operators and SmbTaskCore depended on Nitro headers. Publish a typed variant instead and convert only in HybridSmbTask. - add SmbTaskResult and ListingResult; EntryStream still holds listing rows - move hand-written JSIConverters into bridge/DomainConverters.hpp - strip jsi includes from SmbTaskCore, SmbTask, and OperatorBase --- cpp/shared/bridge/DomainConverters.hpp | 324 ++++++++++++++++ cpp/shared/bridge/HybridSmbTask.cpp | 36 +- cpp/shared/core/SmbModels.hpp | 345 ------------------ cpp/shared/core/SmbTask.hpp | 6 - cpp/shared/core/SmbTaskCore.cpp | 16 +- cpp/shared/core/SmbTaskCore.hpp | 18 +- cpp/shared/core/SmbTaskResult.hpp | 18 + cpp/shared/operators/Operator.hpp | 18 +- cpp/shared/operators/OperatorBase.cpp | 4 +- cpp/shared/operators/OperatorBase.hpp | 11 +- .../listing/ListDirectoryOperator.cpp | 12 +- 11 files changed, 400 insertions(+), 408 deletions(-) create mode 100644 cpp/shared/bridge/DomainConverters.hpp create mode 100644 cpp/shared/core/SmbTaskResult.hpp diff --git a/cpp/shared/bridge/DomainConverters.hpp b/cpp/shared/bridge/DomainConverters.hpp new file mode 100644 index 0000000..8a2ebaa --- /dev/null +++ b/cpp/shared/bridge/DomainConverters.hpp @@ -0,0 +1,324 @@ +#pragma once + +#include +#include + +#include "../core/SmbModels.hpp" + +// Hand-written JSIConverters for domain result types. +// SmbFileInfo is recursive — Nitrogen 0.37.2 cannot generate it. +// Other result structs are returned via raw getResultValue, not Nitrogen method tables. +namespace margelo::nitro { +using namespace react_native_smb; + +namespace react_native_smb_detail { +inline jsi::Value smbSecurityDescriptorToJSI(jsi::Runtime& runtime, const SmbSecurityDescriptor& sd); +inline SmbSecurityDescriptor smbSecurityDescriptorFromJSI(jsi::Runtime& runtime, const jsi::Value& value); +} // namespace react_native_smb_detail + +template <> +struct JSIConverter { + static jsi::Value toJSI(jsi::Runtime& runtime, const SmbConnectionInfo& connection) { + jsi::Object obj(runtime); + obj.setProperty(runtime, "url", jsi::String::createFromUtf8(runtime, connection.url)); + obj.setProperty(runtime, "server", jsi::String::createFromUtf8(runtime, connection.server)); + obj.setProperty(runtime, "share", jsi::String::createFromUtf8(runtime, connection.share)); + obj.setProperty(runtime, "isConnected", jsi::Value(connection.isConnected)); + return obj; + } + + static SmbConnectionInfo fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + throw std::invalid_argument("SmbConnectionInfo must be an object"); + } + jsi::Object obj = value.asObject(runtime); + return SmbConnectionInfo{obj.getProperty(runtime, "url").asString(runtime).utf8(runtime), + obj.getProperty(runtime, "server").asString(runtime).utf8(runtime), + obj.getProperty(runtime, "share").asString(runtime).utf8(runtime), + obj.getProperty(runtime, "isConnected").asBool()}; + } + + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } +}; + +template <> +struct JSIConverter { + static jsi::Value toJSI(jsi::Runtime& runtime, const SmbFileInfo& fileInfo) { + jsi::Object obj(runtime); + obj.setProperty(runtime, "name", jsi::String::createFromUtf8(runtime, fileInfo.name)); + obj.setProperty(runtime, "path", jsi::String::createFromUtf8(runtime, fileInfo.path)); + obj.setProperty(runtime, "size", jsi::Value(static_cast(fileInfo.size))); + obj.setProperty(runtime, "isDirectory", jsi::Value(fileInfo.isDirectory)); + obj.setProperty(runtime, "modifiedAt", jsi::Value(static_cast(fileInfo.modifiedAt))); + obj.setProperty(runtime, "accessedAt", jsi::Value(static_cast(fileInfo.accessedAt))); + obj.setProperty(runtime, "createdAt", jsi::Value(static_cast(fileInfo.createdAt))); + obj.setProperty(runtime, "changedAt", jsi::Value(static_cast(fileInfo.changedAt))); + obj.setProperty(runtime, "childCount", jsi::Value(static_cast(fileInfo.childCount))); + + jsi::Array childrenArray(runtime, fileInfo.children.size()); + for (size_t i = 0; i < fileInfo.children.size(); i++) { + childrenArray.setValueAtIndex(runtime, i, toJSI(runtime, fileInfo.children[i])); + } + obj.setProperty(runtime, "children", std::move(childrenArray)); + + if (fileInfo.securityDescriptor.has_value()) { + obj.setProperty(runtime, "securityDescriptor", + react_native_smb_detail::smbSecurityDescriptorToJSI(runtime, *fileInfo.securityDescriptor)); + } + + return obj; + } + + static SmbFileInfo fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + throw std::invalid_argument("SmbFileInfo must be an object"); + } + + jsi::Object obj = value.asObject(runtime); + + std::vector children; + if (obj.hasProperty(runtime, "children")) { + jsi::Value childrenValue = obj.getProperty(runtime, "children"); + if (childrenValue.isObject() && childrenValue.asObject(runtime).isArray(runtime)) { + jsi::Array childrenArray = childrenValue.asObject(runtime).asArray(runtime); + size_t childrenCount = childrenArray.size(runtime); + children.reserve(childrenCount); + for (size_t i = 0; i < childrenCount; i++) { + children.push_back(fromJSI(runtime, childrenArray.getValueAtIndex(runtime, i))); + } + } + } + + std::optional securityDescriptor; + if (obj.hasProperty(runtime, "securityDescriptor")) { + jsi::Value securityDescriptorValue = obj.getProperty(runtime, "securityDescriptor"); + if (securityDescriptorValue.isObject()) { + securityDescriptor = react_native_smb_detail::smbSecurityDescriptorFromJSI(runtime, securityDescriptorValue); + } + } + + return SmbFileInfo{obj.getProperty(runtime, "name").asString(runtime).utf8(runtime), + obj.getProperty(runtime, "path").asString(runtime).utf8(runtime), + static_cast(obj.getProperty(runtime, "size").asNumber()), + obj.getProperty(runtime, "isDirectory").asBool(), + static_cast(obj.getProperty(runtime, "modifiedAt").asNumber()), + static_cast(obj.hasProperty(runtime, "accessedAt") ? obj.getProperty(runtime, "accessedAt").asNumber() : 0), + static_cast(obj.hasProperty(runtime, "createdAt") ? obj.getProperty(runtime, "createdAt").asNumber() : 0), + static_cast(obj.hasProperty(runtime, "changedAt") ? obj.getProperty(runtime, "changedAt").asNumber() : 0), + static_cast(obj.hasProperty(runtime, "childCount") ? obj.getProperty(runtime, "childCount").asNumber() : -1), + children, + securityDescriptor}; + } + + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } +}; + +template <> +struct JSIConverter { + static jsi::Value toJSI(jsi::Runtime& runtime, const SmbShare& share) { + jsi::Object obj(runtime); + obj.setProperty(runtime, "name", jsi::String::createFromUtf8(runtime, share.name)); + obj.setProperty(runtime, "comment", jsi::String::createFromUtf8(runtime, share.comment)); + return obj; + } + + static SmbShare fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + throw std::invalid_argument("SmbShare must be an object"); + } + jsi::Object obj = value.asObject(runtime); + return SmbShare{obj.getProperty(runtime, "name").asString(runtime).utf8(runtime), + obj.getProperty(runtime, "comment").asString(runtime).utf8(runtime)}; + } + + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } +}; + +template <> +struct JSIConverter { + static jsi::Value toJSI(jsi::Runtime& runtime, const SmbAce& ace) { + jsi::Object obj(runtime); + obj.setProperty(runtime, "aceType", jsi::String::createFromUtf8(runtime, ace.aceType)); + + jsi::Array aceFlagsArray = jsi::Array(runtime, ace.aceFlags.size()); + for (size_t i = 0; i < ace.aceFlags.size(); i++) { + aceFlagsArray.setValueAtIndex(runtime, i, jsi::String::createFromUtf8(runtime, ace.aceFlags[i])); + } + obj.setProperty(runtime, "aceFlags", aceFlagsArray); + + jsi::Array maskArray = jsi::Array(runtime, ace.mask.size()); + for (size_t i = 0; i < ace.mask.size(); i++) { + maskArray.setValueAtIndex(runtime, i, jsi::String::createFromUtf8(runtime, ace.mask[i])); + } + obj.setProperty(runtime, "mask", maskArray); + + obj.setProperty(runtime, "sid", jsi::String::createFromUtf8(runtime, ace.sid)); + return obj; + } + + static SmbAce fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + throw std::invalid_argument("SmbAce must be an object"); + } + + jsi::Object obj = value.asObject(runtime); + SmbAce ace; + ace.aceType = obj.getProperty(runtime, "aceType").asString(runtime).utf8(runtime); + + if (obj.hasProperty(runtime, "aceFlags")) { + jsi::Value aceFlagsValue = obj.getProperty(runtime, "aceFlags"); + if (aceFlagsValue.isObject() && aceFlagsValue.asObject(runtime).isArray(runtime)) { + jsi::Array aceFlagsArray = aceFlagsValue.asObject(runtime).asArray(runtime); + size_t flagsCount = aceFlagsArray.size(runtime); + ace.aceFlags.reserve(flagsCount); + for (size_t i = 0; i < flagsCount; i++) { + jsi::Value flagItem = aceFlagsArray.getValueAtIndex(runtime, i); + if (flagItem.isString()) { + ace.aceFlags.push_back(flagItem.asString(runtime).utf8(runtime)); + } + } + } + } + + if (obj.hasProperty(runtime, "mask")) { + jsi::Value maskValue = obj.getProperty(runtime, "mask"); + if (maskValue.isObject() && maskValue.asObject(runtime).isArray(runtime)) { + jsi::Array maskArray = maskValue.asObject(runtime).asArray(runtime); + size_t maskCount = maskArray.size(runtime); + ace.mask.reserve(maskCount); + for (size_t i = 0; i < maskCount; i++) { + jsi::Value maskItem = maskArray.getValueAtIndex(runtime, i); + if (maskItem.isString()) { + ace.mask.push_back(maskItem.asString(runtime).utf8(runtime)); + } + } + } + } + + ace.sid = obj.getProperty(runtime, "sid").asString(runtime).utf8(runtime); + return ace; + } + + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } +}; + +template <> +struct JSIConverter { + static jsi::Value toJSI(jsi::Runtime& runtime, const SmbAcl& acl) { + jsi::Object obj(runtime); + obj.setProperty(runtime, "revision", jsi::Value(static_cast(acl.revision))); + obj.setProperty(runtime, "aceCount", jsi::Value(static_cast(acl.aceCount))); + + jsi::Array aces = jsi::Array(runtime, acl.aces.size()); + for (size_t i = 0; i < acl.aces.size(); i++) { + aces.setValueAtIndex(runtime, i, JSIConverter::toJSI(runtime, acl.aces[i])); + } + obj.setProperty(runtime, "aces", aces); + return obj; + } + + static SmbAcl fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + throw std::invalid_argument("SmbAcl must be an object"); + } + + jsi::Object obj = value.asObject(runtime); + SmbAcl acl; + acl.revision = static_cast(obj.getProperty(runtime, "revision").asNumber()); + acl.aceCount = static_cast(obj.getProperty(runtime, "aceCount").asNumber()); + + if (obj.hasProperty(runtime, "aces")) { + jsi::Array aces = obj.getProperty(runtime, "aces").asObject(runtime).asArray(runtime); + size_t aceCount = aces.size(runtime); + acl.aces.reserve(aceCount); + for (size_t i = 0; i < aceCount; i++) { + acl.aces.push_back(JSIConverter::fromJSI(runtime, aces.getValueAtIndex(runtime, i))); + } + } + + return acl; + } + + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } +}; + +template <> +struct JSIConverter { + static jsi::Value toJSI(jsi::Runtime& runtime, const SmbSecurityDescriptor& sd) { + jsi::Object obj(runtime); + obj.setProperty(runtime, "revision", jsi::Value(static_cast(sd.revision))); + + jsi::Array controlArray = jsi::Array(runtime, sd.control.size()); + for (size_t i = 0; i < sd.control.size(); i++) { + controlArray.setValueAtIndex(runtime, i, jsi::String::createFromUtf8(runtime, sd.control[i])); + } + obj.setProperty(runtime, "control", controlArray); + + obj.setProperty(runtime, "ownerSid", jsi::String::createFromUtf8(runtime, sd.ownerSid)); + obj.setProperty(runtime, "groupSid", jsi::String::createFromUtf8(runtime, sd.groupSid)); + obj.setProperty(runtime, "dacl", JSIConverter::toJSI(runtime, sd.dacl)); + return obj; + } + + static SmbSecurityDescriptor fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + throw std::invalid_argument("SmbSecurityDescriptor must be an object"); + } + + jsi::Object obj = value.asObject(runtime); + SmbSecurityDescriptor sd; + sd.revision = static_cast(obj.getProperty(runtime, "revision").asNumber()); + + if (obj.hasProperty(runtime, "control")) { + jsi::Value controlValue = obj.getProperty(runtime, "control"); + if (controlValue.isObject() && controlValue.asObject(runtime).isArray(runtime)) { + jsi::Array controlArray = controlValue.asObject(runtime).asArray(runtime); + size_t controlCount = controlArray.size(runtime); + sd.control.reserve(controlCount); + for (size_t i = 0; i < controlCount; i++) { + jsi::Value controlItem = controlArray.getValueAtIndex(runtime, i); + if (controlItem.isString()) { + sd.control.push_back(controlItem.asString(runtime).utf8(runtime)); + } + } + } + } + + sd.ownerSid = obj.getProperty(runtime, "ownerSid").asString(runtime).utf8(runtime); + sd.groupSid = obj.getProperty(runtime, "groupSid").asString(runtime).utf8(runtime); + sd.dacl = JSIConverter::fromJSI(runtime, obj.getProperty(runtime, "dacl")); + return sd; + } + + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + (void)runtime; + return value.isObject(); + } +}; + +namespace react_native_smb_detail { +inline jsi::Value smbSecurityDescriptorToJSI(jsi::Runtime& runtime, const SmbSecurityDescriptor& sd) { + return JSIConverter::toJSI(runtime, sd); +} + +inline SmbSecurityDescriptor smbSecurityDescriptorFromJSI(jsi::Runtime& runtime, const jsi::Value& value) { + return JSIConverter::fromJSI(runtime, value); +} +} // namespace react_native_smb_detail + +} // namespace margelo::nitro diff --git a/cpp/shared/bridge/HybridSmbTask.cpp b/cpp/shared/bridge/HybridSmbTask.cpp index b7dbe78..23ec39a 100644 --- a/cpp/shared/bridge/HybridSmbTask.cpp +++ b/cpp/shared/bridge/HybridSmbTask.cpp @@ -1,9 +1,14 @@ #include "HybridSmbTask.hpp" #include +#include +#include +#include -#include "../core/SmbModels.hpp" +#include "DomainConverters.hpp" +#include "../core/EntryStream.hpp" #include "../core/SmbTask.hpp" +#include "../core/SmbTaskResult.hpp" namespace margelo::nitro::smb { @@ -32,7 +37,34 @@ void HybridSmbTask::unsubscribeEntries(const std::string& subscriptionId) { task facebook::jsi::Value HybridSmbTask::getResultValueRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& /*thisValue*/, const facebook::jsi::Value* /*args*/, size_t /*count*/) { - return task_->getResultValue(runtime); + using react_native_smb::ListingResult; + using react_native_smb::SmbConnectionInfo; + using react_native_smb::SmbFileInfo; + using react_native_smb::SmbSecurityDescriptor; + using react_native_smb::SmbShare; + using react_native_smb::SmbTaskResult; + + const SmbTaskResult value = task_->publishedResult(); + try { + return std::visit( + [&](const auto& v) -> facebook::jsi::Value { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return facebook::jsi::Value::undefined(); + } else if constexpr (std::is_same_v) { + const auto& stream = task_->entryStream(); + if (!stream) return facebook::jsi::Value::undefined(); + return stream->read([&](const std::vector& entries) { + return JSIConverter>::toJSI(runtime, entries); + }); + } else { + return JSIConverter::toJSI(runtime, v); + } + }, + value); + } catch (...) { + return facebook::jsi::Value::undefined(); + } } facebook::jsi::Value HybridSmbTask::drainEntriesRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& /*thisValue*/, diff --git a/cpp/shared/core/SmbModels.hpp b/cpp/shared/core/SmbModels.hpp index b2cffd8..09e7ba8 100644 --- a/cpp/shared/core/SmbModels.hpp +++ b/cpp/shared/core/SmbModels.hpp @@ -1,6 +1,5 @@ #pragma once -#include #include #include #include @@ -61,347 +60,3 @@ struct SmbFileInfo { }; } // namespace react_native_smb - -// Hand-written JSIConverters for domain result types. -// SmbFileInfo is recursive — Nitrogen 0.37.2 cannot generate it. -// Other result structs are returned via raw getResultValue, not Nitrogen method tables. -namespace margelo::nitro { -using namespace react_native_smb; - -namespace react_native_smb_detail { -inline jsi::Value smbSecurityDescriptorToJSI(jsi::Runtime& runtime, const SmbSecurityDescriptor& sd); -inline SmbSecurityDescriptor smbSecurityDescriptorFromJSI(jsi::Runtime& runtime, const jsi::Value& value); -} // namespace react_native_smb_detail - -template <> -struct JSIConverter { - static jsi::Value toJSI(jsi::Runtime& runtime, const SmbCredentials& credentials) { - jsi::Object obj(runtime); - obj.setProperty(runtime, "username", jsi::String::createFromUtf8(runtime, credentials.username)); - obj.setProperty(runtime, "password", jsi::String::createFromUtf8(runtime, credentials.password)); - return obj; - } - - static SmbCredentials fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { - if (!value.isObject()) { - throw std::invalid_argument("SmbCredentials must be an object"); - } - jsi::Object obj = value.asObject(runtime); - SmbCredentials credentials; - credentials.username = obj.getProperty(runtime, "username").asString(runtime).utf8(runtime); - credentials.password = obj.getProperty(runtime, "password").asString(runtime).utf8(runtime); - return credentials; - } - - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { - (void)runtime; - return value.isObject(); - } -}; - -template <> -struct JSIConverter { - static jsi::Value toJSI(jsi::Runtime& runtime, const SmbConnectionInfo& connection) { - jsi::Object obj(runtime); - obj.setProperty(runtime, "url", jsi::String::createFromUtf8(runtime, connection.url)); - obj.setProperty(runtime, "server", jsi::String::createFromUtf8(runtime, connection.server)); - obj.setProperty(runtime, "share", jsi::String::createFromUtf8(runtime, connection.share)); - obj.setProperty(runtime, "isConnected", jsi::Value(connection.isConnected)); - return obj; - } - - static SmbConnectionInfo fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { - if (!value.isObject()) { - throw std::invalid_argument("SmbConnectionInfo must be an object"); - } - jsi::Object obj = value.asObject(runtime); - return SmbConnectionInfo{obj.getProperty(runtime, "url").asString(runtime).utf8(runtime), - obj.getProperty(runtime, "server").asString(runtime).utf8(runtime), - obj.getProperty(runtime, "share").asString(runtime).utf8(runtime), - obj.getProperty(runtime, "isConnected").asBool()}; - } - - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { - (void)runtime; - return value.isObject(); - } -}; - -template <> -struct JSIConverter { - static jsi::Value toJSI(jsi::Runtime& runtime, const SmbFileInfo& fileInfo) { - jsi::Object obj(runtime); - obj.setProperty(runtime, "name", jsi::String::createFromUtf8(runtime, fileInfo.name)); - obj.setProperty(runtime, "path", jsi::String::createFromUtf8(runtime, fileInfo.path)); - obj.setProperty(runtime, "size", jsi::Value(static_cast(fileInfo.size))); - obj.setProperty(runtime, "isDirectory", jsi::Value(fileInfo.isDirectory)); - obj.setProperty(runtime, "modifiedAt", jsi::Value(static_cast(fileInfo.modifiedAt))); - obj.setProperty(runtime, "accessedAt", jsi::Value(static_cast(fileInfo.accessedAt))); - obj.setProperty(runtime, "createdAt", jsi::Value(static_cast(fileInfo.createdAt))); - obj.setProperty(runtime, "changedAt", jsi::Value(static_cast(fileInfo.changedAt))); - obj.setProperty(runtime, "childCount", jsi::Value(static_cast(fileInfo.childCount))); - - jsi::Array childrenArray(runtime, fileInfo.children.size()); - for (size_t i = 0; i < fileInfo.children.size(); i++) { - childrenArray.setValueAtIndex(runtime, i, toJSI(runtime, fileInfo.children[i])); - } - obj.setProperty(runtime, "children", std::move(childrenArray)); - - if (fileInfo.securityDescriptor.has_value()) { - obj.setProperty(runtime, "securityDescriptor", - react_native_smb_detail::smbSecurityDescriptorToJSI(runtime, *fileInfo.securityDescriptor)); - } - - return obj; - } - - static SmbFileInfo fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { - if (!value.isObject()) { - throw std::invalid_argument("SmbFileInfo must be an object"); - } - - jsi::Object obj = value.asObject(runtime); - - std::vector children; - if (obj.hasProperty(runtime, "children")) { - jsi::Value childrenValue = obj.getProperty(runtime, "children"); - if (childrenValue.isObject() && childrenValue.asObject(runtime).isArray(runtime)) { - jsi::Array childrenArray = childrenValue.asObject(runtime).asArray(runtime); - size_t childrenCount = childrenArray.size(runtime); - children.reserve(childrenCount); - for (size_t i = 0; i < childrenCount; i++) { - children.push_back(fromJSI(runtime, childrenArray.getValueAtIndex(runtime, i))); - } - } - } - - std::optional securityDescriptor; - if (obj.hasProperty(runtime, "securityDescriptor")) { - jsi::Value securityDescriptorValue = obj.getProperty(runtime, "securityDescriptor"); - if (securityDescriptorValue.isObject()) { - securityDescriptor = react_native_smb_detail::smbSecurityDescriptorFromJSI(runtime, securityDescriptorValue); - } - } - - return SmbFileInfo{obj.getProperty(runtime, "name").asString(runtime).utf8(runtime), - obj.getProperty(runtime, "path").asString(runtime).utf8(runtime), - static_cast(obj.getProperty(runtime, "size").asNumber()), - obj.getProperty(runtime, "isDirectory").asBool(), - static_cast(obj.getProperty(runtime, "modifiedAt").asNumber()), - static_cast(obj.hasProperty(runtime, "accessedAt") ? obj.getProperty(runtime, "accessedAt").asNumber() : 0), - static_cast(obj.hasProperty(runtime, "createdAt") ? obj.getProperty(runtime, "createdAt").asNumber() : 0), - static_cast(obj.hasProperty(runtime, "changedAt") ? obj.getProperty(runtime, "changedAt").asNumber() : 0), - static_cast(obj.hasProperty(runtime, "childCount") ? obj.getProperty(runtime, "childCount").asNumber() : -1), - children, - securityDescriptor}; - } - - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { - (void)runtime; - return value.isObject(); - } -}; - -template <> -struct JSIConverter { - static jsi::Value toJSI(jsi::Runtime& runtime, const SmbShare& share) { - jsi::Object obj(runtime); - obj.setProperty(runtime, "name", jsi::String::createFromUtf8(runtime, share.name)); - obj.setProperty(runtime, "comment", jsi::String::createFromUtf8(runtime, share.comment)); - return obj; - } - - static SmbShare fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { - if (!value.isObject()) { - throw std::invalid_argument("SmbShare must be an object"); - } - jsi::Object obj = value.asObject(runtime); - return SmbShare{obj.getProperty(runtime, "name").asString(runtime).utf8(runtime), - obj.getProperty(runtime, "comment").asString(runtime).utf8(runtime)}; - } - - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { - (void)runtime; - return value.isObject(); - } -}; - -template <> -struct JSIConverter { - static jsi::Value toJSI(jsi::Runtime& runtime, const SmbAce& ace) { - jsi::Object obj(runtime); - obj.setProperty(runtime, "aceType", jsi::String::createFromUtf8(runtime, ace.aceType)); - - jsi::Array aceFlagsArray = jsi::Array(runtime, ace.aceFlags.size()); - for (size_t i = 0; i < ace.aceFlags.size(); i++) { - aceFlagsArray.setValueAtIndex(runtime, i, jsi::String::createFromUtf8(runtime, ace.aceFlags[i])); - } - obj.setProperty(runtime, "aceFlags", aceFlagsArray); - - jsi::Array maskArray = jsi::Array(runtime, ace.mask.size()); - for (size_t i = 0; i < ace.mask.size(); i++) { - maskArray.setValueAtIndex(runtime, i, jsi::String::createFromUtf8(runtime, ace.mask[i])); - } - obj.setProperty(runtime, "mask", maskArray); - - obj.setProperty(runtime, "sid", jsi::String::createFromUtf8(runtime, ace.sid)); - return obj; - } - - static SmbAce fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { - if (!value.isObject()) { - throw std::invalid_argument("SmbAce must be an object"); - } - - jsi::Object obj = value.asObject(runtime); - SmbAce ace; - ace.aceType = obj.getProperty(runtime, "aceType").asString(runtime).utf8(runtime); - - if (obj.hasProperty(runtime, "aceFlags")) { - jsi::Value aceFlagsValue = obj.getProperty(runtime, "aceFlags"); - if (aceFlagsValue.isObject() && aceFlagsValue.asObject(runtime).isArray(runtime)) { - jsi::Array aceFlagsArray = aceFlagsValue.asObject(runtime).asArray(runtime); - size_t flagsCount = aceFlagsArray.size(runtime); - ace.aceFlags.reserve(flagsCount); - for (size_t i = 0; i < flagsCount; i++) { - jsi::Value flagItem = aceFlagsArray.getValueAtIndex(runtime, i); - if (flagItem.isString()) { - ace.aceFlags.push_back(flagItem.asString(runtime).utf8(runtime)); - } - } - } - } - - if (obj.hasProperty(runtime, "mask")) { - jsi::Value maskValue = obj.getProperty(runtime, "mask"); - if (maskValue.isObject() && maskValue.asObject(runtime).isArray(runtime)) { - jsi::Array maskArray = maskValue.asObject(runtime).asArray(runtime); - size_t maskCount = maskArray.size(runtime); - ace.mask.reserve(maskCount); - for (size_t i = 0; i < maskCount; i++) { - jsi::Value maskItem = maskArray.getValueAtIndex(runtime, i); - if (maskItem.isString()) { - ace.mask.push_back(maskItem.asString(runtime).utf8(runtime)); - } - } - } - } - - ace.sid = obj.getProperty(runtime, "sid").asString(runtime).utf8(runtime); - return ace; - } - - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { - (void)runtime; - return value.isObject(); - } -}; - -template <> -struct JSIConverter { - static jsi::Value toJSI(jsi::Runtime& runtime, const SmbAcl& acl) { - jsi::Object obj(runtime); - obj.setProperty(runtime, "revision", jsi::Value(static_cast(acl.revision))); - obj.setProperty(runtime, "aceCount", jsi::Value(static_cast(acl.aceCount))); - - jsi::Array aces = jsi::Array(runtime, acl.aces.size()); - for (size_t i = 0; i < acl.aces.size(); i++) { - aces.setValueAtIndex(runtime, i, JSIConverter::toJSI(runtime, acl.aces[i])); - } - obj.setProperty(runtime, "aces", aces); - return obj; - } - - static SmbAcl fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { - if (!value.isObject()) { - throw std::invalid_argument("SmbAcl must be an object"); - } - - jsi::Object obj = value.asObject(runtime); - SmbAcl acl; - acl.revision = static_cast(obj.getProperty(runtime, "revision").asNumber()); - acl.aceCount = static_cast(obj.getProperty(runtime, "aceCount").asNumber()); - - if (obj.hasProperty(runtime, "aces")) { - jsi::Array aces = obj.getProperty(runtime, "aces").asObject(runtime).asArray(runtime); - size_t aceCount = aces.size(runtime); - acl.aces.reserve(aceCount); - for (size_t i = 0; i < aceCount; i++) { - acl.aces.push_back(JSIConverter::fromJSI(runtime, aces.getValueAtIndex(runtime, i))); - } - } - - return acl; - } - - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { - (void)runtime; - return value.isObject(); - } -}; - -template <> -struct JSIConverter { - static jsi::Value toJSI(jsi::Runtime& runtime, const SmbSecurityDescriptor& sd) { - jsi::Object obj(runtime); - obj.setProperty(runtime, "revision", jsi::Value(static_cast(sd.revision))); - - jsi::Array controlArray = jsi::Array(runtime, sd.control.size()); - for (size_t i = 0; i < sd.control.size(); i++) { - controlArray.setValueAtIndex(runtime, i, jsi::String::createFromUtf8(runtime, sd.control[i])); - } - obj.setProperty(runtime, "control", controlArray); - - obj.setProperty(runtime, "ownerSid", jsi::String::createFromUtf8(runtime, sd.ownerSid)); - obj.setProperty(runtime, "groupSid", jsi::String::createFromUtf8(runtime, sd.groupSid)); - obj.setProperty(runtime, "dacl", JSIConverter::toJSI(runtime, sd.dacl)); - return obj; - } - - static SmbSecurityDescriptor fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { - if (!value.isObject()) { - throw std::invalid_argument("SmbSecurityDescriptor must be an object"); - } - - jsi::Object obj = value.asObject(runtime); - SmbSecurityDescriptor sd; - sd.revision = static_cast(obj.getProperty(runtime, "revision").asNumber()); - - if (obj.hasProperty(runtime, "control")) { - jsi::Value controlValue = obj.getProperty(runtime, "control"); - if (controlValue.isObject() && controlValue.asObject(runtime).isArray(runtime)) { - jsi::Array controlArray = controlValue.asObject(runtime).asArray(runtime); - size_t controlCount = controlArray.size(runtime); - sd.control.reserve(controlCount); - for (size_t i = 0; i < controlCount; i++) { - jsi::Value controlItem = controlArray.getValueAtIndex(runtime, i); - if (controlItem.isString()) { - sd.control.push_back(controlItem.asString(runtime).utf8(runtime)); - } - } - } - } - - sd.ownerSid = obj.getProperty(runtime, "ownerSid").asString(runtime).utf8(runtime); - sd.groupSid = obj.getProperty(runtime, "groupSid").asString(runtime).utf8(runtime); - sd.dacl = JSIConverter::fromJSI(runtime, obj.getProperty(runtime, "dacl")); - return sd; - } - - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { - (void)runtime; - return value.isObject(); - } -}; - -namespace react_native_smb_detail { -inline jsi::Value smbSecurityDescriptorToJSI(jsi::Runtime& runtime, const SmbSecurityDescriptor& sd) { - return JSIConverter::toJSI(runtime, sd); -} - -inline SmbSecurityDescriptor smbSecurityDescriptorFromJSI(jsi::Runtime& runtime, const jsi::Value& value) { - return JSIConverter::fromJSI(runtime, value); -} -} // namespace react_native_smb_detail - -} // namespace margelo::nitro diff --git a/cpp/shared/core/SmbTask.hpp b/cpp/shared/core/SmbTask.hpp index 2e819db..420e3e3 100644 --- a/cpp/shared/core/SmbTask.hpp +++ b/cpp/shared/core/SmbTask.hpp @@ -8,8 +8,6 @@ #include #include -#include - #include "SmbTaskCore.hpp" namespace react_native_smb { @@ -19,8 +17,6 @@ class SmbConnectionPool; class EntryStream; struct SmbFileInfo; -namespace jsi = facebook::jsi; - class SmbTask : public SmbTaskCore, public std::enable_shared_from_this { public: using EntriesListener = std::function; @@ -46,8 +42,6 @@ class SmbTask : public SmbTaskCore, public std::enable_shared_from_this std::future result() { return completionFuture(); } - jsi::Value getResultValue(jsi::Runtime& runtime) const { return SmbTaskCore::getResultValue(runtime); } - private: std::weak_ptr pool_; std::shared_ptr entries_; diff --git a/cpp/shared/core/SmbTaskCore.cpp b/cpp/shared/core/SmbTaskCore.cpp index bb2233e..4ed7a2e 100644 --- a/cpp/shared/core/SmbTaskCore.cpp +++ b/cpp/shared/core/SmbTaskCore.cpp @@ -9,8 +9,6 @@ namespace react_native_smb { -namespace jsi = facebook::jsi; - namespace { std::string sanitizedErrorMessage(std::string message) { @@ -117,20 +115,14 @@ void SmbTaskCore::unsubscribe(const std::string& id) { listeners_.erase(id); } -void SmbTaskCore::publishResult(std::any value, - std::function converter) { +void SmbTaskCore::publishResult(SmbTaskResult value) { if (settled_.load(std::memory_order_acquire)) return; resultValue_ = std::move(value); - resultConverter_ = std::move(converter); } -jsi::Value SmbTaskCore::getResultValue(jsi::Runtime& runtime) const { - if (!resultConverter_) return jsi::Value::undefined(); - try { - return resultConverter_(runtime, resultValue_); - } catch (...) { - return jsi::Value::undefined(); - } +SmbTaskResult SmbTaskCore::publishedResult() const { + std::lock_guard lk(stateMutex_); + return resultValue_; } std::future SmbTaskCore::completionFuture() { return done_.get_future(); } diff --git a/cpp/shared/core/SmbTaskCore.hpp b/cpp/shared/core/SmbTaskCore.hpp index 9b55630..f7df1cb 100644 --- a/cpp/shared/core/SmbTaskCore.hpp +++ b/cpp/shared/core/SmbTaskCore.hpp @@ -1,29 +1,26 @@ #pragma once -#include #include #include #include #include #include +#include #include #include #include -#include - #include "CancellationToken.hpp" #include "SmbEnums.hpp" +#include "SmbTaskResult.hpp" #include "SmbTypes.hpp" namespace react_native_smb { class OperatorBase; -namespace jsi = facebook::jsi; - // Thread-safe state, result storage, and subscriber fan-out. No HybridObject, -// no pool orchestration. +// no pool orchestration, no JSI. class SmbTaskCore { public: SmbTaskCore(std::string id, SmbOperatorKind kind); @@ -43,8 +40,8 @@ class SmbTaskCore { void onOpStatus(size_t opIndex, SmbTaskStatus s, const std::string& error, int code); void onOpProgress(size_t opIndex, double done, double total); - void publishResult(std::any value, std::function converter); - jsi::Value getResultValue(jsi::Runtime& runtime) const; + void publishResult(SmbTaskResult value); + SmbTaskResult publishedResult() const; std::string subscribe(SnapshotListener listener); void unsubscribe(const std::string& id); @@ -97,8 +94,7 @@ class SmbTaskCore { mutable std::mutex listenersMutex_; std::atomic nextListenerId_{1}; - std::any resultValue_; - std::function resultConverter_; + SmbTaskResult resultValue_; void writeToSnapshot(SmbTaskState& out) const; void notifyListeners(); @@ -106,4 +102,4 @@ class SmbTaskCore { void maybeSettle(); }; -} // namespace react_native_smb \ No newline at end of file +} // namespace react_native_smb diff --git a/cpp/shared/core/SmbTaskResult.hpp b/cpp/shared/core/SmbTaskResult.hpp new file mode 100644 index 0000000..b25c9c3 --- /dev/null +++ b/cpp/shared/core/SmbTaskResult.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include +#include +#include + +#include "SmbModels.hpp" + +namespace react_native_smb { + +// Sentinel for listDirectory: entries live in the task's EntryStream. +struct ListingResult {}; + +// Typed result storage for domain tasks. Bridge converts to JSI. +using SmbTaskResult = std::variant, SmbFileInfo, + SmbSecurityDescriptor, ListingResult>; + +} // namespace react_native_smb diff --git a/cpp/shared/operators/Operator.hpp b/cpp/shared/operators/Operator.hpp index e3d4ee2..893b0cf 100644 --- a/cpp/shared/operators/Operator.hpp +++ b/cpp/shared/operators/Operator.hpp @@ -2,10 +2,7 @@ #include "OperatorBase.hpp" -// For JSIConverter in publishThisResult convenience. -#include "../core/SmbModels.hpp" - -namespace jsi = facebook::jsi; +#include "../core/SmbTaskResult.hpp" namespace react_native_smb { @@ -20,16 +17,9 @@ class Operator : public OperatorBase { protected: T result_{}; - // Convenience for value-producing operators: publish our result_ + the - // correct converter directly to the owning task. Call this at the end of a - // successful run() (before or after emitStatus(Success)). - void publishThisResult() { - publishResult(std::any(result_), [](jsi::Runtime& rt, const std::any& a) -> jsi::Value { - const T* v = std::any_cast(&a); - if (!v) return jsi::Value::undefined(); - return margelo::nitro::JSIConverter::toJSI(rt, *v); - }); - } + // Convenience for value-producing operators: publish our result_ directly + // to the owning task. Call this at the end of a successful run(). + void publishThisResult() { publishResult(SmbTaskResult{result_}); } }; } // namespace react_native_smb diff --git a/cpp/shared/operators/OperatorBase.cpp b/cpp/shared/operators/OperatorBase.cpp index e9b8656..0f8943c 100644 --- a/cpp/shared/operators/OperatorBase.cpp +++ b/cpp/shared/operators/OperatorBase.cpp @@ -50,8 +50,8 @@ void OperatorBase::setSourceDestination(const std::string& source, const std::st if (ctx_.task) ctx_.task->setPaths(source, destination); } -void OperatorBase::publishResult(std::any value, std::function converter) { - if (ctx_.task) ctx_.task->publishResult(std::move(value), std::move(converter)); +void OperatorBase::publishResult(SmbTaskResult value) { + if (ctx_.task) ctx_.task->publishResult(std::move(value)); } std::shared_ptr OperatorBase::entryStream() const { diff --git a/cpp/shared/operators/OperatorBase.hpp b/cpp/shared/operators/OperatorBase.hpp index dd81498..d42d85a 100644 --- a/cpp/shared/operators/OperatorBase.hpp +++ b/cpp/shared/operators/OperatorBase.hpp @@ -1,25 +1,20 @@ #pragma once -#include #include -#include #include #include #include -#include - #include "../connection/MetadataContextLease.hpp" #include "../connection/PoolContextHandle.hpp" #include "../connection/PoolTypes.hpp" #include "../core/CancellationToken.hpp" #include "../core/OperatorContext.hpp" #include "../core/SmbEnums.hpp" +#include "../core/SmbTaskResult.hpp" namespace react_native_smb { -namespace jsi = facebook::jsi; - class SmbConnectionPool; class SmbTask; class EntryStream; @@ -50,7 +45,7 @@ class OperatorBase { size_t spawn(std::vector> moreOps); void addExpectedBytes(int64_t bytes); void setSourceDestination(const std::string& source, const std::string& destination); - void publishResult(std::any value, std::function converter); + void publishResult(SmbTaskResult value); // Owning task's incremental listing stream (null when detached from a task). std::shared_ptr entryStream() const; @@ -58,4 +53,4 @@ class OperatorBase { OperatorContext ctx_{}; }; -} // namespace react_native_smb \ No newline at end of file +} // namespace react_native_smb diff --git a/cpp/shared/operators/listing/ListDirectoryOperator.cpp b/cpp/shared/operators/listing/ListDirectoryOperator.cpp index aebdc72..76cddcc 100644 --- a/cpp/shared/operators/listing/ListDirectoryOperator.cpp +++ b/cpp/shared/operators/listing/ListDirectoryOperator.cpp @@ -1,12 +1,12 @@ #include "ListDirectoryOperator.hpp" -#include #include #include -#include "../../core/SmbModels.hpp" #include "../../connection/SmbConnectionPool.hpp" #include "../../core/EntryStream.hpp" +#include "../../core/SmbModels.hpp" +#include "../../core/SmbTaskResult.hpp" #include "../../io/listing/DirectoryLister.hpp" namespace react_native_smb { @@ -27,12 +27,8 @@ void ListDirectoryOperator::run() { }); if (isCancelled()) return; - // The stream already holds every entry; convert from it instead of keeping a copy. - publishResult(std::any(), [stream](jsi::Runtime& rt, const std::any&) -> jsi::Value { - return stream->read([&rt](const std::vector& entries) { - return margelo::nitro::JSIConverter>::toJSI(rt, entries); - }); - }); + // Entries live in the stream; bridge reads them on getResultValue. + publishResult(ListingResult{}); emitStatus(SmbTaskStatus::Success); } From 36ed5a353132f8883d907ec41837e98109ec28a1 Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:33:14 +0800 Subject: [PATCH 4/5] refactor(listing): split NativeSmbListTask from NativeSmbTask Entry streaming methods belonged on every HybridSmbTask even though only listDirectory uses them, and every task allocated an EntryStream. Generate a listing HybridObject that extends NativeSmbTask and create the stream only for ListDirectory. - add NativeSmbListTask.nitro.ts and HybridSmbListTask with raw drainEntries - keep getResultValue on HybridSmbTask; listDirectory returns the list hybrid - Nitrogen uses virtual inheritance for the HybridObject diamond --- cpp/shared/bridge/HybridSMB.cpp | 17 +++-- cpp/shared/bridge/HybridSMB.hpp | 8 ++- cpp/shared/bridge/HybridSmbListTask.cpp | 46 +++++++++++++ cpp/shared/bridge/HybridSmbListTask.hpp | 32 +++++++++ cpp/shared/bridge/HybridSmbTask.cpp | 17 ----- cpp/shared/bridge/HybridSmbTask.hpp | 10 +-- cpp/shared/core/SmbTask.cpp | 16 ++--- cpp/shared/core/SmbTask.hpp | 7 +- cpp/shared/operators/OperatorBase.cpp | 3 +- .../android/ReactNativeSmb+autolinking.cmake | 1 + .../c++/HybridNativeSmbListTaskSpec.cpp | 23 +++++++ .../c++/HybridNativeSmbListTaskSpec.hpp | 67 +++++++++++++++++++ .../shared/c++/HybridNativeSmbTaskSpec.cpp | 2 - .../shared/c++/HybridNativeSmbTaskSpec.hpp | 2 - .../shared/c++/HybridReactNativeSmbSpec.hpp | 5 +- src/core/SmbClient.ts | 2 +- src/specs/NativeSmbListTask.nitro.ts | 10 +++ src/specs/NativeSmbTask.nitro.ts | 8 +-- src/specs/ReactNativeSmb.nitro.ts | 3 +- src/types.ts | 23 ++++--- 20 files changed, 232 insertions(+), 70 deletions(-) create mode 100644 cpp/shared/bridge/HybridSmbListTask.cpp create mode 100644 cpp/shared/bridge/HybridSmbListTask.hpp create mode 100644 nitrogen/generated/shared/c++/HybridNativeSmbListTaskSpec.cpp create mode 100644 nitrogen/generated/shared/c++/HybridNativeSmbListTaskSpec.hpp create mode 100644 src/specs/NativeSmbListTask.nitro.ts diff --git a/cpp/shared/bridge/HybridSMB.cpp b/cpp/shared/bridge/HybridSMB.cpp index 6048c62..96f30f0 100644 --- a/cpp/shared/bridge/HybridSMB.cpp +++ b/cpp/shared/bridge/HybridSMB.cpp @@ -1,6 +1,7 @@ #include "HybridSMB.hpp" #include "BridgeMapping.hpp" +#include "HybridSmbListTask.hpp" #include #include @@ -46,8 +47,7 @@ void HybridSMB::releaseTaskRun(const std::shared_ptr& state) { } template -std::shared_ptr HybridSMB::createTask(const std::string& taskId, std::unique_ptr seedOp, - ExecutionLane lane) { +std::shared_ptr HybridSMB::startTask(const std::string& taskId, std::unique_ptr seedOp, ExecutionLane lane) { std::lock_guard shutdownLock(shutdownMutex_); if (disposed_.load(std::memory_order_acquire)) { SmbException::raise(SmbErrorCode::NotConnected, "SMB client has been destroyed"); @@ -90,7 +90,13 @@ std::shared_ptr HybridSMB::createTask(const std::string throw; } - return std::make_shared(std::move(task)); + return task; +} + +template +std::shared_ptr HybridSMB::createTask(const std::string& taskId, std::unique_ptr seedOp, + ExecutionLane lane) { + return std::make_shared(startTask(taskId, std::move(seedOp), lane)); } HybridSMB::HybridSMB() : HybridObject(TAG) { @@ -185,8 +191,9 @@ std::shared_ptr HybridSMB::connectShare(const std::stri } // --- listing --- -std::shared_ptr HybridSMB::listDirectory(const std::string& taskId, const std::string& path, double maxDepth, bool includeSecurityDescriptor, double batchSize) { - return createTask(taskId, std::make_unique(path, static_cast(maxDepth), includeSecurityDescriptor, static_cast(batchSize))); +std::shared_ptr HybridSMB::listDirectory(const std::string& taskId, const std::string& path, double maxDepth, bool includeSecurityDescriptor, double batchSize) { + auto task = startTask(taskId, std::make_unique(path, static_cast(maxDepth), includeSecurityDescriptor, static_cast(batchSize))); + return std::make_shared(std::move(task)); } std::shared_ptr HybridSMB::getPathInfo(const std::string& taskId, const std::string& path) { diff --git a/cpp/shared/bridge/HybridSMB.hpp b/cpp/shared/bridge/HybridSMB.hpp index ed22547..2d889a2 100644 --- a/cpp/shared/bridge/HybridSMB.hpp +++ b/cpp/shared/bridge/HybridSMB.hpp @@ -1,6 +1,8 @@ #pragma once +#include "HybridNativeSmbListTaskSpec.hpp" #include "HybridReactNativeSmbSpec.hpp" +#include "HybridSmbListTask.hpp" #include "HybridSmbTask.hpp" #include "../connection/SmbConnectionPool.hpp" @@ -54,6 +56,10 @@ class HybridSMB : public HybridReactNativeSmbSpec { enum class ExecutionLane { Shared, Lifecycle }; + template + std::shared_ptr startTask(const std::string& taskId, std::unique_ptr seedOp, + ExecutionLane lane = ExecutionLane::Shared); + template std::shared_ptr createTask(const std::string& taskId, std::unique_ptr seedOp, ExecutionLane lane = ExecutionLane::Shared); @@ -74,7 +80,7 @@ class HybridSMB : public HybridReactNativeSmbSpec { std::shared_ptr listShares(const std::string& taskId) override; // --- listing --- - std::shared_ptr listDirectory(const std::string& taskId, const std::string& path, double maxDepth, bool includeSecurityDescriptor, double batchSize) override; + std::shared_ptr listDirectory(const std::string& taskId, const std::string& path, double maxDepth, bool includeSecurityDescriptor, double batchSize) override; std::shared_ptr getPathInfo(const std::string& taskId, const std::string& path) override; std::shared_ptr getSecurityDescriptor(const std::string& taskId, const std::string& path) override; diff --git a/cpp/shared/bridge/HybridSmbListTask.cpp b/cpp/shared/bridge/HybridSmbListTask.cpp new file mode 100644 index 0000000..a4c8b62 --- /dev/null +++ b/cpp/shared/bridge/HybridSmbListTask.cpp @@ -0,0 +1,46 @@ +#include "HybridSmbListTask.hpp" + +#include +#include + +#include "DomainConverters.hpp" +#include "../core/EntryStream.hpp" +#include "../core/SmbModels.hpp" +#include "../core/SmbTask.hpp" + +namespace margelo::nitro::smb { + +HybridSmbListTask::HybridSmbListTask(std::shared_ptr task) + : HybridObject(HybridNativeSmbListTaskSpec::TAG), HybridSmbTask(std::move(task)) { + if (!task_->entryStream()) { + throw std::invalid_argument("HybridSmbListTask requires a listing SmbTask with an EntryStream"); + } +} + +std::string HybridSmbListTask::subscribeEntries(const std::function& listener) { + return task_->entryStream()->subscribe(listener); +} + +void HybridSmbListTask::unsubscribeEntries(const std::string& subscriptionId) { + task_->entryStream()->unsubscribe(subscriptionId); +} + +facebook::jsi::Value HybridSmbListTask::drainEntriesRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& /*thisValue*/, + const facebook::jsi::Value* args, size_t count) { + if (count < 1 || !args[0].isString()) { + throw facebook::jsi::JSError(runtime, "drainEntries(subscriptionId: string) requires a string argument"); + } + const std::string subscriptionId = args[0].asString(runtime).utf8(runtime); + auto entries = task_->entryStream()->drain(subscriptionId); + return JSIConverter>::toJSI(runtime, entries); +} + +void HybridSmbListTask::loadHybridMethods() { + HybridNativeSmbListTaskSpec::loadHybridMethods(); + registerHybrids(this, [](Prototype& prototype) { + prototype.registerRawHybridMethod("getResultValue", 0, &HybridSmbTask::getResultValueRaw); + prototype.registerRawHybridMethod("drainEntries", 1, &HybridSmbListTask::drainEntriesRaw); + }); +} + +} // namespace margelo::nitro::smb diff --git a/cpp/shared/bridge/HybridSmbListTask.hpp b/cpp/shared/bridge/HybridSmbListTask.hpp new file mode 100644 index 0000000..09faa44 --- /dev/null +++ b/cpp/shared/bridge/HybridSmbListTask.hpp @@ -0,0 +1,32 @@ +#pragma once + +#include "HybridNativeSmbListTaskSpec.hpp" +#include "HybridSmbTask.hpp" + +#include +#include +#include + +namespace margelo::nitro::smb { + +/** + * Listing HybridObject: NativeSmbListTask methods plus raw drainEntries. + * Virtual inheritance of HybridNativeSmbTaskSpec is required by Nitrogen. + */ +class HybridSmbListTask : public HybridNativeSmbListTaskSpec, public HybridSmbTask { + public: + explicit HybridSmbListTask(std::shared_ptr task); + ~HybridSmbListTask() override = default; + + std::string subscribeEntries(const std::function& listener) override; + void unsubscribeEntries(const std::string& subscriptionId) override; + + protected: + void loadHybridMethods() override; + + private: + facebook::jsi::Value drainEntriesRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& thisValue, + const facebook::jsi::Value* args, size_t count); +}; + +} // namespace margelo::nitro::smb diff --git a/cpp/shared/bridge/HybridSmbTask.cpp b/cpp/shared/bridge/HybridSmbTask.cpp index 23ec39a..a2ad26c 100644 --- a/cpp/shared/bridge/HybridSmbTask.cpp +++ b/cpp/shared/bridge/HybridSmbTask.cpp @@ -29,12 +29,6 @@ std::string HybridSmbTask::subscribe(const std::functionunsubscribe(subscriptionId); } -std::string HybridSmbTask::subscribeEntries(const std::function& listener) { - return task_->subscribeEntries(listener); -} - -void HybridSmbTask::unsubscribeEntries(const std::string& subscriptionId) { task_->unsubscribeEntries(subscriptionId); } - facebook::jsi::Value HybridSmbTask::getResultValueRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& /*thisValue*/, const facebook::jsi::Value* /*args*/, size_t /*count*/) { using react_native_smb::ListingResult; @@ -67,21 +61,10 @@ facebook::jsi::Value HybridSmbTask::getResultValueRaw(facebook::jsi::Runtime& ru } } -facebook::jsi::Value HybridSmbTask::drainEntriesRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& /*thisValue*/, - const facebook::jsi::Value* args, size_t count) { - if (count < 1 || !args[0].isString()) { - throw facebook::jsi::JSError(runtime, "drainEntries(subscriptionId: string) requires a string argument"); - } - const std::string subscriptionId = args[0].asString(runtime).utf8(runtime); - auto entries = task_->drainEntries(subscriptionId); - return JSIConverter>::toJSI(runtime, entries); -} - void HybridSmbTask::loadHybridMethods() { HybridNativeSmbTaskSpec::loadHybridMethods(); registerHybrids(this, [](Prototype& prototype) { prototype.registerRawHybridMethod("getResultValue", 0, &HybridSmbTask::getResultValueRaw); - prototype.registerRawHybridMethod("drainEntries", 1, &HybridSmbTask::drainEntriesRaw); }); } diff --git a/cpp/shared/bridge/HybridSmbTask.hpp b/cpp/shared/bridge/HybridSmbTask.hpp index a464877..f8afeca 100644 --- a/cpp/shared/bridge/HybridSmbTask.hpp +++ b/cpp/shared/bridge/HybridSmbTask.hpp @@ -16,9 +16,9 @@ namespace margelo::nitro::smb { /** * Nitro adapter around domain SmbTask. * Typed Hybrid methods come from HybridNativeSmbTaskSpec. - * getResultValue / drainEntries are registered as raw JSI methods. + * getResultValue is registered as a raw JSI method. */ -class HybridSmbTask : public HybridNativeSmbTaskSpec { +class HybridSmbTask : public virtual HybridNativeSmbTaskSpec { public: explicit HybridSmbTask(std::shared_ptr task); ~HybridSmbTask() override = default; @@ -27,19 +27,15 @@ class HybridSmbTask : public HybridNativeSmbTaskSpec { std::unordered_map get() override; std::string subscribe(const std::function&)>& listener) override; void unsubscribe(const std::string& subscriptionId) override; - std::string subscribeEntries(const std::function& listener) override; - void unsubscribeEntries(const std::string& subscriptionId) override; protected: void loadHybridMethods() override; - private: std::shared_ptr task_; facebook::jsi::Value getResultValueRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& thisValue, const facebook::jsi::Value* args, size_t count); - facebook::jsi::Value drainEntriesRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& thisValue, - const facebook::jsi::Value* args, size_t count); }; + } // namespace margelo::nitro::smb diff --git a/cpp/shared/core/SmbTask.cpp b/cpp/shared/core/SmbTask.cpp index f0075d6..b63a908 100644 --- a/cpp/shared/core/SmbTask.cpp +++ b/cpp/shared/core/SmbTask.cpp @@ -7,15 +7,15 @@ #include "../util/SmbErrorMapper.hpp" #include "../util/SmbException.hpp" #include "EntryStream.hpp" -#include "SmbModels.hpp" #include "TaskSnapshotCodec.hpp" namespace react_native_smb { SmbTask::SmbTask(std::string id, std::unique_ptr seedOp, std::shared_ptr pool) - : SmbTaskCore(std::move(id), seedOp->kind()), - pool_(pool), - entries_(std::make_shared()) { + : SmbTaskCore(std::move(id), seedOp->kind()), pool_(pool) { + if (seedOp->kind() == SmbOperatorKind::ListDirectory) { + entries_ = std::make_shared(); + } ops_.push_back(std::move(seedOp)); opProgress_.resize(1); } @@ -119,12 +119,4 @@ std::string SmbTask::subscribeMap(const std::functionsubscribe(listener); -} - -void SmbTask::unsubscribeEntries(const std::string& id) { entries_->unsubscribe(id); } - -std::vector SmbTask::drainEntries(const std::string& id) { return entries_->drain(id); } - } // namespace react_native_smb diff --git a/cpp/shared/core/SmbTask.hpp b/cpp/shared/core/SmbTask.hpp index 420e3e3..79440b8 100644 --- a/cpp/shared/core/SmbTask.hpp +++ b/cpp/shared/core/SmbTask.hpp @@ -19,8 +19,6 @@ struct SmbFileInfo; class SmbTask : public SmbTaskCore, public std::enable_shared_from_this { public: - using EntriesListener = std::function; - SmbTask(std::string id, std::unique_ptr seedOp, std::shared_ptr pool); ~SmbTask(); @@ -35,16 +33,13 @@ class SmbTask : public SmbTaskCore, public std::enable_shared_from_this std::string subscribeMap(const std::function&)>& listener); void unsubscribe(const std::string& id) { SmbTaskCore::unsubscribe(id); } - std::string subscribeEntries(const EntriesListener& listener); - void unsubscribeEntries(const std::string& id); - std::vector drainEntries(const std::string& id); const std::shared_ptr& entryStream() const { return entries_; } std::future result() { return completionFuture(); } private: std::weak_ptr pool_; - std::shared_ptr entries_; + std::shared_ptr entries_; // non-null only for ListDirectory void launchOp(size_t opIndex); size_t appendOps(std::vector>& more); diff --git a/cpp/shared/operators/OperatorBase.cpp b/cpp/shared/operators/OperatorBase.cpp index 0f8943c..4132fd5 100644 --- a/cpp/shared/operators/OperatorBase.cpp +++ b/cpp/shared/operators/OperatorBase.cpp @@ -55,7 +55,8 @@ void OperatorBase::publishResult(SmbTaskResult value) { } std::shared_ptr OperatorBase::entryStream() const { - return ctx_.task ? ctx_.task->entryStream() : nullptr; + if (!ctx_.task) return nullptr; + return ctx_.task->entryStream(); } } // namespace react_native_smb \ No newline at end of file diff --git a/nitrogen/generated/android/ReactNativeSmb+autolinking.cmake b/nitrogen/generated/android/ReactNativeSmb+autolinking.cmake index 5130e48..6f192f2 100644 --- a/nitrogen/generated/android/ReactNativeSmb+autolinking.cmake +++ b/nitrogen/generated/android/ReactNativeSmb+autolinking.cmake @@ -33,6 +33,7 @@ target_sources( # Autolinking Setup ../nitrogen/generated/android/ReactNativeSmbOnLoad.cpp # Shared Nitrogen C++ sources + ../nitrogen/generated/shared/c++/HybridNativeSmbListTaskSpec.cpp ../nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.cpp ../nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.cpp # Android-specific Nitrogen C++ sources diff --git a/nitrogen/generated/shared/c++/HybridNativeSmbListTaskSpec.cpp b/nitrogen/generated/shared/c++/HybridNativeSmbListTaskSpec.cpp new file mode 100644 index 0000000..a1dedd8 --- /dev/null +++ b/nitrogen/generated/shared/c++/HybridNativeSmbListTaskSpec.cpp @@ -0,0 +1,23 @@ +/// +/// HybridNativeSmbListTaskSpec.cpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#include "HybridNativeSmbListTaskSpec.hpp" + +namespace margelo::nitro::smb { + + void HybridNativeSmbListTaskSpec::loadHybridMethods() { + // load base methods/properties + HybridObject::loadHybridMethods(); + HybridNativeSmbTaskSpec::loadHybridMethods(); + // load custom methods/properties + registerHybrids(this, [](Prototype& prototype) { + prototype.registerHybridMethod("subscribeEntries", &HybridNativeSmbListTaskSpec::subscribeEntries); + prototype.registerHybridMethod("unsubscribeEntries", &HybridNativeSmbListTaskSpec::unsubscribeEntries); + }); + } + +} // namespace margelo::nitro::smb diff --git a/nitrogen/generated/shared/c++/HybridNativeSmbListTaskSpec.hpp b/nitrogen/generated/shared/c++/HybridNativeSmbListTaskSpec.hpp new file mode 100644 index 0000000..5c1cee9 --- /dev/null +++ b/nitrogen/generated/shared/c++/HybridNativeSmbListTaskSpec.hpp @@ -0,0 +1,67 @@ +/// +/// HybridNativeSmbListTaskSpec.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +// Forward declaration of `HybridNativeSmbTaskSpec` to properly resolve imports. +namespace margelo::nitro::smb { class HybridNativeSmbTaskSpec; } + +#include +#include +#include +#include "HybridNativeSmbTaskSpec.hpp" + +namespace margelo::nitro::smb { + + using namespace margelo::nitro; + + /** + * An abstract base class for `NativeSmbListTask` + * Inherit this class to create instances of `HybridNativeSmbListTaskSpec` in C++. + * You must explicitly call `HybridObject`'s constructor yourself, because it is virtual. + * @example + * ```cpp + * class HybridNativeSmbListTask: public HybridNativeSmbListTaskSpec { + * public: + * HybridNativeSmbListTask(...): HybridObject(TAG) { ... } + * // ... + * }; + * ``` + */ + class HybridNativeSmbListTaskSpec: public virtual HybridObject, public virtual HybridNativeSmbTaskSpec { + public: + // Constructor + explicit HybridNativeSmbListTaskSpec(): HybridObject(TAG) { } + + // Destructor + ~HybridNativeSmbListTaskSpec() override = default; + + public: + // Properties + + + public: + // Methods + virtual std::string subscribeEntries(const std::function& listener) = 0; + virtual void unsubscribeEntries(const std::string& subscriptionId) = 0; + + protected: + // Hybrid Setup + void loadHybridMethods() override; + + protected: + // Tag for logging + static constexpr auto TAG = "NativeSmbListTask"; + }; + +} // namespace margelo::nitro::smb diff --git a/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.cpp b/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.cpp index 5a25825..f9279c8 100644 --- a/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.cpp +++ b/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.cpp @@ -18,8 +18,6 @@ namespace margelo::nitro::smb { prototype.registerHybridMethod("get", &HybridNativeSmbTaskSpec::get); prototype.registerHybridMethod("subscribe", &HybridNativeSmbTaskSpec::subscribe); prototype.registerHybridMethod("unsubscribe", &HybridNativeSmbTaskSpec::unsubscribe); - prototype.registerHybridMethod("subscribeEntries", &HybridNativeSmbTaskSpec::subscribeEntries); - prototype.registerHybridMethod("unsubscribeEntries", &HybridNativeSmbTaskSpec::unsubscribeEntries); }); } diff --git a/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp b/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp index d0cdf35..baa309f 100644 --- a/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp +++ b/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp @@ -54,8 +54,6 @@ namespace margelo::nitro::smb { virtual std::unordered_map get() = 0; virtual std::string subscribe(const std::function& /* snapshot */)>& listener) = 0; virtual void unsubscribe(const std::string& subscriptionId) = 0; - virtual std::string subscribeEntries(const std::function& listener) = 0; - virtual void unsubscribeEntries(const std::string& subscriptionId) = 0; protected: // Hybrid Setup diff --git a/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp b/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp index 1a90e50..1f61dda 100644 --- a/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp +++ b/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp @@ -17,11 +17,14 @@ namespace margelo::nitro::smb { class HybridNativeSmbTaskSpec; } // Forward declaration of `SmbCredentials` to properly resolve imports. namespace margelo::nitro::smb { struct SmbCredentials; } +// Forward declaration of `HybridNativeSmbListTaskSpec` to properly resolve imports. +namespace margelo::nitro::smb { class HybridNativeSmbListTaskSpec; } #include #include "HybridNativeSmbTaskSpec.hpp" #include #include "SmbCredentials.hpp" +#include "HybridNativeSmbListTaskSpec.hpp" #include #include #include @@ -65,7 +68,7 @@ namespace margelo::nitro::smb { virtual std::shared_ptr connectShare(const std::string& taskId, const std::string& share) = 0; virtual std::shared_ptr disconnect(const std::string& taskId) = 0; virtual std::shared_ptr listShares(const std::string& taskId) = 0; - virtual std::shared_ptr listDirectory(const std::string& taskId, const std::string& path, double maxDepth, bool includeSecurityDescriptor, double batchSize) = 0; + virtual std::shared_ptr listDirectory(const std::string& taskId, const std::string& path, double maxDepth, bool includeSecurityDescriptor, double batchSize) = 0; virtual std::shared_ptr getPathInfo(const std::string& taskId, const std::string& path) = 0; virtual std::shared_ptr getSecurityDescriptor(const std::string& taskId, const std::string& path) = 0; virtual std::shared_ptr downloadFile(const std::string& taskId, const std::string& remotePath, const std::string& localPath) = 0; diff --git a/src/core/SmbClient.ts b/src/core/SmbClient.ts index 0bd2874..372c014 100644 --- a/src/core/SmbClient.ts +++ b/src/core/SmbClient.ts @@ -89,7 +89,7 @@ export class SmbClient { listDirectory(path: string, options: ListDirectoryOptions = {}): SmbListTask { const { maxDepth = 0, includeSecurityDescriptor = false, batchSize = DEFAULT_LIST_BATCH_SIZE } = options; const id = generateTaskId(); - // drainEntries is a raw JSI method on every HybridSmbTask; list ops use NativeSmbListTask. + // drainEntries / getResultValue are raw JSI methods on HybridSmbListTask. return new SmbListTask( id, this.native.listDirectory(id, path, maxDepth, includeSecurityDescriptor, batchSize) as NativeSmbListTask, diff --git a/src/specs/NativeSmbListTask.nitro.ts b/src/specs/NativeSmbListTask.nitro.ts new file mode 100644 index 0000000..501de73 --- /dev/null +++ b/src/specs/NativeSmbListTask.nitro.ts @@ -0,0 +1,10 @@ +import type { NativeSmbTask } from './NativeSmbTask.nitro' + +/** + * Listing HybridObject. Extends NativeSmbTask with entry-stream signals. + * `drainEntries` stays a raw JSI method (recursive SmbFileInfo). + */ +export interface NativeSmbListTask extends NativeSmbTask { + subscribeEntries(listener: () => void): string + unsubscribeEntries(subscriptionId: string): void +} diff --git a/src/specs/NativeSmbTask.nitro.ts b/src/specs/NativeSmbTask.nitro.ts index 298c09f..6505bd2 100644 --- a/src/specs/NativeSmbTask.nitro.ts +++ b/src/specs/NativeSmbTask.nitro.ts @@ -3,15 +3,13 @@ import type { HybridObject } from 'react-native-nitro-modules' /** * Nitro HybridObject for one native SMB operation. * - * `getResultValue` and `drainEntries` are registered as raw JSI methods in - * HybridSmbTask (result type varies; SmbFileInfo is recursive and cannot be - * Nitrogen-generated). + * `getResultValue` is registered as a raw JSI method in HybridSmbTask + * (result type varies per operator). Listing entry streaming lives on + * NativeSmbListTask. */ export interface NativeSmbTask extends HybridObject<{ ios: 'c++'; android: 'c++' }> { cancel(): void get(): Record subscribe(listener: (snapshot: Record) => void): string unsubscribe(subscriptionId: string): void - subscribeEntries(listener: () => void): string - unsubscribeEntries(subscriptionId: string): void } diff --git a/src/specs/ReactNativeSmb.nitro.ts b/src/specs/ReactNativeSmb.nitro.ts index a1ee89a..bb16f98 100644 --- a/src/specs/ReactNativeSmb.nitro.ts +++ b/src/specs/ReactNativeSmb.nitro.ts @@ -1,4 +1,5 @@ import type { HybridObject, Int64 } from 'react-native-nitro-modules' +import type { NativeSmbListTask } from './NativeSmbListTask.nitro' import type { NativeSmbTask } from './NativeSmbTask.nitro' import type { SmbCredentials } from './types' @@ -22,7 +23,7 @@ export interface ReactNativeSmb extends HybridObject<{ ios: 'c++'; android: 'c++ maxDepth: number, includeSecurityDescriptor: boolean, batchSize: number, - ): NativeSmbTask + ): NativeSmbListTask getPathInfo(taskId: string, path: string): NativeSmbTask getSecurityDescriptor(taskId: string, path: string): NativeSmbTask diff --git a/src/types.ts b/src/types.ts index 5dc3d91..55dba91 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,4 @@ +import type { NativeSmbListTask as NitroNativeSmbListTask } from './specs/NativeSmbListTask.nitro' import type { NativeSmbTask as NitroNativeSmbTask } from './specs/NativeSmbTask.nitro' export type { @@ -139,17 +140,21 @@ export interface PoolInfo { /** * Native HybridObject for one SMB task. - * Nitrogen generates cancel/get/subscribe/…; getResultValue and drainEntries - * are registered as raw JSI methods on HybridSmbTask. + * Nitrogen generates cancel/get/subscribe/…; getResultValue is a raw JSI method. */ export type NativeSmbTask = NitroNativeSmbTask & { getResultValue(): unknown } -export type NativeSmbListTask = NativeSmbTask & { - /** - * Payload-free wake for new entries. Call {@link drainEntries} to pull every - * entry appended since the last drain (including a late-subscribe replay). - */ - drainEntries(subscriptionId: string): SmbFileInfo[] -} +/** + * Listing HybridObject. Nitrogen generates entry signals; drainEntries is raw + * because SmbFileInfo is recursive. + */ +export type NativeSmbListTask = NitroNativeSmbListTask & + NativeSmbTask & { + /** + * Payload-free wake for new entries. Call {@link drainEntries} to pull every + * entry appended since the last drain (including a late-subscribe replay). + */ + drainEntries(subscriptionId: string): SmbFileInfo[] + } From 6487c8a180b5c35dd41de59c49d896ee9fa7d7a8 Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:37:25 +0800 Subject: [PATCH 5/5] refactor(nitro): expose typed task snapshots and pool info String-map snapshots forced a hand-written codec on both sides and hid enum/struct types from Nitrogen. Specs now carry SmbTaskState and PoolInfo so the bridge maps domain DTOs once and JS consumes typed values. - add TaskStatus/SmbOperatorKind/SlotState plus snapshot/pool structs to specs - bridge with toBridge; drop TaskSnapshotCodec and decode.ts - update SmbTask/TransferStore/SmbClient and test mocks to typed objects --- cpp/shared/bridge/BridgeMapping.hpp | 65 ++++++++ cpp/shared/bridge/HybridSMB.cpp | 82 ++++------ cpp/shared/bridge/HybridSMB.hpp | 21 +-- cpp/shared/bridge/HybridSmbTask.cpp | 14 +- cpp/shared/bridge/HybridSmbTask.hpp | 14 +- cpp/shared/core/SmbTask.cpp | 17 -- cpp/shared/core/SmbTask.hpp | 7 +- cpp/shared/core/SmbTypes.hpp | 2 +- cpp/shared/core/TaskSnapshotCodec.cpp | 32 ---- cpp/shared/core/TaskSnapshotCodec.hpp | 41 ----- example/package-lock.json | 2 +- .../shared/c++/HybridNativeSmbTaskSpec.hpp | 9 +- .../shared/c++/HybridReactNativeSmbSpec.hpp | 22 ++- nitrogen/generated/shared/c++/PoolInfo.hpp | 89 +++++++++++ .../generated/shared/c++/PoolSlotInfo.hpp | 112 +++++++++++++ nitrogen/generated/shared/c++/SlotState.hpp | 63 ++++++++ .../generated/shared/c++/SmbOperatorKind.hpp | 76 +++++++++ .../generated/shared/c++/SmbTaskState.hpp | 148 ++++++++++++++++++ nitrogen/generated/shared/c++/TaskStatus.hpp | 66 ++++++++ src/bridge/decode.ts | 100 ------------ src/core/SmbClient.ts | 7 +- src/core/SmbTask.ts | 10 +- src/core/TransferStore.ts | 15 +- src/specs/NativeSmbTask.nitro.ts | 5 +- src/specs/ReactNativeSmb.nitro.ts | 16 +- src/specs/types.ts | 75 ++++++++- src/types.ts | 77 ++------- tests/SmbListTask.test.ts | 27 ++-- tests/TransferStore.test.ts | 29 ++-- tests/helpers/taskSnapshot.ts | 30 ++++ tests/taskResult.test.ts | 69 ++++---- 31 files changed, 891 insertions(+), 451 deletions(-) delete mode 100644 cpp/shared/core/TaskSnapshotCodec.cpp delete mode 100644 cpp/shared/core/TaskSnapshotCodec.hpp create mode 100644 nitrogen/generated/shared/c++/PoolInfo.hpp create mode 100644 nitrogen/generated/shared/c++/PoolSlotInfo.hpp create mode 100644 nitrogen/generated/shared/c++/SlotState.hpp create mode 100644 nitrogen/generated/shared/c++/SmbOperatorKind.hpp create mode 100644 nitrogen/generated/shared/c++/SmbTaskState.hpp create mode 100644 nitrogen/generated/shared/c++/TaskStatus.hpp delete mode 100644 src/bridge/decode.ts create mode 100644 tests/helpers/taskSnapshot.ts diff --git a/cpp/shared/bridge/BridgeMapping.hpp b/cpp/shared/bridge/BridgeMapping.hpp index 4e0dec0..f66392f 100644 --- a/cpp/shared/bridge/BridgeMapping.hpp +++ b/cpp/shared/bridge/BridgeMapping.hpp @@ -1,7 +1,18 @@ #pragma once +#include "../connection/PoolTypes.hpp" +#include "../core/SmbEnums.hpp" #include "../core/SmbModels.hpp" +#include "../core/SmbTypes.hpp" +#include "PoolInfo.hpp" +#include "PoolSlotInfo.hpp" #include "SmbCredentials.hpp" +#include "SmbOperatorKind.hpp" +#include "SmbTaskState.hpp" +#include "SlotState.hpp" +#include "TaskStatus.hpp" + +#include namespace margelo::nitro::smb { @@ -9,4 +20,58 @@ inline react_native_smb::SmbCredentials fromBridge(const SmbCredentials& credent return react_native_smb::SmbCredentials{credentials.username, credentials.password}; } +inline SmbOperatorKind toBridge(react_native_smb::SmbOperatorKind kind) { + return static_cast(static_cast(kind)); +} + +inline TaskStatus toBridge(react_native_smb::SmbTaskStatus status) { + return static_cast(static_cast(status)); +} + +inline SlotState toBridge(react_native_smb::SlotState state) { + return static_cast(static_cast(state)); +} + +inline SmbTaskState toBridge(const react_native_smb::SmbTaskState& state) { + return SmbTaskState( + state.taskId, + toBridge(state.kind), + toBridge(state.status), + react_native_smb::isDeterminate(state.kind), + state.progress, + static_cast(state.bytesDone), + static_cast(state.totalBytes), + state.bytesPerSecond, + state.etaSeconds, + state.sourcePath, + state.destinationPath, + static_cast(state.errorCode), + state.errorMessage, + static_cast(state.startedAt), + static_cast(state.updatedAt), + static_cast(state.endedAt)); +} + +inline PoolSlotInfo toBridge(const react_native_smb::PoolSlotInfo& slot) { + return PoolSlotInfo( + static_cast(slot.index), + slot.interactiveOnly, + toBridge(slot.state), + slot.isConnected, + slot.shareName, + slot.taskId, + toBridge(slot.kind)); +} + +inline PoolInfo toBridge(const std::vector& status) { + std::vector slots; + slots.reserve(status.size()); + double poolSize = 0; + for (const auto& slot : status) { + poolSize = static_cast(slot.poolSize); + slots.push_back(toBridge(slot)); + } + return PoolInfo(poolSize, std::move(slots)); +} + } // namespace margelo::nitro::smb diff --git a/cpp/shared/bridge/HybridSMB.cpp b/cpp/shared/bridge/HybridSMB.cpp index 96f30f0..01314fd 100644 --- a/cpp/shared/bridge/HybridSMB.cpp +++ b/cpp/shared/bridge/HybridSMB.cpp @@ -8,7 +8,6 @@ #include #include "../connection/PoolTypes.hpp" -#include "../core/TaskSnapshotCodec.hpp" #include "../operators/connection/ConnectOperator.hpp" #include "../operators/connection/ConnectShareOperator.hpp" #include "../operators/connection/DisconnectOperator.hpp" @@ -31,10 +30,9 @@ namespace margelo::nitro::smb { using react_native_smb::SmbTask; -using react_native_smb::SmbTaskState; -using react_native_smb::TaskSnapshotCodec; +using DomainTaskState = react_native_smb::SmbTaskState; +using DomainPoolSlotInfo = react_native_smb::PoolSlotInfo; using react_native_smb::isTransferKind; -using react_native_smb::PoolSlotInfo; using react_native_smb::SmbErrorCode; using react_native_smb::SmbException; @@ -258,40 +256,20 @@ void HybridSMB::resetPool() { if (pool_) pool_->resetPool(); } -namespace { - -std::unordered_map encodePoolSlot(const PoolSlotInfo& s) { - std::unordered_map m; - m["poolSize"] = std::to_string(s.poolSize); - m["index"] = std::to_string(s.index); - m["interactiveOnly"] = s.interactiveOnly ? "1" : "0"; - m["state"] = std::to_string(static_cast(s.state)); - m["kind"] = std::to_string(static_cast(s.kind)); - m["isConnected"] = s.isConnected ? "1" : "0"; - m["shareName"] = s.shareName; - m["taskId"] = s.taskId; - return m; +PoolInfo HybridSMB::getPoolInfo() { + if (!pool_) return PoolInfo(0, {}); + return toBridge(pool_->getPoolStatus()); } -} // namespace - -std::vector> HybridSMB::getPoolInfo() { - std::vector> out; - if (!pool_) return out; - for (const auto& s : pool_->getPoolStatus()) out.push_back(encodePoolSlot(s)); - return out; -} - -std::string HybridSMB::subscribePoolInfo(const std::function>&)>& listener) { +std::string HybridSMB::subscribePoolInfo(const std::function& listener) { std::string key = std::to_string(poolListenerToken_.fetch_add(1)); { std::lock_guard lock(poolListenersMutex_); poolListeners_.emplace(key, listener); } if (pool_) { - size_t obsId = pool_->addObserver([this, key](const std::vector& status) { - std::vector> out; - for (const auto& s : status) out.push_back(encodePoolSlot(s)); + size_t obsId = pool_->addObserver([this, key](const std::vector& status) { + const PoolInfo info = toBridge(status); PoolListener cb; { std::lock_guard lock(poolListenersMutex_); @@ -300,7 +278,7 @@ std::string HybridSMB::subscribePoolInfo(const std::function&)>& listener) { +std::string HybridSMB::subscribeTaskEvents(const std::function& listener) { if (!observer_) return ""; - auto eventId = std::make_shared>(1); - return observer_->subscribeAll([listener, eventId](const SmbTaskState& s) { - std::unordered_map m = TaskSnapshotCodec::encode(s); - m["eventId"] = std::to_string(eventId->fetch_add(1)); - m["type"] = std::to_string(static_cast(s.status)); - m["ts"] = std::to_string(s.updatedAt); - listener(m); + return observer_->subscribeAll([listener](const DomainTaskState& state) { + if (listener) { + try { + listener(toBridge(state)); + } catch (...) { + } + } }); } @@ -344,35 +322,35 @@ void HybridSMB::unsubscribeTaskEvents(const std::string& subscriptionId) { if (observer_) observer_->unsubscribe(subscriptionId); } -std::unordered_map HybridSMB::getTask(const std::string& taskId) { - if (!observer_) return TaskSnapshotCodec::notFound(); +std::optional HybridSMB::getTask(const std::string& taskId) { + if (!observer_) return std::nullopt; auto snapshot = observer_->getTask(taskId); - if (!snapshot) return TaskSnapshotCodec::notFound(); - return TaskSnapshotCodec::encode(*snapshot); + if (!snapshot) return std::nullopt; + return toBridge(*snapshot); } -std::vector> HybridSMB::getActiveTasks() { - std::vector> out; +std::vector HybridSMB::getActiveTasks() { + std::vector out; if (!observer_) return out; - for (const auto& snapshot : observer_->getActive()) out.push_back(TaskSnapshotCodec::encode(snapshot)); + for (const auto& snapshot : observer_->getActive()) out.push_back(toBridge(snapshot)); return out; } -std::vector> HybridSMB::getTransferTasks() { - std::vector> out; +std::vector HybridSMB::getTransferTasks() { + std::vector out; if (!observer_) return out; - for (const auto& snapshot : observer_->getTransfers()) out.push_back(TaskSnapshotCodec::encode(snapshot)); + for (const auto& snapshot : observer_->getTransfers()) out.push_back(toBridge(snapshot)); return out; } -std::vector> HybridSMB::getTaskHistory(double limit, double offset) { - std::vector> out; +std::vector HybridSMB::getTaskHistory(double limit, double offset) { + std::vector out; if (!observer_) return out; const int limitInt = static_cast(limit); const int offsetInt = static_cast(offset); const size_t safeLimit = limitInt < 0 ? 0 : static_cast(limitInt); const size_t safeOffset = offsetInt < 0 ? 0 : static_cast(offsetInt); - for (const auto& snapshot : observer_->getHistory(safeLimit, safeOffset)) out.push_back(TaskSnapshotCodec::encode(snapshot)); + for (const auto& snapshot : observer_->getHistory(safeLimit, safeOffset)) out.push_back(toBridge(snapshot)); return out; } diff --git a/cpp/shared/bridge/HybridSMB.hpp b/cpp/shared/bridge/HybridSMB.hpp index 2d889a2..0e3b532 100644 --- a/cpp/shared/bridge/HybridSMB.hpp +++ b/cpp/shared/bridge/HybridSMB.hpp @@ -11,6 +11,9 @@ #include "../core/TaskObserverHub.hpp" #include "../operators/OperatorBase.hpp" +#include "PoolInfo.hpp" +#include "SmbTaskState.hpp" + #include #include #include @@ -19,8 +22,8 @@ #include #include #include +#include #include -#include #include namespace margelo::nitro::smb { @@ -48,7 +51,7 @@ class HybridSMB : public HybridReactNativeSmbSpec { void shutdownImpl(); static void releaseTaskRun(const std::shared_ptr& state); - using PoolListener = std::function>&)>; + using PoolListener = std::function; std::map poolListeners_; std::map poolObserverIds_; std::mutex poolListenersMutex_; @@ -97,12 +100,12 @@ class HybridSMB : public HybridReactNativeSmbSpec { std::shared_ptr duplicateItem(const std::string& taskId, const std::string& path) override; // --- tasks --- - std::string subscribeTaskEvents(const std::function&)>& listener) override; + std::string subscribeTaskEvents(const std::function& listener) override; void unsubscribeTaskEvents(const std::string& subscriptionId) override; - std::unordered_map getTask(const std::string& taskId) override; - std::vector> getActiveTasks() override; - std::vector> getTransferTasks() override; - std::vector> getTaskHistory(double limit, double offset) override; + std::optional getTask(const std::string& taskId) override; + std::vector getActiveTasks() override; + std::vector getTransferTasks() override; + std::vector getTaskHistory(double limit, double offset) override; void cancelTask(const std::string& taskId) override; void cancelTransferTasks() override; void clearTaskHistory(int64_t beforeTs) override; @@ -111,9 +114,9 @@ class HybridSMB : public HybridReactNativeSmbSpec { std::shared_ptr> destroy() override; // --- pool --- - std::string subscribePoolInfo(const std::function>&)>& listener) override; + std::string subscribePoolInfo(const std::function& listener) override; void unsubscribePoolInfo(const std::string& subscriptionId) override; - std::vector> getPoolInfo() override; + PoolInfo getPoolInfo() override; void resetPool() override; }; diff --git a/cpp/shared/bridge/HybridSmbTask.cpp b/cpp/shared/bridge/HybridSmbTask.cpp index a2ad26c..f107220 100644 --- a/cpp/shared/bridge/HybridSmbTask.cpp +++ b/cpp/shared/bridge/HybridSmbTask.cpp @@ -5,6 +5,7 @@ #include #include +#include "BridgeMapping.hpp" #include "DomainConverters.hpp" #include "../core/EntryStream.hpp" #include "../core/SmbTask.hpp" @@ -21,10 +22,17 @@ HybridSmbTask::HybridSmbTask(std::shared_ptr task) void HybridSmbTask::cancel() { task_->cancel(); } -std::unordered_map HybridSmbTask::get() { return task_->get(); } +SmbTaskState HybridSmbTask::get() { return toBridge(task_->getState()); } -std::string HybridSmbTask::subscribe(const std::function&)>& listener) { - return task_->subscribeMap(listener); +std::string HybridSmbTask::subscribe(const std::function& listener) { + return task_->subscribe([listener](const react_native_smb::SmbTaskState& state) { + if (listener) { + try { + listener(toBridge(state)); + } catch (...) { + } + } + }); } void HybridSmbTask::unsubscribe(const std::string& subscriptionId) { task_->unsubscribe(subscriptionId); } diff --git a/cpp/shared/bridge/HybridSmbTask.hpp b/cpp/shared/bridge/HybridSmbTask.hpp index f8afeca..218f334 100644 --- a/cpp/shared/bridge/HybridSmbTask.hpp +++ b/cpp/shared/bridge/HybridSmbTask.hpp @@ -1,11 +1,11 @@ #pragma once #include "HybridNativeSmbTaskSpec.hpp" +#include "SmbTaskState.hpp" #include #include #include -#include namespace react_native_smb { class SmbTask; @@ -24,18 +24,18 @@ class HybridSmbTask : public virtual HybridNativeSmbTaskSpec { ~HybridSmbTask() override = default; void cancel() override; - std::unordered_map get() override; - std::string subscribe(const std::function&)>& listener) override; + SmbTaskState get() override; + std::string subscribe(const std::function& listener) override; void unsubscribe(const std::string& subscriptionId) override; + // Public so HybridSmbListTask can register the same raw method on its prototype. + facebook::jsi::Value getResultValueRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& thisValue, + const facebook::jsi::Value* args, size_t count); + protected: void loadHybridMethods() override; std::shared_ptr task_; - - facebook::jsi::Value getResultValueRaw(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& thisValue, - const facebook::jsi::Value* args, size_t count); }; - } // namespace margelo::nitro::smb diff --git a/cpp/shared/core/SmbTask.cpp b/cpp/shared/core/SmbTask.cpp index b63a908..9d7676b 100644 --- a/cpp/shared/core/SmbTask.cpp +++ b/cpp/shared/core/SmbTask.cpp @@ -7,8 +7,6 @@ #include "../util/SmbErrorMapper.hpp" #include "../util/SmbException.hpp" #include "EntryStream.hpp" -#include "TaskSnapshotCodec.hpp" - namespace react_native_smb { SmbTask::SmbTask(std::string id, std::unique_ptr seedOp, std::shared_ptr pool) @@ -104,19 +102,4 @@ size_t SmbTask::spawn(std::vector> moreOps) { return first; } -std::unordered_map SmbTask::get() { - return TaskSnapshotCodec::encode(getState()); -} - -std::string SmbTask::subscribeMap(const std::function&)>& listener) { - return SmbTaskCore::subscribe([listener](const SmbTaskState& s) { - if (listener) { - try { - listener(TaskSnapshotCodec::encode(s)); - } catch (...) { - } - } - }); -} - } // namespace react_native_smb diff --git a/cpp/shared/core/SmbTask.hpp b/cpp/shared/core/SmbTask.hpp index 79440b8..211ed57 100644 --- a/cpp/shared/core/SmbTask.hpp +++ b/cpp/shared/core/SmbTask.hpp @@ -1,11 +1,9 @@ #pragma once #include -#include #include #include #include -#include #include #include "SmbTaskCore.hpp" @@ -25,13 +23,12 @@ class SmbTask : public SmbTaskCore, public std::enable_shared_from_this void start(); size_t spawn(std::vector> moreOps); + using SmbTaskCore::getState; using SmbTaskCore::subscribe; + using SmbTaskCore::unsubscribe; std::string getId() { return SmbTaskCore::getId(); } void cancel(); - std::unordered_map get(); - std::string subscribeMap(const std::function&)>& listener); - void unsubscribe(const std::string& id) { SmbTaskCore::unsubscribe(id); } const std::shared_ptr& entryStream() const { return entries_; } diff --git a/cpp/shared/core/SmbTypes.hpp b/cpp/shared/core/SmbTypes.hpp index 44fd058..126f608 100644 --- a/cpp/shared/core/SmbTypes.hpp +++ b/cpp/shared/core/SmbTypes.hpp @@ -9,7 +9,7 @@ namespace react_native_smb { // Immutable snapshot a task broadcasts to its subscribers. Pure data (DTO). -// Projected to/from a Nitro string map by TaskSnapshotCodec. +// Bridge maps this to Nitrogen SmbTaskState via BridgeMapping::toBridge. struct SmbTaskState { std::string taskId; SmbOperatorKind kind{SmbOperatorKind::Initialize}; diff --git a/cpp/shared/core/TaskSnapshotCodec.cpp b/cpp/shared/core/TaskSnapshotCodec.cpp deleted file mode 100644 index 9188b67..0000000 --- a/cpp/shared/core/TaskSnapshotCodec.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "TaskSnapshotCodec.hpp" - -#include "SmbEnums.hpp" - -namespace react_native_smb { - -std::unordered_map TaskSnapshotCodec::encode(const SmbTaskState& s) { - return { - {Keys::exists, "1"}, - {Keys::taskId, s.taskId}, - {Keys::kind, std::to_string(static_cast(s.kind))}, - {Keys::operation, operationName(s.kind)}, - {Keys::status, std::to_string(static_cast(s.status))}, - {Keys::determinate, isDeterminate(s.kind) ? "1" : "0"}, - {Keys::progress, std::to_string(s.progress)}, - {Keys::errorCode, std::to_string(s.errorCode)}, - {Keys::errorMessage, s.errorMessage}, - {Keys::sourcePath, s.sourcePath}, - {Keys::destinationPath, s.destinationPath}, - {Keys::bytesDone, std::to_string(s.bytesDone)}, - {Keys::totalBytes, std::to_string(s.totalBytes)}, - {Keys::bytesPerSecond, std::to_string(s.bytesPerSecond)}, - {Keys::etaSeconds, std::to_string(s.etaSeconds)}, - {Keys::startedAt, std::to_string(s.startedAt)}, - {Keys::updatedAt, std::to_string(s.updatedAt)}, - {Keys::endedAt, std::to_string(s.endedAt)}, - }; -} - -std::unordered_map TaskSnapshotCodec::notFound() { return {{Keys::exists, "0"}}; } - -} // namespace react_native_smb diff --git a/cpp/shared/core/TaskSnapshotCodec.hpp b/cpp/shared/core/TaskSnapshotCodec.hpp deleted file mode 100644 index 0a13ed1..0000000 --- a/cpp/shared/core/TaskSnapshotCodec.hpp +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include - -#include "SmbTypes.hpp" - -namespace react_native_smb { - -// Single source of truth for the SmbTaskState -> Nitro string-map projection. -// The TS decoder (src/bridge/decode.ts) mirrors these key names. -class TaskSnapshotCodec { - public: - struct Keys { - static constexpr const char* exists = "exists"; // "1" / "0" sentinel for getTask - static constexpr const char* taskId = "taskId"; - static constexpr const char* kind = "kind"; // int(SmbOperatorKind) - static constexpr const char* operation = "operation"; // debug only; TS ignores - static constexpr const char* status = "status"; // int(SmbTaskStatus) - static constexpr const char* determinate = "determinate"; - static constexpr const char* progress = "progress"; - static constexpr const char* errorCode = "errorCode"; - static constexpr const char* errorMessage = "errorMessage"; - static constexpr const char* sourcePath = "sourcePath"; - static constexpr const char* destinationPath = "destinationPath"; - static constexpr const char* bytesDone = "bytesDone"; - static constexpr const char* totalBytes = "totalBytes"; - static constexpr const char* bytesPerSecond = "bytesPerSecond"; - static constexpr const char* etaSeconds = "etaSeconds"; - static constexpr const char* startedAt = "startedAt"; - static constexpr const char* updatedAt = "updatedAt"; - static constexpr const char* endedAt = "endedAt"; - }; - - static std::unordered_map encode(const SmbTaskState& s); - - // Sentinel map for "task not found". - static std::unordered_map notFound(); -}; - -} // namespace react_native_smb diff --git a/example/package-lock.json b/example/package-lock.json index b6c5097..a312d58 100644 --- a/example/package-lock.json +++ b/example/package-lock.json @@ -42,7 +42,7 @@ "peerDependencies": { "react": ">=19.0.0", "react-native": ">=0.76.0", - "react-native-nitro-modules": "*" + "react-native-nitro-modules": ">=0.37.2" }, "peerDependenciesMeta": { "react-native-nitro-modules": { diff --git a/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp b/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp index baa309f..7a9db0e 100644 --- a/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp +++ b/nitrogen/generated/shared/c++/HybridNativeSmbTaskSpec.hpp @@ -13,10 +13,11 @@ #error NitroModules cannot be found! Are you sure you installed NitroModules properly? #endif +// Forward declaration of `SmbTaskState` to properly resolve imports. +namespace margelo::nitro::smb { struct SmbTaskState; } - +#include "SmbTaskState.hpp" #include -#include #include namespace margelo::nitro::smb { @@ -51,8 +52,8 @@ namespace margelo::nitro::smb { public: // Methods virtual void cancel() = 0; - virtual std::unordered_map get() = 0; - virtual std::string subscribe(const std::function& /* snapshot */)>& listener) = 0; + virtual SmbTaskState get() = 0; + virtual std::string subscribe(const std::function& listener) = 0; virtual void unsubscribe(const std::string& subscriptionId) = 0; protected: diff --git a/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp b/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp index 1f61dda..f42fef9 100644 --- a/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp +++ b/nitrogen/generated/shared/c++/HybridReactNativeSmbSpec.hpp @@ -19,16 +19,22 @@ namespace margelo::nitro::smb { class HybridNativeSmbTaskSpec; } namespace margelo::nitro::smb { struct SmbCredentials; } // Forward declaration of `HybridNativeSmbListTaskSpec` to properly resolve imports. namespace margelo::nitro::smb { class HybridNativeSmbListTaskSpec; } +// Forward declaration of `SmbTaskState` to properly resolve imports. +namespace margelo::nitro::smb { struct SmbTaskState; } +// Forward declaration of `PoolInfo` to properly resolve imports. +namespace margelo::nitro::smb { struct PoolInfo; } #include #include "HybridNativeSmbTaskSpec.hpp" #include #include "SmbCredentials.hpp" #include "HybridNativeSmbListTaskSpec.hpp" -#include +#include "SmbTaskState.hpp" #include +#include #include #include +#include "PoolInfo.hpp" namespace margelo::nitro::smb { @@ -79,19 +85,19 @@ namespace margelo::nitro::smb { virtual std::shared_ptr renameItem(const std::string& taskId, const std::string& currentPath, const std::string& newName) = 0; virtual std::shared_ptr copyItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath, bool recursive) = 0; virtual std::shared_ptr duplicateItem(const std::string& taskId, const std::string& path) = 0; - virtual std::string subscribeTaskEvents(const std::function& /* event */)>& listener) = 0; + virtual std::string subscribeTaskEvents(const std::function& listener) = 0; virtual void unsubscribeTaskEvents(const std::string& subscriptionId) = 0; - virtual std::unordered_map getTask(const std::string& taskId) = 0; - virtual std::vector> getActiveTasks() = 0; - virtual std::vector> getTransferTasks() = 0; - virtual std::vector> getTaskHistory(double limit, double offset) = 0; + virtual std::optional getTask(const std::string& taskId) = 0; + virtual std::vector getActiveTasks() = 0; + virtual std::vector getTransferTasks() = 0; + virtual std::vector getTaskHistory(double limit, double offset) = 0; virtual void cancelTask(const std::string& taskId) = 0; virtual void cancelTransferTasks() = 0; virtual void clearTaskHistory(int64_t beforeTs) = 0; virtual std::shared_ptr> destroy() = 0; - virtual std::string subscribePoolInfo(const std::function>& /* snapshot */)>& listener) = 0; + virtual std::string subscribePoolInfo(const std::function& listener) = 0; virtual void unsubscribePoolInfo(const std::string& subscriptionId) = 0; - virtual std::vector> getPoolInfo() = 0; + virtual PoolInfo getPoolInfo() = 0; virtual void resetPool() = 0; protected: diff --git a/nitrogen/generated/shared/c++/PoolInfo.hpp b/nitrogen/generated/shared/c++/PoolInfo.hpp new file mode 100644 index 0000000..78b2c51 --- /dev/null +++ b/nitrogen/generated/shared/c++/PoolInfo.hpp @@ -0,0 +1,89 @@ +/// +/// PoolInfo.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +// Forward declaration of `PoolSlotInfo` to properly resolve imports. +namespace margelo::nitro::smb { struct PoolSlotInfo; } + +#include "PoolSlotInfo.hpp" +#include + +namespace margelo::nitro::smb { + + /** + * A struct which can be represented as a JavaScript object (PoolInfo). + */ + struct PoolInfo final { + public: + double poolSize SWIFT_PRIVATE; + std::vector slots SWIFT_PRIVATE; + + public: + PoolInfo() = default; + explicit PoolInfo(double poolSize, std::vector slots): poolSize(poolSize), slots(slots) {} + + public: + friend bool operator==(const PoolInfo& lhs, const PoolInfo& rhs) = default; + }; + +} // namespace margelo::nitro::smb + +namespace margelo::nitro { + + // C++ PoolInfo <> JS PoolInfo (object) + template <> + struct JSIConverter final { + static inline margelo::nitro::smb::PoolInfo fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + jsi::Object obj = arg.asObject(runtime); + return margelo::nitro::smb::PoolInfo( + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "poolSize"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "slots"))) + ); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::smb::PoolInfo& arg) { + jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "poolSize"), JSIConverter::toJSI(runtime, arg.poolSize)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "slots"), JSIConverter>::toJSI(runtime, arg.slots)); + return obj; + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + return false; + } + jsi::Object obj = value.getObject(runtime); + if (!nitro::isPlainObject(runtime, obj)) { + return false; + } + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "poolSize")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "slots")))) return false; + return true; + } + }; + +} // namespace margelo::nitro diff --git a/nitrogen/generated/shared/c++/PoolSlotInfo.hpp b/nitrogen/generated/shared/c++/PoolSlotInfo.hpp new file mode 100644 index 0000000..7c46e29 --- /dev/null +++ b/nitrogen/generated/shared/c++/PoolSlotInfo.hpp @@ -0,0 +1,112 @@ +/// +/// PoolSlotInfo.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +// Forward declaration of `SlotState` to properly resolve imports. +namespace margelo::nitro::smb { enum class SlotState; } +// Forward declaration of `SmbOperatorKind` to properly resolve imports. +namespace margelo::nitro::smb { enum class SmbOperatorKind; } + +#include "SlotState.hpp" +#include +#include "SmbOperatorKind.hpp" + +namespace margelo::nitro::smb { + + /** + * A struct which can be represented as a JavaScript object (PoolSlotInfo). + */ + struct PoolSlotInfo final { + public: + double index SWIFT_PRIVATE; + bool interactiveOnly SWIFT_PRIVATE; + SlotState state SWIFT_PRIVATE; + bool isConnected SWIFT_PRIVATE; + std::string shareName SWIFT_PRIVATE; + std::string taskId SWIFT_PRIVATE; + SmbOperatorKind kind SWIFT_PRIVATE; + + public: + PoolSlotInfo() = default; + explicit PoolSlotInfo(double index, bool interactiveOnly, SlotState state, bool isConnected, std::string shareName, std::string taskId, SmbOperatorKind kind): index(index), interactiveOnly(interactiveOnly), state(state), isConnected(isConnected), shareName(shareName), taskId(taskId), kind(kind) {} + + public: + friend bool operator==(const PoolSlotInfo& lhs, const PoolSlotInfo& rhs) = default; + }; + +} // namespace margelo::nitro::smb + +namespace margelo::nitro { + + // C++ PoolSlotInfo <> JS PoolSlotInfo (object) + template <> + struct JSIConverter final { + static inline margelo::nitro::smb::PoolSlotInfo fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + jsi::Object obj = arg.asObject(runtime); + return margelo::nitro::smb::PoolSlotInfo( + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "index"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "interactiveOnly"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "state"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "isConnected"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "shareName"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "taskId"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "kind"))) + ); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::smb::PoolSlotInfo& arg) { + jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "index"), JSIConverter::toJSI(runtime, arg.index)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "interactiveOnly"), JSIConverter::toJSI(runtime, arg.interactiveOnly)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "state"), JSIConverter::toJSI(runtime, arg.state)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "isConnected"), JSIConverter::toJSI(runtime, arg.isConnected)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "shareName"), JSIConverter::toJSI(runtime, arg.shareName)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "taskId"), JSIConverter::toJSI(runtime, arg.taskId)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "kind"), JSIConverter::toJSI(runtime, arg.kind)); + return obj; + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + return false; + } + jsi::Object obj = value.getObject(runtime); + if (!nitro::isPlainObject(runtime, obj)) { + return false; + } + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "index")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "interactiveOnly")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "state")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "isConnected")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "shareName")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "taskId")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "kind")))) return false; + return true; + } + }; + +} // namespace margelo::nitro diff --git a/nitrogen/generated/shared/c++/SlotState.hpp b/nitrogen/generated/shared/c++/SlotState.hpp new file mode 100644 index 0000000..ad50072 --- /dev/null +++ b/nitrogen/generated/shared/c++/SlotState.hpp @@ -0,0 +1,63 @@ +/// +/// SlotState.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +namespace margelo::nitro::smb { + + /** + * An enum which can be represented as a JavaScript enum (SlotState). + */ + enum class SlotState { + IDLE SWIFT_NAME(idle) = 0, + ASSIGNED SWIFT_NAME(assigned) = 1, + ACTIVATING SWIFT_NAME(activating) = 2, + } CLOSED_ENUM; + +} // namespace margelo::nitro::smb + +namespace margelo::nitro { + + // C++ SlotState <> JS SlotState (enum) + template <> + struct JSIConverter final { + static inline margelo::nitro::smb::SlotState fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + int enumValue = JSIConverter::fromJSI(runtime, arg); + return static_cast(enumValue); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, margelo::nitro::smb::SlotState arg) { + int enumValue = static_cast(arg); + return JSIConverter::toJSI(runtime, enumValue); + } + static inline bool canConvert(jsi::Runtime&, const jsi::Value& value) { + if (!value.isNumber()) { + return false; + } + double number = value.getNumber(); + int integer = static_cast(number); + if (number != integer) { + // The integer is not the same value as the double - we truncated floating points. + // Enums are all integers, so the input floating point number is obviously invalid. + return false; + } + // Check if we are within the bounds of the enum. + return integer >= 0 && integer <= 2; + } + }; + +} // namespace margelo::nitro diff --git a/nitrogen/generated/shared/c++/SmbOperatorKind.hpp b/nitrogen/generated/shared/c++/SmbOperatorKind.hpp new file mode 100644 index 0000000..47d11c9 --- /dev/null +++ b/nitrogen/generated/shared/c++/SmbOperatorKind.hpp @@ -0,0 +1,76 @@ +/// +/// SmbOperatorKind.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +namespace margelo::nitro::smb { + + /** + * An enum which can be represented as a JavaScript enum (SmbOperatorKind). + */ + enum class SmbOperatorKind { + INITIALIZE SWIFT_NAME(initialize) = 0, + CONNECT SWIFT_NAME(connect) = 1, + CONNECTSHARE SWIFT_NAME(connectshare) = 2, + DISCONNECT SWIFT_NAME(disconnect) = 3, + LISTSHARES SWIFT_NAME(listshares) = 4, + LISTDIRECTORY SWIFT_NAME(listdirectory) = 5, + GETPATHINFO SWIFT_NAME(getpathinfo) = 6, + GETSECURITYDESCRIPTOR SWIFT_NAME(getsecuritydescriptor) = 7, + DOWNLOADFILE SWIFT_NAME(downloadfile) = 8, + UPLOADFILE SWIFT_NAME(uploadfile) = 9, + CREATEDIRECTORY SWIFT_NAME(createdirectory) = 10, + DELETEITEM SWIFT_NAME(deleteitem) = 11, + MOVEITEM SWIFT_NAME(moveitem) = 12, + RENAMEITEM SWIFT_NAME(renameitem) = 13, + COPYITEM SWIFT_NAME(copyitem) = 14, + DUPLICATEITEM SWIFT_NAME(duplicateitem) = 15, + } CLOSED_ENUM; + +} // namespace margelo::nitro::smb + +namespace margelo::nitro { + + // C++ SmbOperatorKind <> JS SmbOperatorKind (enum) + template <> + struct JSIConverter final { + static inline margelo::nitro::smb::SmbOperatorKind fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + int enumValue = JSIConverter::fromJSI(runtime, arg); + return static_cast(enumValue); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, margelo::nitro::smb::SmbOperatorKind arg) { + int enumValue = static_cast(arg); + return JSIConverter::toJSI(runtime, enumValue); + } + static inline bool canConvert(jsi::Runtime&, const jsi::Value& value) { + if (!value.isNumber()) { + return false; + } + double number = value.getNumber(); + int integer = static_cast(number); + if (number != integer) { + // The integer is not the same value as the double - we truncated floating points. + // Enums are all integers, so the input floating point number is obviously invalid. + return false; + } + // Check if we are within the bounds of the enum. + return integer >= 0 && integer <= 15; + } + }; + +} // namespace margelo::nitro diff --git a/nitrogen/generated/shared/c++/SmbTaskState.hpp b/nitrogen/generated/shared/c++/SmbTaskState.hpp new file mode 100644 index 0000000..b5c665e --- /dev/null +++ b/nitrogen/generated/shared/c++/SmbTaskState.hpp @@ -0,0 +1,148 @@ +/// +/// SmbTaskState.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +// Forward declaration of `SmbOperatorKind` to properly resolve imports. +namespace margelo::nitro::smb { enum class SmbOperatorKind; } +// Forward declaration of `TaskStatus` to properly resolve imports. +namespace margelo::nitro::smb { enum class TaskStatus; } + +#include +#include "SmbOperatorKind.hpp" +#include "TaskStatus.hpp" + +namespace margelo::nitro::smb { + + /** + * A struct which can be represented as a JavaScript object (SmbTaskState). + */ + struct SmbTaskState final { + public: + std::string taskId SWIFT_PRIVATE; + SmbOperatorKind kind SWIFT_PRIVATE; + TaskStatus status SWIFT_PRIVATE; + bool determinate SWIFT_PRIVATE; + double progress SWIFT_PRIVATE; + double bytesDone SWIFT_PRIVATE; + double totalBytes SWIFT_PRIVATE; + double bytesPerSecond SWIFT_PRIVATE; + double etaSeconds SWIFT_PRIVATE; + std::string sourcePath SWIFT_PRIVATE; + std::string destinationPath SWIFT_PRIVATE; + double errorCode SWIFT_PRIVATE; + std::string errorMessage SWIFT_PRIVATE; + double startedAt SWIFT_PRIVATE; + double updatedAt SWIFT_PRIVATE; + double endedAt SWIFT_PRIVATE; + + public: + SmbTaskState() = default; + explicit SmbTaskState(std::string taskId, SmbOperatorKind kind, TaskStatus status, bool determinate, double progress, double bytesDone, double totalBytes, double bytesPerSecond, double etaSeconds, std::string sourcePath, std::string destinationPath, double errorCode, std::string errorMessage, double startedAt, double updatedAt, double endedAt): taskId(taskId), kind(kind), status(status), determinate(determinate), progress(progress), bytesDone(bytesDone), totalBytes(totalBytes), bytesPerSecond(bytesPerSecond), etaSeconds(etaSeconds), sourcePath(sourcePath), destinationPath(destinationPath), errorCode(errorCode), errorMessage(errorMessage), startedAt(startedAt), updatedAt(updatedAt), endedAt(endedAt) {} + + public: + friend bool operator==(const SmbTaskState& lhs, const SmbTaskState& rhs) = default; + }; + +} // namespace margelo::nitro::smb + +namespace margelo::nitro { + + // C++ SmbTaskState <> JS SmbTaskState (object) + template <> + struct JSIConverter final { + static inline margelo::nitro::smb::SmbTaskState fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + jsi::Object obj = arg.asObject(runtime); + return margelo::nitro::smb::SmbTaskState( + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "taskId"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "kind"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "status"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "determinate"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "progress"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "bytesDone"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "totalBytes"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "bytesPerSecond"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "etaSeconds"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "sourcePath"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "destinationPath"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "errorCode"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "errorMessage"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "startedAt"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "updatedAt"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "endedAt"))) + ); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::smb::SmbTaskState& arg) { + jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "taskId"), JSIConverter::toJSI(runtime, arg.taskId)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "kind"), JSIConverter::toJSI(runtime, arg.kind)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "status"), JSIConverter::toJSI(runtime, arg.status)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "determinate"), JSIConverter::toJSI(runtime, arg.determinate)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "progress"), JSIConverter::toJSI(runtime, arg.progress)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "bytesDone"), JSIConverter::toJSI(runtime, arg.bytesDone)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "totalBytes"), JSIConverter::toJSI(runtime, arg.totalBytes)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "bytesPerSecond"), JSIConverter::toJSI(runtime, arg.bytesPerSecond)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "etaSeconds"), JSIConverter::toJSI(runtime, arg.etaSeconds)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "sourcePath"), JSIConverter::toJSI(runtime, arg.sourcePath)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "destinationPath"), JSIConverter::toJSI(runtime, arg.destinationPath)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "errorCode"), JSIConverter::toJSI(runtime, arg.errorCode)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "errorMessage"), JSIConverter::toJSI(runtime, arg.errorMessage)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "startedAt"), JSIConverter::toJSI(runtime, arg.startedAt)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "updatedAt"), JSIConverter::toJSI(runtime, arg.updatedAt)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "endedAt"), JSIConverter::toJSI(runtime, arg.endedAt)); + return obj; + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + return false; + } + jsi::Object obj = value.getObject(runtime); + if (!nitro::isPlainObject(runtime, obj)) { + return false; + } + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "taskId")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "kind")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "status")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "determinate")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "progress")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "bytesDone")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "totalBytes")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "bytesPerSecond")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "etaSeconds")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "sourcePath")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "destinationPath")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "errorCode")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "errorMessage")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "startedAt")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "updatedAt")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "endedAt")))) return false; + return true; + } + }; + +} // namespace margelo::nitro diff --git a/nitrogen/generated/shared/c++/TaskStatus.hpp b/nitrogen/generated/shared/c++/TaskStatus.hpp new file mode 100644 index 0000000..e064c59 --- /dev/null +++ b/nitrogen/generated/shared/c++/TaskStatus.hpp @@ -0,0 +1,66 @@ +/// +/// TaskStatus.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +namespace margelo::nitro::smb { + + /** + * An enum which can be represented as a JavaScript enum (TaskStatus). + */ + enum class TaskStatus { + IDLE SWIFT_NAME(idle) = 0, + PENDING SWIFT_NAME(pending) = 1, + RUNNING SWIFT_NAME(running) = 2, + SUCCESS SWIFT_NAME(success) = 3, + ERROR SWIFT_NAME(error) = 4, + CANCELLED SWIFT_NAME(cancelled) = 5, + } CLOSED_ENUM; + +} // namespace margelo::nitro::smb + +namespace margelo::nitro { + + // C++ TaskStatus <> JS TaskStatus (enum) + template <> + struct JSIConverter final { + static inline margelo::nitro::smb::TaskStatus fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + int enumValue = JSIConverter::fromJSI(runtime, arg); + return static_cast(enumValue); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, margelo::nitro::smb::TaskStatus arg) { + int enumValue = static_cast(arg); + return JSIConverter::toJSI(runtime, enumValue); + } + static inline bool canConvert(jsi::Runtime&, const jsi::Value& value) { + if (!value.isNumber()) { + return false; + } + double number = value.getNumber(); + int integer = static_cast(number); + if (number != integer) { + // The integer is not the same value as the double - we truncated floating points. + // Enums are all integers, so the input floating point number is obviously invalid. + return false; + } + // Check if we are within the bounds of the enum. + return integer >= 0 && integer <= 5; + } + }; + +} // namespace margelo::nitro diff --git a/src/bridge/decode.ts b/src/bridge/decode.ts deleted file mode 100644 index ad9117c..0000000 --- a/src/bridge/decode.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { - SmbOperatorKind, - SmbError, - SlotState, - TaskStatus, - type PoolInfo, - type PoolSlotInfo, - type SmbTaskState, -} from '../types'; - -function parseIntField(raw: Record, key: string): number { - const v = raw[key]; - if (v === undefined || v === '') { - throw new Error(`Missing bridge field: ${key}`); - } - const n = parseInt(v, 10); - if (!Number.isFinite(n)) { - throw new Error(`Invalid bridge field ${key}: ${v}`); - } - return n; -} - -function parseIntOptional(raw: Record, key: string, fallback = 0): number { - const v = raw[key]; - if (v === undefined || v === '') return fallback; - const n = parseInt(v, 10); - return Number.isFinite(n) ? n : fallback; -} - -function parseFloatField(raw: Record, key: string, fallback = 0): number { - const v = raw[key]; - if (v === undefined || v === '') return fallback; - const n = parseFloat(v); - return Number.isFinite(n) ? n : fallback; -} - -function parseBoolField(raw: Record, key: string): boolean { - const v = raw[key]; - return v === '1' || v === 'true'; -} - -function enumFromInt(value: number, enumObj: Record): T { - const valid = Object.values(enumObj).filter((v): v is number => typeof v === 'number'); - if (valid.includes(value)) { - return value as T; - } - throw new Error(`Invalid enum value: ${value}`); -} - -function errorFromInt(value: number): SmbError { - const valid = Object.values(SmbError).filter((v): v is SmbError => typeof v === 'number'); - return valid.includes(value as SmbError) ? (value as SmbError) : SmbError.Unknown; -} - -export function shapeTaskSnapshot(raw: Record): SmbTaskState | null { - if (raw.exists === '0') return null; - - const kind = enumFromInt(parseIntField(raw, 'kind'), SmbOperatorKind); - const status = enumFromInt(parseIntField(raw, 'status'), TaskStatus); - - return { - taskId: raw.taskId ?? '', - kind, - status, - determinate: parseBoolField(raw, 'determinate'), - progress: parseFloatField(raw, 'progress'), - bytesDone: parseIntOptional(raw, 'bytesDone'), - totalBytes: parseIntOptional(raw, 'totalBytes'), - bytesPerSecond: parseFloatField(raw, 'bytesPerSecond'), - etaSeconds: parseFloatField(raw, 'etaSeconds'), - sourcePath: raw.sourcePath ?? '', - destinationPath: raw.destinationPath ?? '', - errorCode: errorFromInt(parseIntOptional(raw, 'errorCode')), - errorMessage: raw.errorMessage ?? '', - startedAt: parseIntOptional(raw, 'startedAt'), - updatedAt: parseIntOptional(raw, 'updatedAt'), - endedAt: parseIntOptional(raw, 'endedAt'), - }; -} - -function shapePoolSlot(raw: Record): PoolSlotInfo { - return { - index: parseIntField(raw, 'index'), - interactiveOnly: parseBoolField(raw, 'interactiveOnly'), - state: enumFromInt(parseIntField(raw, 'state'), SlotState), - isConnected: parseBoolField(raw, 'isConnected'), - shareName: raw.shareName ?? '', - taskId: raw.taskId ?? '', - kind: enumFromInt(parseIntField(raw, 'kind'), SmbOperatorKind), - }; -} - -export function shapePoolInfo(raw: Array>): PoolInfo { - if (!raw || raw.length === 0) return { poolSize: 0, slots: [] }; - const poolSize = parseIntField(raw[0], 'poolSize'); - return { - poolSize, - slots: raw.map(shapePoolSlot), - }; -} diff --git a/src/core/SmbClient.ts b/src/core/SmbClient.ts index 372c014..4f924e4 100644 --- a/src/core/SmbClient.ts +++ b/src/core/SmbClient.ts @@ -1,5 +1,4 @@ import { NitroModules } from 'react-native-nitro-modules'; -import { shapePoolInfo } from '../bridge/decode'; import type { ReactNativeSmb } from '../ReactNativeSmb'; import type { ListDirectoryOptions, @@ -145,13 +144,11 @@ export class SmbClient { } getPoolInfo(): PoolInfo { - return shapePoolInfo(this.native.getPoolInfo()); + return this.native.getPoolInfo(); } subscribePoolInfo(cb: (info: PoolInfo) => void): string { - const id = this.native.subscribePoolInfo((raw) => { - cb(shapePoolInfo(raw)); - }); + const id = this.native.subscribePoolInfo(cb); cb(this.getPoolInfo()); return id; } diff --git a/src/core/SmbTask.ts b/src/core/SmbTask.ts index 35df2ec..1f764a8 100644 --- a/src/core/SmbTask.ts +++ b/src/core/SmbTask.ts @@ -1,4 +1,3 @@ -import { shapeTaskSnapshot } from '../bridge/decode'; import { isTerminalStatus } from '../labels'; import { TaskStatus, type NativeSmbTask, type SmbTaskState } from '../types'; import { taskDone, taskResult } from './taskResult'; @@ -38,7 +37,7 @@ export class SmbTask { /** One-shot snapshot without subscribing. */ get(): SmbTaskState | null { - return shapeTaskSnapshot(this.native.get()); + return this.native.get(); } /** Latest known snapshot, reading native state once when needed. */ @@ -75,11 +74,6 @@ export class SmbTask { listener?.(effective); }; - const receive = (raw: Record) => { - const snap = shapeTaskSnapshot(raw); - if (snap) receiveSnapshot(snap); - }; - const unsubscribe = () => { if (!active) return; active = false; @@ -89,7 +83,7 @@ export class SmbTask { }; try { - subId = this.native.subscribe(receive); + subId = this.native.subscribe(receiveSnapshot); const initial = this.get(); if (initial) receiveSnapshot(initial); } catch (error) { diff --git a/src/core/TransferStore.ts b/src/core/TransferStore.ts index a034e97..067a0e9 100644 --- a/src/core/TransferStore.ts +++ b/src/core/TransferStore.ts @@ -1,4 +1,3 @@ -import { shapeTaskSnapshot } from '../bridge/decode'; import { isTerminalStatus, isTransferKind } from '../labels'; import type { ReactNativeSmb } from '../ReactNativeSmb'; import { type SmbTaskState } from '../types'; @@ -26,16 +25,15 @@ export class TransferStore { const generation = ++this.generation; try { - subId = this.native.subscribeTaskEvents((raw) => { + subId = this.native.subscribeTaskEvents((snap) => { if (this.generation !== generation) return; try { - this.upsert(raw); + this.upsert(snap); } catch {} }); - for (const raw of this.native.getTransferTasks()) { - const snap = shapeTaskSnapshot(raw); - if (!snap || !isTransferKind(snap.kind) || this.hidden.has(snap.taskId)) continue; + for (const snap of this.native.getTransferTasks()) { + if (!isTransferKind(snap.kind) || this.hidden.has(snap.taskId)) continue; // Events received after subscription are newer than this hydration snapshot. if (!this.tasks.has(snap.taskId)) this.tasks.set(snap.taskId, snap); } @@ -78,9 +76,8 @@ export class TransferStore { return this.snapshot; } - private upsert(raw: Record): void { - const snap = shapeTaskSnapshot(raw); - if (!snap || !isTransferKind(snap.kind) || this.hidden.has(snap.taskId)) return; + private upsert(snap: SmbTaskState): void { + if (!isTransferKind(snap.kind) || this.hidden.has(snap.taskId)) return; const existing = this.tasks.get(snap.taskId); if (existing && (isTerminalStatus(existing.status) || snap.updatedAt < existing.updatedAt)) return; diff --git a/src/specs/NativeSmbTask.nitro.ts b/src/specs/NativeSmbTask.nitro.ts index 6505bd2..cc3e4b3 100644 --- a/src/specs/NativeSmbTask.nitro.ts +++ b/src/specs/NativeSmbTask.nitro.ts @@ -1,4 +1,5 @@ import type { HybridObject } from 'react-native-nitro-modules' +import type { SmbTaskState } from './types' /** * Nitro HybridObject for one native SMB operation. @@ -9,7 +10,7 @@ import type { HybridObject } from 'react-native-nitro-modules' */ export interface NativeSmbTask extends HybridObject<{ ios: 'c++'; android: 'c++' }> { cancel(): void - get(): Record - subscribe(listener: (snapshot: Record) => void): string + get(): SmbTaskState + subscribe(listener: (snapshot: SmbTaskState) => void): string unsubscribe(subscriptionId: string): void } diff --git a/src/specs/ReactNativeSmb.nitro.ts b/src/specs/ReactNativeSmb.nitro.ts index bb16f98..9e6a163 100644 --- a/src/specs/ReactNativeSmb.nitro.ts +++ b/src/specs/ReactNativeSmb.nitro.ts @@ -1,7 +1,7 @@ import type { HybridObject, Int64 } from 'react-native-nitro-modules' import type { NativeSmbListTask } from './NativeSmbListTask.nitro' import type { NativeSmbTask } from './NativeSmbTask.nitro' -import type { SmbCredentials } from './types' +import type { PoolInfo, SmbCredentials, SmbTaskState } from './types' /** * Nitro HybridObject for the SMB client. @@ -37,20 +37,20 @@ export interface ReactNativeSmb extends HybridObject<{ ios: 'c++'; android: 'c++ copyItem(taskId: string, fromPath: string, toPath: string, recursive: boolean): NativeSmbTask duplicateItem(taskId: string, path: string): NativeSmbTask - subscribeTaskEvents(listener: (event: Record) => void): string + subscribeTaskEvents(listener: (event: SmbTaskState) => void): string unsubscribeTaskEvents(subscriptionId: string): void - getTask(taskId: string): Record - getActiveTasks(): Record[] - getTransferTasks(): Record[] - getTaskHistory(limit: number, offset: number): Record[] + getTask(taskId: string): SmbTaskState | undefined + getActiveTasks(): SmbTaskState[] + getTransferTasks(): SmbTaskState[] + getTaskHistory(limit: number, offset: number): SmbTaskState[] cancelTask(taskId: string): void cancelTransferTasks(): void clearTaskHistory(beforeTs: Int64): void destroy(): Promise - subscribePoolInfo(listener: (snapshot: Record[]) => void): string + subscribePoolInfo(listener: (info: PoolInfo) => void): string unsubscribePoolInfo(subscriptionId: string): void - getPoolInfo(): Record[] + getPoolInfo(): PoolInfo resetPool(): void } diff --git a/src/specs/types.ts b/src/specs/types.ts index 3951959..5b15578 100644 --- a/src/specs/types.ts +++ b/src/specs/types.ts @@ -1,6 +1,6 @@ /** - * Structs shared by Nitrogen HybridObject specs. - * Domain C++ keeps its own SmbModels with int64_t; bridge maps between them. + * Structs and enums shared by Nitrogen HybridObject specs. + * Domain C++ keeps its own models; bridge maps between them. * SmbFileInfo is intentionally absent — Nitrogen 0.37.2 cannot generate * recursive structs; it stays hand-converted via JSIConverter. */ @@ -42,3 +42,74 @@ export interface SmbSecurityDescriptor { groupSid: string dacl: SmbAcl } + +/** Mirrors domain SmbTaskStatus — numeric values must stay stable. */ +export enum TaskStatus { + Idle = 0, + Pending = 1, + Running = 2, + Success = 3, + Error = 4, + Cancelled = 5, +} + +/** Mirrors domain SmbOperatorKind — numeric values must stay stable. */ +export enum SmbOperatorKind { + Initialize = 0, + Connect = 1, + ConnectShare = 2, + Disconnect = 3, + ListShares = 4, + ListDirectory = 5, + GetPathInfo = 6, + GetSecurityDescriptor = 7, + DownloadFile = 8, + UploadFile = 9, + CreateDirectory = 10, + DeleteItem = 11, + MoveItem = 12, + RenameItem = 13, + CopyItem = 14, + DuplicateItem = 15, +} + +/** Mirrors domain SlotState — numeric values must stay stable. */ +export enum SlotState { + Idle = 0, + Assigned = 1, + Activating = 2, +} + +export interface SmbTaskState { + taskId: string + kind: SmbOperatorKind + status: TaskStatus + determinate: boolean + progress: number + bytesDone: number + totalBytes: number + bytesPerSecond: number + etaSeconds: number + sourcePath: string + destinationPath: string + errorCode: number + errorMessage: string + startedAt: number + updatedAt: number + endedAt: number +} + +export interface PoolSlotInfo { + index: number + interactiveOnly: boolean + state: SlotState + isConnected: boolean + shareName: string + taskId: string + kind: SmbOperatorKind +} + +export interface PoolInfo { + poolSize: number + slots: PoolSlotInfo[] +} diff --git a/src/types.ts b/src/types.ts index 55dba91..7ec8a34 100644 --- a/src/types.ts +++ b/src/types.ts @@ -8,6 +8,15 @@ export type { SmbAce, SmbAcl, SmbSecurityDescriptor, + SmbTaskState, + PoolSlotInfo, + PoolInfo, +} from './specs/types' + +export { + TaskStatus, + SmbOperatorKind, + SlotState, } from './specs/types' export enum SmbError { @@ -70,74 +79,6 @@ export interface PathComponents { readonly fullFileName: string } -export enum TaskStatus { - Idle = 0, - Pending = 1, - Running = 2, - Success = 3, - Error = 4, - Cancelled = 5, -} - -export enum SmbOperatorKind { - Initialize = 0, - Connect = 1, - ConnectShare = 2, - Disconnect = 3, - ListShares = 4, - ListDirectory = 5, - GetPathInfo = 6, - GetSecurityDescriptor = 7, - DownloadFile = 8, - UploadFile = 9, - CreateDirectory = 10, - DeleteItem = 11, - MoveItem = 12, - RenameItem = 13, - CopyItem = 14, - DuplicateItem = 15, -} - -export enum SlotState { - Idle = 0, - Assigned = 1, - Activating = 2, -} - -export interface SmbTaskState { - readonly taskId: string - readonly kind: SmbOperatorKind - readonly status: TaskStatus - readonly determinate: boolean - readonly progress: number - readonly bytesDone: number - readonly totalBytes: number - readonly bytesPerSecond: number - readonly etaSeconds: number - readonly sourcePath: string - readonly destinationPath: string - readonly errorCode: number - readonly errorMessage: string - readonly startedAt: number - readonly updatedAt: number - readonly endedAt: number -} - -export interface PoolSlotInfo { - readonly index: number - readonly interactiveOnly: boolean - readonly state: SlotState - readonly isConnected: boolean - readonly shareName: string - readonly taskId: string - readonly kind: SmbOperatorKind -} - -export interface PoolInfo { - readonly poolSize: number - readonly slots: PoolSlotInfo[] -} - /** * Native HybridObject for one SMB task. * Nitrogen generates cancel/get/subscribe/…; getResultValue is a raw JSI method. diff --git a/tests/SmbListTask.test.ts b/tests/SmbListTask.test.ts index 17bf7a9..14b552e 100644 --- a/tests/SmbListTask.test.ts +++ b/tests/SmbListTask.test.ts @@ -7,16 +7,15 @@ import { TaskStatus, type NativeSmbListTask, type SmbFileInfo, + type SmbTaskState, } from '../src/types'; +import { makeTaskSnapshot } from './helpers/taskSnapshot'; -function snapshot(status: TaskStatus, overrides: Record = {}): Record { - return { - exists: '1', - taskId: 'task-1', - kind: String(SmbOperatorKind.ListDirectory), - status: String(status), +function snapshot(status: TaskStatus, overrides: Partial = {}): SmbTaskState { + return makeTaskSnapshot(status, { + kind: SmbOperatorKind.ListDirectory, ...overrides, - }; + }); } function entry(name: string): SmbFileInfo { @@ -42,8 +41,8 @@ type EntrySubscriber = { /** Mirrors native EntryStream notify-and-drain delivery. */ class FakeNativeListTask implements NativeSmbListTask { - current: Record; - readonly listeners = new Map) => void>(); + current: SmbTaskState; + readonly listeners = new Map void>(); readonly entrySubscribers = new Map(); readonly unsubscribedEntries: string[] = []; readonly emitted: SmbFileInfo[] = []; @@ -52,17 +51,17 @@ class FakeNativeListTask implements NativeSmbListTask { private nextId = 1; private deferSignals = false; - constructor(current: Record) { + constructor(current: SmbTaskState) { this.current = current; } cancel(): void {} - get(): Record { + get(): SmbTaskState { return this.current; } - subscribe(listener: (raw: Record) => void): string { + subscribe(listener: (snap: SmbTaskState) => void): string { const id = `sub-${this.nextId++}`; this.listeners.set(id, listener); return id; @@ -117,7 +116,7 @@ class FakeNativeListTask implements NativeSmbListTask { } } - emit(next: Record): void { + emit(next: SmbTaskState): void { this.current = next; for (const listener of this.listeners.values()) listener(next); } @@ -266,7 +265,7 @@ describe('SmbListTask completion', () => { it('wait() rejects with the task error', async () => { const native = new FakeNativeListTask( - snapshot(TaskStatus.Error, { errorCode: String(SmbError.AccessDenied), errorMessage: 'denied' }), + snapshot(TaskStatus.Error, { errorCode: SmbError.AccessDenied, errorMessage: 'denied' }), ); await expect(new SmbListTask('task-1', native).wait()).rejects.toMatchObject({ diff --git a/tests/TransferStore.test.ts b/tests/TransferStore.test.ts index 08e3d88..e949108 100644 --- a/tests/TransferStore.test.ts +++ b/tests/TransferStore.test.ts @@ -2,27 +2,24 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { ReactNativeSmb } from '../src/ReactNativeSmb'; import { TransferStore } from '../src/core/TransferStore'; -import { SmbOperatorKind, TaskStatus } from '../src/types'; +import { SmbOperatorKind, TaskStatus, type SmbTaskState } from '../src/types'; +import { makeTaskSnapshot } from './helpers/taskSnapshot'; -function snapshot(taskId: string, status: TaskStatus, updatedAt = 1): Record { - return { - exists: '1', +function snapshot(taskId: string, status: TaskStatus, updatedAt = 1): SmbTaskState { + return makeTaskSnapshot(status, { taskId, - kind: String(SmbOperatorKind.DownloadFile), - status: String(status), - determinate: 'true', - progress: status === TaskStatus.Success ? '1' : '0.5', - updatedAt: String(updatedAt), - }; + kind: SmbOperatorKind.DownloadFile, + updatedAt, + }); } class FakeNative { - transfers: Record[] = []; - readonly listeners = new Map) => void>(); + transfers: SmbTaskState[] = []; + readonly listeners = new Map void>(); readonly unsubscribed: string[] = []; throwOnTransfers = false; - subscribeTaskEvents(listener: (raw: Record) => void): string { + subscribeTaskEvents(listener: (snap: SmbTaskState) => void): string { const id = `sub-${this.listeners.size + 1}`; this.listeners.set(id, listener); return id; @@ -33,13 +30,13 @@ class FakeNative { this.listeners.delete(id); } - getTransferTasks(): Record[] { + getTransferTasks(): SmbTaskState[] { if (this.throwOnTransfers) throw new Error('transfer task query failed'); return this.transfers; } - emit(raw: Record): void { - for (const listener of this.listeners.values()) listener(raw); + emit(snap: SmbTaskState): void { + for (const listener of this.listeners.values()) listener(snap); } } diff --git a/tests/helpers/taskSnapshot.ts b/tests/helpers/taskSnapshot.ts new file mode 100644 index 0000000..7c96825 --- /dev/null +++ b/tests/helpers/taskSnapshot.ts @@ -0,0 +1,30 @@ +import { + SmbOperatorKind, + TaskStatus, + type SmbTaskState, +} from '../../src/types'; + +export function makeTaskSnapshot( + status: TaskStatus, + overrides: Partial = {}, +): SmbTaskState { + return { + taskId: 'task-1', + kind: SmbOperatorKind.DownloadFile, + status, + determinate: true, + progress: status === TaskStatus.Success ? 1 : 0.5, + bytesDone: 0, + totalBytes: 0, + bytesPerSecond: 0, + etaSeconds: 0, + sourcePath: '', + destinationPath: '', + errorCode: 0, + errorMessage: '', + startedAt: 0, + updatedAt: 1, + endedAt: 0, + ...overrides, + }; +} diff --git a/tests/taskResult.test.ts b/tests/taskResult.test.ts index fe1a651..d799a5b 100644 --- a/tests/taskResult.test.ts +++ b/tests/taskResult.test.ts @@ -1,42 +1,31 @@ import { describe, expect, it } from 'vitest'; import { SmbTask } from '../src/core/SmbTask'; -import { SmbError, SmbTaskError, SmbOperatorKind, TaskStatus, type NativeSmbTask } from '../src/types'; - -function snapshot(status: TaskStatus, overrides: Record = {}): Record { - return { - exists: '1', - taskId: 'task-1', - kind: String(SmbOperatorKind.DownloadFile), - status: String(status), - determinate: 'true', - progress: status === TaskStatus.Success ? '1' : '0.5', - ...overrides, - }; -} +import { SmbError, SmbTaskError, TaskStatus, type NativeSmbTask, type SmbTaskState } from '../src/types'; +import { makeTaskSnapshot } from './helpers/taskSnapshot'; class FakeNativeTask implements NativeSmbTask { - current: Record; - readonly listeners = new Map) => void>(); + current: SmbTaskState; + readonly listeners = new Map void>(); readonly unsubscribed: string[] = []; result: unknown = 'result'; resultError?: Error; unsubscribeError?: Error; - onSubscribe?: (listener: (raw: Record) => void) => void; + onSubscribe?: (listener: (snap: SmbTaskState) => void) => void; getError?: Error; - constructor(current: Record) { + constructor(current: SmbTaskState) { this.current = current; } cancel(): void {} - get(): Record { + get(): SmbTaskState { if (this.getError) throw this.getError; return this.current; } - subscribe(listener: (raw: Record) => void): string { + subscribe(listener: (snap: SmbTaskState) => void): string { const id = `sub-${this.listeners.size + 1}`; this.listeners.set(id, listener); this.onSubscribe?.(listener); @@ -54,7 +43,7 @@ class FakeNativeTask implements NativeSmbTask { return this.result; } - emit(next: Record): void { + emit(next: SmbTaskState): void { this.current = next; for (const listener of this.listeners.values()) listener(next); } @@ -62,13 +51,15 @@ class FakeNativeTask implements NativeSmbTask { describe('SmbTask.result', () => { it('settles terminal states read before subscribing without a listener', async () => { - const success = new FakeNativeTask(snapshot(TaskStatus.Success)); + const success = new FakeNativeTask(makeTaskSnapshot(TaskStatus.Success)); await expect(new SmbTask('task-1', success).result()).resolves.toBe('result'); expect(success.listeners.size).toBe(0); for (const status of [TaskStatus.Error, TaskStatus.Cancelled]) { const native = new FakeNativeTask( - snapshot(status, { errorCode: String(status === TaskStatus.Cancelled ? SmbError.Cancelled : SmbError.Unknown) }), + makeTaskSnapshot(status, { + errorCode: status === TaskStatus.Cancelled ? SmbError.Cancelled : SmbError.Unknown, + }), ); await expect(new SmbTask('task-1', native).result()).rejects.toMatchObject({ code: status === TaskStatus.Cancelled ? SmbError.Cancelled : SmbError.Unknown, @@ -78,9 +69,9 @@ describe('SmbTask.result', () => { }); it('cleans up when subscription synchronously reports completion', async () => { - const native = new FakeNativeTask(snapshot(TaskStatus.Running)); + const native = new FakeNativeTask(makeTaskSnapshot(TaskStatus.Running)); native.onSubscribe = (listener) => { - native.current = snapshot(TaskStatus.Success); + native.current = makeTaskSnapshot(TaskStatus.Success); listener(native.current); }; @@ -89,26 +80,26 @@ describe('SmbTask.result', () => { }); it('settles only once when terminal events are repeated', async () => { - const native = new FakeNativeTask(snapshot(TaskStatus.Running)); + const native = new FakeNativeTask(makeTaskSnapshot(TaskStatus.Running)); const task = new SmbTask('task-1', native); const result = task.result(); - native.emit(snapshot(TaskStatus.Success)); - native.emit(snapshot(TaskStatus.Error)); + native.emit(makeTaskSnapshot(TaskStatus.Success)); + native.emit(makeTaskSnapshot(TaskStatus.Error)); await expect(result).resolves.toBe('result'); expect(native.unsubscribed).toEqual(['sub-1']); }); it('delivers terminal state to every active subscriber', async () => { - const native = new FakeNativeTask(snapshot(TaskStatus.Running)); + const native = new FakeNativeTask(makeTaskSnapshot(TaskStatus.Running)); const task = new SmbTask('task-1', native); const observed: TaskStatus[] = []; const unsubscribe = task.subscribe((snap) => observed.push(snap.status)); const result = task.result(); - native.emit(snapshot(TaskStatus.Success)); - native.emit(snapshot(TaskStatus.Error)); + native.emit(makeTaskSnapshot(TaskStatus.Success)); + native.emit(makeTaskSnapshot(TaskStatus.Error)); await expect(result).resolves.toBe('result'); expect(observed).toEqual([TaskStatus.Running, TaskStatus.Success]); @@ -119,29 +110,29 @@ describe('SmbTask.result', () => { }); it('rejects and cleans up when result conversion fails', async () => { - const native = new FakeNativeTask(snapshot(TaskStatus.Running)); + const native = new FakeNativeTask(makeTaskSnapshot(TaskStatus.Running)); native.resultError = new Error('result conversion failed'); const result = new SmbTask('task-1', native).result(); - native.emit(snapshot(TaskStatus.Success)); + native.emit(makeTaskSnapshot(TaskStatus.Success)); await expect(result).rejects.toThrow('result conversion failed'); expect(native.unsubscribed).toEqual(['sub-1']); }); it('settles even when native unsubscription fails', async () => { - const native = new FakeNativeTask(snapshot(TaskStatus.Running)); + const native = new FakeNativeTask(makeTaskSnapshot(TaskStatus.Running)); native.unsubscribeError = new Error('unsubscribe failed'); const result = new SmbTask('task-1', native).result(); - native.emit(snapshot(TaskStatus.Success)); + native.emit(makeTaskSnapshot(TaskStatus.Success)); await expect(result).resolves.toBe('result'); expect(native.unsubscribed).toEqual(['sub-1']); }); it('rejects when native subscription fails', async () => { - const native = new FakeNativeTask(snapshot(TaskStatus.Running)); + const native = new FakeNativeTask(makeTaskSnapshot(TaskStatus.Running)); native.subscribe = () => { throw new Error('subscription failed'); }; @@ -150,7 +141,7 @@ describe('SmbTask.result', () => { }); it('unsubscribes when initial snapshot reading fails after subscription', () => { - const native = new FakeNativeTask(snapshot(TaskStatus.Running)); + const native = new FakeNativeTask(makeTaskSnapshot(TaskStatus.Running)); native.getError = new Error('bridge failure'); const task = new SmbTask('task-1', native); @@ -159,13 +150,13 @@ describe('SmbTask.result', () => { }); it('does not regress a cached terminal snapshot', () => { - const native = new FakeNativeTask(snapshot(TaskStatus.Running, { updatedAt: '1' })); + const native = new FakeNativeTask(makeTaskSnapshot(TaskStatus.Running, { updatedAt: 1 })); const task = new SmbTask('task-1', native); const observed: TaskStatus[] = []; task.subscribe((snap) => observed.push(snap.status)); - native.emit(snapshot(TaskStatus.Success, { updatedAt: '3' })); - native.emit(snapshot(TaskStatus.Running, { updatedAt: '2' })); + native.emit(makeTaskSnapshot(TaskStatus.Success, { updatedAt: 3 })); + native.emit(makeTaskSnapshot(TaskStatus.Running, { updatedAt: 2 })); expect(task.getSnapshot()?.status).toBe(TaskStatus.Success); expect(observed.at(-1)).toBe(TaskStatus.Success);