diff --git a/cocos/rendering/legacy/index.jsb.ts b/cocos/rendering/legacy/index.jsb.ts index bcd517a770..5419a9ad77 100644 --- a/cocos/rendering/legacy/index.jsb.ts +++ b/cocos/rendering/legacy/index.jsb.ts @@ -53,7 +53,9 @@ import { RenderTexture } from '../../asset/assets/render-texture'; export function createDefaultPipeline (): ForwardPipeline { const rppl = new ForwardPipeline(); - rppl.initialize({ flows: [] }); + if (!window.oh) { + rppl.initialize({ flows: [] }); + } return rppl; } export const ForwardPipeline: typeof NrForwardPipeline = nr.ForwardPipeline; diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index d01596560b..7449558b3c 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -16,6 +16,9 @@ cc_set_if_undefined(CC_DEBUG_FORCE OFF) cc_set_if_undefined(USE_SE_V8 ON) cc_set_if_undefined(USE_SE_SM OFF) cc_set_if_undefined(USE_SE_NAPI OFF) +if(OPENHARMONY) + cc_set_if_undefined(USE_SE_JSVM OFF) +endif() cc_set_if_undefined(USE_V8_DEBUGGER ON) cc_set_if_undefined(USE_V8_DEBUGGER_FORCE OFF) cc_set_if_undefined(USE_SOCKET ON) @@ -344,21 +347,32 @@ NO_WERROR cocos/audio/common/utils/primitives.cpp cocos/audio/android/OpenSLHelper.h cocos/audio/android/PcmAudioPlayer.cpp cocos/audio/android/PcmAudioPlayer.h - cocos/audio/android/PcmAudioService.cpp - cocos/audio/android/PcmAudioService.h cocos/audio/android/PcmBufferProvider.cpp cocos/audio/android/PcmBufferProvider.h cocos/audio/android/PcmData.cpp cocos/audio/android/PcmData.h cocos/audio/android/Track.cpp cocos/audio/android/Track.h - cocos/audio/android/UrlAudioPlayer.cpp - cocos/audio/android/UrlAudioPlayer.h cocos/audio/android/utils/Compat.h cocos/audio/android/utils/Errors.h cocos/audio/android/utils/Utils.cpp cocos/audio/android/utils/Utils.h ) + if(ANDROID) + cocos_source_files( + cocos/audio/android/PcmAudioService.cpp + cocos/audio/android/PcmAudioService.h + cocos/audio/android/UrlAudioPlayer.cpp + cocos/audio/android/UrlAudioPlayer.h + ) + elseif(OPENHARMONY) + cocos_source_files( + cocos/audio/openharmony/PcmAudioService.cpp + cocos/audio/openharmony/PcmAudioService.h + cocos/audio/openharmony/UrlAudioPlayer.cpp + cocos/audio/openharmony/UrlAudioPlayer.h + ) + endif() elseif(OHOS) cocos_source_files( cocos/audio/common/utils/tinysndfile.cpp @@ -558,7 +572,9 @@ elseif(OPENHARMONY) cocos_source_files( cocos/platform/openharmony/napi/NapiHelper.cpp cocos/platform/openharmony/napi/NapiHelper.h - + cocos/platform/openharmony/napi/NapiValueConverter.cpp + cocos/platform/openharmony/napi/NapiValueConverter.h + cocos/platform/openharmony/napi/native_common.h cocos/platform/openharmony/WorkerMessageQueue.cpp cocos/platform/openharmony/WorkerMessageQueue.h cocos/platform/openharmony/OpenHarmonyPlatform.cpp @@ -2576,6 +2592,8 @@ if(ANDROID) elseif(OPENHARMONY) cocos_source_files( cocos/bindings/manual/jsb_platform_openharmony.cpp + cocos/bindings/manual/JavaScriptArkTsBridge.cpp + cocos/bindings/manual/JavaScriptArkTsBridge.h ) elseif(OHOS) cocos_source_files( @@ -2696,6 +2714,25 @@ if(USE_SE_NAPI) ) endif() + + +if(OPENHARMONY AND USE_SE_JSVM) + cocos_source_files(MODULE ccbindings + cocos/bindings/jswrapper/jsvm/Class.cpp + cocos/bindings/jswrapper/jsvm/Class.h + cocos/bindings/jswrapper/jsvm/HelperMacros.cpp + cocos/bindings/jswrapper/jsvm/HelperMacros.h + cocos/bindings/jswrapper/jsvm/Object.cpp + cocos/bindings/jswrapper/jsvm/Object.h + cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp + cocos/bindings/jswrapper/jsvm/ScriptEngine.h + cocos/bindings/jswrapper/jsvm/SeApi.h + cocos/bindings/jswrapper/jsvm/Utils.cpp + cocos/bindings/jswrapper/jsvm/Utils.h + cocos/bindings/jswrapper/jsvm/CommonHeader.h + ) +endif() + cocos_source_files(MODULE ccbindings cocos/bindings/jswrapper/config.h cocos/bindings/jswrapper/config.cpp @@ -3075,6 +3112,7 @@ function(cc_apply_definations target) $<$:SCRIPT_ENGINE_TYPE=1> $<$:SCRIPT_ENGINE_TYPE=2> $<$:SCRIPT_ENGINE_TYPE=5> + $<$:SCRIPT_ENGINE_TYPE=6> $<$,$>:CC_DEBUG=1> ) endfunction() @@ -3268,14 +3306,55 @@ if(OPENHARMONY) find_library( hilog-lib hilog_ndk.z ) - - find_library( libace-lib - libace_ndk.z ) - - target_link_libraries(${ENGINE_NAME} PUBLIC - ${EGL-lib} ${GLESv3-lib} ${hilog-lib} libace_napi.z.so libace_ndk.z.so libz.so libuv.so libnative_drawing.so librawfile.z.so libOpenSLES.so + + find_library( # Sets the name of the path variable. + libace-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + ace_ndk.z ) + find_library( # Sets the name of the path variable. + libnapi-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + ace_napi.z ) + find_library( # Sets the name of the path variable. + libuv-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + uv ) + find_library( # Sets the name of the path variable. + rawfile-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + rawfile.z ) + set(LIBS + ${EGL-lib} + ${GLESv3-lib} + ${hilog-lib} + ${libace-lib} + ${libnapi-lib} + ${libuv-lib} + ${rawfile-lib} + libnative_drawing.so + libc++.a + libOpenSLES.so + libohaudio.so + libavplayer.so + libnative_window.so + libnative_buffer.so + libbundle_ndk.z.so + libace_napi.z.so + libace_ndk.z.so + libz.so + librawfile.z.so ${CC_EXTERNAL_LIBS} ) + if(USE_SE_JSVM) + list(APPEND LIBS libjsvm.so) + endif() + + target_link_libraries(${ENGINE_NAME} PUBLIC ${LIBS}) + endif() if(APPLE) diff --git a/native/cocos/audio/android/AudioEngine-inl.cpp b/native/cocos/audio/android/AudioEngine-inl.cpp index c19fb545ce..2a2d8b27bd 100644 --- a/native/cocos/audio/android/AudioEngine-inl.cpp +++ b/native/cocos/audio/android/AudioEngine-inl.cpp @@ -69,10 +69,6 @@ AudioEngineImpl *gAudioImpl = nullptr; int outputSampleRate = 44100; #if CC_PLATFORM == CC_PLATFORM_ANDROID int bufferSizeInFrames = 192; -#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY -// TODO(hack) : There is currently a bug in the opensles module, -// so openharmony must configure a fixed size, otherwise the callback will be suspended -int bufferSizeInFrames = 2048; #endif void getAudioInfo() { @@ -129,7 +125,7 @@ static int fdGetter(const ccstd::string &url, off_t *start, off_t *length) { #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY FileUtilsOpenHarmony* fileUtils = dynamic_cast(FileUtils::getInstance()); if(fileUtils) { - RawFileDescriptor descriptor; + RawFileDescriptor64 descriptor; fileUtils->getRawFileDescriptor(url, descriptor); fd = descriptor.fd; } @@ -193,25 +189,27 @@ bool AudioEngineImpl::init() { CC_LOG_ERROR("get the engine interface fail"); break; } + #if CC_PLATFORM == CC_PLATFORM_ANDROID + // create output mix + const SLInterfaceID outputMixIIDs[] = {}; + const SLboolean outputMixReqs[] = {}; + result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs); + if (SL_RESULT_SUCCESS != result) { + CC_LOG_ERROR("create output mix fail"); + break; + } - // create output mix - const SLInterfaceID outputMixIIDs[] = {}; - const SLboolean outputMixReqs[] = {}; - result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs); - if (SL_RESULT_SUCCESS != result) { - CC_LOG_ERROR("create output mix fail"); - break; - } - - // realize the output mix - result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE); - if (SL_RESULT_SUCCESS != result) { - CC_LOG_ERROR("realize the output mix fail"); - break; - } - - _audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils); + // realize the output mix + result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE); + if (SL_RESULT_SUCCESS != result) { + CC_LOG_ERROR("realize the output mix fail"); + break; + } + _audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils); + #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + _audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, outputSampleRate, fdGetter, &gCallerThreadUtils); + #endif ret = true; } while (false); @@ -229,9 +227,14 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu auto audioId = AudioEngine::INVALID_AUDIO_ID; do { - if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) { - break; - } + #if CC_PLATFORM == CC_PLATFORM_ANDROID + if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) { + break; + } + #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + if (_audioPlayerProvider == nullptr) + break; + #endif auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); @@ -434,9 +437,12 @@ PCMHeader AudioEngineImpl::getPCMHeader(const char *url) { CC_LOG_DEBUG("file %s pcm data already cached", url); return header; } - + #if CC_PLATFORM == CC_PLATFORM_ANDROID AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter); - + #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder( + _engineEngine, fileFullPath, _audioPlayerProvider->getBufferSizeInFrames(), outputSampleRate, fdGetter); + #endif if (decoder == nullptr) { CC_LOG_DEBUG("decode %s failed, the file formate might not support", url); return header; @@ -470,7 +476,12 @@ ccstd::vector AudioEngineImpl::getOriginalPCMBuffer(const char *url, ui if (_audioPlayerProvider->getPcmData(url, data)) { CC_LOG_DEBUG("file %s pcm data already cached", url); } else { + #if CC_PLATFORM == CC_PLATFORM_ANDROID AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter); + #else + AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder( + _engineEngine, fileFullPath, _audioPlayerProvider->getBufferSizeInFrames(), outputSampleRate, fdGetter); + #endif if (decoder == nullptr) { CC_LOG_DEBUG("decode %s failed, the file formate might not support", url); return pcmData; diff --git a/native/cocos/audio/android/AudioMixer.cpp b/native/cocos/audio/android/AudioMixer.cpp index b4d888f7a8..675ddac664 100644 --- a/native/cocos/audio/android/AudioMixer.cpp +++ b/native/cocos/audio/android/AudioMixer.cpp @@ -145,6 +145,10 @@ static inline audio_format_t selectMixerInFormat(audio_format_t inputFormat __un return kUseFloat && kUseNewMixer ? AUDIO_FORMAT_PCM_FLOAT : AUDIO_FORMAT_PCM_16_BIT; } +void AudioMixer::setBufferSize(size_t size) { + mState.frameCount = size; +} + int AudioMixer::getTrackName(audio_channel_mask_t channelMask, audio_format_t format, int sessionId) { if (!isValidPcmTrackFormat(format)) { diff --git a/native/cocos/audio/android/AudioMixer.h b/native/cocos/audio/android/AudioMixer.h index 729c1db2ef..bb56df3c0f 100644 --- a/native/cocos/audio/android/AudioMixer.h +++ b/native/cocos/audio/android/AudioMixer.h @@ -119,6 +119,7 @@ public: void setParameter(int name, int target, int param, void *value); void setBufferProvider(int name, AudioBufferProvider *bufferProvider); + void setBufferSize(size_t size); void process(int64_t pts); uint32_t trackNames() const { return mTrackNames; } diff --git a/native/cocos/audio/android/AudioMixerController.cpp b/native/cocos/audio/android/AudioMixerController.cpp index 31aec82d13..b16783d606 100644 --- a/native/cocos/audio/android/AudioMixerController.cpp +++ b/native/cocos/audio/android/AudioMixerController.cpp @@ -33,17 +33,25 @@ #include "base/memory/Memory.h" namespace cc { - +#if CC_PLATFORM == CC_PLATFORM_ANDROID AudioMixerController::AudioMixerController(int bufferSizeInFrames, int sampleRate, int channelCount) : _bufferSizeInFrames(bufferSizeInFrames), _sampleRate(sampleRate), _channelCount(channelCount), _mixer(nullptr), _isPaused(false), _isMixingFrame(false) { ALOGV("In the constructor of AudioMixerController!"); - - _mixingBuffer.size = (size_t)bufferSizeInFrames * 2 * channelCount; + // NOLINTNEXTLINE(bugprone-misplaced-widening-cast) + _mixingBuffer.size = static_cast(bufferSizeInFrames * 2 * channelCount); // Don't use posix_memalign since it was added from API 16, it will crash on Android 2.3 // Therefore, for a workaround, we uses memalign here. _mixingBuffer.buf = memalign(32, _mixingBuffer.size); memset(_mixingBuffer.buf, 0, _mixingBuffer.size); } +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +AudioMixerController::AudioMixerController(int sampleRate, int channelCount) +: _sampleRate(sampleRate), _channelCount(channelCount), _mixer(nullptr), _isPaused(false), _isMixingFrame(false) { + ALOGV("In the constructor of AudioMixerController!"); + int32_t maxBufferLength = MAX_AUDIO_BUFFER_SIZE * channelCount * 2; + _mixingBuffer.buf = memalign(32, maxBufferLength); +} +#endif AudioMixerController::~AudioMixerController() { destroy(); @@ -56,11 +64,31 @@ AudioMixerController::~AudioMixerController() { free(_mixingBuffer.buf); } +#if CC_PLATFORM == CC_PLATFORM_ANDROID bool AudioMixerController::init() { _mixer = ccnew AudioMixer(_bufferSizeInFrames, _sampleRate); return _mixer != nullptr; } +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +void AudioMixerController::updateBufferSize(int bufferSize) { + _mixer->setBufferSize(bufferSize / _channelCount / 2); + _mixingBuffer.size = bufferSize; + + uint32_t channelMask = audio_channel_out_mask_from_count(_channelCount); + int32_t name = _mixer->getTrackName(channelMask, AUDIO_FORMAT_PCM_16_BIT, AUDIO_SESSION_OUTPUT_MIX); + _mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER, + _mixingBuffer.buf); +} + +bool AudioMixerController::init(int bufferSizeInFrames) { + _mixingBuffer.size = static_cast(bufferSizeInFrames * 2 * _channelCount); + memset(_mixingBuffer.buf, 0, _mixingBuffer.size); + _bufferSizeInFrames = bufferSizeInFrames; + _mixer = ccnew AudioMixer(_bufferSizeInFrames, _sampleRate); + return _mixer != nullptr; +} +#endif bool AudioMixerController::addTrack(Track *track) { ALOG_ASSERT(track != nullptr, "Shouldn't pass nullptr to addTrack"); bool ret = false; @@ -85,8 +113,9 @@ static void removeItemFromVector(ccstd::vector &v, T item) { } void AudioMixerController::initTrack(Track *track, ccstd::vector &tracksToRemove) { - if (track->isInitialized()) + if (track->isInitialized()) { return; + } uint32_t channelMask = audio_channel_out_mask_from_count(2); int32_t name = _mixer->getTrackName(channelMask, AUDIO_FORMAT_PCM_16_BIT, @@ -103,22 +132,22 @@ void AudioMixerController::initTrack(Track *track, ccstd::vector &track name, AudioMixer::TRACK, AudioMixer::MIXER_FORMAT, - (void *)(uintptr_t)AUDIO_FORMAT_PCM_16_BIT); + reinterpret_cast(static_cast(AUDIO_FORMAT_PCM_16_BIT))); _mixer->setParameter( name, AudioMixer::TRACK, AudioMixer::FORMAT, - (void *)(uintptr_t)AUDIO_FORMAT_PCM_16_BIT); + reinterpret_cast(static_cast(AUDIO_FORMAT_PCM_16_BIT))); _mixer->setParameter( name, AudioMixer::TRACK, AudioMixer::MIXER_CHANNEL_MASK, - (void *)(uintptr_t)channelMask); + reinterpret_cast(static_cast(channelMask))); _mixer->setParameter( name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK, - (void *)(uintptr_t)channelMask); + reinterpret_cast(static_cast(channelMask))); track->setName(name); _mixer->enable(name); @@ -258,7 +287,7 @@ void AudioMixerController::mixOneFrame() { auto mixEnd = clockNow(); float mixInterval = intervalInMS(mixStart, mixEnd); - ALOGV_IF(mixInterval > 1.0f, "Mix a frame waste: %fms", mixInterval); + ALOGV_IF(mixInterval > 1.0F, "Mix a frame waste: %fms", mixInterval); _isMixingFrame = false; } @@ -280,17 +309,16 @@ void AudioMixerController::resume() { bool AudioMixerController::hasPlayingTacks() { std::lock_guard lk(_activeTracksMutex); - if (_activeTracks.empty()) + if (_activeTracks.empty()) { return false; - - for (auto &&track : _activeTracks) { - Track::State state = track->getState(); - if (state == Track::State::IDLE || state == Track::State::PLAYING || state == Track::State::RESUMED) { - return true; - } } - return false; + bool result = std::any_of(_activeTracks.begin(), _activeTracks.end(), [](Track *track) { + Track::State state = track->getState(); + return state == Track::State::IDLE || state == Track::State::PLAYING || state == Track::State::RESUMED; + }); + + return result; } } // namespace cc diff --git a/native/cocos/audio/android/AudioMixerController.h b/native/cocos/audio/android/AudioMixerController.h index 534e61f6e2..b9690a92ba 100644 --- a/native/cocos/audio/android/AudioMixerController.h +++ b/native/cocos/audio/android/AudioMixerController.h @@ -32,6 +32,11 @@ #include "audio/android/utils/Errors.h" #include "base/std/container/vector.h" +#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY +// for openharmony platform, buffer size is 4458 in normal latency mode, 240 in fast latency mode +#define MAX_AUDIO_BUFFER_SIZE 4458 +#endif + namespace cc { class Track; @@ -43,13 +48,17 @@ public: void *buf; size_t size; }; - +#if CC_PLATFORM == CC_PLATFORM_ANDROID AudioMixerController(int bufferSizeInFrames, int sampleRate, int channelCount); + bool init(); +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + AudioMixerController(int sampleRate, int channelCount); + void updateBufferSize(int bufferSize); + bool init(int bufferSizeInFrames); +#endif ~AudioMixerController(); - bool init(); - bool addTrack(Track *track); bool hasPlayingTacks(); @@ -65,7 +74,6 @@ private: void destroy(); void initTrack(Track *track, ccstd::vector &tracksToRemove); -private: int _bufferSizeInFrames; int _sampleRate; int _channelCount; diff --git a/native/cocos/audio/android/AudioPlayerProvider.cpp b/native/cocos/audio/android/AudioPlayerProvider.cpp index 7817bfde3b..1e929ca031 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.cpp +++ b/native/cocos/audio/android/AudioPlayerProvider.cpp @@ -38,16 +38,18 @@ #include "audio/android/AudioPlayerProvider.h" #include "audio/android/ICallerThreadUtils.h" #include "audio/android/PcmAudioPlayer.h" -#include "audio/android/PcmAudioService.h" -#include "audio/android/UrlAudioPlayer.h" #include "audio/android/utils/Utils.h" #include "base/ThreadPool.h" #include "base/memory/Memory.h" #if CC_PLATFORM == CC_PLATFORM_ANDROID #include +#include "audio/android/UrlAudioPlayer.h" +#include "audio/android/PcmAudioService.h" #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY #include "cocos/platform/FileUtils.h" #include "cocos/platform/openharmony/FileUtils-OpenHarmony.h" +#include "audio/openharmony/UrlAudioPlayer.h" +#include "audio/openharmony/PcmAudioService.h" #endif #include // for std::find_if #include @@ -87,6 +89,7 @@ static AudioFileIndicator gAudioFileIndicator[] = { {".ogg", 128000}, {".mp3", 160000}}; +#if CC_PLATFORM == CC_PLATFORM_ANDROID AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outputMixObject, int deviceSampleRate, int bufferSizeInFrames, const FdGetterCallback &fdGetterCallback, //NOLINT(modernize-pass-by-value) @@ -102,6 +105,21 @@ AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outp ALOG_ASSERT(callerThreadUtils != nullptr, "Caller thread utils parameter should not be nullptr!"); } +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, int deviceSampleRate, + const FdGetterCallback &fdGetterCallback, + ICallerThreadUtils *callerThreadUtils) + : _engineItf(engineItf), _deviceSampleRate(deviceSampleRate), _fdGetterCallback(fdGetterCallback), + _callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr), + _mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2)) +{ + _mixController = ccnew AudioMixerController(_deviceSampleRate, 2); + _pcmAudioService = ccnew PcmAudioService(); + _pcmAudioService->init(_mixController, 2, deviceSampleRate, &_bufferSizeInFrames); + _mixController->init(_bufferSizeInFrames); + ALOG_ASSERT(callerThreadUtils != nullptr, "Caller thread utils parameter should not be nullptr!"); +} +#endif AudioPlayerProvider::~AudioPlayerProvider() { ALOGV("~AudioPlayerProvider()"); @@ -324,8 +342,8 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( off_t start = 0; off_t length = 0; int assetFd = -1; -#if CC_PLATFORM == CC_PLATFORM_ANDROID if (audioFilePath[0] != '/') { +#if CC_PLATFORM == CC_PLATFORM_ANDROID ccstd::string relativePath; size_t position = audioFilePath.find("@assets/"); @@ -344,6 +362,22 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( } fileSize = length; +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + RawFileDescriptor64 descriptor; + FileUtilsOpenHarmony* fileUtils = static_cast(FileUtils::getInstance()); + if(!fileUtils) { + return info; + } + FileUtils::Status status = fileUtils->getRawFileDescriptor(audioFilePath, descriptor); + + if(status != FileUtils::Status::OK || descriptor.fd<= 0) { + ALOGE("Failed to open file descriptor for %s", audioFilePath.c_str()); + return info; + } + assetFd = descriptor.fd; + start = descriptor.start; + fileSize = descriptor.length; +#endif } else { FILE *fp = fopen(audioFilePath.c_str(), "rb"); if (fp != nullptr) { @@ -358,32 +392,19 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( info.assetFd = std::make_shared(assetFd); info.start = start; info.length = fileSize; -#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - FileUtilsOpenHarmony* fileUtils = dynamic_cast(FileUtils::getInstance()); - if(!fileUtils) { - return info; - } - - RawFileDescriptor descriptor; - fileUtils->getRawFileDescriptor(audioFilePath, descriptor); - info.url = audioFilePath; - info.assetFd = std::make_shared(descriptor.fd); - info.start = descriptor.start; - info.length = descriptor.length; -#endif - ALOGV("(%s) file size: %ld", audioFilePath.c_str(), fileSize); - return info; } bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(readability-convert-member-functions-to-static) -#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY - // TODO(qgh): OpenHarmony system does not support this function yet - return true; -#endif //REFINE: If file size is smaller than 100k, we think it's a small file. This value should be set by developers. auto &audioFileInfo = const_cast(info); + #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY + if(audioFileInfo.url[0] == '/') { + // avplayer does not support playing audio files in sandbox path currently. + return true; + } + #endif size_t judgeCount = sizeof(gAudioFileIndicator) / sizeof(gAudioFileIndicator[0]); size_t pos = audioFileInfo.url.rfind('.'); ccstd::string extension; @@ -451,15 +472,22 @@ UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer( } #if CC_PLATFORM == CC_PLATFORM_ANDROID SLuint32 locatorType = info.assetFd->getFd() > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI; -#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - SLuint32 locatorType = SL_DATALOCATOR_URI; -#endif - auto *urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils); bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length); if (!ret) { SL_SAFE_DELETE(urlPlayer); } +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + auto urlPlayer = new (std::nothrow) UrlAudioPlayer(_callerThreadUtils); + bool ret = urlPlayer->prepare(info.url, info.assetFd, info.start, info.length); + if (!ret) + { + if (urlPlayer != nullptr) { + delete urlPlayer; + urlPlayer = nullptr; + } + } +#endif return urlPlayer; } diff --git a/native/cocos/audio/android/AudioPlayerProvider.h b/native/cocos/audio/android/AudioPlayerProvider.h index 6b42cc1660..8e850a8731 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.h +++ b/native/cocos/audio/android/AudioPlayerProvider.h @@ -46,9 +46,17 @@ class LegacyThreadPool; class AudioPlayerProvider { public: +#if CC_PLATFORM == CC_PLATFORM_ANDROID AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outputMixObject, int deviceSampleRate, int bufferSizeInFrames, const FdGetterCallback &fdGetterCallback, ICallerThreadUtils *callerThreadUtils); +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + AudioPlayerProvider(SLEngineItf engineItf, int deviceSampleRate, + const FdGetterCallback &fdGetterCallback, ICallerThreadUtils *callerThreadUtils); + int getBufferSizeInFrames() const { + return _bufferSizeInFrames; + } +#endif virtual ~AudioPlayerProvider(); bool isFileCached(const ccstd::string &audioFilePath); diff --git a/native/cocos/audio/android/cutils/log.h b/native/cocos/audio/android/cutils/log.h index 22eacb3bd1..fa32d12feb 100644 --- a/native/cocos/audio/android/cutils/log.h +++ b/native/cocos/audio/android/cutils/log.h @@ -36,8 +36,8 @@ #if CC_PLATFORM == CC_PLATFORM_ANDROID #include #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY -// TODO(qgh):May be implemented in later versions -// #include +#include +#define LOG_VERBOSE LOG_INFO #endif #ifdef __cplusplus @@ -90,7 +90,11 @@ extern "C" { * Simplified macro to send a verbose log message using the current LOG_TAG. */ #ifndef ALOGV - #define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) +#if CC_PLATFORM == CC_PLATFORM_ANDROID + #define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + #define __ALOGV(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) +#endif #if LOG_NDEBUG #define ALOGV(...) \ do { \ @@ -415,7 +419,7 @@ extern "C" { ? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \ : (void)0) #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - #define LOG_ALWAYS_FATAL_IF(cond, ...) + #define LOG_ALWAYS_FATAL_IF(cond, ...) ((void)0 ) #endif #endif @@ -424,7 +428,7 @@ extern "C" { #define LOG_ALWAYS_FATAL(...) \ (((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__))) #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - #define LOG_ALWAYS_FATAL(...) + #define LOG_ALWAYS_FATAL(...) ((void) OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) #endif #endif @@ -472,9 +476,15 @@ extern "C" { * The second argument may be NULL or "" to indicate the "global" tag. */ #ifndef ALOG - #define ALOG(priority, tag, ...) \ +#if CC_PLATFORM == CC_PLATFORM_ANDROID +#define ALOG(priority, tag, ...) \ LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__) +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +#define ALOG(priority, tag, ...) \ + LOG_PRI(priority, tag, __VA_ARGS__) #endif +#endif + /* * Log macro that allows you to specify a number for the priority. @@ -484,7 +494,7 @@ extern "C" { #define LOG_PRI(priority, tag, ...) \ android_printLog(priority, tag, __VA_ARGS__) #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - #define LOG_PRI(priority, tag, ...) ((void)0) + #define LOG_PRI(priority, tag, ...) ((void) OH_LOG_Print(LOG_APP, priority, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) #endif #endif diff --git a/native/cocos/audio/openharmony/PcmAudioService.cpp b/native/cocos/audio/openharmony/PcmAudioService.cpp new file mode 100644 index 0000000000..3844eb717f --- /dev/null +++ b/native/cocos/audio/openharmony/PcmAudioService.cpp @@ -0,0 +1,152 @@ +/**************************************************************************** +Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#define LOG_TAG "PcmAudioService" + +#include "audio/openharmony/PcmAudioService.h" +#include "audio/android/AudioMixerController.h" +#include "audio/android/cutils/log.h" +#include "audio/android/utils/Compat.h" +namespace cc { + +static ccstd::vector __silenceData;//NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + +PcmAudioService::PcmAudioService() +: _controller(nullptr) { +} + +PcmAudioService::~PcmAudioService() { + ALOGV("PcmAudioService() (%p), before destroy play object", this); + if (_audioRenderer != nullptr) { + OH_AudioRenderer_Stop(_audioRenderer); + OH_AudioRenderer_Release(_audioRenderer); + } + + if (_builder != nullptr) { + OH_AudioStreamBuilder_Destroy(_builder); + } +} + +int32_t PcmAudioService::AudioRendererOnWriteData(OH_AudioRenderer *renderer, + void *userData, + void *buffer, + int32_t bufferLen) { + auto *thiz = reinterpret_cast(userData); + if (bufferLen != thiz->_bufferSizeInBytes) { + __silenceData.resize(bufferLen, 0x00); + thiz->_bufferSizeInBytes = bufferLen; + thiz->_controller->updateBufferSize(thiz->_bufferSizeInBytes); + } + + if (thiz->_controller->hasPlayingTacks()) { + if (thiz->_controller->isPaused()) { + memcpy(buffer, __silenceData.data(), bufferLen); + } else { + thiz->_controller->mixOneFrame(); + auto *current = thiz->_controller->current(); + ALOG_ASSERT(current != nullptr, "current buffer is nullptr ..."); + memcpy(buffer, current->buf, current->size < bufferLen ? current->size : bufferLen); + } + } else { + memcpy(buffer, __silenceData.data(), bufferLen); + } + + return 0; +} + +int32_t PcmAudioService::AudioRendererOnInterrupt(OH_AudioRenderer *renderer, + void *userData, + OH_AudioInterrupt_ForceType type, + OH_AudioInterrupt_Hint hint) { + auto *thiz = reinterpret_cast(userData); + if (thiz->_audioRenderer != nullptr) { + if (hint == AUDIOSTREAM_INTERRUPT_HINT_RESUME) { + OH_AudioRenderer_Start(thiz->_audioRenderer); + } else if (hint == AUDIOSTREAM_INTERRUPT_HINT_PAUSE) { + OH_AudioRenderer_Pause(thiz->_audioRenderer); + } + } + return 0; +} + +bool PcmAudioService::init(AudioMixerController *controller, int numChannels, int sampleRate, int *bufferSizeInBytes) { + _controller = controller; + + OH_AudioStream_Result ret; + OH_AudioStream_Type type = AUDIOSTREAM_TYPE_RENDERER; + ret = OH_AudioStreamBuilder_Create(&_builder, type); + if (ret != AUDIOSTREAM_SUCCESS) { + return false; + } + + OH_AudioStreamBuilder_SetSamplingRate(_builder, sampleRate); + OH_AudioStreamBuilder_SetChannelCount(_builder, numChannels); + OH_AudioStreamBuilder_SetLatencyMode(_builder, AUDIOSTREAM_LATENCY_MODE_FAST); + OH_AudioStreamBuilder_SetRendererInfo(_builder, AUDIOSTREAM_USAGE_GAME); + + OH_AudioRenderer_Callbacks callbacks; + callbacks.OH_AudioRenderer_OnWriteData = AudioRendererOnWriteData; + callbacks.OH_AudioRenderer_OnInterruptEvent = AudioRendererOnInterrupt; + callbacks.OH_AudioRenderer_OnError = nullptr; + callbacks.OH_AudioRenderer_OnStreamEvent = nullptr; + ret = OH_AudioStreamBuilder_SetRendererCallback(_builder, callbacks, this); + if (ret != AUDIOSTREAM_SUCCESS) { + return false; + } + + ret = OH_AudioStreamBuilder_GenerateRenderer(_builder, &_audioRenderer); + if (ret != AUDIOSTREAM_SUCCESS) { + return false; + } + + int32_t buffer_size; + OH_AudioRenderer_GetFrameSizeInCallback(_audioRenderer, &buffer_size); + _bufferSizeInBytes = buffer_size * numChannels * 2; + *bufferSizeInBytes = buffer_size; + + if (__silenceData.empty()) { + __silenceData.resize(_bufferSizeInBytes, 0x00); + } + + ret = OH_AudioRenderer_Start(_audioRenderer); + if (ret != AUDIOSTREAM_SUCCESS) { + return false; + } + + return true; +} + +void PcmAudioService::pause() { + if (_audioRenderer != nullptr) { + OH_AudioRenderer_Pause(_audioRenderer); + } +} + +void PcmAudioService::resume() { + if (_audioRenderer != nullptr) { + OH_AudioRenderer_Start(_audioRenderer); + } +} +} // namespace cocos2d \ No newline at end of file diff --git a/native/cocos/audio/openharmony/PcmAudioService.h b/native/cocos/audio/openharmony/PcmAudioService.h new file mode 100644 index 0000000000..73eadaa14f --- /dev/null +++ b/native/cocos/audio/openharmony/PcmAudioService.h @@ -0,0 +1,64 @@ +/**************************************************************************** +Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "audio/android/IAudioPlayer.h" +#include "audio/android/PcmData.h" +#include "audio/android/utils/Compat.h" + +#include +#include +#include +#include + +namespace cc { + +class AudioMixerController; + +class PcmAudioService { +public: + PcmAudioService(); + virtual ~PcmAudioService(); + + // openharmony platform add bufferSizeInBytes pointer param to get ohaudio buffersize, which is needed by AudioMixer. + bool init(AudioMixerController* controller, int numChannels, int sampleRate, int* bufferSizeInBytes); + + void pause(); + void resume(); + +private: + static int32_t AudioRendererOnWriteData(OH_AudioRenderer* renderer, void* userData, void* buffer, int32_t bufferLen); + static int32_t AudioRendererOnInterrupt(OH_AudioRenderer* renderer, void* userData, OH_AudioInterrupt_ForceType type, OH_AudioInterrupt_Hint hint); + int _bufferSizeInBytes; + + AudioMixerController* _controller; + OH_AudioRenderer* _audioRenderer; + OH_AudioStreamBuilder* _builder; + + friend class AudioPlayerProvider; +}; + +} // namespace cc diff --git a/native/cocos/audio/openharmony/UrlAudioPlayer.cpp b/native/cocos/audio/openharmony/UrlAudioPlayer.cpp new file mode 100644 index 0000000000..71f2bac7f1 --- /dev/null +++ b/native/cocos/audio/openharmony/UrlAudioPlayer.cpp @@ -0,0 +1,321 @@ +/**************************************************************************** +Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#define LOG_TAG "UrlAudioPlayer" + +#include "audio/openharmony/UrlAudioPlayer.h" +#include +#include // for std::find +#include "audio/android/ICallerThreadUtils.h" +#include "audio/android/cutils/log.h" +#include "cocos/application/ApplicationManager.h" + +namespace { + +std::mutex __playerContainerMutex; + +std::map __playerContainer; +std::once_flag __onceFlag; + +} // namespace + +namespace cc { + +UrlAudioPlayer::UrlAudioPlayer(ICallerThreadUtils *callerThreadUtils) +: _callerThreadUtils(callerThreadUtils), _id(-1), _playObj(nullptr), _volume(0.0f), _duration(0.0f), _isLoop(false), _isAudioFocus(true), _state(State::INVALID), _playEventCallback(nullptr), _isDestroyed(std::make_shared(false)) { + _callerThreadId = callerThreadUtils->getCallerThreadId(); +} + +UrlAudioPlayer::~UrlAudioPlayer() { + __playerContainerMutex.lock(); + + auto it = __playerContainer.begin(); + while (it != __playerContainer.end()) { + if (it->second == this) { + it = __playerContainer.erase(it); + } else { + it++; + } + } + + __playerContainerMutex.unlock(); +} + +void UrlAudioPlayer::setPlayEventCallback(const PlayEventCallback &playEventCallback) { + _playEventCallback = playEventCallback; +} + +void UrlAudioPlayer::stop() { + int32_t status = OH_AVPlayer_Stop(_playObj); + if (status != 0) { + ALOGE("UrlAudioPlayer::stop failed"); + return; + } + + if (_state == State::PLAYING || _state == State::PAUSED) { + setLoop(false); + setState(State::STOPPED); + + if (_playEventCallback != nullptr) { + _playEventCallback(State::STOPPED); + } + + destroy(); + delete this; + } else { + ALOGW("UrlAudioPlayer (%p, state:%d) isn't playing or paused, could not invoke stop!", this, static_cast(_state)); + } +} + +void UrlAudioPlayer::pause() { + if (_state == State::PLAYING) { + int32_t status = OH_AVPlayer_Pause(_playObj); + if (status != 0) { + ALOGE("UrlAudioPlayer::pause failed"); + return; + } + setState(State::PAUSED); + } else { + ALOGW("UrlAudioPlayer (%p, state:%d) isn't playing, could not invoke pause!", this, static_cast(_state)); + } +} + +void UrlAudioPlayer::resume() { + if (_state == State::PAUSED) { + int32_t status = OH_AVPlayer_Play(_playObj); + if (status != 0) { + ALOGE("UrlAudioPlayer::resume failed"); + return; + } + setState(State::PLAYING); + } else { + ALOGW("UrlAudioPlayer (%p, state:%d) isn't paused, could not invoke resume!", this, static_cast(_state)); + } +} + +void UrlAudioPlayer::play() { + if (_state == State::INITIALIZED || _state == State::PAUSED) { + int32_t status = OH_AVPlayer_Play(_playObj); + if (status != 0) { + ALOGE("UrlAudioPlayer::play failed"); + return; + } + setState(State::PLAYING); + } else { + ALOGW("UrlAudioPlayer (%p, state:%d) isn't paused or initialized, could not invoke play!", this, static_cast(_state)); + } +} + +void UrlAudioPlayer::setVolumeToAVPlayer(float volume) { + int32_t status = OH_AVPlayer_SetVolume(_playObj, volume, volume); + if (status != 0) { + ALOGE("UrlAudioPlayer::setVolume %f failed", volume); + } +} + +void UrlAudioPlayer::setVolume(float volume) { + _volume = volume; + if (_isAudioFocus) { + setVolumeToAVPlayer(_volume); + } +} + +float UrlAudioPlayer::getVolume() const { + return _volume; +} + +void UrlAudioPlayer::setAudioFocus(bool isFocus) { + _isAudioFocus = isFocus; + float volume = _isAudioFocus ? _volume : 0.0f; + setVolumeToAVPlayer(volume); +} + +float UrlAudioPlayer::getDuration() const { + if (_duration > 0) { + return _duration; + } + + int32_t duration = 0; + int32_t status = OH_AVPlayer_GetDuration(_playObj, &duration); + if (status != 0) { + ALOGE("UrlAudioPlayer::getDuration failed"); + return -1.0f; + } + + const_cast(this)->_duration = duration / 1000.0f; + if (_duration <= 0) { + return -1.0f; + } + return _duration; +} + +float UrlAudioPlayer::getPosition() const { + int32_t currentTime = 0; + int status = OH_AVPlayer_GetCurrentTime(_playObj, ¤tTime); + if (status != 0) { + ALOGE("UrlAudioPlayer::getPosition failed"); + return -1.0f; + } + return currentTime / 1000.0f; +} + +bool UrlAudioPlayer::setPosition(float pos) { + int32_t millisecond = 1000.0f * pos; + int status = OH_AVPlayer_Seek(_playObj, millisecond, AV_SEEK_NEXT_SYNC); + if (status != 0) { + ALOGE("UrlAudioPlayer::setPosition %f failed", pos); + return false; + } + return true; +} + +void UrlAudioPlayer::onInfo(OH_AVPlayer *player, AVPlayerOnInfoType type, int32_t extra) { + if (type == AV_INFO_TYPE_STATE_CHANGE) { + if (extra == AV_COMPLETED) { + UrlAudioPlayer *audioPlayer = nullptr; + auto it = __playerContainer.find(player); + if (it != __playerContainer.end()) { + UrlAudioPlayer *audioPlayer = it->second; + audioPlayer->playEventCallback(); + } + } + } else if (type == AV_INFO_TYPE_INTERRUPT_EVENT) { + auto it = __playerContainer.find(player); + if (it != __playerContainer.end()) { + UrlAudioPlayer *audioPlayer = it->second; + const int32_t interruptHintResume = 1; + const int32_t interruptHintPause = 2; + if (extra == interruptHintResume) { + audioPlayer->resume(); + } else if (extra == interruptHintPause) { + audioPlayer->pause(); + } else { + ALOGV("UrlAudioPlayer was interrupted, hint type is %d", extra); + } + } + } +} + +void UrlAudioPlayer::onError(OH_AVPlayer *player, int32_t errorCode, const char *errorMsg) { + ALOGE("UrlAudioPlayer play failed, errorCode is: %d, errorMsg is %s", errorCode, errorMsg); +} + +void UrlAudioPlayer::playEventCallback() { + std::shared_ptr isDestroyed = _isDestroyed; + auto func = [this, isDestroyed]() { + // If it was destroyed, just return. + if (*isDestroyed) { + ALOGV("The UrlAudioPlayer (%p) was destroyed!", this); + return; + } + + // Note that It's in the caller's thread (Cocos Thread) + // If state is already stopped, ignore the play over event. + if (_state == State::STOPPED) { + return; + } + + setState(State::OVER); + if (_playEventCallback != nullptr) { + _playEventCallback(State::OVER); + } + + ALOGV("UrlAudioPlayer (%p) played over, destroy self ...", this); + destroy(); + delete this; + }; + + if (_callerThreadId == std::this_thread::get_id()) { + func(); + } else { + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread(func); + } +} + +bool UrlAudioPlayer::prepare(const std::string &url, std::shared_ptr assetFd, int32_t start, int32_t length) { + _url = url; + _assetFd = assetFd; + _playObj = OH_AVPlayer_Create(); + + __playerContainerMutex.lock(); + __playerContainer[_playObj] = this; + __playerContainerMutex.unlock(); + + AVPlayerCallback callback; + callback.onInfo = this->onInfo; + callback.onError = this->onError; + OH_AVPlayer_SetPlayerCallback(_playObj, callback); + OH_AVPlayer_SetFDSource(_playObj, _assetFd->getFd(), start, length); + OH_AVPlayer_SetAudioRendererInfo(_playObj, OH_AudioStream_Usage::AUDIOSTREAM_USAGE_GAME); + OH_AVErrCode code = OH_AVPlayer_Prepare(_playObj); + if (code == AV_ERR_OK) { + setState(State::INITIALIZED); + return true; + } + + ALOGE("Oops, prepare error: %d", (int)code); + return false; +} + +void UrlAudioPlayer::rewind() { + // Not supported currently. since cocos audio engine will new -> prepare -> play again. +} + +void UrlAudioPlayer::setLoop(bool isLoop) { + _isLoop = isLoop; + int status = OH_AVPlayer_SetLooping(_playObj, _isLoop); + if (status != 0) { + ALOGE("UrlAudioPlayer::setLoop %d failed", _isLoop ? 1 : 0); + } +} + +bool UrlAudioPlayer::isLoop() const { + return _isLoop; +} + +void UrlAudioPlayer::stopAll() { + __playerContainerMutex.lock(); + auto temp = __playerContainer; + __playerContainerMutex.unlock(); + + auto it = temp.begin(); + while (it != temp.end()) { + UrlAudioPlayer *thiz = it->second; + thiz->stop(); + it++; + } +} + +void UrlAudioPlayer::destroy() { + if (!*_isDestroyed) { + *_isDestroyed = true; + OH_AVErrCode code = OH_AVPlayer_Release(_playObj); + if (code == AV_ERR_OK) { + ALOGE("UrlAudioPlayer release error, code: %d", code); + } + } +} + +} // namespace cc diff --git a/native/cocos/audio/openharmony/UrlAudioPlayer.h b/native/cocos/audio/openharmony/UrlAudioPlayer.h new file mode 100644 index 0000000000..3a01ba9fd7 --- /dev/null +++ b/native/cocos/audio/openharmony/UrlAudioPlayer.h @@ -0,0 +1,121 @@ +/**************************************************************************** +Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include "audio/android/AssetFd.h" +#include "audio/android/IAudioPlayer.h" +#include "multimedia/player_framework/avplayer.h" + +namespace cc { + +class ICallerThreadUtils; +// class AssetFd; + +class UrlAudioPlayer : public IAudioPlayer { +public: + // Override Functions Begin + virtual int getId() const override { return _id; }; + + virtual void setId(int id) override { _id = id; }; + + virtual std::string getUrl() const override { return _url; }; + + virtual State getState() const override { return _state; }; + + virtual void play() override; + + virtual void pause() override; + + virtual void resume() override; + + virtual void stop() override; + + virtual void rewind() override; + + virtual void setVolume(float volume) override; + + virtual float getVolume() const override; + + virtual void setAudioFocus(bool isFocus) override; + + virtual void setLoop(bool isLoop) override; + + virtual bool isLoop() const override; + + virtual float getDuration() const override; + + virtual float getPosition() const override; + + virtual bool setPosition(float pos) override; + + virtual void setPlayEventCallback(const PlayEventCallback &playEventCallback) override; + +private: + UrlAudioPlayer(ICallerThreadUtils *callerThreadUtils); + virtual ~UrlAudioPlayer(); + + bool prepare(const std::string &url, std::shared_ptr assetFd, int32_t start, int32_t length); + + static void onInfo(OH_AVPlayer *player, AVPlayerOnInfoType type, int32_t extra); + + static void onError(OH_AVPlayer *player, int32_t errorCode, const char *errorMsg); + + static void stopAll(); + + void destroy(); + + inline void setState(State state) { _state = state; }; + + void playEventCallback(); + + void setVolumeToAVPlayer(float volume); + +private: + ICallerThreadUtils *_callerThreadUtils; + int _id; + std::string _url; + + std::shared_ptr _assetFd; + OH_AVPlayer *_playObj; + float _volume; + float _duration; + bool _isLoop; + bool _isAudioFocus; + State _state; + + PlayEventCallback _playEventCallback; + + std::thread::id _callerThreadId; + std::shared_ptr _isDestroyed; + + friend class AudioPlayerProvider; +}; + +} // namespace cc diff --git a/native/cocos/bindings/jswrapper/Object.h b/native/cocos/bindings/jswrapper/Object.h index f439b1b0d8..bed507f583 100644 --- a/native/cocos/bindings/jswrapper/Object.h +++ b/native/cocos/bindings/jswrapper/Object.h @@ -46,4 +46,9 @@ #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI #include "napi/Object.h" +#endif + + +#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM + #include "jsvm/Object.h" #endif \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/SeApi.h b/native/cocos/bindings/jswrapper/SeApi.h index b187a727ef..87d5a0aaff 100644 --- a/native/cocos/bindings/jswrapper/SeApi.h +++ b/native/cocos/bindings/jswrapper/SeApi.h @@ -47,6 +47,10 @@ #include "napi/SeApi.h" #endif +#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM + #include "jsvm/SeApi.h" +#endif + #include "HandleObject.h" #include "Object.h" #include "State.h" diff --git a/native/cocos/bindings/jswrapper/config.h b/native/cocos/bindings/jswrapper/config.h index c66c13a9d0..fb0defaf45 100644 --- a/native/cocos/bindings/jswrapper/config.h +++ b/native/cocos/bindings/jswrapper/config.h @@ -33,6 +33,7 @@ #define SCRIPT_ENGINE_SM 1 #define SCRIPT_ENGINE_V8 2 #define SCRIPT_ENGINE_NAPI 5 +#define SCRIPT_ENGINE_JSVM 6 #ifndef SCRIPT_ENGINE_TYPE #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY diff --git a/native/cocos/bindings/jswrapper/jsvm/Class.cpp b/native/cocos/bindings/jswrapper/jsvm/Class.cpp new file mode 100644 index 0000000000..c4b2ed7545 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/Class.cpp @@ -0,0 +1,248 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "Class.h" +#include +#include "CommonHeader.h" +#include "ScriptEngine.h" +#include "Utils.h" + +namespace se { + +JSVM_Value *Class::_exports = nullptr; +std::vector __allClasses; + +Class::Class() { + __allClasses.push_back(this); +}; + +Class::~Class() { +} + +/* static */ +Class *Class::create(const std::string &clsName, se::Object *parent, Object *parentProto, JSVM_Callback ctor) { + Class *cls = new Class(); + if (cls != nullptr && !cls->init(clsName, parent, parentProto, ctor)) { + delete cls; + cls = nullptr; + } + return cls; +} + +Class* Class::create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor) { + se::AutoHandleScope scope; + se::Object *currentParent = parent; + se::Value tmp; + for (auto i = 0; i < classPath.size() - 1; i++) { + bool ok = currentParent->getProperty(*(classPath.begin() + i), &tmp); + assert(ok); // class or namespace in path is not defined + currentParent = tmp.toObject(); + } + return create(*(classPath.end() - 1), currentParent, parentProto, ctor); +} + +bool Class::init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor) { + _name = clsName; + _parent = parent; + if (_parent != nullptr) + _parent->incRef(); + _parentProto = parentProto; + + if (_parentProto != nullptr) + _parentProto->incRef(); + if (ctor) { + _ctorFunc = ctor; + } + + return true; +} + +JSVM_Value Class::_defaultCtor(JSVM_Env env, JSVM_CallbackInfo info) { + JSVM_Value thisArg; + JSVM_Status status; + NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, nullptr, nullptr, &thisArg, nullptr)); + return thisArg; +} + +void Class::defineProperty(const char* name, JSVM_Callback g, JSVM_Callback s) { + _properties.push_back({name, nullptr, nullptr, g, s, 0, JSVM_DEFAULT_JSPROPERTY}); +} + +void Class::defineProperty(const std::initializer_list &names, JSVM_Callback g, JSVM_Callback s) { + for (const auto *name : names) { + defineProperty(name, g, s); + } +} + +void Class::defineStaticProperty(const char* name, JSVM_Callback g, JSVM_Callback s) { + if(g != nullptr && s != nullptr) + _properties.push_back({name, nullptr, nullptr, g, s, 0, JSVM_STATIC}); +} + +void Class::defineFunction(const char* name, JSVM_Callback func) { + // When JSVM defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function + _properties.push_back({name, nullptr, func, nullptr, nullptr, nullptr, JSVM_JSPROPERTY_NO_RECEIVER_CHECK}); +} + +void Class::defineStaticFunction(const char* name, JSVM_Callback func) { + _properties.push_back({name, nullptr, func, nullptr, nullptr, 0, JSVM_PropertyAttributes((int)JSVM_STATIC|(int)JSVM_WRITABLE)}); +} + +bool Class::defineStaticProperty(const char *name, const Value &v, PropertyAttribute attribute /* = PropertyAttribute::NONE */) { + // TODO(qgh): Assigning get and set to nullptr in openharmony will cause a crash + //napi_value value; + //internal::seToJsValue(v, &value); + //_properties.push_back({name, nullptr, nullptr, nullptr, nullptr, value, napi_static, 0}); + return true; +} + +void Class::defineFinalizeFunction(JSVM_Finalize func) { + assert(func != nullptr); + _finalizeFunc = func; +} + +JSVM_Finalize Class::_getFinalizeFunction() const { + return _finalizeFunc; +} + +bool Class::install() { + auto env = ScriptEngine::getEnv(); + JSVM_Value cons; + JSVM_Status status; + NODE_API_CALL(status, env, OH_JSVM_DefineClass(env, _name.c_str(), -1, _ctorFunc, _properties.size(), _properties.data(), &cons)); + if (_parentProto) { + inherit(env, cons, _parentProto->_getJSObject()); + } + + NODE_API_CALL(status, env, OH_JSVM_CreateReference(env, cons, 1, &_constructor)); + NODE_API_CALL(status, env, OH_JSVM_SetNamedProperty(env, _parent->_getJSObject(), _name.c_str(), cons)); + + JSVM_Value proto; + NODE_API_CALL(status, env, OH_JSVM_GetNamedProperty(env, cons, "prototype", &proto)); + + if (status == JSVM_OK) { + _proto = Object::_createJSObject(env, proto, nullptr); + _proto->root(); + } + + return true; +} + +JSVM_Status Class::inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superProto) { + JSVM_Value global, objectClass, setProto; + JSVM_Value argv[2]; + JSVM_Value callbackResult = nullptr; + + JSVM_Status status; + NODE_API_CALL(status, env, OH_JSVM_GetGlobal(env, &global)); + NODE_API_CALL(status, env, OH_JSVM_GetNamedProperty(env, global, "Object", &objectClass)); + if (status != JSVM_OK) { + return JSVM_OK; + } + NODE_API_CALL(status, env, OH_JSVM_GetNamedProperty(env, objectClass, "setPrototypeOf", &setProto)); + if (status != JSVM_OK) { + return JSVM_OK; + } + NODE_API_CALL(status, env, OH_JSVM_GetNamedProperty(env, subclass, "prototype", &argv[0])); + if (status != JSVM_OK) { + return JSVM_OK; + } + argv[1] = superProto; + NODE_API_CALL(status, env, OH_JSVM_CallFunction(env, objectClass, setProto, 2, argv, &callbackResult)); + if (status != JSVM_OK) { + return JSVM_OK; + } + return JSVM_OK; +} + +JSVM_Value Class::_createJSObjectWithClass(Class *cls) { + assert(cls); + JSVM_Value clsCtor = cls->_getCtorFunc(); + if (!clsCtor) { + LOGE("get ctor func err"); + return nullptr; + } + auto env = ScriptEngine::getEnv(); + JSVM_Value obj = nullptr; + JSVM_Status status; + + se::ScriptEngine::getInstance()->_setNeedCallConstructor(false); + NODE_API_CALL(status, env, OH_JSVM_NewInstance(env, clsCtor, 0, nullptr, &obj)); + se::ScriptEngine::getInstance()->_setNeedCallConstructor(true); + return obj; +} + +Object *Class::getProto() const { + //not impl + return _proto; +} + +JSVM_Ref Class::_getCtorRef() const { + return _constructor; +} + +JSVM_Value Class::_getCtorFunc() const { + assert(_constructor); + JSVM_Value result = nullptr; + JSVM_Status status; + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_GetReferenceValue(ScriptEngine::getEnv(), _constructor, &result)); + return result; +} + +void Class::_setCtor(Object *obj) { + assert(!_ctor.has_value()); + _ctor = obj; + if (obj != nullptr) { + obj->root(); + obj->incRef(); + } +} + +void Class::destroy() { + SAFE_DEC_REF(_parent); + SAFE_DEC_REF(_proto); + SAFE_DEC_REF(_parentProto); + if (_ctor.has_value()) { + if (_ctor.value() != nullptr) { + _ctor.value()->unroot(); + _ctor.value()->decRef(); + } + _ctor.reset(); + } +} + +void Class::cleanup() { + for (auto cls : __allClasses) { + cls->destroy(); + } + + se::ScriptEngine::getInstance()->addAfterCleanupHook([]() { + for (auto cls : __allClasses) { + delete cls; + } + __allClasses.clear(); + }); +} +}; // namespace se \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/jsvm/Class.h b/native/cocos/bindings/jswrapper/jsvm/Class.h new file mode 100644 index 0000000000..175682e6b8 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/Class.h @@ -0,0 +1,84 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once +#include +#include +#include "CommonHeader.h" +#include "Object.h" +#include "../Define.h" + +namespace se { +class Class { +public: + static Class *create(const std::string &clsName, se::Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr); + static Class *create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr); + + void defineFunction(const char* name, JSVM_Callback func); + void defineProperty(const char* name, JSVM_Callback g, JSVM_Callback s); + void defineProperty(const std::initializer_list &names, JSVM_Callback g, JSVM_Callback s); + + void defineStaticFunction(const char* name, JSVM_Callback func); + void defineStaticProperty(const char* name, JSVM_Callback g, JSVM_Callback s); + bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE); + + static JSVM_Value _createJSObjectWithClass(Class *cls); + + void defineFinalizeFunction(JSVM_Finalize func); + JSVM_Finalize _getFinalizeFunction() const; + + + Object * getProto() const; + bool install(); + JSVM_Status inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superclass); + JSVM_Ref _getCtorRef() const; + JSVM_Value _getCtorFunc() const; + const char * getName() const { return _name.c_str(); } + static void setExports(JSVM_Value *expPtr) { _exports = expPtr; } + static void cleanup(); + // Private API used in wrapper + void _setCtor(Object *obj); // NOLINT(readability-identifier-naming) + inline const std::optional &_getCtor() const { return _ctor; } // NOLINT(readability-identifier-naming) +private: + Class(); + ~Class(); + bool init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr); + void destroy(); + static JSVM_Value _defaultCtor(JSVM_Env env, JSVM_CallbackInfo info); + +private: + std::optional _ctor; + static JSVM_Value * _exports; + std::string _name; + Object * _parent = nullptr; + Object * _proto = nullptr; + Object * _parentProto = nullptr; + JSVM_CallbackStruct _ctorStruct = {Class::_defaultCtor,nullptr}; + JSVM_Callback _ctorFunc = &_ctorStruct; + JSVM_Ref _constructor = nullptr; + std::vector _properties; + JSVM_Finalize _finalizeFunc = nullptr; +}; +}; // namespace se \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h b/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h new file mode 100644 index 0000000000..9f6e5bf059 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h @@ -0,0 +1,90 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once +#include "ark_runtime/jsvm.h" +#include "platform/openharmony/napi/native_common.h" + +// Empty value so that macros here are able to return NULL or void +#define NODE_API_RETVAL_NOTHING // Intentionally blank #define + +// Returns NULL on failed assertion. +// This is meant to be used inside JSVM_Callback methods. +#define NODE_API_ASSERT(env, assertion, message) \ + NODE_API_ASSERT_BASE(env, assertion, message, NULL) + +// Returns empty on failed assertion. +// This is meant to be used inside functions with void return type. +#define NODE_API_ASSERT_RETURN_VOID(env, assertion, message) \ + NODE_API_ASSERT_BASE(env, assertion, message, NODE_API_RETVAL_NOTHING) + +#define NODE_API_CALL_BASE(env, the_call, ret_val) \ + do { \ + if ((the_call) != JSVM_OK) { \ + assert(false); \ + } \ + } while (0) + +// Returns nullptr if the_call doesn't return JSVM_OK. +#define NODE_API_CALL(status, env, the_call) \ + status = the_call; \ + if (status != JSVM_OK) { \ + bool isPending = false; \ + if (JSVM_OK == OH_JSVM_IsExceptionPending((env), &isPending) && isPending) { \ + JSVM_Value error; \ + if (JSVM_OK == OH_JSVM_GetAndClearLastException((env), &error)) { \ + JSVM_Value stack; \ + OH_JSVM_GetNamedProperty((env), error, "stack", &stack); \ + JSVM_Value message; \ + OH_JSVM_GetNamedProperty((env), error, "message", &message); \ + char stackstr[256]; \ + OH_JSVM_GetValueStringUtf8(env, stack, stackstr, 256, nullptr); \ + SE_LOGE("JSVM error stack: %{public}s", stackstr); \ + char messagestr[256]; \ + OH_JSVM_GetValueStringUtf8(env, message, messagestr, 256, nullptr); \ + SE_LOGE("JSVM error message: %{public}s", messagestr); \ + } \ + } \ + } \ + NODE_API_CALL_BASE(env, status, nullptr) + +// Returns empty if the_call doesn't return JSVM_OK. +#define NODE_API_CALL_RETURN_VOID(env, the_call) \ + NODE_API_CALL_BASE(env, the_call, NODE_API_RETVAL_NOTHING) + +#define DECLARE_NODE_API_PROPERTY(name, func) \ + { (name), nullptr, (func), nullptr, nullptr, nullptr, JSVM_DEFAULT, nullptr } + +#define DECLARE_NODE_API_GETTER(name, func) \ + { (name), nullptr, nullptr, (func), nullptr, nullptr, JSVM_DEFAULT, nullptr } + +void add_returned_status(JSVM_Env env, + const char* key, + JSVM_Value object, + char* expected_message, + JSVM_Status expected_status, + JSVM_Status actual_status); + +void add_last_status(JSVM_Env env, const char* key, JSVM_Value return_value); diff --git a/native/cocos/bindings/jswrapper/jsvm/HelperMacros.cpp b/native/cocos/bindings/jswrapper/jsvm/HelperMacros.cpp new file mode 100644 index 0000000000..23e917f996 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/HelperMacros.cpp @@ -0,0 +1,145 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "HelperMacros.h" +#include "../State.h" +#include "Class.h" +#include "Object.h" +#include "ScriptEngine.h" +#include "Utils.h" + +SE_HOT JSVM_Value jsbFunctionWrapper(JSVM_Env env, JSVM_CallbackInfo info, se_function_ptr func, const char *funcName) { + JSVM_Status status; + bool ret = false; + JSVM_Value _this; + se::ValueArray seArgs; + seArgs.reserve(15); + size_t argc = 15; + JSVM_Value args[15]; + NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, &argc, args, &_this, NULL)); + + void* nativeThisObject = nullptr; + status = OH_JSVM_Unwrap(env, _this, &nativeThisObject); + se::internal::jsToSeArgs(argc, args, &seArgs); + se::State state(reinterpret_cast(nativeThisObject), seArgs); + ret = func(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); + return nullptr; + } + JSVM_Value retVal; + if (se::internal::setReturnValue(state.rval(), retVal)) + return retVal; + return nullptr; +} + +SE_HOT void jsbFinalizeWrapper(void *thisObject, se_function_ptr func, const char *funcName) { + se::State state(reinterpret_cast(thisObject)); + bool ret = func(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); + } +} + +SE_HOT JSVM_Value jsbConstructorWrapper(JSVM_Env env, JSVM_CallbackInfo info, se_function_ptr func, se_finalize_ptr finalizeCb, se::Class *cls, const char *funcName) { + JSVM_Status status; + bool ret = false; + JSVM_Value _this; + se::ValueArray seArgs; + seArgs.reserve(10); + size_t argc = 10; + JSVM_Value args[10]; + NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, &argc, args, &_this, NULL)); + if (!se::ScriptEngine::getInstance()->_needCallConstructor()) { + return _this; + } + se::internal::jsToSeArgs(argc, args, &seArgs); + se::Object *thisObject = se::Object::_createJSObject(env, _this, cls); + thisObject->_setFinalizeCallback(finalizeCb); + se::State state(thisObject, seArgs); + ret = func(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); + } + se::Value property; + bool foundCtor = false; + if (!cls->_getCtor().has_value()) { + foundCtor = thisObject->getProperty("_ctor", &property, true); + if (foundCtor) { + cls->_setCtor(property.toObject()); + } else { + cls->_setCtor(nullptr); + } + } else { + auto *ctorObj = cls->_getCtor().value(); + if (ctorObj != nullptr) { + property.setObject(ctorObj); + foundCtor = true; + } + } + + if (foundCtor) { + property.toObject()->call(seArgs, thisObject); + } + return _this; +} + +SE_HOT JSVM_Value jsbGetterWrapper(JSVM_Env env, JSVM_CallbackInfo info, se_function_ptr func, const char *funcName) { + JSVM_Value _this; + JSVM_Status status; + NODE_API_CALL(status, env, + OH_JSVM_GetCbInfo(env, info, nullptr, nullptr, &_this, nullptr)); + void* obj = nullptr; + status = OH_JSVM_Unwrap(env, _this, &obj); + se::State state(reinterpret_cast(obj)); + bool ret = func(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); + return nullptr; + } + JSVM_Value retVal; + se::internal::setReturnValue(state.rval(), retVal); + return retVal; +} + +SE_HOT JSVM_Value jsbSetterWrapper(JSVM_Env env, JSVM_CallbackInfo info, se_function_ptr func, const char *funcName) { + JSVM_Status status; + size_t argc = 1; + JSVM_Value args[1]; + JSVM_Value _this; + se::Value data; + NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, &argc, args, &_this, nullptr)); + se::internal::jsToSeValue(args[0], &data); + se::ValueArray args2; + args2.reserve(10); + args2.push_back(std::move(data)); + void* nativeThisObject = nullptr; + status = OH_JSVM_Unwrap(env, _this, &nativeThisObject); + se::State state(reinterpret_cast(nativeThisObject), args2); + bool ret = func(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); + } + return nullptr; +} diff --git a/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h b/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h new file mode 100644 index 0000000000..4202d8838d --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h @@ -0,0 +1,146 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "CommonHeader.h" +#if !defined(_WIN) + #include + + #ifndef LOGI + #define LOGI(...) ((void) OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGW(...) ((void) OH_LOG_Print(LOG_APP, LOG_WARN, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGE(...) ((void) OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGD(...) ((void) OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #endif +#else + #define LOGI + #define LOGW + #define LOGE +#endif +namespace se { +class Class; +class Object; +class State; +} // namespace se +using se_function_ptr = bool (*)(se::State &state); +using se_finalize_ptr = void (*)(JSVM_Env env, void *nativeObject, void *hint); + +JSVM_Value jsbFunctionWrapper(JSVM_Env, JSVM_CallbackInfo, se_function_ptr, const char *); +void jsbFinalizeWrapper(void *thisObject, se_function_ptr, const char *); +JSVM_Value jsbConstructorWrapper(JSVM_Env, JSVM_CallbackInfo, se_function_ptr, se_finalize_ptr finalizeCb, se::Class *, + const char *); +JSVM_Value jsbGetterWrapper(JSVM_Env, JSVM_CallbackInfo, se_function_ptr, const char *); +JSVM_Value jsbSetterWrapper(JSVM_Env, JSVM_CallbackInfo, se_function_ptr, const char *); +#ifdef __GNUC__ + #define SE_UNUSED __attribute__((unused)) + #define SE_HOT __attribute__((hot)) +#else + #define SE_UNUSED + #define SE_HOT +#endif + +template +constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier-naming) + return reinterpret_cast(s.nativeThisObject()); +} + +#define SAFE_INC_REF(obj) \ + if (obj != nullptr) \ + obj->incRef() +#define SAFE_DEC_REF(obj) \ + if ((obj) != nullptr) { \ + (obj)->decRef(); \ + (obj) = nullptr; \ + } + +#define SE_QUOTEME_(x) #x // NOLINT(readability-identifier-naming) +#define SE_QUOTEME(x) SE_QUOTEME_(x) +#define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__) + +#define SE_BIND_PROP_GET_IMPL(funcName, postFix) \ + JSVM_Value funcName##postFix##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ + return jsbGetterWrapper(env, info, funcName, #funcName); \ + } \ + JSVM_CallbackStruct funcName##postFix##RegistryStruct = {(funcName##postFix##Registry),nullptr}; + +#define SE_BIND_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, ) +#define SE_BIND_FUNC_AS_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, _asGetter) + +#define SE_BIND_PROP_SET_IMPL(funcName, postFix) \ + JSVM_Value funcName##postFix##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ + return jsbSetterWrapper(env, info, funcName, #funcName); \ + } \ + JSVM_CallbackStruct funcName##postFix##RegistryStruct = {(funcName##postFix##Registry),nullptr}; + +#define SE_BIND_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, ) +#define SE_BIND_FUNC_AS_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, _asSetter) + +#define SE_DECLARE_FUNC(funcName) \ + JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info); \ + extern JSVM_CallbackStruct funcName##RegistryStruct; + +#define SE_BIND_FUNC(funcName) \ + JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ + return jsbFunctionWrapper(env, info, funcName, #funcName); \ + } \ + JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry),nullptr}; + +#define SE_BIND_FUNC_FAST(funcName) \ + JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ + JSVM_Status status; \ + JSVM_Value _this; \ + size_t argc = 15; \ + JSVM_Value args[15]; \ + void *nativeThisObject = nullptr; \ + NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, &argc, args, &_this, NULL)); \ + status = OH_JSVM_Unwrap(env, _this, &nativeThisObject); \ + auto *nativeObject = nativeThisObject != nullptr ? ((se::Object*)nativeThisObject)->getPrivateData() : nullptr; \ + funcName(nativeObject); \ + return nullptr; \ + } \ + JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry),nullptr}; + +#define SE_BIND_CTOR(funcName, cls, finalizeCb) \ + JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ + return jsbConstructorWrapper(env, info, funcName, _SE(finalizeCb), cls, #funcName); \ + } \ + JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry),nullptr}; + + +#define SE_BIND_SUB_CLS_CTOR SE_BIND_CTOR + +#define SE_DECLARE_FINALIZE_FUNC(funcName) \ + void funcName##RegistryStruct(JSVM_Env env, void *nativeObject, void * /*finalize_hint*/); \ + +#define SE_BIND_FINALIZE_FUNC(funcName) \ + void funcName##RegistryStruct(JSVM_Env env, void *nativeObject, void *hint /*finalize_hint*/) { \ + if (nativeObject == nullptr) { \ + return; \ + } \ + jsbFinalizeWrapper(nativeObject, funcName, #funcName); \ + } + +#define _SE(name) &(name##RegistryStruct) \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/jsvm/Object.cpp b/native/cocos/bindings/jswrapper/jsvm/Object.cpp new file mode 100644 index 0000000000..02560a20aa --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/Object.cpp @@ -0,0 +1,871 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "Object.h" +#include +#include +#include "../MappingUtils.h" +#include "Class.h" +#include "ScriptEngine.h" +#include "Utils.h" +#include "application/ApplicationManager.h" + +#define MAX_STRING_LEN 512 + +namespace se { +std::unique_ptr> __objectMap; // Currently, the value `void*` is always nullptr + +Object::Object() {} +Object::~Object() { + if (__objectMap) { + __objectMap->erase(this); + } +} + +Object* Object::createObjectWithClass(Class* cls) { + JSVM_Value jsobj = Class::_createJSObjectWithClass(cls); + Object* obj = Object::_createJSObject(ScriptEngine::getEnv(), jsobj, cls); + return obj; +} + +bool Object::setProperty(const char* name, const Value& data) { + JSVM_Status status; + JSVM_Value jsVal; + internal::seToJsValue(data, &jsVal); + NODE_API_CALL(status, _env, OH_JSVM_SetNamedProperty(_env, _objRef.getValue(_env), name, jsVal)); + return status == JSVM_OK; +} + +bool Object::getProperty(const char* name, Value* d) { + JSVM_Status status; + JSVM_Value jsVal; + Value data; + NODE_API_CALL(status, _env, OH_JSVM_GetNamedProperty(_env, _objRef.getValue(_env), name, &jsVal)); + if (status == JSVM_OK) { + internal::jsToSeValue(jsVal, &data); + *d = data; + if (data.isUndefined()) { + return false; + } + return true; + } + return false; +} + +PrivateObjectBase* Object::getPrivateObject() const { + return _privateObject; +} + +void Object::setPrivateObject(PrivateObjectBase* data) { + assert(_privateData == nullptr); +#if CC_DEBUG + if (data != nullptr) { + NativePtrToObjectMap::filter(data->getRaw(), _getClass()) + .forEach([&](se::Object* seObj) { + auto* pri = seObj->getPrivateObject(); + SE_LOGE("Already exists object %s/[%s], trying to add %s/[%s]\n", pri->getName(), typeid(*pri).name(), data->getName(), typeid(*data).name()); + #if JSB_TRACK_OBJECT_CREATION + SE_LOGE(" previous object created at %s\n", it->second->_objectCreationStackFrame.c_str()); + #endif + CC_ABORT(); + }); + } +#endif + + if (data) { + _privateData = data->getRaw(); + _privateObject = data; + NativePtrToObjectMap::emplace(_privateData, this); + } + + JSVM_Status status; + auto tmpThis = _objRef.getValue(_env); + JSVM_Ref result = nullptr; + NODE_API_CALL(status, _env, + OH_JSVM_Wrap(_env, tmpThis, this, sendWeakCallback, + (void*)this /* finalize_hint */, &result)); + //_objRef.setWeakref(_env, result); + setProperty("__native_ptr__", se::Value(static_cast(reinterpret_cast(data)))); + return; +} + + +bool Object::deleteProperty(const char *name) { + JSVM_Status status; + JSVM_Value key; + NODE_API_CALL(status, _env, OH_JSVM_GetNamedProperty(_env, _objRef.getValue(_env), name, &key)); + if (status != JSVM_OK) { + return false; + } + bool ret = false; + NODE_API_CALL(status, _env, OH_JSVM_DeleteProperty(_env, _objRef.getValue(_env), key, &ret)); + return ret; +} + +bool Object::isArray() const { + JSVM_Status status; + bool ret = false; + NODE_API_CALL(status, _env, OH_JSVM_IsArray(_env, _objRef.getValue(_env), &ret)); + return ret; +} + +bool Object::getArrayLength(uint32_t* length) const { + JSVM_Status status; + uint32_t len = 0; + NODE_API_CALL(status, _env, OH_JSVM_GetArrayLength(_env, _objRef.getValue(_env), &len)); + if (length) { + *length = len; + } + return true; +} + +bool Object::getArrayElement(uint32_t index, Value* data) const { + JSVM_Status status; + JSVM_Value val; + NODE_API_CALL(status, _env, OH_JSVM_GetElement(_env, _objRef.getValue(_env), index, &val)); + internal::jsToSeValue(val, data); + return true; +} + +bool Object::setArrayElement(uint32_t index, const Value& data) { + JSVM_Status status; + JSVM_Value val; + internal::seToJsValue(data, &val); + NODE_API_CALL(status, _env, OH_JSVM_SetElement(_env, _objRef.getValue(_env), index, val)); + return true; +} + +bool Object::isTypedArray() const { + JSVM_Status status; + bool ret = false; + NODE_API_CALL(status, _env, OH_JSVM_IsTypedarray(_env, _objRef.getValue(_env), &ret)); + return ret; +} + +bool Object::isProxy() const { + //return const_cast(this)->_obj.handle(__isolate)->IsProxy(); + // todo: + return false; +} + +Object::TypedArrayType Object::getTypedArrayType() const { + JSVM_Status status; + JSVM_TypedarrayType type; + JSVM_Value inputBuffer; + size_t byteOffset; + size_t length; + NODE_API_CALL(status, _env, OH_JSVM_GetTypedarrayInfo(_env, _objRef.getValue(_env), &type, &length, NULL, &inputBuffer, &byteOffset)); + + TypedArrayType ret = TypedArrayType::NONE; + switch (type) { + case JSVM_INT8_ARRAY: + ret = TypedArrayType::INT8; + break; + case JSVM_UINT8_ARRAY: + ret = TypedArrayType::UINT8; + break; + case JSVM_UINT8_CLAMPED_ARRAY: + ret = TypedArrayType::UINT8_CLAMPED; + break; + case JSVM_INT16_ARRAY: + ret = TypedArrayType::INT16; + break; + case JSVM_UINT16_ARRAY: + ret = TypedArrayType::UINT16; + break; + case JSVM_INT32_ARRAY: + ret = TypedArrayType::INT32; + break; + case JSVM_UINT32_ARRAY: + ret = TypedArrayType::UINT32; + break; + case JSVM_FLOAT32_ARRAY: + ret = TypedArrayType::FLOAT32; + break; + case JSVM_FLOAT64_ARRAY: + ret = TypedArrayType::FLOAT64; + break; + case JSVM_BIGINT64_ARRAY: + ret = TypedArrayType::BIGINT64; + break; + case JSVM_BIGUINT64_ARRAY: + ret = TypedArrayType::BIGUINT64; + break; + default: + break; + } + return ret; +} + +bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const { + JSVM_Status status; + JSVM_TypedarrayType type; + JSVM_Value inputBuffer; + size_t byteOffset; + size_t arrayLength; + void* data = nullptr; + NODE_API_CALL(status, _env, OH_JSVM_GetTypedarrayInfo(_env, _objRef.getValue(_env), &type, &arrayLength, &data, &inputBuffer, &byteOffset)); + *ptr = (uint8_t*)(data); + if (length) { + size_t bytesOfElement = 1; + switch (type) { + case JSVM_INT16_ARRAY: + case JSVM_UINT16_ARRAY: + bytesOfElement = 2; + break; + case JSVM_INT32_ARRAY: + case JSVM_UINT32_ARRAY: + case JSVM_FLOAT32_ARRAY: + bytesOfElement = 4; + break; + case JSVM_FLOAT64_ARRAY: + case JSVM_BIGINT64_ARRAY: + case JSVM_BIGUINT64_ARRAY: + bytesOfElement = 8; + break; + default: + break; + } + *length = arrayLength * bytesOfElement; + } + return true; +} + +bool Object::isArrayBuffer() const { + bool ret = false; + JSVM_Status status; + NODE_API_CALL(status, _env, OH_JSVM_IsArraybuffer(_env, _objRef.getValue(_env), &ret)); + return ret; +} + +bool Object::getArrayBufferData(uint8_t** ptr, size_t* length) const { + JSVM_Status status; + size_t len = 0; + NODE_API_CALL(status, _env, OH_JSVM_GetArraybufferInfo(_env, _objRef.getValue(_env), reinterpret_cast(ptr), &len)); + if (length) { + *length = len; + } + return true; +} + +Object* Object::createTypedArray(Object::TypedArrayType type, const void* data, size_t byteLength) { + JSVM_Status status; + if (type == TypedArrayType::NONE) { + SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!"); + return nullptr; + } + + JSVM_TypedarrayType jsvmType; + JSVM_Value outputBuffer; + void* outputPtr = nullptr; + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArraybuffer(ScriptEngine::getEnv(), byteLength, &outputPtr, &outputBuffer)); + if (outputPtr && data && byteLength > 0) { + memcpy(outputPtr, data, byteLength); + } + size_t sizeOfEle = 0; + switch (type) { + case TypedArrayType::INT8: + jsvmType = JSVM_INT8_ARRAY; + sizeOfEle = 1; + break; + case TypedArrayType::UINT8: + jsvmType = JSVM_UINT8_ARRAY; + sizeOfEle = 1; + break; + case TypedArrayType::UINT8_CLAMPED: + jsvmType = JSVM_UINT8_CLAMPED_ARRAY; + sizeOfEle = 1; + break; + case TypedArrayType::INT16: + jsvmType = JSVM_INT16_ARRAY; + sizeOfEle = 2; + break; + case TypedArrayType::UINT16: + jsvmType = JSVM_UINT16_ARRAY; + sizeOfEle = 2; + break; + case TypedArrayType::INT32: + jsvmType = JSVM_INT32_ARRAY; + sizeOfEle = 4; + break; + case TypedArrayType::UINT32: + jsvmType = JSVM_UINT32_ARRAY; + sizeOfEle = 4; + break; + case TypedArrayType::FLOAT32: + jsvmType = JSVM_FLOAT32_ARRAY; + sizeOfEle = 4; + break; + case TypedArrayType::FLOAT64: + jsvmType = JSVM_FLOAT64_ARRAY; + sizeOfEle = 8; + break; + case TypedArrayType::BIGINT64: + jsvmType = JSVM_BIGINT64_ARRAY; + sizeOfEle = 8; + break; + case TypedArrayType::BIGUINT64: + jsvmType = JSVM_BIGUINT64_ARRAY; + sizeOfEle = 8; + break; + default: + assert(false); // Should never go here. + break; + } + size_t eleCounts = byteLength / sizeOfEle; + JSVM_Value outputArray; + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateTypedarray(ScriptEngine::getEnv(), jsvmType, eleCounts, outputBuffer, 0, &outputArray)); + + Object* obj = Object::_createJSObject(ScriptEngine::getEnv(), outputArray, nullptr); + return obj; +} + +Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj) { + return Object::createTypedArrayWithBuffer(type, obj, 0); +} + +Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset) { + size_t byteLength{0}; + uint8_t *skip{nullptr}; + + if (obj->getArrayBufferData(&skip, &byteLength)) { + return Object::createTypedArrayWithBuffer(type, obj, offset, byteLength - offset); + } + + assert(false); + return nullptr; +} + +Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset, size_t byteLength) { + if (type == TypedArrayType::NONE) { + SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!"); + return nullptr; + } + + + assert(obj->isArrayBuffer()); + JSVM_Status status; + JSVM_Value outputBuffer = obj->_getJSObject(); + JSVM_TypedarrayType jsvmType; + + size_t sizeOfEle = 0; + switch (type) { + case TypedArrayType::INT8: + jsvmType = JSVM_INT8_ARRAY; + sizeOfEle = 1; + break; + case TypedArrayType::UINT8: + jsvmType = JSVM_UINT8_ARRAY; + sizeOfEle = 1; + break; + case TypedArrayType::INT16: + jsvmType = JSVM_INT8_ARRAY; + sizeOfEle = 2; + case TypedArrayType::UINT16: + jsvmType = JSVM_UINT8_ARRAY; + sizeOfEle = 2; + break; + case TypedArrayType::INT32: + jsvmType = JSVM_INT32_ARRAY; + sizeOfEle = 4; + case TypedArrayType::UINT32: + jsvmType = JSVM_UINT32_ARRAY; + sizeOfEle = 4; + case TypedArrayType::FLOAT32: + jsvmType = JSVM_FLOAT32_ARRAY; + sizeOfEle = 4; + break; + case TypedArrayType::FLOAT64: + jsvmType = JSVM_FLOAT64_ARRAY; + sizeOfEle = 8; + break; + case TypedArrayType::BIGINT64: + jsvmType = JSVM_BIGINT64_ARRAY; + sizeOfEle = 8; + break; + case TypedArrayType::BIGUINT64: + jsvmType = JSVM_BIGUINT64_ARRAY; + sizeOfEle = 8; + break; + default: + assert(false); // Should never go here. + break; + } + size_t eleCounts = byteLength / sizeOfEle; + JSVM_Value outputArray; + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateTypedarray(ScriptEngine::getEnv(), jsvmType, eleCounts, outputBuffer, offset, &outputArray)); + + return Object::_createJSObject(ScriptEngine::getEnv(), outputArray, nullptr); +} + +Object* Object::createExternalArrayBufferObject(void* contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void* freeUserData) { + JSVM_Status status; + JSVM_Value result; + if (freeFunc) { + struct ExternalArrayBufferCallbackParams* param = new (struct ExternalArrayBufferCallbackParams); + param->func = freeFunc; + param->contents = contents; + param->byteLength = byteLength; + param->userData = freeUserData; + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArraybuffer(ScriptEngine::getEnv(), byteLength, &contents, &result)); + param->func(param->contents, param->byteLength, param->userData); + delete param; + } else { + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArraybuffer(ScriptEngine::getEnv(), byteLength, &contents, &result)); + } + + Object* obj = Object::_createJSObject(ScriptEngine::getEnv(), result, nullptr); + return obj; +} + + +bool Object::isFunction() const { + JSVM_ValueType valuetype0; + JSVM_Status status; + NODE_API_CALL(status, _env, OH_JSVM_Typeof(_env, _objRef.getValue(_env), &valuetype0)); + return (valuetype0 == JSVM_ValueType::JSVM_FUNCTION); +} + +bool Object::defineFunction(const char* funcName, JSVM_Callback func) { + JSVM_Value fn; + JSVM_Status status; + NODE_API_CALL(status, _env, OH_JSVM_CreateFunction(_env, funcName, JSVM_AUTO_LENGTH, func, &fn)); + NODE_API_CALL(status, _env, OH_JSVM_SetNamedProperty(_env, _objRef.getValue(_env), funcName, fn)); + return true; +} + +bool Object::defineProperty(const char* name, JSVM_Callback getter, JSVM_Callback setter) { + JSVM_Status status; + JSVM_PropertyDescriptor properties[] = {{name, nullptr, nullptr, getter, setter, 0, JSVM_DEFAULT}}; + status = OH_JSVM_DefineProperties(_env, _objRef.getValue(_env), sizeof(properties) / sizeof(JSVM_PropertyDescriptor), properties); + if (status == JSVM_OK) { + return true; + } + return false; +} + +Object* Object::_createJSObject(JSVM_Env env, JSVM_Value js_object, Class* cls) { // NOLINT(readability-identifier-naming) + Object* ret = new Object(); + if (!ret->init(env, js_object, cls)) { + delete ret; + ret = nullptr; + } + return ret; +} + +Object* Object::createPlainObject() { + JSVM_Value result; + JSVM_Status status; + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateObject(ScriptEngine::getEnv(), &result)); + Object* obj = _createJSObject(ScriptEngine::getEnv(), result, nullptr); + return obj; +} + +Object* Object::createArrayObject(size_t length) { + JSVM_Value result; + JSVM_Status status; + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArrayWithLength(ScriptEngine::getEnv(), length, &result)); + Object* obj = _createJSObject(ScriptEngine::getEnv(), result, nullptr); + return obj; +} + +Object* Object::createArrayBufferObject(const void* data, size_t byteLength) { + JSVM_Value result; + JSVM_Status status; + void* retData; + Object* obj = nullptr; + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArraybuffer(ScriptEngine::getEnv(), byteLength, &retData, &result)); + if (status == JSVM_OK) { + if (data) { + memcpy(retData, data, byteLength); + } + obj = _createJSObject(ScriptEngine::getEnv(), result, nullptr); + } + return obj; +} + +bool Object::getAllKeys(std::vector* allKeys) const { + JSVM_Status status; + JSVM_Value names; + + NODE_API_CALL(status, _env, OH_JSVM_GetPropertyNames(_env, _objRef.getValue(_env), &names)); + if (status != JSVM_OK) { + return false; + } + uint32_t name_len = 0; + NODE_API_CALL(status, _env, OH_JSVM_GetArrayLength(_env, names, &name_len)); + for (uint32_t i = 0; i < name_len; i++) { + JSVM_Value val; + NODE_API_CALL(status, _env, OH_JSVM_GetElement(_env, names, i, &val)); + if (status == JSVM_OK) { + char buffer[MAX_STRING_LEN]; + size_t result = 0; + NODE_API_CALL(status, _env, OH_JSVM_GetValueStringUtf8(_env, val, buffer, MAX_STRING_LEN, &result)); + if (result > 0) { + allKeys->push_back(buffer); + } + } + } + + return true; +} + +bool Object::init(JSVM_Env env, JSVM_Value js_object, Class* cls) { + assert(env); + _cls = cls; + _env = env; + _objRef.initWeakref(env, js_object); + + if (__objectMap) { + assert(__objectMap->find(this) == __objectMap->end()); + __objectMap->emplace(this, nullptr); + } + return true; +} + +bool Object::call(const ValueArray& args, Object* thisObject, Value* rval) { + size_t argc = 0; + std::vector argv; + argv.reserve(10); + argc = args.size(); + internal::seToJsArgs(_env, args, &argv); + JSVM_Value return_val; + JSVM_Status status; + assert(isFunction()); + JSVM_Value thisObj = thisObject ? thisObject->_getJSObject() : ({ + JSVM_Value undefinedValue; + OH_JSVM_GetUndefined(_env, &undefinedValue); + undefinedValue; + }); + NODE_API_CALL(status, _env, + OH_JSVM_CallFunction(_env, thisObj, _getJSObject(), argc, argv.data(), &return_val)); + if (rval) { + internal::jsToSeValue(return_val, rval); + } + return true; +} + +void Object::_setFinalizeCallback(JSVM_Finalize finalizeCb) { + assert(finalizeCb != nullptr); + _finalizeCb = finalizeCb; +} + +// void Object::setPrivateData(void* data){ +// assert(_privateData == nullptr); +// assert(NativePtrToObjectMap::find(data) == NativePtrToObjectMap::end()); +// JSVM_Status status; +// NativePtrToObjectMap::emplace(data, this); +// _privateData = data; +// //issue https://github.com/nodejs/node/issues/23999 +// auto tmpThis = _objRef.getValue(_env); +// //_objRef.deleteRef(); +// NODE_API_CALL(status, _env, +// OH_JSVM_Wrap(_env, tmpThis, data, sendWeakCallback, +// (void*)this /* finalize_hint */, nullptr)); +// //_objRef.setWeakref(_env, result); +// setProperty("__native_ptr__", se::Value(static_cast(reinterpret_cast(data)))); +// } + +void* Object::getPrivateData() const{ + return _privateData; +} + +bool Object::attachObject(Object* obj) { + assert(obj); + + Object* global = ScriptEngine::getInstance()->getGlobalObject(); + Value jsbVal; + if (!global->getProperty("jsb", &jsbVal)) { + return false; + } + Object* jsbObj = jsbVal.toObject(); + + Value func; + + if (!jsbObj->getProperty("registerNativeRef", &func)) { + return false; + } + + ValueArray args; + args.push_back(Value(this)); + args.push_back(Value(obj)); + func.toObject()->call(args, global); + return true; +} + +bool Object::detachObject(Object* obj) { + assert(obj); + + Object* global = ScriptEngine::getInstance()->getGlobalObject(); + Value jsbVal; + if (!global->getProperty("jsb", &jsbVal)) { + return false; + } + Object* jsbObj = jsbVal.toObject(); + + Value func; + + if (!jsbObj->getProperty("unregisterNativeRef", &func)) { + return false; + } + + ValueArray args; + args.push_back(Value(this)); + args.push_back(Value(obj)); + func.toObject()->call(args, global); + return true; +} + +std::string Object::toString() const { + std::string ret; + JSVM_Status status; + if (isFunction() || isArray() || isTypedArray()) { + JSVM_Value result; + NODE_API_CALL(status, _env, OH_JSVM_CoerceToString(_env, _objRef.getValue(_env), &result)); + char buffer[MAX_STRING_LEN]; + size_t result_t = 0; + NODE_API_CALL(status, _env, OH_JSVM_GetValueStringUtf8(_env, result, buffer, MAX_STRING_LEN, &result_t)); + ret = buffer; + } else if (isArrayBuffer()) { + ret = "[object ArrayBuffer]"; + } else { + ret = "[object Object]"; + } + return ret; +} + +void Object::root() { + JSVM_Status status; + if (_rootCount == 0) { + uint32_t result = 0; + _objRef.incRef(_env); + } + ++_rootCount; +} + +void Object::unroot() { + JSVM_Status status; + if (_rootCount > 0) { + --_rootCount; + if (_rootCount == 0) { + _objRef.decRef(_env); + } + } +} + +bool Object::isRooted() const { + return _rootCount > 0; +} + +Class* Object::_getClass() const { + return _cls; +} + +Object* Object::getObjectWithPtr(void* ptr) { + Object* obj = nullptr; + auto iter = NativePtrToObjectMap::find(ptr); + if (iter != NativePtrToObjectMap::end()) { + obj = iter->second; + obj->incRef(); + } + return obj; +} + +JSVM_Value Object::_getJSObject() const { + return _objRef.getValue(_env); +} + +void Object::sendWeakCallback(JSVM_Env env, void* nativeObject, void* finalizeHint /*finalize_hint*/) { + auto cb = std::bind(weakCallback, env, nativeObject, finalizeHint); + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread(cb); +} + +void Object::weakCallback(JSVM_Env env, void* nativeObject, void* finalizeHint /*finalize_hint*/) { + if (finalizeHint) { + if (nativeObject == nullptr) { + return; + } + void *rawPtr = reinterpret_cast(finalizeHint)->_privateData; + Object* seObj = reinterpret_cast(finalizeHint); + Object* rawPtrObj = reinterpret_cast(rawPtr); + if(rawPtrObj->getRefCount() == 0) { + return; + } + if (seObj->_onCleaingPrivateData) { //called by cleanPrivateData, not release seObj; + return; + } + if (seObj->_clearMappingInFinalizer && rawPtr != nullptr) { + auto iter = NativePtrToObjectMap::find(rawPtr); + if (iter != NativePtrToObjectMap::end()) { + NativePtrToObjectMap::erase(iter); + } else { + SE_LOGE("not find ptr in NativePtrToObjectMap"); + } + } + + if (seObj->_finalizeCb != nullptr) { + seObj->_finalizeCb(env, rawPtr, rawPtr); + } else { + assert(seObj->_getClass() != nullptr); + if (seObj->_getClass()->_getFinalizeFunction() != nullptr) { + seObj->_getClass()->_getFinalizeFunction()(env, rawPtr, rawPtr); + } + } + seObj->decRef(); + } +} + +void Object::setup() { + __objectMap = std::make_unique>(); +} + +void Object::cleanup() { + void* nativeObj = nullptr; + Object* obj = nullptr; + Class* cls = nullptr; + + const auto& nativePtrToObjectMap = NativePtrToObjectMap::instance(); + for (const auto& e : nativePtrToObjectMap) { + nativeObj = e.first; + obj = e.second; + + if (obj->_finalizeCb != nullptr) { + obj->_finalizeCb(ScriptEngine::getEnv(), nativeObj, nullptr); + } else { + if (obj->_getClass() != nullptr) { + if (obj->_getClass()->_getFinalizeFunction() != nullptr) { + obj->_getClass()->_getFinalizeFunction()(ScriptEngine::getEnv(), nativeObj, nullptr); + } + } + } + obj->decRef(); + } + + NativePtrToObjectMap::clear(); + + if (__objectMap) { + for (const auto& e : *__objectMap) { + obj = e.first; + cls = obj->_getClass(); + obj->_rootCount = 0; + + } + } + + __objectMap.reset(); +} + +Object* Object::createJSONObject(const std::string& jsonStr) { + auto _env = ScriptEngine::getEnv(); + JSVM_Status status; + JSVM_Value global; + // 获取js全局对象 + NODE_API_CALL(status, _env, OH_JSVM_GetGlobal(_env, &global)); + assert(status == JSVM_OK); + + // 获取js对象中的JSON对象 + JSVM_Value globalJsonObj; + NODE_API_CALL(status, _env, OH_JSVM_GetNamedProperty(_env, global, "JSON", &globalJsonObj)); + + // 获取js对象中的parse方法 + JSVM_Value parseFunc; + NODE_API_CALL(status, _env, OH_JSVM_GetNamedProperty(_env, globalJsonObj, "parse", &parseFunc)); + + // 创建一个js的string,字符源于输入的std::string jsonStr + JSVM_Value jsJsonStr; + NODE_API_CALL(status, _env, OH_JSVM_CreateStringUtf8(_env, jsonStr.c_str(), jsonStr.length(), &jsJsonStr)); + + // 调用js中的JSON.parse将jsJsonStr转换成js对象 + JSVM_Value jsObj; + NODE_API_CALL(status, _env, OH_JSVM_CallFunction(_env, globalJsonObj, parseFunc, 1, &jsJsonStr ,&jsObj)); + + Object *obj = nullptr; + obj = Object::_createJSObject(_env, jsObj, nullptr); + return obj; +} + +Object *Object::createJSONObject(std::u16string &&jsonStr) { + auto _env = ScriptEngine::getEnv(); + JSVM_Status status; + JSVM_Value global; + // 获取js全局对象 + NODE_API_CALL(status, _env, OH_JSVM_GetGlobal(_env, &global)); + assert(status == JSVM_OK); + + // 获取js对象中的JSON对象 + JSVM_Value globalJsonObj; + NODE_API_CALL(status, _env, OH_JSVM_GetNamedProperty(_env, global, "JSON", &globalJsonObj)); + + // 获取js对象中的parse方法 + JSVM_Value parseFunc; + NODE_API_CALL(status, _env, OH_JSVM_GetNamedProperty(_env, globalJsonObj, "parse", &parseFunc)); + + // 创建一个js的string,字符源于输入的std::string jsonStr + JSVM_Value jsJsonStr; + NODE_API_CALL(status, _env, OH_JSVM_CreateStringUtf16(_env, jsonStr.c_str(), jsonStr.length(), &jsJsonStr)); + + // 调用js中的JSON.parse将jsJsonStr转换成js对象 + JSVM_Value jsObj; + NODE_API_CALL(status, _env, OH_JSVM_CallFunction(_env, globalJsonObj, parseFunc, 1, &jsJsonStr ,&jsObj)); + + Object *obj = nullptr; + obj = Object::_createJSObject(_env, jsObj, nullptr); + return obj; +} + +Object* Object::createProxyTarget(se::Object* proxy) { + // SE_ASSERT(proxy->isProxy(), "parameter is not a Proxy object"); + // v8::Local jsobj = proxy->getProxyTarget().As(); + // Object *obj = Object::_createJSObject(nullptr, jsobj); + // return obj; + return nullptr; +} + +void Object::clearPrivateData(bool clearMapping) { + if (_privateObject != nullptr) { + JSVM_Status status; + void* result = nullptr; + auto tmpThis = _objRef.getValue(_env); + _onCleaingPrivateData = true; + if (clearMapping) { + NativePtrToObjectMap::erase(_privateData); + } + NODE_API_CALL(status, _env, OH_JSVM_RemoveWrap(_env, tmpThis, &result)); + delete _privateObject; + _privateObject = nullptr; + _privateData = nullptr; + _onCleaingPrivateData = false; + } +} + +Object* Object::createUTF8String(const std::string& str) { + JSVM_Status status; + JSVM_Value result; + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateStringUtf8(ScriptEngine::getEnv(), str.c_str(), JSVM_AUTO_LENGTH, &result)); + Object* obj = _createJSObject(ScriptEngine::getEnv(), result, nullptr); + return obj; +} + +} // namespace se diff --git a/native/cocos/bindings/jswrapper/jsvm/Object.h b/native/cocos/bindings/jswrapper/jsvm/Object.h new file mode 100644 index 0000000000..c6238130d3 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/Object.h @@ -0,0 +1,505 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once +#include +#include "../RefCounter.h" +#include "../Value.h" +#include "../config.h" +#include "CommonHeader.h" +#include "HelperMacros.h" +#include "../PrivateObject.h" + +namespace se { +class Class; + namespace internal { + struct PrivateData; + } + +class ObjectRef { +private: + JSVM_Ref _ref = nullptr; + int _refCounts = 0; + JSVM_Env _env = nullptr; + JSVM_Value _obj = nullptr; + +public: + ~ObjectRef() { + deleteRef(); + } + JSVM_Value getValue(JSVM_Env env) const { + JSVM_Value result; + JSVM_Status status; + NODE_API_CALL(status, env, OH_JSVM_GetReferenceValue(env, _ref, &result)); + assert(status == JSVM_OK); + assert(result != nullptr); + return result; + } + void initWeakref(JSVM_Env env, JSVM_Value obj) { + assert(_ref == nullptr); + _obj = obj; + _env = env; + OH_JSVM_CreateReference(env, obj, 0, &_ref); + } + void setWeakref(JSVM_Env env, JSVM_Ref ref) { + assert(_ref == nullptr); + _ref = ref; + } + void initStrongRef(JSVM_Env env, JSVM_Value obj) { + assert(_ref == nullptr); + _refCounts = 1; + _obj = obj; + OH_JSVM_CreateReference(env, obj, _refCounts, &_ref); + _env = env; + } + void incRef(JSVM_Env env) { + assert(_refCounts == 0); + if (_refCounts == 0) { + uint32_t result = 0; + _refCounts = 1; + OH_JSVM_ReferenceRef(env, _ref, &result); + } + } + void decRef(JSVM_Env env) { + assert(_refCounts == 1); + uint32_t result = 0; + if (_refCounts > 0) { + _refCounts--; + if (_refCounts == 0) { + OH_JSVM_ReferenceUnref(env, _ref, &result); + } + } + } + void deleteRef() { + _refCounts = 0; + if (!_ref) { + return; + } + OH_JSVM_DeleteReference(_env, _ref); + _ref = nullptr; + } +}; + +class Object; + +class Object : public RefCounter { +public: + enum class TypedArrayType { + NONE, + INT8, + INT16, + INT32, + UINT8, + UINT8_CLAMPED, + UINT16, + UINT32, + FLOAT32, + FLOAT64, + BIGINT64, + BIGUINT64 + }; + + using BufferContentsFreeFunc = void (*)(void *contents, size_t byteLength, void *userData); + + struct ExternalArrayBufferCallbackParams { + BufferContentsFreeFunc func{nullptr}; + void *contents{nullptr}; + size_t byteLength{0}; + void *userData{0}; + }; + + Object(); + ~Object(); + /** + * @brief Sets a property to an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] value A value to be used as the property's value. + * @return true if the property is set successfully, otherwise false. + */ + bool setProperty(const char *name, const Value &data); + + inline bool setProperty(const std::string &name, const Value &value) { + return setProperty(name.c_str(), value); + } + + /** + * @brief Gets a property from an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[out] value The property's value if object has the property, otherwise the undefined value. + * @return true if object has the property, otherwise false. + */ + bool getProperty(const char *name, Value *data); + + inline bool getProperty(const char *name, Value *data, bool cachePropertyName) { + return getProperty(name, data); + } + + inline bool getProperty(const std::string &name, Value *value) { + return getProperty(name.c_str(), value); + } + + void setPrivateObject(PrivateObjectBase *data); + PrivateObjectBase *getPrivateObject() const; + + /** + * @brief Get the underlying private data as std::shared_ptr + * + * @tparam T + * @return std::shared_ptr + */ + template + inline std::shared_ptr getPrivateSharedPtr() const { + assert(_privateObject->isSharedPtr()); + return static_cast *>(_privateObject)->getData(); + } + + /** + * @brief Get the underlying private data as InstrusivePtr + * + * @tparam T + * @return cc::IntrusivePtr + */ + template + inline cc::IntrusivePtr getPrivateInstrusivePtr() const { + assert(_privateObject->isCCIntrusivePtr()); + return static_cast *>(_privateObject)->getData(); + } + + + /** + * @brief Delete a property of an object. + * @param[in] name A utf-8 string containing the property's name. + * @return true if the property is deleted successfully, otherwise false. + */ + bool deleteProperty(const char *name); + + /** + * @brief Gets an object's private data. + * @return A void* that is the object's private data, if the object has private data, otherwise nullptr. + */ + void* getPrivateData() const; + + /** + * @brief Sets a pointer to private data on an object. + * @param[in] data A void* to set as the object's private data. + * @note This method will associate private data with se::Object by ccstd::unordered_map::emplace. + * It's used for search a se::Object via a void* private data. + */ + template + inline void setPrivateData(T *data) { + static_assert(!std::is_void::value, "void * is not allowed for private data"); + setPrivateObject(se::make_shared_private_object(data)); + } + /** + * @brief Use a InstrusivePtr to hold private data on the se::Object. + * + * @tparam T + * @param data A intrusive pointer object + */ + template + inline void setPrivateData(const cc::IntrusivePtr &data) { + setPrivateObject(se::ccintrusive_ptr_private_object(data)); + } + + /** + * @brief Use a std::shared_ptr to hold private data on the se::Object. + * + * @tparam T + * @param data A shared_ptr object + */ + template + inline void setPrivateData(const std::shared_ptr &data) { + setPrivateObject(se::shared_ptr_private_object(data)); + } + + /** + * @brief Sets a pointer to private data on an object. + * @param[in] data A void* to set as the object's private data. + * @note This method will associate private data with se::Object by ccstd::unordered_map::emplace. + * It's used for search a se::Object via a void* private data. + */ + template + inline void setRawPrivateData(T *data, bool tryDestroyInGC = false) { + static_assert(!std::is_void::value, "void * is not allowed for private data"); + auto *privateObject = se::rawref_private_object(data); + if (tryDestroyInGC) { + privateObject->tryAllowDestroyInGC(); + } + setPrivateObject(privateObject); + } + + /** + * @brief Clears private data of an object. + * @param clearMapping Whether to clear the mapping of native object & se::Object. + */ + void clearPrivateData(bool clearMapping = true); + + + /** + * @brief Sets whether to clear the mapping of native object & se::Object in finalizer + */ + void setClearMappingInFinalizer(bool v) { _clearMappingInFinalizer = v; } + + /** + * @brief Tests whether an object is an array. + * @return true if object is an array, otherwise false. + */ + bool isArray() const; + + /** + * @brief Gets array length of an array object. + * @param[out] length The array length to be stored. It's set to 0 if there is an error. + * @return true if succeed, otherwise false. + */ + bool getArrayLength(uint32_t *length) const; + + /** + * @brief Gets an element from an array object by numeric index. + * @param[in] index An integer value for index. + * @param[out] data The se::Value to be stored for the element in certain index. + * @return true if succeed, otherwise false. + */ + bool getArrayElement(uint32_t index, Value *data) const; + + /** + * @brief Sets an element to an array object by numeric index. + * @param[in] index An integer value for index. + * @param[in] data The se::Value to be set to array with certain index. + * @return true if succeed, otherwise false. + */ + bool setArrayElement(uint32_t index, const Value &data); + + /** @brief Tests whether an object is a typed array. + * @return true if object is a typed array, otherwise false. + */ + bool isTypedArray() const; + + /** @brief Tests whether an object is a proxy object. + * @return true if object is a proxy object, otherwise false. + */ + bool isProxy() const; + + /** + * @brief Gets the type of a typed array object. + * @return The type of a typed array object. + */ + TypedArrayType getTypedArrayType() const; + + /** + * @brief Gets backing store of a typed array object. + * @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object. + * @param[out] length The byte length of a JavaScript Typed Array object. + * @return true if succeed, otherwise false. + */ + bool getTypedArrayData(uint8_t **ptr, size_t *length) const; + /** + * @brief Tests whether an object is an array buffer object. + * @return true if object is an array buffer object, otherwise false. + */ + bool isArrayBuffer() const; + + /** + * @brief Gets buffer data of an array buffer object. + * @param[out] ptr A pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object. + * @param[out] length The number of bytes in a JavaScript data object. + * @return true if succeed, otherwise false. + */ + bool getArrayBufferData(uint8_t **ptr, size_t *length) const; + + /** + * @brief Creates a JavaScript Typed Array Object with specified format from an existing pointer, + if provide a null pointer,then will create a empty JavaScript Typed Array Object. + * @param[in] type The format of typed array. + * @param[in] data A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *createTypedArray(TypedArrayType type, const void *data, size_t byteLength); + + static Object *createTypedArrayWithBuffer(TypedArrayType type, const Object *obj); + static Object *createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset); + static Object *createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset, size_t byteLength); + static Object *createExternalArrayBufferObject(void *contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void *freeUserData = nullptr); + + /** + * @brief Tests whether an object can be called as a function. + * @return true if object can be called as a function, otherwise false. + */ + bool isFunction() const; + + /** + * @brief Defines a function with a native callback for an object. + * @param[in] funcName A utf-8 string containing the function name. + * @param[in] func The native callback triggered by JavaScript code. + * @return true if succeed, otherwise false. + */ + bool defineFunction(const char *funcName, JSVM_Callback func); + + /** + * @brief Defines a property with native accessor callbacks for an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] getter The native callback for getter. + * @param[in] setter The native callback for setter. + * @return true if succeed, otherwise false. + */ + bool defineProperty(const char *name, JSVM_Callback getter, JSVM_Callback setter); + + bool attachObject(Object *obj); + + /** + * @brief Detaches an object from current object. + * @param[in] obj The object to be detached. + * @return true if succeed, otherwise false. + * @note The attached object will not be released if current object is not garbage collected. + */ + bool detachObject(Object *obj); + + /** + * @brief Calls an object as a function. + * @param[in] args A se::Value array of arguments to pass to the function. Pass se::EmptyValueArray if argumentCount is 0. + * @param[in] thisObject The object to use as "this," or NULL to use the global object as "this." + * @param[out] rval The se::Value that results from calling object as a function, passing nullptr if return value is ignored. + * @return true if object is a function and there isn't any errors, otherwise false. + */ + bool call(const ValueArray &args, Object *thisObject, Value *rval = nullptr); + + /** + * @brief Creates a JavaScript Native Binding Object from an existing se::Class instance. + * @param[in] cls The se::Class instance which stores native callback informations. + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *createObjectWithClass(Class *cls); + + static Object *_createJSObject(JSVM_Env env, JSVM_Value js_object, Class *cls); + + /** + * @brief Creates a JavaScript Object like `{} or new Object()`. + * @return A JavaScript Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *createPlainObject(); + + /** + * @brief Creates a JavaScript Array Object like `[] or new Array()`. + * @param[in] length The initical length of array. + * @return A JavaScript Array Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *createArrayObject(size_t length); + + /** + * @brief Creates a JavaScript Array Buffer object from an existing pointer. + * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *createArrayBufferObject(const void *data, size_t byteLength); + /** + * Gets the Proxy Target object + * @param proxy The JavaScript Proxy object. + * @return The target JavaScript object of the parameter. + */ + static Object *createProxyTarget(se::Object *proxy); + /** + * @brief Roots an object from garbage collection. + * @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it. + * An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ + void root(); + + /** + * @brief Unroots an object from garbage collection. + * @note An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ + void unroot(); + + /** + * @brief Tests whether an object is rooted. + * @return true if it has been already rooted, otherwise false. + */ + bool isRooted() const; + + /** + * @brief Creates a JavaScript Object from a JSON formatted string. + * @param[in] jsonStr The utf-8 string containing the JSON string to be parsed. + * @return A JavaScript Object containing the parsed value, or nullptr if the input is invalid. + * @note The return value (non-null) has to be released manually. + */ + static Object *createJSONObject(const std::string &jsonStr); + static Object *createJSONObject(std::u16string &&jsonStr); + /** + * @brief Gets all property names of an object. + * @param[out] allKeys A string vector to store all property names. + * @return true if succeed, otherwise false. + */ + bool getAllKeys(std::vector *allKeys) const; + + /** + * @brief Gets a se::Object from an existing native object pointer. + * @param[in] ptr The native object pointer associated with the se::Object + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *getObjectWithPtr(void *ptr); + + Class * _getClass() const; // NOLINT(readability-identifier-naming) + JSVM_Value _getJSObject() const; + void _setFinalizeCallback(JSVM_Finalize finalizeCb); // NOLINT(readability-identifier-naming) + /** + * @brief Returns the string for describing current object. + * @return The string for describing current object. + */ + std::string toString() const; + + bool init(JSVM_Env env, JSVM_Value js_object, Class *cls); + + static Object *createUTF8String(const std::string& str); + +private: +// Object(); +// virtual ~Object(); + static void sendWeakCallback(JSVM_Env env, void *nativeObject, void * /*finalize_hint*/); + static void weakCallback(JSVM_Env env, void *nativeObject, void * /*finalize_hint*/); + static void setup(); + static void cleanup(); + +private: + ObjectRef _objRef; + JSVM_Finalize _finalizeCb = nullptr; + bool _clearMappingInFinalizer = true; + void* _privateData = nullptr; + PrivateObjectBase *_privateObject = nullptr; + JSVM_Env _env = nullptr; + Class * _cls = nullptr; + uint32_t _rootCount = 0; + bool _onCleaingPrivateData = false; + internal::PrivateData* _internalData; + + friend class ScriptEngine; +}; +}; // namespace se \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp new file mode 100644 index 0000000000..f3447bcbaf --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp @@ -0,0 +1,500 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "ScriptEngine.h" +#include +#include "../MappingUtils.h" +#include "Class.h" +#include "State.h" +#include "Utils.h" +#include "CommonHeader.h" +#include "ark_runtime/jsvm.h" + +#define _EXPOSE_GC "__jsb_gc__" + +namespace se { +AutoHandleScope::AutoHandleScope() { + OH_JSVM_OpenHandleScope(ScriptEngine::getEnv(), &_handleScope); +} + +AutoHandleScope::~AutoHandleScope() { + OH_JSVM_CloseHandleScope(ScriptEngine::getEnv(), _handleScope); +} + +bool __forceGC(State &s) { + ScriptEngine::getInstance()->garbageCollect(); + return true; +} +SE_BIND_FUNC(__forceGC) + +se::Value __oldConsoleLog; +se::Value __oldConsoleDebug; +se::Value __oldConsoleInfo; +se::Value __oldConsoleWarn; +se::Value __oldConsoleError; +se::Value __oldConsoleAssert; + +bool JSB_console_format_log(State& s, const char* prefix, int msgIndex = 0) { + if (msgIndex < 0) + return false; + + const auto& args = s.args(); + int argc = (int)args.size(); + if ((argc - msgIndex) == 1) { + std::string msg = args[msgIndex].toStringForce(); + SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); + } else if (argc > 1) { + std::string msg = args[msgIndex].toStringForce(); + size_t pos; + for (int i = (msgIndex+1); i < argc; ++i) { + pos = msg.find("%"); + if (pos != std::string::npos && pos != (msg.length()-1) && + (msg[pos+1] == 'd' || msg[pos+1] == 's' || msg[pos+1] == 'f')) { + msg.replace(pos, 2, args[i].toStringForce()); + } else { + msg += " " + args[i].toStringForce(); + } + } + + SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); + } + return true; +} + +bool JSB_console_log(State& s) { + JSB_console_format_log(s, ""); + __oldConsoleLog.toObject()->call(s.args(), s.thisObject()); + return true; +} + +SE_BIND_FUNC(JSB_console_log) + +bool JSB_console_debug(State& s) { + JSB_console_format_log(s, "[DEBUG]: "); + __oldConsoleDebug.toObject()->call(s.args(), s.thisObject()); + return true; +} + +SE_BIND_FUNC(JSB_console_debug) + +bool JSB_console_info(State& s) { + JSB_console_format_log(s, "[INFO]: "); + __oldConsoleInfo.toObject()->call(s.args(), s.thisObject()); + return true; +} + +SE_BIND_FUNC(JSB_console_info) + +bool JSB_console_warn(State& s) { + JSB_console_format_log(s, "[WARN]: "); + __oldConsoleWarn.toObject()->call(s.args(), s.thisObject()); + return true; +} + +SE_BIND_FUNC(JSB_console_warn) + +bool JSB_console_error(State& s) { + JSB_console_format_log(s, "[ERROR]: "); + __oldConsoleError.toObject()->call(s.args(), s.thisObject()); + return true; +} + +SE_BIND_FUNC(JSB_console_error) + +bool JSB_console_assert(State& s) { + const auto& args = s.args(); + if (!args.empty()) { + if (args[0].isBoolean() && !args[0].toBoolean()) { + JSB_console_format_log(s, "[ASSERT]: ", 1); + __oldConsoleAssert.toObject()->call(s.args(), s.thisObject()); + } + } + return true; +} + +SE_BIND_FUNC(JSB_console_assert) + +ScriptEngine *gSriptEngineInstance = nullptr; + +ScriptEngine::ScriptEngine() { OH_JSVM_Init(nullptr); }; + +ScriptEngine::~ScriptEngine() = default; + +void ScriptEngine::setFileOperationDelegate(const FileOperationDelegate &delegate) { + _fileOperationDelegate = delegate; +} + +const ScriptEngine::FileOperationDelegate &ScriptEngine::getFileOperationDelegate() const { + return _fileOperationDelegate; +} + +ScriptEngine *ScriptEngine::getInstance() { + if (gSriptEngineInstance == nullptr) { + gSriptEngineInstance = new ScriptEngine(); + } + + return gSriptEngineInstance; +} + +void ScriptEngine::destroyInstance() { + if (gSriptEngineInstance) { + gSriptEngineInstance->cleanup(); + delete gSriptEngineInstance; + gSriptEngineInstance = nullptr; + } +} + +bool ScriptEngine::runScript(const std::string &path, Value *ret /* = nullptr */) { + assert(!path.empty()); + assert(_fileOperationDelegate.isValid()); + + std::string scriptBuffer = _fileOperationDelegate.onGetStringFromFile(path); + + if (!scriptBuffer.empty()) { + return evalString(scriptBuffer.c_str(), scriptBuffer.length(), ret, path.c_str()); + } + + SE_LOGE("ScriptEngine::runScript script %s, buffer is empty!\n", path.c_str()); + return false; +} + +bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, const char *fileName) { + length = length < 0 ? strlen(scriptStr) :length; + JSVM_Status status; + JSVM_Value jsvmStr; + NODE_API_CALL(status, _env, OH_JSVM_CreateStringUtf8(_env, scriptStr, length, &jsvmStr)); + if(status != JSVM_OK) { + SE_LOGE("ScriptEngine::evalString, create string failed, fileName = %{public}s", fileName); + return false; + } + + uint8_t *cachedData = nullptr; + size_t cacheLength = 0; + + bool cacheRejected = false; + JSVM_Script compiledScript; + JSVM_ScriptOrigin scriptOrigin{ + .sourceMapUrl = nullptr, + .resourceName = fileName, + .resourceLineOffset = 0, + .resourceColumnOffset = 0 + }; + + NODE_API_CALL(status, _env, + OH_JSVM_CompileScriptWithOrigin(_env, jsvmStr, cachedData, cacheLength, false, &cacheRejected,&scriptOrigin, &compiledScript)); + + if(status != JSVM_OK) { + SE_LOGE("ScriptEngine::evalSting, compile failed, fileName = %{public}s", fileName); + return false; + } + + JSVM_Value result; + NODE_API_CALL(status, _env, OH_JSVM_RunScript(_env, compiledScript, &result)); + if(status != JSVM_OK) { + SE_LOGE("ScriptEngine::evelSting, run failed, fileName = %{public}s", fileName); + return false; + } + + if(!cachedData || cacheRejected) { + NODE_API_CALL(status, _env, + OH_JSVM_CreateCodeCache(_env, compiledScript, (const uint8_t **)&cachedData, &cacheLength)); + } + + if(ret) { + internal::jsToSeValue(result, ret); + } + + return true; +} + +bool ScriptEngine::init() { + JSVM_Status status; + JSVM_Value result; + + for (const auto &hook : _beforeInitHookArray) { + hook(); + } + + NODE_API_CALL(status, _env, OH_JSVM_CreateVM(nullptr, &_vm)); + NODE_API_CALL(status, _env, OH_JSVM_OpenVMScope(_vm, &_vmScope)); + NODE_API_CALL(status, _env, OH_JSVM_CreateEnv(_vm, 0, nullptr, &_env)); + NODE_API_CALL(status, _env, OH_JSVM_OpenEnvScope(_env, &_envScope)); + + se::AutoHandleScope hs; + + Object::setup(); + NativePtrToObjectMap::init(); + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_GetGlobal(ScriptEngine::getEnv(), &result)); + _globalObj = Object::_createJSObject(ScriptEngine::getEnv(), result, nullptr); + _globalObj->root(); + _globalObj->setProperty("window", Value(_globalObj)); + _globalObj->setProperty("scriptEngineType", se::Value("jsvm")); + + se::Value consoleVal; + if (_globalObj->getProperty("console", &consoleVal) && consoleVal.isObject()) { + consoleVal.toObject()->getProperty("log", &__oldConsoleLog); + consoleVal.toObject()->defineFunction("log", _SE(JSB_console_log)); + + consoleVal.toObject()->getProperty("debug", &__oldConsoleDebug); + consoleVal.toObject()->defineFunction("debug", _SE(JSB_console_debug)); + + consoleVal.toObject()->getProperty("info", &__oldConsoleInfo); + consoleVal.toObject()->defineFunction("info", _SE(JSB_console_info)); + + consoleVal.toObject()->getProperty("warn", &__oldConsoleWarn); + consoleVal.toObject()->defineFunction("warn", _SE(JSB_console_warn)); + + consoleVal.toObject()->getProperty("error", &__oldConsoleError); + consoleVal.toObject()->defineFunction("error", _SE(JSB_console_error)); + + consoleVal.toObject()->getProperty("assert", &__oldConsoleAssert); + consoleVal.toObject()->defineFunction("assert", _SE(JSB_console_assert)); + } + + _globalObj->defineFunction("log", _SE(JSB_console_log)); + _globalObj->defineFunction("forceGC", _SE(__forceGC)); + + _globalObj->getProperty(_EXPOSE_GC, &_gcFuncValue); + if(_gcFuncValue.isObject() && _gcFuncValue.toObject()->isFunction()) { + _gcFunc = _gcFuncValue.toObject(); + } else { + _gcFunc = nullptr; + } + + _isValid = true; + + for (const auto &hook : _afterInitHookArray) { + hook(); + } + _afterInitHookArray.clear(); + + return _isValid; +} + +Object *ScriptEngine::getGlobalObject() const { return _globalObj; } + +bool ScriptEngine::start() { + bool ok = true; + if (!init()) { + return false; + } + se::AutoHandleScope hs; + + _startTime = std::chrono::steady_clock::now(); + for (auto cb : _permRegisterCallbackArray) { + ok = cb(_globalObj); + assert(ok); + if (!ok) { + break; + } + } + + for (auto cb : _registerCallbackArray) { + ok = cb(_globalObj); + assert(ok); + if (!ok) { + break; + } + } + + // After ScriptEngine is started, _registerCallbackArray isn't needed. Therefore, clear it here. + _registerCallbackArray.clear(); + + return ok; +} + +void ScriptEngine::cleanup() { + if (!_isValid) { + return; + } + + SE_LOGD("ScriptEngine::cleanup begin ...\n"); + _isInCleanup = true; + + do{ + se::AutoHandleScope hs; + for (const auto &hook : _beforeCleanupHookArray) { + hook(); + } + _beforeCleanupHookArray.clear(); + }while (0); + + + SAFE_DEC_REF(_globalObj); + Object::cleanup(); + Class::cleanup(); + garbageCollect(); + + JSVM_Status status; + NODE_API_CALL(status, _env, OH_JSVM_CloseEnvScope(_env, _envScope)); + + NODE_API_CALL(status, _env, OH_JSVM_DestroyEnv(_env)); + NODE_API_CALL(status, _env, OH_JSVM_CloseVMScope(_vm, _vmScope)); + NODE_API_CALL(status, _env, OH_JSVM_DestroyVM(_vm)); + _envScope = nullptr; + _env = nullptr; + _vmScope = nullptr; + _vm = nullptr; + + _globalObj = nullptr; + _isValid = false; + + _registerCallbackArray.clear(); + + for (const auto &hook : _afterCleanupHookArray) { + hook(); + } + _afterCleanupHookArray.clear(); + + _isInCleanup = false; + NativePtrToObjectMap::destroy(); + SE_LOGD("ScriptEngine::cleanup end ...\n"); +} + +void ScriptEngine::addBeforeCleanupHook(const std::function &hook) { + _beforeCleanupHookArray.push_back(hook); + return; +} + +void ScriptEngine::addBeforeInitHook(const std::function &hook) { + _beforeInitHookArray.push_back(hook); +} + +void ScriptEngine::addAfterCleanupHook(const std::function &hook) { + _afterCleanupHookArray.push_back(hook); + return; +} + +void ScriptEngine::addRegisterCallback(RegisterCallback cb) { + assert(std::find(_registerCallbackArray.begin(), _registerCallbackArray.end(), cb) == _registerCallbackArray.end()); + _registerCallbackArray.push_back(cb); +} + +JSVM_Env ScriptEngine::getEnv() { return getInstance()->_env; } + +void ScriptEngine::setEnv(JSVM_Env env) { getInstance()->_env = env; } + +void ScriptEngine::addPermanentRegisterCallback(RegisterCallback cb) { + if (std::find(_permRegisterCallbackArray.begin(), _permRegisterCallbackArray.end(), cb) == _permRegisterCallbackArray.end()) { + _permRegisterCallbackArray.push_back(cb); + } +} + +void ScriptEngine::setExceptionCallback(const ExceptionCallback &cb) { + //not impl + return; +} + +const std::chrono::steady_clock::time_point &ScriptEngine::getStartTime() const { return _startTime; } + +bool ScriptEngine::isValid() const { return _isValid; } + +void ScriptEngine::enableDebugger(const std::string &serverAddr, uint32_t port, bool isWait) { + //not impl + return; +} + +bool ScriptEngine::saveByteCodeToFile(const std::string &path, const std::string &pathBc) { + //not impl + return true; +} + +void ScriptEngine::clearException() { + //not impl + return; +} + +void ScriptEngine::garbageCollect() { + SE_LOGD("GC begin ..., (js->native map) size: %{public}d",(int)NativePtrToObjectMap::size()); + + if(_gcFunc == nullptr) { + JSVM_Status status; + NODE_API_CALL(status, _env, OH_JSVM_MemoryPressureNotification(_env, JSVM_MEMORY_PRESSURE_LEVEL_CRITICAL)); + } else { + _gcFunc->call({}, nullptr); + } + + SE_LOGD("GC end ..., (js->native map) size: %{public}d",(int)NativePtrToObjectMap::size()); +} + +bool ScriptEngine::isGarbageCollecting() const { + return _isGarbageCollecting; +} + +void ScriptEngine::_setGarbageCollecting(bool isGarbageCollecting) { //NOLINT(readability-identifier-naming) + _isGarbageCollecting = isGarbageCollecting; +} + +void ScriptEngine::setJSExceptionCallback(const ExceptionCallback &cb) { + //not impl + return; +} + +void ScriptEngine::addAfterInitHook(const std::function &hook) { + _afterInitHookArray.push_back(hook); + return; +} + +std::string ScriptEngine::getCurrentStackTrace() { + //not impl + return ""; +} + +void ScriptEngine::_setNeedCallConstructor(bool need) { _isneedCallConstructor = need; } + +bool ScriptEngine::_needCallConstructor() { return _isneedCallConstructor; } + +bool ScriptEngine::callFunction(Object *targetObj, const char *funcName, uint32_t argc, Value *args, Value *rval) { + Value objFunc; + if (!targetObj->getProperty(funcName, &objFunc)) { + return false; + } + + ValueArray argv; + + for (size_t i = 0; i < argc; ++i) { + argv.push_back(args[i]); + } + + objFunc.toObject()->call(argv, targetObj, rval); + + return true; +} + +void ScriptEngine::handlePromiseExceptions() { + //not impl + assert(true); + return; +} + +void ScriptEngine::mainLoopUpdate() { + // empty implementation +} + +void ScriptEngine::throwException(const std::string &errorMessage) { + JSVM_Status status; + NODE_API_CALL_RETURN_VOID(getEnv(), OH_JSVM_ThrowError(getEnv(), nullptr, errorMessage.c_str())); +} +}; // namespace se diff --git a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h new file mode 100644 index 0000000000..16e87966fa --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h @@ -0,0 +1,313 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include +#include "../Value.h" +#include "../config.h" +#include "CommonHeader.h" + +using HandleScope = JSVM_HandleScope; +namespace se { +class AutoHandleScope { +public: + // This interface needs to be implemented in JSVM, similar to V8. + // Ref:https://nodejs.org/docs/latest-v17.x/api/n-api.html#object-lifetime-management + AutoHandleScope(); + ~AutoHandleScope(); + +private: + HandleScope _handleScope; +}; +using RegisterCallback = bool (*)(Object *); +using ExceptionCallback = std::function; // location, message, stack + +class ScriptEngine { +public: + /** + * Delegate class for file operation + */ + class FileOperationDelegate { + public: + FileOperationDelegate() + : onGetDataFromFile(nullptr), + onGetStringFromFile(nullptr), + onCheckFileExist(nullptr), + onGetFullPath(nullptr) {} + + /** + * @brief Tests whether delegate is valid. + */ + bool isValid() const { + return onGetDataFromFile != nullptr && onGetStringFromFile != nullptr && onCheckFileExist != nullptr && onGetFullPath != nullptr; + } + + // path, buffer, buffer size + std::function &)> onGetDataFromFile; + // path, return file string content. + std::function onGetStringFromFile; + // path + std::function onCheckFileExist; + // path, return full path + std::function onGetFullPath; + }; + ScriptEngine(); + ~ScriptEngine(); + /** + * @brief Sets the delegate for file operation. + * @param delegate[in] The delegate instance for file operation. + */ + void setFileOperationDelegate(const FileOperationDelegate &delegate); + + /** + * @brief Compile script file into v8::ScriptCompiler::CachedData and save to file. + * @param[in] path The path of script file. + * @param[in] pathBc The location where bytecode file should be written to. The path should be ends with ".bc", which indicates a bytecode file. + * @return true if succeed, otherwise false. + */ + bool saveByteCodeToFile(const std::string &path, const std::string &pathBc); + + /** + * @brief Gets the delegate for file operation. + * @return The delegate for file operation + */ + const FileOperationDelegate &getFileOperationDelegate() const; + + static ScriptEngine *getInstance(); + + /** + * @brief Destroys the instance of script engine. + */ + static void destroyInstance(); + + /** + * @brief Clears all exceptions. + */ + void clearException(); + + /** + * @brief Sets the callback function while an exception is fired in JS. + * @param[in] cb The callback function to notify that an exception is fired. + */ + void setJSExceptionCallback(const ExceptionCallback &cb); + + /** + * @brief Sets the callback function while an exception is fired. + * @param[in] cb The callback function to notify that an exception is fired. + */ + void setExceptionCallback(const ExceptionCallback &cb); + + /** + * @brief Grab a snapshot of the current JavaScript execution stack. + * @return current stack trace string + */ + std::string getCurrentStackTrace(); + /** + * @brief Executes a utf-8 string buffer which contains JavaScript code. + * @param[in] script A utf-8 string buffer, if it isn't null-terminated, parameter `length` should be assigned and > 0. + * @param[in] length The length of parameter `scriptStr`, it will be set to string length internally if passing < 0 and parameter `scriptStr` is null-terminated. + * @param[in] ret The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. + * @param[in] fileName A string containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information. + * @return true if succeed, otherwise false. + */ + bool evalString(const char *script, ssize_t length = -1, Value *ret = nullptr, const char *fileName = nullptr); + + /** + * @brief Adds a callback for registering a native binding module, which will not be removed by ScriptEngine::cleanup. + * @param[in] cb A callback for registering a native binding module. + * @note This method just add a callback to a vector, callbacks is invoked in `start` method. + */ + void addPermanentRegisterCallback(RegisterCallback cb); + + /** + * @brief Starts the script engine. + * @return true if succeed, otherwise false. + * @note This method will invoke all callbacks of native binding modules by the order of registration. + */ + bool start(); + + /** + * @brief Initializes script engine. + * @return true if succeed, otherwise false. + * @note This method will create JavaScript context and global object. + */ + bool init(); + + /** + * @brief Adds a hook function before initializing script engine. + * @param[in] hook A hook function to be invoked before initializing script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ + void addBeforeInitHook(const std::function &hook); + + /** + * @brief Adds a hook function after initializing script engine. + * @param[in] hook A hook function to be invoked before initializing script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ + void addAfterInitHook(const std::function &hook); + + /** + * @brief Cleanups script engine. + * @note This method will removes all objects in JavaScript VM even whose are rooted, then shutdown JavaScript VMf. + */ + void cleanup(); + + /** + * @brief Adds a hook function before cleanuping script engine. + * @param[in] hook A hook function to be invoked before cleanuping script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ + void addBeforeCleanupHook(const std::function &hook); + + /** + * @brief Adds a hook function after cleanuping script engine. + * @param[in] hook A hook function to be invoked after cleanuping script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ + void addAfterCleanupHook(const std::function &hook); + /** + * @brief Gets the global object of JavaScript VM. + * @return The se::Object stores the global JavaScript object. + */ + Object *getGlobalObject() const; + + static JSVM_Env getEnv(); + static void setEnv(JSVM_Env env); + + /** + * @brief Adds a callback for registering a native binding module. + * @param[in] cb A callback for registering a native binding module. + * @note This method just add a callback to a vector, callbacks is invoked in `start` method. + */ + void addRegisterCallback(RegisterCallback cb); + + const std::chrono::steady_clock::time_point &getStartTime() const; + + /** + * @brief Tests whether script engine is doing garbage collection. + * @return true if it's in garbage collection, otherwise false. + */ + bool isGarbageCollecting() const; + + /** + * @brief Performs a JavaScript garbage collection. + */ + void garbageCollect(); + + /** + * @brief Tests whether script engine is being cleaned up. + * @return true if it's in cleaning up, otherwise false. + */ + bool isInCleanup() const { return _isInCleanup; } + /** + * @brief Executes a file which contains JavaScript code. + * @param[in] path Script file path. + * @param[in] ret The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. + * @return true if succeed, otherwise false. + */ + bool runScript(const std::string &path, Value *ret = nullptr); + + /** + * @brief Tests whether script engine is valid. + * @return true if it's valid, otherwise false. + */ + bool isValid() const; + + /** + * @brief Enables JavaScript debugger + * @param[in] serverAddr The address of debugger server. + * @param[in] isWait Whether wait debugger attach when loading. + */ + void enableDebugger(const std::string &serverAddr, uint32_t port, bool isWait = false); + + /** + * @brief Tests whether JavaScript debugger is enabled + * @return true if JavaScript debugger is enabled, otherwise false. + */ + bool isDebuggerEnabled() const; + + /** + * @brief Main loop update trigger, it's need to invoked in main thread every frame. + */ + void mainLoopUpdate(); + + bool runByteCodeFile(const std::string &pathBc, Value *ret /* = nullptr */); + + /** + * @brief Throw JS exception + */ + void throwException(const std::string &errorMessage); + + /** + * @brief for jsvm_new_instance, skip constructor. + */ + void _setNeedCallConstructor(bool need); + + /** + * @brief for jsvm_new_instance, skip constructor. + */ + bool _needCallConstructor(); + + /** + * @brief Fast version of call script function, faster than Object::call + */ + bool callFunction(Object *targetObj, const char *funcName, uint32_t argc, Value *args, Value *rval = nullptr); + + void _setGarbageCollecting(bool isGarbageCollecting); // NOLINT(readability-identifier-naming) + + void handlePromiseExceptions(); + +private: + FileOperationDelegate _fileOperationDelegate; + std::vector _registerCallbackArray; + std::vector _permRegisterCallbackArray; + + std::vector> _beforeInitHookArray; + std::vector> _afterInitHookArray; + std::vector> _beforeCleanupHookArray; + std::vector> _afterCleanupHookArray; + + Object * _globalObj = nullptr; + Value _gcFuncValue; + Object *_gcFunc{nullptr}; + + JSVM_Env _env = nullptr; + JSVM_VM _vm = nullptr; + JSVM_VMScope _vmScope = nullptr; + JSVM_EnvScope _envScope = nullptr; + + bool _isValid{false}; + bool _isGarbageCollecting{false}; + bool _isInCleanup{false}; + bool _isErrorHandleWorking{false}; + bool _isneedCallConstructor{true}; + std::chrono::steady_clock::time_point _startTime; + + JSVM_HandleScope _handleScope; +}; +}; // namespace se diff --git a/native/cocos/bindings/jswrapper/jsvm/SeApi.h b/native/cocos/bindings/jswrapper/jsvm/SeApi.h new file mode 100644 index 0000000000..639abd485a --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/SeApi.h @@ -0,0 +1,32 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "Class.h" +#include "HelperMacros.h" +#include "Object.h" +#include "ScriptEngine.h" +#include "Utils.h" \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/jsvm/Utils.cpp b/native/cocos/bindings/jswrapper/jsvm/Utils.cpp new file mode 100644 index 0000000000..7d3381ecde --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/Utils.cpp @@ -0,0 +1,198 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "Utils.h" +#include "CommonHeader.h" +#include "ScriptEngine.h" +#include "Class.h" + +#define MAX_STRING_LENS 1024 + +namespace se { +namespace internal { +void jsToSeValue(const target_value& value, Value* v) { + assert(v != nullptr); + auto env = ScriptEngine::getEnv(); + JSVM_Status status; + JSVM_ValueType valType; + int64_t iRet = 0; + double dRet = 0.0; + bool bRet = false; + bool lossless = false; + size_t len = 0; + void* privateObjPtr = nullptr; + void* nativePtr = nullptr; + Object* obj = nullptr; + + if (!value) { + valType = JSVM_ValueType::JSVM_UNDEFINED; + }else { + NODE_API_CALL(status, env, OH_JSVM_Typeof(env, value, &valType)); + } + + switch (valType) { + case JSVM_ValueType::JSVM_UNDEFINED: + v->setUndefined(); + break; + case JSVM_ValueType::JSVM_NULL: + v->setNull(); + break; + case JSVM_ValueType::JSVM_NUMBER: + NODE_API_CALL(status, env, OH_JSVM_GetValueDouble(env, value, &dRet)); + if (status == JSVM_OK) { + v->setDouble(dRet); + } else { + v->setUndefined(); + } + break; + case JSVM_ValueType::JSVM_BIGINT: + NODE_API_CALL(status, env, OH_JSVM_GetValueBigintInt64(env, value, &iRet, &lossless)); + if (lossless) { + v->setInt64(iRet); + } else { + v->setUndefined(); + } + + break; + case JSVM_ValueType::JSVM_STRING: + NODE_API_CALL(status, env, OH_JSVM_GetValueStringUtf8(env, value, nullptr, 0, &len)); + if (status == JSVM_OK) { + std::string valueStr; + len += 1; + valueStr.resize(len); + NODE_API_CALL(status, env, OH_JSVM_GetValueStringUtf8(env, value, const_cast(valueStr.data()), valueStr.size(), &len)); + if (valueStr.length() != len) { + valueStr.resize(len); + } + v->setString(valueStr); + } else { + v->setUndefined(); + } + break; + case JSVM_ValueType::JSVM_BOOLEAN: + NODE_API_CALL(status, env, OH_JSVM_GetValueBool(env, value, &bRet)); + if (status == JSVM_OK) { + v->setBoolean(bRet); + } else { + v->setUndefined(); + } + break; + case JSVM_ValueType::JSVM_OBJECT: + case JSVM_ValueType::JSVM_FUNCTION: + status = OH_JSVM_Unwrap(env, value, &privateObjPtr); + if (status == JSVM_OK && privateObjPtr) { + nativePtr = reinterpret_cast(privateObjPtr)->getPrivateData(); + } + if(nativePtr) { + obj = Object::getObjectWithPtr(nativePtr); + } + if (obj == nullptr) { + obj = Object::_createJSObject(env, value, nullptr); + } + if (obj) { + v->setObject(obj, true); + obj->decRef(); + } else { + v->setUndefined(); + } + break; + default: + break; + } +} + +void jsToSeArgs(size_t argc, target_value* argv, ValueArray* outArr) { + assert(outArr != nullptr); + for (int i = 0; i < argc; i++) { + Value v; + jsToSeValue(argv[i], &v); + outArr->push_back(v); + } +} + +bool seToJsValue(const Value& v, target_value* outJsVal) { + assert(outJsVal != nullptr); + auto env = ScriptEngine::getEnv(); + bool ret = false; + JSVM_Status status = JSVM_OK; + switch (v.getType()) { + case Value::Type::Number: + NODE_API_CALL(status, env, OH_JSVM_CreateDouble(env, v.toDouble(), outJsVal)); + ret = (status == JSVM_OK); + break; + case Value::Type::String: + NODE_API_CALL(status, env, OH_JSVM_CreateStringUtf8(env, v.toString().c_str(), v.toString().length(), outJsVal)); + ret = (status == JSVM_OK); + break; + case Value::Type::Boolean: + NODE_API_CALL(status, env, OH_JSVM_GetBoolean(env, v.toBoolean(), outJsVal)); + ret = (status == JSVM_OK); + break; + case Value::Type::Object: + *outJsVal = v.toObject()->_getJSObject(); + ret = (outJsVal != nullptr); + break; + case Value::Type::Null: + NODE_API_CALL(status, env, OH_JSVM_GetNull(env, outJsVal)); + ret = (status == JSVM_OK); + break; + case Value::Type::Undefined: + NODE_API_CALL(status, env, OH_JSVM_GetUndefined(env, outJsVal)); + ret = (status == JSVM_OK); + break; + case Value::Type::BigInt: + NODE_API_CALL(status, env, OH_JSVM_CreateBigintInt64(env, v.toInt64(), outJsVal)); + ret = (status == JSVM_OK); + break; + default: + assert(false); + break; + } + //LOGI("type :%d", v.getType()); + return ret; +} + +void seToJsArgs(JSVM_Env env, const ValueArray& args, std::vector* outArr) { + assert(outArr != nullptr); + for (const auto& data : args) { + JSVM_Value jsval; + seToJsValue(data, &jsval); + outArr->push_back(jsval); + } +} + +bool setReturnValue(const Value& data, target_value& argv) { + if (data.getType() == Value::Type::BigInt) { + // TODO: fix 'TypeError: Cannot mix BigInt and other types, use explicit conversions' for spine & dragonbones + auto env = ScriptEngine::getEnv(); + JSVM_Status status; + NODE_API_CALL(status, env, OH_JSVM_CreateDouble(env, data.toDouble(), &argv)); + return true; + } + + return seToJsValue(data, &argv); +} +} // namespace internal +}; // namespace se diff --git a/native/cocos/bindings/jswrapper/jsvm/Utils.h b/native/cocos/bindings/jswrapper/jsvm/Utils.h new file mode 100644 index 0000000000..2f6925f022 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm/Utils.h @@ -0,0 +1,46 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "../config.h" +#include "Object.h" +namespace se { + +namespace internal { + +using target_value = JSVM_Value; +struct PrivateData { + void * data; + Object *seObj; +}; + +bool setReturnValue(const Value &data, target_value &argv); +void jsToSeValue(const target_value &value, Value *v); +void jsToSeArgs(size_t argc, target_value *argv, ValueArray *outArr); +bool seToJsValue(const Value &v, target_value *jsval); +void seToJsArgs(JSVM_Env env, const ValueArray &args, std::vector *outArr); +} // namespace internal +} // namespace se diff --git a/native/cocos/bindings/jswrapper/napi/Object.cpp b/native/cocos/bindings/jswrapper/napi/Object.cpp index 3977838fa2..732d140357 100644 --- a/native/cocos/bindings/jswrapper/napi/Object.cpp +++ b/native/cocos/bindings/jswrapper/napi/Object.cpp @@ -287,6 +287,7 @@ Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object* ob return nullptr; } + CC_ASSERT(obj->isArrayBuffer()); napi_status status; napi_value outputBuffer = obj->_getJSObject(); @@ -660,16 +661,12 @@ void Object::weakCallback(napi_env env, void* nativeObject, void* finalizeHint / } } - // TODO: remove test code before releasing. - const char* clsName = seObj->_getClass()->getName(); - CC_LOG_INFO("weakCallback class name:%s, ptr:%p", clsName, rawPtr); - if (seObj->_finalizeCb != nullptr) { - seObj->_finalizeCb(env, nativeObject, finalizeHint); + seObj->_finalizeCb(env, rawPtr, rawPtr); } else { assert(seObj->_getClass() != nullptr); if (seObj->_getClass()->_getFinalizeFunction() != nullptr) { - seObj->_getClass()->_getFinalizeFunction()(env, nativeObject, finalizeHint); + seObj->_getClass()->_getFinalizeFunction()(env, rawPtr, rawPtr); } } seObj->decRef(); diff --git a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp index 7ac9b71aaa..b7ccaa0e1e 100644 --- a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp @@ -240,7 +240,7 @@ public: // https://github.com/cocos/cocos-engine/issues/13342 flags.append(" --no-turbo-escape"); - #if (CC_PLATFORM == CC_PLATFORM_IOS) + #if (CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY) flags.append(" --jitless"); #endif if (!flags.empty()) { diff --git a/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp b/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp new file mode 100644 index 0000000000..8d8e253afb --- /dev/null +++ b/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2013-2016 Chukong Technologies Inc. + * Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "cocos/bindings/manual/JavaScriptArkTsBridge.h" +#include +#include "bundle/native_interface_bundle.h" +#include "cocos/platform/openharmony/napi/NapiHelper.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/bindings/manual/jsb_conversions.h" + +#define JSA_ERR_OK (0) +#define JSA_ERR_TYPE_NOT_SUPPORT (-1) +#define JSA_ERR_INVALID_SIGNATURES (-2) +#define JSA_ERR_METHOD_NOT_FOUND (-3) +#define JSA_ERR_EXCEPTION_OCCURRED (-4) +#define JSA_ERR_VM_THREAD_DETACHED (-5) +#define JSA_ERR_VM_FAILURE (-6) +#define JSA_ERR_CLASS_NOT_FOUND (-7) + +class JavaScriptArkTsBridge { +public: + class CallInfo { + public: + CallInfo(bool isSyn, const char* clsPath, const char* methodName, const char* paramStr) + : _error(JSA_ERR_OK), _isSyn(isSyn), _clsPath(clsPath), _methodName(methodName), _paramStr(paramStr) { + } + ~CallInfo(); + + int getErrorCode() const { return _error; } + + bool execute(se::Value& rval); + + private: + int _error{0}; + bool _isSyn{false}; + const char* _clsPath{nullptr}; + const char* _methodName{nullptr}; + const char* _paramStr{nullptr}; + }; + +public: + static char* __getModuleInfo(const char* module_name); + static char* bundle_name; +}; + +char* JavaScriptArkTsBridge::bundle_name = nullptr; + +JavaScriptArkTsBridge::CallInfo::~CallInfo() {} + +char* JavaScriptArkTsBridge::__getModuleInfo(const char* module_name) { + if (bundle_name == NULL) { + OH_NativeBundle_ApplicationInfo info = OH_NativeBundle_GetCurrentApplicationInfo(); + bundle_name = info.bundleName; + } + + char* module_info = (char*)malloc((strlen(bundle_name) + strlen(module_name) + 1) * sizeof(char*)); + strcpy(module_info, ""); + strcat(module_info, bundle_name); + strcat(module_info, "/"); + strcat(module_info, module_name); + + return module_info; +} + +se::Value convertToSeValue(const cc::CallbackParamType& value) { + return std::visit([](auto&& arg) -> se::Value { + return se::Value(arg); + }, value); +} + +bool JavaScriptArkTsBridge::CallInfo::execute(se::Value& rval) { + const char* module_name; + const char* method; + + std::string methodStr = _methodName; + std::string::size_type pos = methodStr.find("/"); + if (pos != std::string::npos) { + std::string str1 = methodStr.substr(0, pos); + module_name = str1.c_str(); + std::string str2 = methodStr.substr(pos + 1); + method = str2.c_str(); + } else { + method = _methodName; + std::string pathStr = _clsPath; + pos = pathStr.find("/"); + module_name = pos != std::string::npos ? pathStr.substr(0, pos).c_str() : "entry"; + } + + auto env = cc::NapiHelper::getWorkerEnv(); + + napi_status status; + napi_value result; + char* module_info = __getModuleInfo(module_name); + status = napi_load_module_with_info(env, _clsPath, module_info, &result); + free(module_info); + module_info = nullptr; + if (status != napi_ok) { + CC_LOG_WARNING("callNativeMethod napi_load_module_with_info fail, status=%{public}d", status); + return false; + } + + napi_value func; + status = napi_get_named_property(env, result, method, &func); + if (status != napi_ok) { + CC_LOG_WARNING("callNativeMethod napi_get_named_property fail, status=%{public}d", status); + return false; + } + + if (_isSyn) { + napi_value jsArg = Napi::String::New(env, _paramStr); + napi_value return_val; + status = napi_call_function(env, result, func, 1, &jsArg, &return_val); + if (status != napi_ok) { + CC_LOG_WARNING("callNativeMethod napi_call_function fail, status=%{public}d", status); + return false; + } + + napi_valuetype valueType; + status = napi_typeof(env, return_val, &valueType); + if (status != napi_ok) { + CC_LOG_WARNING("callNativeMethod napi_typeof fail, status=%{public}d", status); + return false; + } + + switch (valueType) { + case napi_string: { + size_t str_size; + napi_get_value_string_utf8(env, return_val, nullptr, 0, &str_size); + char* buf = new char[str_size + 1]; + napi_get_value_string_utf8(env, return_val, buf, str_size + 1, &str_size); + rval = se::Value(std::string(buf)); + delete[] buf; + break; + } + case napi_number: { + double num_value; + napi_get_value_double(env, return_val, &num_value); + CC_LOG_INFO("Returned number: %f", num_value); + rval = se::Value(num_value); + break; + } + case napi_boolean: { + bool bool_value; + napi_get_value_bool(env, return_val, &bool_value); + rval = se::Value(bool_value); + break; + } + default: + CC_LOG_WARNING("Unhandled return value type"); + break; + } + return true; + } + + std::promise promise; + std::function cb = [&promise](cc::CallbackParamType message) { + promise.set_value(message); + }; + cc::AsyncCallParam* callParam = new cc::AsyncCallParam{cb, _paramStr, func}; + cc::JSFunction::getFunction("executeNativeMethod").invokeAsync(callParam); + cc::CallbackParamType methodResult = promise.get_future().get(); + rval = se::Value(convertToSeValue(methodResult)); + return true; +} + +se::Class* __jsb_JavaScriptArkTsBridge_class = nullptr; + +static bool JavaScriptArkTsBridge_finalize(se::State& s) { + JavaScriptArkTsBridge* cobj = (JavaScriptArkTsBridge*)s.nativeThisObject(); + delete cobj; + return true; +} +SE_BIND_FINALIZE_FUNC(JavaScriptArkTsBridge_finalize) + +static bool JavaScriptArkTsBridge_constructor(se::State& s) { + JavaScriptArkTsBridge* cobj = new (std::nothrow) JavaScriptArkTsBridge(); + s.thisObject()->setPrivateData(cobj); + return true; +} +SE_BIND_CTOR(JavaScriptArkTsBridge_constructor, __jsb_JavaScriptArkTsBridge_class, JavaScriptArkTsBridge_finalize) + +static bool JavaScriptArkTsBridge_callStaticMethod(se::State& s) { + const auto& args = s.args(); + int argc = (int)args.size(); + + if (argc == 4) { + bool ok = false; + bool isSyn; + std::string clsPath, methodName, paramStr; + + isSyn = seval_to_type(args[0], ok); + SE_PRECONDITION2(ok, false, "Converting isSyn failed!"); + + clsPath = seval_to_type(args[1], ok); + SE_PRECONDITION2(ok, false, "Converting clsPath failed!"); + + methodName = seval_to_type(args[2], ok); + SE_PRECONDITION2(ok, false, "Converting methodName failed!"); + + paramStr = seval_to_type(args[3], ok); + SE_PRECONDITION2(ok, false, "Converting paramStr failed!"); + + JavaScriptArkTsBridge::CallInfo call(isSyn, clsPath.c_str(), methodName.c_str(), paramStr.c_str()); + ok = call.execute(s.rval()); + if (!ok) { + s.rval().setUndefined(); + SE_REPORT_ERROR("call (%s.%s) failed, result code: %d", clsPath.c_str(), methodName.c_str(), + call.getErrorCode()); + return false; + } + } else { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting ==4", argc); + return false; + } + return true; +} +SE_BIND_FUNC(JavaScriptArkTsBridge_callStaticMethod) + +bool register_javascript_arkTs_bridge(se::Object* obj) { + se::Class* cls = se::Class::create("JavaScriptArkTsBridge", obj, nullptr, _SE(JavaScriptArkTsBridge_constructor)); + cls->defineFinalizeFunction(_SE(JavaScriptArkTsBridge_finalize)); + + cls->defineFunction("callStaticMethod", _SE(JavaScriptArkTsBridge_callStaticMethod)); + + cls->install(); + __jsb_JavaScriptArkTsBridge_class = cls; + + se::ScriptEngine::getInstance()->clearException(); + + return true; +} diff --git a/native/cocos/bindings/manual/JavaScriptArkTsBridge.h b/native/cocos/bindings/manual/JavaScriptArkTsBridge.h new file mode 100644 index 0000000000..5d80d08ca9 --- /dev/null +++ b/native/cocos/bindings/manual/JavaScriptArkTsBridge.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2013-2016 Chukong Technologies Inc. + * Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#pragma once + +namespace se { + class Object; +} + +bool register_javascript_arkTs_bridge(se::Object* obj); \ No newline at end of file diff --git a/native/cocos/bindings/manual/jsb_cocos_manual.cpp b/native/cocos/bindings/manual/jsb_cocos_manual.cpp index ec38981e78..21b8116f78 100644 --- a/native/cocos/bindings/manual/jsb_cocos_manual.cpp +++ b/native/cocos/bindings/manual/jsb_cocos_manual.cpp @@ -738,19 +738,21 @@ static bool js_readFile_doJob(const ccstd::string &fullPath, typename ReadFileDo return false; } - // TODO(cjh): OpenHarmony NAPI support -#if SCRIPT_ENGINE_TYPE != SCRIPT_ENGINE_NAPI + if constexpr (std::is_same_v && isJson) { +// TODO(cjh): OpenHarmony NAPI support +#if SCRIPT_ENGINE_TYPE != SCRIPT_ENGINE_NAPI auto u16str = std::make_shared(); if (!cc::StringUtils::UTF8ToUTF16(*content, *u16str)) { CC_LOG_ERROR("UTF8ToUTF16 failed, file: %s", fullPath.c_str()); return false; } outValue = u16str; +#endif } else { outValue = content; } -#endif + return true; } diff --git a/native/cocos/bindings/manual/jsb_module_register.cpp b/native/cocos/bindings/manual/jsb_module_register.cpp index 6ca0b06713..63237ec6ce 100644 --- a/native/cocos/bindings/manual/jsb_module_register.cpp +++ b/native/cocos/bindings/manual/jsb_module_register.cpp @@ -80,6 +80,10 @@ #include "cocos/bindings/manual/JavaScriptJavaBridge.h" #endif +#if (CC_PLATFORM == CC_PLATFORM_OPENHARMONY) + #include "cocos/bindings/manual/JavaScriptArkTsBridge.h" +#endif + #if(CC_PLATFORM == CC_PLATFORM_OPENHARMONY) #if CC_USE_WEBVIEW #include "cocos/bindings/auto/jsb_webview_auto.h" @@ -167,6 +171,10 @@ bool jsb_register_all_modules() { se->addRegisterCallback(register_script_native_bridge); #endif +#if (CC_PLATFORM == CC_PLATFORM_OPENHARMONY) + se->addRegisterCallback(register_javascript_arkTs_bridge); +#endif + #if CC_USE_AUDIO se->addRegisterCallback(register_all_audio); se->addRegisterCallback(register_all_audio_manual); diff --git a/native/cocos/bindings/manual/jsb_platform.h b/native/cocos/bindings/manual/jsb_platform.h index 189b1218a6..4df49e8cab 100644 --- a/native/cocos/bindings/manual/jsb_platform.h +++ b/native/cocos/bindings/manual/jsb_platform.h @@ -26,9 +26,17 @@ #include "base/std/container/string.h" #include "base/std/container/unordered_map.h" +#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY +#include +#include +#endif namespace se { class Object; } bool register_platform_bindings(se::Object *obj); // NOLINT[readability-identifier-naming] const ccstd::unordered_map &getFontFamilyNameMap(); +#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY +const std::string defaultFontKey = "openharmony_system_font"; +const std::unordered_map& getFontFamilyCollectionMap(); +#endif diff --git a/native/cocos/bindings/manual/jsb_platform_openharmony.cpp b/native/cocos/bindings/manual/jsb_platform_openharmony.cpp index 9dc9431a4b..fcf2032e94 100644 --- a/native/cocos/bindings/manual/jsb_platform_openharmony.cpp +++ b/native/cocos/bindings/manual/jsb_platform_openharmony.cpp @@ -29,10 +29,18 @@ #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/bindings/manual/jsb_global_init.h" #include "cocos/platform/FileUtils.h" - +#include +#include #include using namespace cc; +static std::unordered_map _fontCollectionMap = { + { defaultFontKey, OH_Drawing_CreateSharedFontCollection() } +}; + +const std::unordered_map& getFontFamilyCollectionMap() { + return _fontCollectionMap; +} static std::unordered_map _fontFamilyNameMap; @@ -41,8 +49,50 @@ const std::unordered_map &getFontFamilyNameMap() { } static bool JSB_loadFont(se::State &s) { - // TODO(qgh):Currently it does not support loading OpenHarmony fonts, it may be supported in the future - return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc >= 1) { + s.rval().setNull(); + + std::string fontFamily; + ok &= seval_to_std_string(args[0], &fontFamily); + SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: fontFamily"); + + std::string source; + ok &= seval_to_std_string(args[1], &source); + SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source"); + + std::string fontFilePath; + std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); + std::match_results results; + if (std::regex_search(source.cbegin(), source.cend(), results, re)) + { + fontFilePath = results[1].str(); + } + + fontFilePath = FileUtils::getInstance()->fullPathForFilename(fontFilePath); + if (fontFilePath.empty()) + { + SE_LOGE("Font (%s) doesn't exist!", fontFilePath.c_str()); + return true; + } + + OH_Drawing_FontCollection *_fontCollection = OH_Drawing_CreateSharedFontCollection(); + Data bufferData = FileUtils::getInstance()->getDataFromFile(fontFilePath); + if (bufferData.isNull()) { + SE_LOGE("bufferData read error (%s)!", fontFilePath.c_str()); + return true; + } + OH_Drawing_RegisterFontBuffer(_fontCollection, fontFamily.c_str(), bufferData.getBytes(), bufferData.getSize()); + _fontCollectionMap.emplace(fontFamily, _fontCollection); + s.rval().setString(fontFamily); + + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; } SE_BIND_FUNC(JSB_loadFont) diff --git a/native/cocos/core/DataView.h b/native/cocos/core/DataView.h index 1b3414bcc6..8ddad6686a 100644 --- a/native/cocos/core/DataView.h +++ b/native/cocos/core/DataView.h @@ -27,6 +27,7 @@ #include "base/Macros.h" #include "base/std/variant.h" #include "core/ArrayBuffer.h" +#include "base/std/container/unordered_map.h" namespace cc { diff --git a/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp index ae056834e2..c9d0763322 100644 --- a/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp +++ b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp @@ -29,20 +29,20 @@ #include #include -#include -#include -#include +#include #include #include -#include +#include +#include #include +#include -#include "base/memory/Memory.h" #include "base/Log.h" +#include "base/memory/Memory.h" namespace cc { -NativeResourceManager* FileUtilsOpenHarmony::_nativeResourceManager = nullptr; +NativeResourceManager *FileUtilsOpenHarmony::_nativeResourceManager = nullptr; FileUtils *createFileUtils() { return ccnew FileUtilsOpenHarmony(); @@ -59,7 +59,7 @@ bool FileUtilsOpenHarmony::initResourceManager(napi_env env, napi_value param) { return true; } -FileUtils::Status FileUtilsOpenHarmony::getRawFileDescriptor(const std::string &filename,RawFileDescriptor& descriptor) { +FileUtils::Status FileUtilsOpenHarmony::getRawFileDescriptor(const std::string &filename, RawFileDescriptor64 &descriptor) { if (filename.empty()) { return FileUtils::Status::NOT_EXISTS; } @@ -74,19 +74,19 @@ FileUtils::Status FileUtilsOpenHarmony::getRawFileDescriptor(const std::string & return FileUtils::Status::NOT_INITIALIZED; } - RawFile *rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, fullPath.c_str()); + RawFile64 *rawFile = OH_ResourceManager_OpenRawFile64(_nativeResourceManager, fullPath.c_str()); if (nullptr == rawFile) { return FileUtils::Status::OPEN_FAILED; } - bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor); + bool result = OH_ResourceManager_GetRawFileDescriptor64(rawFile, &descriptor); if (!result) { - OH_ResourceManager_CloseRawFile(rawFile); + OH_ResourceManager_CloseRawFile64(rawFile); return FileUtils::Status::OPEN_FAILED; } - OH_ResourceManager_CloseRawFile(rawFile); - return FileUtils::Status::OK; + OH_ResourceManager_CloseRawFile64(rawFile); + return FileUtils::Status::OK; } FileUtils::Status FileUtilsOpenHarmony::getContents(const std::string &filename, ResizableBuffer *buffer) { @@ -108,31 +108,31 @@ FileUtils::Status FileUtilsOpenHarmony::getContents(const std::string &filename, return FileUtils::Status::NOT_INITIALIZED; } - RawFile *rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, fullPath.c_str()); + RawFile64 *rawFile = OH_ResourceManager_OpenRawFile64(_nativeResourceManager, fullPath.c_str()); if (nullptr == rawFile) { return FileUtils::Status::OPEN_FAILED; } - auto size = OH_ResourceManager_GetRawFileSize(rawFile); + int64_t size = OH_ResourceManager_GetRawFileSize64(rawFile); buffer->resize(size); assert(buffer->buffer()); - int readsize = OH_ResourceManager_ReadRawFile(rawFile, buffer->buffer(), size); + int64_t readsize = OH_ResourceManager_ReadRawFile64(rawFile, buffer->buffer(), size); // TODO(unknown): read error if (readsize < size) { if (readsize >= 0) { buffer->resize(readsize); } - OH_ResourceManager_CloseRawFile(rawFile); + OH_ResourceManager_CloseRawFile64(rawFile); return FileUtils::Status::READ_FAILED; } - OH_ResourceManager_CloseRawFile(rawFile); + OH_ResourceManager_CloseRawFile64(rawFile); return FileUtils::Status::OK; } FileUtilsOpenHarmony::~FileUtilsOpenHarmony() { - if(_nativeResourceManager) + if (_nativeResourceManager) OH_ResourceManager_ReleaseNativeResourceManager(_nativeResourceManager); } @@ -166,10 +166,10 @@ long FileUtilsOpenHarmony::getFileSize(const std::string &filepath) { } long filesize = 0; - RawFile* rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, fullPath.c_str()); - if(rawFile) { - filesize = OH_ResourceManager_GetRawFileSize(rawFile); - OH_ResourceManager_CloseRawFile(rawFile); + RawFile64 *rawFile = OH_ResourceManager_OpenRawFile64(_nativeResourceManager, fullPath.c_str()); + if (rawFile) { + filesize = OH_ResourceManager_GetRawFileSize64(rawFile); + OH_ResourceManager_CloseRawFile64(rawFile); } return filesize; } @@ -192,9 +192,9 @@ bool FileUtilsOpenHarmony::isFileExistInternal(const std::string &strFilePath) c return false; } - RawFile* rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, strPath.c_str()); - if(rawFile) { - OH_ResourceManager_CloseRawFile(rawFile); + RawFile64 *rawFile = OH_ResourceManager_OpenRawFile64(_nativeResourceManager, strPath.c_str()); + if (rawFile) { + OH_ResourceManager_CloseRawFile64(rawFile); return true; } return false; @@ -212,14 +212,14 @@ bool FileUtilsOpenHarmony::isDirectoryExistInternal(const std::string &dirPath) if (dirPathMf.find(_defaultResRootPath) == 0) { dirPathMf = dirPathMf.substr(_defaultResRootPath.length(), dirPathMf.length()); } - + if (nullptr == _nativeResourceManager) { CC_LOG_ERROR("nativeResourceManager is nullptr"); return false; } - RawDir* rawDir = OH_ResourceManager_OpenRawDir(_nativeResourceManager, dirPathMf.c_str()); - if(rawDir) { + RawDir *rawDir = OH_ResourceManager_OpenRawDir(_nativeResourceManager, dirPathMf.c_str()); + if (rawDir) { OH_ResourceManager_CloseRawDir(rawDir); return true; } @@ -249,7 +249,7 @@ bool FileUtilsOpenHarmony::removeDirectory(const std::string &dirPath) { return false; } struct dirent *dir{nullptr}; - struct stat st; + struct stat st; while ((dir = readdir(directory)) != NULL) { if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) { continue; @@ -278,4 +278,4 @@ bool FileUtilsOpenHarmony::removeDirectory(const std::string &dirPath) { return true; } -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/platform/openharmony/FileUtils-OpenHarmony.h b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.h index 54dc84b228..f1f713b2bc 100644 --- a/native/cocos/platform/openharmony/FileUtils-OpenHarmony.h +++ b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.h @@ -26,10 +26,10 @@ //clang-format off #include //clang-format on +#include #include #include #include -#include #include "base/Macros.h" #include "platform/FileUtils.h" @@ -39,7 +39,7 @@ namespace cc { class CC_DLL FileUtilsOpenHarmony : public FileUtils { public: FileUtilsOpenHarmony(); - ~FileUtilsOpenHarmony() override; + ~FileUtilsOpenHarmony() override; static bool initResourceManager(napi_env env, napi_value info); bool init() override; @@ -47,25 +47,26 @@ public: bool isAbsolutePath(const std::string &strPath) const override; std::string getWritablePath() const override; - + long getFileSize(const std::string &filepath) override; std::string getSuitableFOpen(const std::string &filenameUtf8) const override; FileUtils::Status getContents(const std::string &filename, ResizableBuffer *buffer) override; - - FileUtils::Status getRawFileDescriptor(const std::string &filename,RawFileDescriptor& descriptor); + + FileUtils::Status getRawFileDescriptor(const std::string &filename, RawFileDescriptor64 &descriptor); bool renameFile(const std::string &oldfullpath, const std::string &newfullpath) override; bool removeFile(const std::string &filepath) override; bool removeDirectory(const std::string &dirPath) override; static std::string _ohWritablePath; + private: bool isFileExistInternal(const std::string &strFilePath) const override; bool isDirectoryExistInternal(const std::string &dirPath) const override; - static NativeResourceManager* _nativeResourceManager; + static NativeResourceManager *_nativeResourceManager; }; } // namespace cc diff --git a/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp b/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp index 41a7c2093e..79867b7c54 100644 --- a/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp +++ b/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp @@ -69,6 +69,42 @@ void onSurfaceCreatedCB(OH_NativeXComponent* component, void* window) { windowMgr->createWindow(info); } +void onSurfaceHideCB(OH_NativeXComponent* component, void* window) { + int32_t ret; + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize); + if(ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + return; + } + sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_HIDE, component, window); +} + +void onSurfaceShowCB(OH_NativeXComponent* component, void* window) { + int32_t ret; + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize); + if(ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + return; + } + sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_SHOW, component, window); +} + + +cc::TouchEvent::Type touchTypeTransform(OH_NativeXComponent_TouchEventType touchType) { + if (touchType == OH_NATIVEXCOMPONENT_DOWN) { + return cc::TouchEvent::Type::BEGAN; + } else if (touchType == OH_NATIVEXCOMPONENT_MOVE) { + return cc::TouchEvent::Type::MOVED; + } else if (touchType == OH_NATIVEXCOMPONENT_UP) { + return cc::TouchEvent::Type::ENDED; + } else if (touchType == OH_NATIVEXCOMPONENT_CANCEL) { + return cc::TouchEvent::Type::CANCELLED; + } + return cc::TouchEvent::Type::UNKNOWN; +} + void dispatchTouchEventCB(OH_NativeXComponent* component, void* window) { OH_NativeXComponent_TouchEvent touchEvent; int32_t ret = OH_NativeXComponent_GetTouchEvent(component, window, &touchEvent); @@ -153,6 +189,8 @@ int32_t OpenHarmonyPlatform::run(int argc, const char** argv) { void OpenHarmonyPlatform::setNativeXComponent(OH_NativeXComponent* component) { _component = component; OH_NativeXComponent_RegisterCallback(_component, &_callback); + OH_NativeXComponent_RegisterSurfaceHideCallback(_component, onSurfaceHideCB); + OH_NativeXComponent_RegisterSurfaceShowCallback(_component, onSurfaceShowCB); } void OpenHarmonyPlatform::enqueue(const WorkerMessageData& msg) { @@ -200,6 +238,14 @@ void OpenHarmonyPlatform::onMessageCallback(const uv_async_t* /* req */) { OH_NativeXComponent* nativexcomponet = reinterpret_cast(msgData.data); CC_ASSERT(nativexcomponet != nullptr); platform->onSurfaceChanged(nativexcomponet, msgData.window); + } else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_SHOW) { + OH_NativeXComponent* nativexcomponet = reinterpret_cast(msgData.data); + CC_ASSERT(nativexcomponet != nullptr); + platform->onSurfaceShow(msgData.window); + } else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_HIDE) { + OH_NativeXComponent* nativexcomponet = reinterpret_cast(msgData.data); + CC_ASSERT(nativexcomponet != nullptr); + platform->onSurfaceHide(); } else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_DESTROY) { CC_LOG_INFO("onMessageCallback WM_XCOMPONENT_SURFACE_DESTROY ..."); OH_NativeXComponent* nativexcomponet = reinterpret_cast(msgData.data); @@ -221,8 +267,6 @@ void OpenHarmonyPlatform::onMessageCallback(const uv_async_t* /* req */) { if (msgData.type == MessageType::WM_VSYNC) { platform->runTask(); } - // CC_ASSERT(false); - //} } } @@ -234,6 +278,10 @@ void OpenHarmonyPlatform::onShowNative() { ev.type = WindowEvent::Type::SHOW; ev.windowId = cc::ISystemWindow::mainWindowId; events::WindowEvent::broadcast(ev); + onResume(); + if (_timerInited) { + uv_timer_start(&_timerHandle, &OpenHarmonyPlatform::timerCb, 0, 1); + } } void OpenHarmonyPlatform::onHideNative() { @@ -241,33 +289,40 @@ void OpenHarmonyPlatform::onHideNative() { ev.type = WindowEvent::Type::HIDDEN; ev.windowId = cc::ISystemWindow::mainWindowId; events::WindowEvent::broadcast(ev); + onPause(); + if (_timerInited) { + uv_timer_stop(&_timerHandle); + } } void OpenHarmonyPlatform::onDestroyNative() { onDestroy(); + if (_timerInited) { + uv_timer_stop(&_timerHandle); + } } void OpenHarmonyPlatform::timerCb(uv_timer_t* handle) { OpenHarmonyPlatform::getInstance()->runTask(); } +void OpenHarmonyPlatform::restartJSVM() { + g_started = false; +} + void OpenHarmonyPlatform::workerInit(uv_loop_t* loop) { _workerLoop = loop; if (_workerLoop) { + uv_timer_init(_workerLoop, &_timerHandle); + _timerInited = true; uv_async_init(_workerLoop, &_messageSignal, reinterpret_cast(OpenHarmonyPlatform::onMessageCallback)); - } + if (!_messageQueue.empty()) { + triggerMessageSignal(); // trigger the signal to handle the pending message + } + } } void OpenHarmonyPlatform::requestVSync() { - //CC_LOG_ERROR("OpenHarmonyPlatform::requestVSync1"); - //OH_NativeVSync_RequestFrame(OpenHarmonyPlatform::getInstance()->_nativeVSync, OnVSync, nullptr); - if (_workerLoop) { - // // Todo: Starting the timer in this way is inaccurate and will be fixed later. - uv_timer_init(_workerLoop, &_timerHandle); - // The tick function needs to be called as quickly as possible because it is controlling the frame rate inside the engine. - uv_timer_start(&_timerHandle, &OpenHarmonyPlatform::timerCb, 0, 1); - } - //CC_LOG_ERROR("OpenHarmonyPlatform::requestVSync2"); } int32_t OpenHarmonyPlatform::loop() { @@ -296,6 +351,15 @@ void OpenHarmonyPlatform::onSurfaceDestroyed(OH_NativeXComponent* component, voi windowMgr->removeWindow(window); } +void OpenHarmonyPlatform::onSurfaceHide() { + +} + +void OpenHarmonyPlatform::onSurfaceShow(void* window) { + +} + + ISystemWindow* OpenHarmonyPlatform::createNativeWindow(uint32_t windowId, void* externalHandle) { SystemWindow* window = ccnew SystemWindow(windowId, externalHandle); uint64_t width = 0; diff --git a/native/cocos/platform/openharmony/OpenHarmonyPlatform.h b/native/cocos/platform/openharmony/OpenHarmonyPlatform.h index 64eed20802..691f10cb94 100644 --- a/native/cocos/platform/openharmony/OpenHarmonyPlatform.h +++ b/native/cocos/platform/openharmony/OpenHarmonyPlatform.h @@ -48,15 +48,18 @@ public: void onHideNative(); void onDestroyNative(); + void restartJSVM(); void workerInit(uv_loop_t* loop); void setNativeXComponent(OH_NativeXComponent* component); int32_t run(int argc, const char** argv) override; + void resume(); + void pause(); int32_t loop() override; void requestVSync(); - + void enqueue(const WorkerMessageData& data); bool dequeue(WorkerMessageData* data); @@ -67,7 +70,9 @@ public: void onSurfaceCreated(OH_NativeXComponent* component, void* window); void onSurfaceChanged(OH_NativeXComponent* component, void* window); void onSurfaceDestroyed(OH_NativeXComponent* component, void* window); - + void onSurfaceHide(); + void onSurfaceShow(void* window); + static void onMessageCallback(const uv_async_t* req); static void timerCb(uv_timer_t* handle); @@ -76,6 +81,9 @@ public: uv_timer_t _timerHandle; uv_loop_t* _workerLoop{nullptr}; uv_async_t _messageSignal{}; + bool _timerInited{false}; WorkerMessageQueue _messageQueue; + //game started + bool g_started = false; }; -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/platform/openharmony/WorkerMessageQueue.h b/native/cocos/platform/openharmony/WorkerMessageQueue.h index ec0743e131..867383e323 100644 --- a/native/cocos/platform/openharmony/WorkerMessageQueue.h +++ b/native/cocos/platform/openharmony/WorkerMessageQueue.h @@ -37,6 +37,8 @@ enum class MessageType { WM_XCOMPONENT_SURFACE_CREATED = 0, WM_XCOMPONENT_TOUCH_EVENT, WM_XCOMPONENT_SURFACE_CHANGED, + WM_XCOMPONENT_SURFACE_HIDE, + WM_XCOMPONENT_SURFACE_SHOW, WM_XCOMPONENT_SURFACE_DESTROY, WM_APP_SHOW, WM_APP_HIDE, diff --git a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp index fa86339f5f..58b73a02a4 100644 --- a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp +++ b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp @@ -64,10 +64,6 @@ CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { _typographyStyle = nullptr; } - if(_fontCollection) { - OH_Drawing_DestroyFontCollection(_fontCollection); - } - if(_typographyCreate) { OH_Drawing_DestroyTypographyHandler(_typographyCreate); _typographyCreate = nullptr; @@ -200,13 +196,30 @@ void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, bool /* smallCaps */) { _fontName = fontName; _fontSize = static_cast(fontSize); - ccstd::string fontPath; - if (!_fontName.empty()) { - const char* fontFamilies[1]; - fontFamilies[0] = fontName.c_str(); - OH_Drawing_SetTextStyleFontFamilies(_textStyle, 1, fontFamilies); - OH_Drawing_SetTextStyleLocale(_textStyle, "en"); + if (_typographyCreate) { + OH_Drawing_DestroyTypographyHandler(_typographyCreate); } + if (_textStyle) { + OH_Drawing_DestroyTextStyle(_textStyle); + } + + const auto &fontInfoMap = getFontFamilyCollectionMap(); + auto it = fontInfoMap.find(_fontName); + if (it != fontInfoMap.end()) { + _fontCollection = it->second; + } else { + _fontCollection = fontInfoMap.at(defaultFontKey); + } + _typographyStyle = OH_Drawing_CreateTypographyStyle(); + OH_Drawing_SetTypographyTextDirection(_typographyStyle, TEXT_DIRECTION_LTR); + OH_Drawing_SetTypographyTextAlign(_typographyStyle, TEXT_ALIGN_LEFT); + _typographyCreate = OH_Drawing_CreateTypographyHandler(_typographyStyle, _fontCollection); + _textStyle = OH_Drawing_CreateTextStyle(); + + const char *fontFamilies[1]; + fontFamilies[0] = fontName.c_str(); + OH_Drawing_SetTextStyleFontFamilies(_textStyle, 1, fontFamilies); + if (_fontSize) OH_Drawing_SetTextStyleFontSize(_textStyle, _fontSize); if (bold) diff --git a/native/cocos/platform/openharmony/modules/Screen.cpp b/native/cocos/platform/openharmony/modules/Screen.cpp index 82f3846ce2..fb41452209 100644 --- a/native/cocos/platform/openharmony/modules/Screen.cpp +++ b/native/cocos/platform/openharmony/modules/Screen.cpp @@ -56,11 +56,11 @@ Screen::Orientation Screen::getDeviceOrientation() const { if(value == 0) { return Orientation::PORTRAIT; } else if(value == 1) { - return Orientation::LANDSCAPE_LEFT; + return Orientation::LANDSCAPE_RIGHT; } else if(value == 2) { return Orientation::PORTRAIT_UPSIDE_DOWN; } else if(value == 3) { - return Orientation::LANDSCAPE_RIGHT; + return Orientation::LANDSCAPE_LEFT; } CC_ASSERT(false); return Orientation::PORTRAIT; diff --git a/native/cocos/platform/openharmony/napi/NapiHelper.cpp b/native/cocos/platform/openharmony/napi/NapiHelper.cpp index 2f4bf8bb2f..8099b517b1 100644 --- a/native/cocos/platform/openharmony/napi/NapiHelper.cpp +++ b/native/cocos/platform/openharmony/napi/NapiHelper.cpp @@ -29,6 +29,7 @@ #include "platform/openharmony/OpenHarmonyPlatform.h" #include "platform/openharmony/modules/SystemWindow.h" #include "platform/openharmony/FileUtils-OpenHarmony.h" +#include "platform/interfaces//modules/IScreen.h" #include "bindings/jswrapper/SeApi.h" #if CC_USE_EDITBOX @@ -51,10 +52,14 @@ enum ContextType { ENGINE_UTILS, EDITBOX_UTILS, WEBVIEW_UTILS, + SYSTEM_UTILS, + DISPLAY_UTILS, UV_ASYNC_SEND, - VIDEO_UTILS, + VIDEO_UTILS }; +#define KEYCODE_BACK_OH 6 + static Napi::Env gWorkerEnv(nullptr); static Napi::FunctionReference* gPostMessageToUIThreadFunc = nullptr; static Napi::FunctionReference* gPostSyncMessageToUIThreadFunc = nullptr; @@ -109,6 +114,17 @@ Napi::Value NapiHelper::napiCallFunction(const char* functionName) { return funcVal.As().Call(env.Global(), {}); } +/* static */ +Napi::Value NapiHelper::napiCallFunction(const char *functionName, float duration) { + auto env = getWorkerEnv(); + auto funcVal = env.Global().Get(functionName); + if (!funcVal.IsFunction()) { + return {}; + } + const std::initializer_list args = { Napi::Number::New(env, duration) }; + return funcVal.As().Call(env.Global(), args); +} + // NAPI Interface static bool exportFunctions(Napi::Object exports) { Napi::MaybeOrValue xcomponentObject = exports.Get(OH_NATIVE_XCOMPONENT_OBJ); @@ -139,6 +155,7 @@ static void napiOnShow(const Napi::CallbackInfo &info) { CC_LOG_INFO("napiOnShow"); cc::WorkerMessageData data{cc::MessageType::WM_APP_SHOW, nullptr, nullptr}; OpenHarmonyPlatform::getInstance()->enqueue(data); + } static void napiOnHide(const Napi::CallbackInfo &info) { @@ -147,6 +164,14 @@ static void napiOnHide(const Napi::CallbackInfo &info) { OpenHarmonyPlatform::getInstance()->enqueue(data); } +static void napiOnBackPress(const Napi::CallbackInfo &info) { + CC_LOG_INFO("NapiHelper::napiOnBackPress"); + KeyboardEvent event; + event.key = KEYCODE_BACK_OH; + event.action = KeyboardEvent::Action::RELEASE; + events::Keyboard::broadcast(event); +} + static void napiOnDestroy(const Napi::CallbackInfo &info) { CC_LOG_INFO("napiOnDestroy"); cc::WorkerMessageData data{cc::MessageType::WM_APP_DESTROY, nullptr, nullptr}; @@ -187,6 +212,32 @@ static void napiWorkerInit(const Napi::CallbackInfo &info) { OpenHarmonyPlatform::getInstance()->workerInit(loop); } +static void napiOnDisplayChange(const Napi::CallbackInfo &info) { + if (info.Length() != 1) { + Napi::Error::New(info.Env(), "1 argument expected").ThrowAsJavaScriptException(); + return; + } + + int32_t rotation = info[0].As().Int32Value(); + + int orientation = static_cast(cc::IScreen::Orientation::PORTRAIT); + switch (rotation) { + case 0: // ROTATION_0 + orientation = static_cast(cc::IScreen::Orientation::PORTRAIT); + break; + case 1: // ROTATION_90 + orientation = static_cast(cc::IScreen::Orientation::LANDSCAPE_RIGHT); + break; + case 2: // ROTATION_180 + orientation = static_cast(cc::IScreen::Orientation::PORTRAIT_UPSIDE_DOWN); + break; + case 3: // ROTATION_270 + orientation = static_cast(cc::IScreen::Orientation::LANDSCAPE_LEFT); + break; + } + cc::events::Orientation::broadcast(orientation); +} + static void napiResourceManagerInit(const Napi::CallbackInfo &info) { if (info.Length() != 1) { Napi::Error::New(info.Env(), "1 argument expected").ThrowAsJavaScriptException(); @@ -210,27 +261,39 @@ static void napiWritablePathInit(const Napi::CallbackInfo &info) { FileUtilsOpenHarmony::_ohWritablePath = info[0].As().Utf8Value(); } +static void registerFunction(const Napi::CallbackInfo &info) { + Napi::Env env = info.Env(); + if(info.Length() != 2) { + Napi::Error::New(info.Env(), "2 argument expected").ThrowAsJavaScriptException(); + return; + } + std::string functionName = info[0].As().Utf8Value(); + if(!info[1].IsFunction()) { + Napi::Error::New(info.Env(), "Function expected").ThrowAsJavaScriptException(); + return; + } + Napi::Function jsFunction = info[1].As(); + napi_ref fucRef; + napi_create_reference(env, jsFunction, 1, &fucRef); + char* name = new char[functionName.length() + 1]; + strcpy(name, functionName.c_str()); + JSFunction* jsFunctionPtr = new JSFunction(name, env, fucRef); + JSFunction::addFunction(name, jsFunctionPtr); + return; +} + +std::unordered_map JSFunction::jsFunctionMap; + static void napiASend(const Napi::CallbackInfo &info) { OpenHarmonyPlatform::getInstance()->triggerMessageSignal(); } static void napiOnVideoEvent(const Napi::CallbackInfo &info) { - if (info.Length() != 3) { - Napi::Error::New(info.Env(), "napiOnVideoEvent, 3 argument expected").ThrowAsJavaScriptException(); + if (info.Length() != 1) { + Napi::Error::New(info.Env(), "napiOnVideoEvent, 1 argument expected").ThrowAsJavaScriptException(); return; } - - int32_t videoTag = info[0].As().Int32Value(); - int32_t videoEvent = info[1].As().Int32Value(); - bool hasArg = false; - double arg = 0.0; - if (info[2].IsNumber()) { - arg = info[2].As().DoubleValue(); - hasArg = true; - } - se::AutoHandleScope hs; - auto *global = se::ScriptEngine::getInstance()->getGlobalObject(); se::Value ohVal; bool ok = global->getProperty("oh", &ohVal); @@ -238,23 +301,16 @@ static void napiOnVideoEvent(const Napi::CallbackInfo &info) { CC_LOG_ERROR("oh var not found"); return; } - se::Value onVideoEventVal; ok = ohVal.toObject()->getProperty("onVideoEvent", &onVideoEventVal); if (!ok || !onVideoEventVal.isObject() || !onVideoEventVal.toObject()->isFunction()) { CC_LOG_ERROR("onVideoEvent not found"); return; } - // Convert args to se::ValueArray se::ValueArray seArgs; - seArgs.reserve(3); - seArgs.emplace_back(se::Value(videoTag)); - seArgs.emplace_back(se::Value(videoEvent)); - if (hasArg) { - seArgs.emplace_back(se::Value(arg)); - } - + seArgs.reserve(1); + seArgs.emplace_back(se::Value(info[0].As().Utf8Value())); ok = onVideoEventVal.toObject()->call(seArgs, ohVal.toObject()); if (!ok) { CC_LOG_ERROR("Call oh.onEventEvent failed!"); @@ -284,6 +340,7 @@ static Napi::Value getContext(const Napi::CallbackInfo &info) { exports["onDestroy"] = Napi::Function::New(env, napiOnDestroy); exports["onShow"] = Napi::Function::New(env, napiOnShow); exports["onHide"] = Napi::Function::New(env, napiOnHide); + exports["onBackPress"] = Napi::Function::New(env, napiOnBackPress); } break; case JS_PAGE_LIFECYCLE: { exports["onPageShow"] = Napi::Function::New(env, napiOnPageShow); @@ -310,11 +367,13 @@ static Napi::Value getContext(const Napi::CallbackInfo &info) { case ENGINE_UTILS: { exports["resourceManagerInit"] = Napi::Function::New(env, napiResourceManagerInit); exports["writablePathInit"] = Napi::Function::New(env, napiWritablePathInit); + exports["registerFunction"] = Napi::Function::New(env, registerFunction); } break; case EDITBOX_UTILS: { #if CC_USE_EDITBOX exports["onTextChange"] = Napi::Function::New(env, OpenHarmonyEditBox::napiOnTextChange); exports["onComplete"] = Napi::Function::New(env, OpenHarmonyEditBox::napiOnComplete); + exports["onConfirm"] = Napi::Function::New(env, OpenHarmonyEditBox::napiOnConfirm); #endif } break; case WEBVIEW_UTILS: { @@ -324,6 +383,9 @@ static Napi::Value getContext(const Napi::CallbackInfo &info) { exports["failLoading"] = Napi::Function::New(env, OpenHarmonyWebView::napiFailLoading); exports["jsCallback"] = Napi::Function::New(env, OpenHarmonyWebView::napiJsCallback); #endif + } break; + case DISPLAY_UTILS: { + exports["onDisplayChange"] = Napi::Function::New(env, napiOnDisplayChange); } break; case UV_ASYNC_SEND: { exports["send"] = Napi::Function::New(env, napiASend); diff --git a/native/cocos/platform/openharmony/napi/NapiHelper.h b/native/cocos/platform/openharmony/napi/NapiHelper.h index e1f59113a8..dde84568f5 100644 --- a/native/cocos/platform/openharmony/napi/NapiHelper.h +++ b/native/cocos/platform/openharmony/napi/NapiHelper.h @@ -29,16 +29,204 @@ #define NAPI_DISABLE_CPP_EXCEPTIONS 1 #define NODE_ADDON_API_DISABLE_DEPRECATED 1 #include "napi.h" +#include "NapiValueConverter.h" +#include "base/Log.h" namespace cc { +using CallbackParamType = std::variant; + +struct AsyncCallParam { + std::function cb; + std::string paramStr; + napi_value callFunc; + napi_ref executeFuncRef; +}; class NapiHelper { public: static Napi::Env getWorkerEnv(); static Napi::Object init(Napi::Env env, Napi::Object exports); static Napi::Value napiCallFunction(const char* functionName); + static Napi::Value napiCallFunction(const char *functionName,float duration); static void postMessageToUIThread(const std::string& type, Napi::Value param); static Napi::Value postSyncMessageToUIThread(const std::string& type, Napi::Value param); }; +class JSFunction { +public: + napi_ref funcRef; + napi_env env; + char* name = nullptr; + +public: + static std::unordered_map jsFunctionMap; + + explicit JSFunction(char* name, napi_env env, napi_ref funcRef) + : name(name), env(env), funcRef(funcRef){} + + explicit JSFunction(char* name, napi_env env) + : name(name), env(env){} + + explicit JSFunction(char* name) + : name(name){} + + static JSFunction getFunction(std::string functionName) + { + return jsFunctionMap.at(functionName); + } + + static void addFunction(std::string name, JSFunction* jsFunction) { + jsFunctionMap.emplace(name, *jsFunction); + } + + template + typename std::enable_if::value, ReturnType>::type + invoke(Args... args) { + napi_value global; + napi_status status = napi_get_global(env, &global); + //if (status != napi_ok) return; + + napi_value func; + status = napi_get_reference_value(env, funcRef, &func); + + napi_value jsArgs[sizeof...(Args)] = {NapiValueConverter::ToNapiValue(env, args)...}; + napi_value return_val; + status = napi_call_function(env, global, func, sizeof...(Args), jsArgs, &return_val); + + ReturnType value; + if (!NapiValueConverter::ToCppValue(env, return_val, value)) { + // Handle error here + } + return value; + } + + template + typename std::enable_if::value, void>::type + invoke(Args... args) { + napi_value global; + napi_status status = napi_get_global(env, &global); + if (status != napi_ok) return; + + napi_value func; + status = napi_get_reference_value(env, funcRef, &func); + + napi_value jsArgs[sizeof...(Args)] = {NapiValueConverter::ToNapiValue(env, args)...}; + napi_value return_val; + status = napi_call_function(env, global, func, sizeof...(Args), jsArgs, &return_val); + } + + void invokeAsync(AsyncCallParam *callParam) { + callParam->executeFuncRef = funcRef; + + napi_status status; + napi_value func; + status = napi_get_reference_value(env, funcRef, &func); + if (status != napi_ok) { + CC_LOG_WARNING("invokeAsync napi_get_reference_value fail,status=%{public}d", status); + return; + } + + napi_value workName; + status = napi_create_string_utf8(env, "Thread-safe call from async work", NAPI_AUTO_LENGTH, &workName); + if (status != napi_ok) { + CC_LOG_WARNING("invokeAsync napi_create_string_utf8 fail,status=%{public}d", status); + return; + } + + napi_threadsafe_function save_func; + status = napi_create_threadsafe_function(env, func, nullptr, workName, 0, 1, nullptr, + [](napi_env env, void *raw, void *hint) {}, callParam, CallJS, &save_func); + if (status != napi_ok) { + CC_LOG_WARNING("invokeAsync napi_create_threadsafe_function fail,status=%{public}d", status); + return; + } + + status = napi_acquire_threadsafe_function(save_func); + if (status != napi_ok) { + CC_LOG_WARNING("invokeAsync napi_acquire_threadsafe_function fail,status=%{public}d", status); + return; + } + + status = napi_call_threadsafe_function(save_func, NULL, napi_tsfn_blocking); + if (status != napi_ok) { + CC_LOG_WARNING("invokeAsync napi_call_threadsafe_function fail,status=%{public}d", status); + return; + } + } + + static void CallJS(napi_env env, napi_value js_cb, void *context, void *data) { + AsyncCallParam *callParam = (AsyncCallParam*) (context); + if (callParam == nullptr) { + CC_LOG_WARNING("CallJS AsyncCallParam callParam is null"); + return; + } + + napi_status status; + status = napi_get_reference_value(env, callParam->executeFuncRef, &js_cb); + if (status != napi_ok) { + CC_LOG_WARNING("CallJS napi_get_reference_value fail,status=%{public}d", status); + return; + } + + auto callback = [](napi_env env, napi_callback_info info) -> napi_value { + size_t argc = 1; + napi_value args[1] = {}; + void *param_in = nullptr; + napi_get_cb_info(env, info, &argc, args, nullptr, ¶m_in); + + napi_value return_val; + napi_get_undefined(env, &return_val); + + AsyncCallParam *callbackParam = reinterpret_cast(param_in); + if (callbackParam == nullptr) { + CC_LOG_WARNING("CallJS AsyncCallParam callbackParam is null"); + return return_val; + } + + napi_valuetype type; + napi_typeof(env, args[0], &type); + + CallbackParamType callbackValue; + + if (type == napi_string) { + std::string resultStr; + NapiValueConverter::ToCppValue(env, args[0], resultStr); + callbackValue = std::move(resultStr); + } else if (type == napi_number) { + double resultNum; + NapiValueConverter::ToCppValue(env, args[0], resultNum); + callbackValue = resultNum; + } else if (type == napi_boolean) { + bool resultBol; + NapiValueConverter::ToCppValue(env, args[0], resultBol); + callbackValue = resultBol; + } else { + callbackValue = "unknown"; + } + callbackParam->cb(callbackValue); + return return_val; + }; + + napi_value callbackFunc = nullptr; + status = napi_create_function(env, "callbackFunc", NAPI_AUTO_LENGTH, callback, callParam, &callbackFunc); + if (status != napi_ok) { + CC_LOG_WARNING("CallJS napi_create_function fail,status=%{public}d", status); + return; + } + + napi_value jsArgs[3] = {callParam->callFunc, NapiValueConverter::ToNapiValue(env, callParam->paramStr), callbackFunc}; + napi_value return_val; + napi_value global; + status = napi_get_global(env, &global); + if (status != napi_ok) { + CC_LOG_WARNING("CallJS napi_get_global fail,status=%{public}d", status); + } + + status = napi_call_function(env, global, js_cb, 3, jsArgs, &return_val); + if (status != napi_ok) { + CC_LOG_WARNING("CallJS napi_call_function fail,status=%{public}d", status); + } + } +}; + } // namespace cc diff --git a/native/cocos/platform/openharmony/napi/NapiValueConverter.cpp b/native/cocos/platform/openharmony/napi/NapiValueConverter.cpp new file mode 100644 index 0000000000..9cfcec7cf5 --- /dev/null +++ b/native/cocos/platform/openharmony/napi/NapiValueConverter.cpp @@ -0,0 +1,89 @@ +#include "NapiValueConverter.h" +#include + +napi_valuetype GetNapiValueType(napi_env env, napi_value value) { + napi_valuetype type; + napi_typeof(env, value, &type); + return type; +} + +template<> +bool NapiValueConverter::ToCppValue(napi_env env, napi_value value, int& result) { + if (GetNapiValueType(env, value) != napi_number) { + napi_throw_type_error(env, nullptr, "Expected number"); + return false; + } + napi_get_value_int32(env, value, &result); + return true; +} + +template<> +bool NapiValueConverter::ToCppValue(napi_env env, napi_value value, bool& result) { + if (GetNapiValueType(env, value) != napi_boolean) { + napi_throw_type_error(env, nullptr, "Expected boolean"); + return false; + } + napi_get_value_bool(env, value, &result); + return true; +} + +template<> +bool NapiValueConverter::ToCppValue(napi_env env, napi_value value, double& result) { + if (GetNapiValueType(env, value) != napi_number) { + napi_throw_type_error(env, nullptr, "Expected number"); + return false; + } + napi_get_value_double(env, value, &result); + return true; +} + +template<> +bool NapiValueConverter::ToCppValue(napi_env env, napi_value value, std::string& result) { + if (GetNapiValueType(env, value) != napi_string) { + napi_throw_type_error(env, nullptr, "Expected string"); + return false; + } + + size_t str_size; + napi_get_value_string_utf8(env, value, nullptr, 0, &str_size); + char* buf = new char[str_size + 1]; + napi_get_value_string_utf8(env, value, buf, str_size + 1, &str_size); + result = std::string(buf); + delete[] buf; + + return true; +} + +napi_value NapiValueConverter::ToNapiValue(napi_env env, int32_t value) { + napi_value result; + napi_create_int32(env, value, &result); + return result; +} + +napi_value NapiValueConverter::ToNapiValue(napi_env env, int64_t value) { + napi_value result; + napi_create_int64(env, value, &result); + return result; +} + +napi_value NapiValueConverter::ToNapiValue(napi_env env, double value) { + napi_value result; + napi_create_double(env, value, &result); + return result; +} + +napi_value NapiValueConverter::ToNapiValue(napi_env env, bool value) { + napi_value result; + napi_get_boolean(env, value, &result); + return result; +} + +napi_value NapiValueConverter::ToNapiValue(napi_env env, const char* value) { + napi_value result; + napi_create_string_utf8(env, value, strlen(value), &result); + return result; +} + +napi_value NapiValueConverter::ToNapiValue(napi_env env, std::string value) { + return ToNapiValue(env, value.c_str()); +} \ No newline at end of file diff --git a/native/cocos/platform/openharmony/napi/NapiValueConverter.h b/native/cocos/platform/openharmony/napi/NapiValueConverter.h new file mode 100644 index 0000000000..89f377a288 --- /dev/null +++ b/native/cocos/platform/openharmony/napi/NapiValueConverter.h @@ -0,0 +1,16 @@ +#include +#include + +class NapiValueConverter { +public: + template + static bool ToCppValue(napi_env env, napi_value value, ReturnType& result); + + static napi_value ToNapiValue(napi_env env, int32_t value); + static napi_value ToNapiValue(napi_env env, int64_t value); + static napi_value ToNapiValue(napi_env env, double value); + static napi_value ToNapiValue(napi_env env, bool value); + static napi_value ToNapiValue(napi_env env, const char* value); + static napi_value ToNapiValue(napi_env env, std::string value); + +}; \ No newline at end of file diff --git a/native/cocos/platform/openharmony/napi/native_common.h b/native/cocos/platform/openharmony/napi/native_common.h new file mode 100644 index 0000000000..c1633d2f23 --- /dev/null +++ b/native/cocos/platform/openharmony/napi/native_common.h @@ -0,0 +1,115 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#pragma once + +#ifndef FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H +#define FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H + +#define DEPRECATED __attribute__((__deprecated__)) + +#ifndef NAPI_VERSION +#define NAPI_VERSION 8 +#endif + +#define NAPI_RETVAL_NOTHING + +#define GET_AND_THROW_LAST_ERROR(env) \ + do { \ + const napi_extended_error_info* errorInfo = nullptr; \ + napi_get_last_error_info((env), &errorInfo); \ + bool isPending = false; \ + napi_is_exception_pending((env), &isPending); \ + if (!isPending && errorInfo != nullptr) { \ + const char* errorMessage = \ + errorInfo->error_message != nullptr ? errorInfo->error_message : "empty error message"; \ + napi_throw_error((env), nullptr, errorMessage); \ + } \ + } while (0) + +#define NAPI_ASSERT_BASE(env, assertion, message, retVal) \ + do { \ + if (!(assertion)) { \ + napi_throw_error((env), nullptr, "assertion (" #assertion ") failed: " message); \ + return retVal; \ + } \ + } while (0) + +#define NAPI_ASSERT(env, assertion, message) NAPI_ASSERT_BASE(env, assertion, message, nullptr) + +#define NAPI_ASSERT_RETURN_VOID(env, assertion, message) NAPI_ASSERT_BASE(env, assertion, message, NAPI_RETVAL_NOTHING) + +#define NAPI_CALL_BASE(env, theCall, retVal) \ + do { \ + if ((theCall) != napi_ok) { \ + GET_AND_THROW_LAST_ERROR((env)); \ + return retVal; \ + } \ + } while (0) + +#define NAPI_CALL(env, theCall) NAPI_CALL_BASE(env, theCall, nullptr) + +#define NAPI_CALL_RETURN_VOID(env, theCall) NAPI_CALL_BASE(env, theCall, NAPI_RETVAL_NOTHING) + +#define DECLARE_NAPI_PROPERTY(name, val) \ + { \ + (name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr \ + } + +#define DECLARE_NAPI_STATIC_PROPERTY(name, val) \ + { \ + (name), nullptr, nullptr, nullptr, nullptr, val, napi_static, nullptr \ + } + +#define DECLARE_NAPI_FUNCTION(name, func) \ + { \ + (name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr \ + } + +#define DECLARE_NAPI_FUNCTION_WITH_DATA(name, func, data) \ + { \ + (name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, data \ + } + +#define DECLARE_NAPI_STATIC_FUNCTION(name, func) \ + { \ + (name), nullptr, (func), nullptr, nullptr, nullptr, napi_static, nullptr \ + } + +#define DECLARE_NAPI_GETTER(name, getter) \ + { \ + (name), nullptr, nullptr, (getter), nullptr, nullptr, napi_default, nullptr \ + } + +#define DECLARE_NAPI_SETTER(name, setter) \ + { \ + (name), nullptr, nullptr, nullptr, (setter), nullptr, napi_default, nullptr \ + } + +#define DECLARE_NAPI_GETTER_SETTER(name, getter, setter) \ + { \ + (name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr \ + } + +#endif /* FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H */ diff --git a/native/cocos/ui/edit-box/EditBox-openharmony.cpp b/native/cocos/ui/edit-box/EditBox-openharmony.cpp index d8ac9b9e94..ee6f4ecfb2 100644 --- a/native/cocos/ui/edit-box/EditBox-openharmony.cpp +++ b/native/cocos/ui/edit-box/EditBox-openharmony.cpp @@ -29,7 +29,6 @@ #include "application/ApplicationManager.h" #include "platform/openharmony/napi/NapiHelper.h" #include "bindings/jswrapper/SeApi.h" - namespace cc { /************************************************************************* @@ -55,9 +54,9 @@ void getTextInputCallback() { } void callJSFunc(const ccstd::string &type, const ccstd::string &text) { - getTextInputCallback(); - se::AutoHandleScope scope; + getTextInputCallback(); + se::ValueArray args; args.push_back(se::Value(type)); args.push_back(se::Value(text)); @@ -70,7 +69,34 @@ void callJSFunc(const ccstd::string &type, const ccstd::string &text) { Implementation of EditBox. ************************************************************************/ void EditBox::show(const EditBox::ShowInfo &showInfo) { - NapiHelper::postMessageToUIThread("showEditBox", Napi::String::New(NapiHelper::getWorkerEnv(), showInfo.defaultValue)); + auto env = NapiHelper::getWorkerEnv(); + auto args = Napi::Object::New(env); + args["defaultValue"] = Napi::String::New(env, showInfo.defaultValue); + args["confirmType"] = Napi::String::New(env, showInfo.confirmType); + args["inputType"] = Napi::String::New(env, showInfo.inputType); + + args["maxLength"] = Napi::Number::New(env, showInfo.maxLength); + args["x"] = Napi::Number::New(env, showInfo.x); + args["y"] = Napi::Number::New(env, showInfo.y); + args["width"] = Napi::Number::New(env, showInfo.width); + args["height"] = Napi::Number::New(env, showInfo.height); + + args["confirmHold"] = Napi::Boolean::New(env, showInfo.confirmHold); + args["isMultiline"] = Napi::Boolean::New(env, showInfo.isMultiline); + + args["fontSize"] = Napi::Number::New(env, showInfo.fontSize); + args["fontColor"] = Napi::Number::New(env, showInfo.fontColor); + args["backColor"] = Napi::Number::New(env, showInfo.backColor); + args["backgroundColor"] = Napi::Number::New(env, showInfo.backgroundColor); + + args["isBold"] = Napi::Boolean::New(env, showInfo.isBold); + args["isItalic"] = Napi::Boolean::New(env, showInfo.isItalic); + args["isUnderline"] = Napi::Boolean::New(env, showInfo.isUnderline); + + args["underlineColor"] = Napi::Number::New(env, showInfo.underlineColor); + args["textAlignment"] = Napi::Number::New(env, showInfo.textAlignment); + + NapiHelper::postMessageToUIThread("showEditBox", args); } void EditBox::hide() { @@ -102,6 +128,22 @@ void OpenHarmonyEditBox::napiOnTextChange(const Napi::CallbackInfo &info) { callJSFunc("input", buffer); } + +void OpenHarmonyEditBox::napiOnConfirm(const Napi::CallbackInfo &info) { + auto env = info.Env(); + if (info.Length() != 1) { + Napi::Error::New(env, "napiOnConfirm, 1 argument expected").ThrowAsJavaScriptException(); + return; + } + + if (!info[0].IsString()) { + Napi::TypeError::New(env, "napiOnConfirm, string argument expected").ThrowAsJavaScriptException(); + return; + } + ccstd::string buffer = info[0].As().Utf8Value(); + callJSFunc("confirm", buffer); +} + } // namespace cc diff --git a/native/cocos/ui/edit-box/EditBox-openharmony.h b/native/cocos/ui/edit-box/EditBox-openharmony.h index e57aaa97f7..775408ca04 100644 --- a/native/cocos/ui/edit-box/EditBox-openharmony.h +++ b/native/cocos/ui/edit-box/EditBox-openharmony.h @@ -33,7 +33,7 @@ class OpenHarmonyEditBox : public EditBox { public: static void napiOnComplete(const Napi::CallbackInfo &info); static void napiOnTextChange(const Napi::CallbackInfo &info); - + static void napiOnConfirm(const Napi::CallbackInfo &info); static napi_value show(const std::string& inputMessage); static napi_value hide(); private: diff --git a/platforms/native/engine/jsb-fs-utils.js b/platforms/native/engine/jsb-fs-utils.js index cfd3268092..549c839d6e 100644 --- a/platforms/native/engine/jsb-fs-utils.js +++ b/platforms/native/engine/jsb-fs-utils.js @@ -176,13 +176,28 @@ const fsUtils = { }, readJson (filePath, onComplete) { - fs.readJsonFile(filePath, (err, jsonObj) => { - if (err) { - cc.warn(`Read json failed: path: ${filePath} message: ${err}`); - err = new Error(err); - } - onComplete && onComplete(err, jsonObj); - }); + if (window.oh && window.scriptEngineType === 'napi') { + fsUtils.readFile(filePath, 'utf8', (err, text) => { + let out = null; + if (!err) { + try { + out = JSON.parse(text); + } catch (e) { + cc.warn(`Read json failed: path: ${filePath} message: ${e.message}`); + err = new Error(e.message); + } + } + onComplete && onComplete(err, out); + }); + } else { + fs.readJsonFile(filePath, (err, jsonObj) => { + if (err) { + cc.warn(`Read json failed: path: ${filePath} message: ${err}`); + err = new Error(err); + } + onComplete && onComplete(err, jsonObj); + }); + } }, readJsonSync (path) { diff --git a/platforms/native/engine/jsb-videoplayer-openharmony.js b/platforms/native/engine/jsb-videoplayer-openharmony.js index 86c35f0c3b..4b31ea29cb 100644 --- a/platforms/native/engine/jsb-videoplayer-openharmony.js +++ b/platforms/native/engine/jsb-videoplayer-openharmony.js @@ -23,20 +23,17 @@ THE SOFTWARE. ****************************************************************************/ -'use strict'; - if (cc.internal.VideoPlayer) { - const { EventType } = cc.internal.VideoPlayer; - let vec3 = cc.Vec3; - let mat4 = cc.Mat4; - let _mat4_temp = new mat4(); + const vec3 = cc.Vec3; + const mat4 = cc.Mat4; + const _mat4_temp = new mat4(); - let _topLeft = new vec3(); - let _bottomRight = new vec3(); - let kWebViewTag = 0; - let videoPlayers = []; + const _topLeft = new vec3(); + const _bottomRight = new vec3(); + let kVideoTag = 0; + const videoPlayers = []; const VideoEvent = { PLAYING: 0, PAUSED: 1, @@ -44,121 +41,138 @@ if (cc.internal.VideoPlayer) { COMPLETED: 3, META_LOADED: 4, CLICKED: 5, - READY_TO_PLAY:6, - UPDATE:7, - QUIT_FULLSCREEN:1000 + READY_TO_PLAY: 6, + UPDATE: 7, + QUIT_FULLSCREEN: 1000, }; - cc.internal.VideoPlayerImplManager.getImpl = function(componenet) { + cc.internal.VideoPlayerImplManager.getImpl = function (componenet) { return new VideoPlayerImplOpenHarmony(componenet); }; - window.oh.onVideoEvent = (tag, ev, args) => { - videoPlayers.forEach(player => { - if (player.index == tag) { - player.dispatchEvent(ev, args); - } + window.oh.onVideoEvent = (args) => { + const data = JSON.parse(args); + videoPlayers.forEach((player) => { + if (player.index === data.videoTag) { + player.dispatchEvent(data.videoEvent, data.args); + } }); }; class VideoPlayer { - constructor() { + constructor () { this._events = {}; this._currentTime = 0; this._duration = 0; - this._videoIndex = kWebViewTag++; + this._videoIndex = kVideoTag++; this._matViewProj_temp = new mat4(); - window.oh.postMessage("createVideo", this._videoIndex); + window.oh.postMessage('createVideo', this._videoIndex); videoPlayers.push(this); } - get index() { + get index () { return this._videoIndex; } - play() { - window.oh.postMessage("startVideo", this._videoIndex); + play () { + window.oh.postMessage('startVideo', this._videoIndex); } - setURL(url) { - window.oh.postMessage("setVideoUrl", {tag:this._videoIndex, url:url}); + + // private function + _isURL (url) { + const regexp = /((http|https):\/\/([\w\-]+\.)+[\w\-]+(\/[\w\u4e00-\u9fa5\-\.\/?\@\%\!\&=\+\~\:\#\;\,]*)?)/ig; + if (regexp.test(url)) { + return true; + } else { + return false; + } } - pause() { - window.oh.postMessage("pauseVideo", this._videoIndex); + + setURL (url) { + if (this._isURL(url)) { + window.oh.postMessage('setVideoUrl', { tag: this._videoIndex, resourceType: 0, url }); + } else { + window.oh.postMessage('setVideoUrl', { tag: this._videoIndex, resourceType: 1, url }); + } } - setVisible(visible) { - window.oh.postMessage("setVideoVisible", {tag:this._videoIndex, visible:visible}); + + pause () { + window.oh.postMessage('pauseVideo', this._videoIndex); } - resume() { - window.oh.postMessage("resumeVideo", this._videoIndex); + setVisible (visible) { + window.oh.postMessage('setVideoVisible', { tag: this._videoIndex, visible }); } - currentTime() { - window.oh.postSyncMessage("currentTime", this._videoIndex).then((result) => { + resume () { + window.oh.postMessage('resumeVideo', this._videoIndex); + } + currentTime () { + window.oh.postSyncMessage('currentTime', this._videoIndex).then((result) => { this._currentTime = result; }); return this._currentTime; } - stop() { - window.oh.postMessage("stopVideo", this._videoIndex); + stop () { + window.oh.postMessage('stopVideo', this._videoIndex); } - seekTo(val) { - window.oh.postMessage("seekVideoTo", {tag:this._videoIndex, time:val}); + seekTo (val) { + window.oh.postMessage('seekVideoTo', { tag: this._videoIndex, time: val }); } - duration() { - window.oh.postSyncMessage("getVideoDuration", this._videoIndex).then((result) => { + duration () { + window.oh.postSyncMessage('getVideoDuration', this._videoIndex).then((result) => { this._duration = result; }); return this._duration; } - destroy() { - window.oh.postMessage("removeVideo", this._videoIndex); + destroy () { + window.oh.postMessage('removeVideo', this._videoIndex); } - setFullScreenEnabled(enable) { - window.oh.postMessage("setFullScreenEnabled", {tag:this._videoIndex, fullScreen:enable}); + setFullScreenEnabled (enable) { + window.oh.postMessage('setFullScreenEnabled', { tag: this._videoIndex, fullScreen: enable }); } - setKeepAspectRatioEnabled(enable) { + setKeepAspectRatioEnabled (enable) { cc.warn('The platform does not support'); } - setFrame(x, y, w, h){ - window.oh.postMessage("setVideoRect", {tag:this._videoIndex, x:x, y:y, w:w, h:h}); + setFrame (x, y, w, h) { + window.oh.postMessage('setVideoRect', { tag: this._videoIndex, x, y, w, h }); } - eventTypeToEventName(ev) { + eventTypeToEventName (ev) { let evString; switch (ev) { case VideoEvent.PLAYING: - evString = "play"; + evString = 'play'; break; case VideoEvent.PAUSED: - evString = "pause"; + evString = 'pause'; break; case VideoEvent.STOPPED: - evString = "stoped"; + evString = 'stoped'; break; case VideoEvent.COMPLETED: - evString = "ended"; + evString = 'ended'; break; case VideoEvent.META_LOADED: - evString = "loadedmetadata"; + evString = 'loadedmetadata'; break; case VideoEvent.CLICKED: - evString = "click"; + evString = 'click'; break; case VideoEvent.READY_TO_PLAY: - evString = "suspend"; + evString = 'suspend'; break; case VideoEvent.UPDATE: - evString = "update"; + evString = 'update'; break; case VideoEvent.QUIT_FULLSCREEN: - evString = "suspend"; + evString = 'suspend'; break; default: - evString = "none"; + evString = 'none'; break; } return evString; } - dispatchEvent(type, args) { - let eventName = this.eventTypeToEventName(type); + dispatchEvent (type, args) { + const eventName = this.eventTypeToEventName(type); const listeners = this._events[eventName]; - + if (listeners) { for (let i = 0; i < listeners.length; i++) { listeners[i](args); @@ -166,16 +180,16 @@ if (cc.internal.VideoPlayer) { } } - addEventListener(name, listener) { + addEventListener (name, listener) { if (!this._events[name]) { this._events[name] = []; } this._events[name].push(listener); } - removeEventListener(name, listener) { + removeEventListener (name, listener) { const listeners = this._events[name]; - + if (listeners && listeners.length > 0) { for (let i = listeners.length; i--; i > 0) { if (listeners[i] === listener) { @@ -188,13 +202,13 @@ if (cc.internal.VideoPlayer) { } class VideoPlayerImplOpenHarmony extends cc.internal.VideoPlayerImpl { - - constructor(componenet) { + constructor (componenet) { super(componenet); this._matViewProj_temp = new mat4(); + this._loaded = false; } - syncClip(clip) { + syncClip (clip) { this.removeVideoPlayer(); if (!clip) { return; @@ -202,7 +216,7 @@ if (cc.internal.VideoPlayer) { this.createVideoPlayer(clip._nativeAsset); } - syncURL(url) { + syncURL (url) { this.removeVideoPlayer(); if (!url) { return; @@ -210,17 +224,24 @@ if (cc.internal.VideoPlayer) { this.createVideoPlayer(url); } - onCanplay () { + onCanPlay (args = 0) { if (this._loaded) { return; } + this._video._duration = args; this._loaded = true; this.video.setVisible(this._visible); this.dispatchEvent(EventType.READY_TO_PLAY); - this.delayedPlay(); + //this.delayedPlay(); } - _bindEvent() { + onUpdate (args = 0) { + if (this.video) { + this.video._currentTime = args; + } + } + + _bindEvent () { this.video.addEventListener('loadedmetadata', this.onLoadedMetadata.bind(this)); this.video.addEventListener('suspend', this.onCanPlay.bind(this)); this.video.addEventListener('play', this.onPlay.bind(this)); @@ -228,9 +249,21 @@ if (cc.internal.VideoPlayer) { this.video.addEventListener('stoped', this.onStoped.bind(this)); this.video.addEventListener('click', this.onClick.bind(this)); this.video.addEventListener('ended', this.onEnded.bind(this)); + this.video.addEventListener('update', this.onUpdate.bind(this)); } - onLoadedMetadata() { + _unBindEvent () { + this.video.removeEventListener('loadedmetadata', this.onLoadedMetadata.bind(this)); + this.video.removeEventListener('suspend', this.onCanPlay.bind(this)); + this.video.removeEventListener('play', this.onPlay.bind(this)); + this.video.removeEventListener('pause', this.onPause.bind(this)); + this.video.removeEventListener('stoped', this.onStoped.bind(this)); + this.video.removeEventListener('click', this.onClick.bind(this)); + this.video.removeEventListener('ended', this.onEnded.bind(this)); + this.video.removeEventListener('update', this.onUpdate.bind(this)); + } + + onLoadedMetadata () { this._loadedMeta = true; this._forceUpdate = true; if (this._visible) { @@ -243,7 +276,7 @@ if (cc.internal.VideoPlayer) { this.delayedPlay(); } - createVideoPlayer(url) { + createVideoPlayer (url) { this._video = new VideoPlayer(); this._bindEvent(); this._video.setVisible(this._visible); @@ -251,12 +284,13 @@ if (cc.internal.VideoPlayer) { this._forceUpdate = true; } - removeVideoPlayer() { - let video = this.video; + removeVideoPlayer () { + const video = this.video; if (video) { video.stop(); video.setVisible(false); video.destroy(); + this._unBindEvent(); this._playing = false; this._loaded = false; this._loadedMeta = false; @@ -273,27 +307,27 @@ if (cc.internal.VideoPlayer) { return this.video.duration(); } - syncPlaybackRate() { + syncPlaybackRate () { cc.warn('The platform does not support'); } - syncVolume() { + syncVolume () { cc.warn('The platform does not support'); } - syncMute() { + syncMute () { cc.warn('The platform does not support'); } - syncLoop() { + syncLoop () { cc.warn('The platform does not support'); } - syncStayOnBottom() { + syncStayOnBottom () { cc.warn('The platform does not support'); } - getCurrentTime() { + getCurrentTime () { if (this.video) { this._cachedCurrentTime = this.video.currentTime(); return this._cachedCurrentTime; @@ -302,13 +336,13 @@ if (cc.internal.VideoPlayer) { } seekTo (val) { - let video = this._video; + const video = this._video; if (!video) return; video.seekTo(val); this._cachedCurrentTime = val; } - disable(noPause) { + disable (noPause) { if (this.video) { if (!noPause) { this.video.pause(); @@ -318,7 +352,7 @@ if (cc.internal.VideoPlayer) { } } - enable() { + enable () { if (this.video) { this.video.setVisible(true); this._visible = true; @@ -330,7 +364,7 @@ if (cc.internal.VideoPlayer) { this.syncCurrentTime(); } - resume() { + resume () { if (this.video) { this.video.resume(); this.syncCurrentTime(); @@ -338,35 +372,35 @@ if (cc.internal.VideoPlayer) { } } - pause() { + pause () { if (this.video) { this._cachedCurrentTime = this.video.currentTime(); this.video.pause(); } } - stop() { + stop () { if (this.video) { - this._ignorePause = true; + //this._ignorePause = true; this.video.seekTo(0); this._cachedCurrentTime = 0; this.video.stop(); } } - canFullScreen(enabled) { + canFullScreen (enabled) { if (this.video) { this.video.setFullScreenEnabled(enabled); } } - syncKeepAspectRatio(enabled) { + syncKeepAspectRatio (enabled) { if (this.video) { this.video.setKeepAspectRatioEnabled(enabled); } } - syncMatrix() { + syncMatrix () { if (!this._video || !this._component || !this._uiTrans) return; const camera = this.UICamera; @@ -376,12 +410,12 @@ if (cc.internal.VideoPlayer) { this._component.node.getWorldMatrix(_mat4_temp); const { width, height } = this._uiTrans.contentSize; - if (!this._forceUpdate && - camera.matViewProj.equals(this._matViewProj_temp) && - this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && - this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && - this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && - this._w === width && this._h === height) { + if (!this._forceUpdate + && camera.matViewProj.equals(this._matViewProj_temp) + && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 + && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 + && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 + && this._w === width && this._h === height) { return; } @@ -396,10 +430,10 @@ if (cc.internal.VideoPlayer) { this._w = width; this._h = height; - let canvas_width = cc.game.canvas.width; - let canvas_height = cc.game.canvas.height; + const canvas_width = cc.game.canvas.width; + const canvas_height = cc.game.canvas.height; - let ap = this._uiTrans.anchorPoint; + const ap = this._uiTrans.anchorPoint; // Vectors in node space vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0); vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0); @@ -412,8 +446,8 @@ if (cc.internal.VideoPlayer) { camera.worldToScreen(_topLeft, _topLeft); camera.worldToScreen(_bottomRight, _bottomRight); - let finalWidth = _bottomRight.x - _topLeft.x; - let finalHeight = _topLeft.y - _bottomRight.y; + const finalWidth = _bottomRight.x - _topLeft.x; + const finalHeight = _topLeft.y - _bottomRight.y; this._video.setFrame(_topLeft.x, canvas_height - _topLeft.y, finalWidth, finalHeight); this._forceUpdate = false; } diff --git a/templates/openharmony/AppScope/app.json5 b/templates/openharmony/AppScope/app.json5 index 3438095bfb..73df64f8b7 100644 --- a/templates/openharmony/AppScope/app.json5 +++ b/templates/openharmony/AppScope/app.json5 @@ -1,6 +1,6 @@ { "app": { - "bundleName": "com.example.openharmonydemo", + "bundleName": "com.example.harmonyosnextdemo", "vendor": "example", "versionCode": 1000000, "versionName": "1.0.0", diff --git a/templates/openharmony/AppScope/resources/base/element/string.json b/templates/openharmony/AppScope/resources/base/element/string.json index 3eb436c973..b8d24dbbd3 100644 --- a/templates/openharmony/AppScope/resources/base/element/string.json +++ b/templates/openharmony/AppScope/resources/base/element/string.json @@ -2,7 +2,7 @@ "string": [ { "name": "app_name", - "value": "OpenHarmonyApp" + "value": "HarmonyOSNextApp" } ] } diff --git a/templates/openharmony/build-profile.json5 b/templates/openharmony/build-profile.json5 index cfb7fe59f2..fa5207f958 100644 --- a/templates/openharmony/build-profile.json5 +++ b/templates/openharmony/build-profile.json5 @@ -1,11 +1,21 @@ { "app": { - "compileSdkVersion": 9, - "compatibleSdkVersion": 9, + "signingConfigs": [ + ], "products": [ { "name": "default", "signingConfig": "default", + "compatibleSdkVersion": "5.0.0(12)", + "runtimeOS": "HarmonyOS" + } + ], + "buildModeSet": [ + { + "name": "debug", + }, + { + "name": "release" } ] }, diff --git a/templates/openharmony/entry/build-profile.json5 b/templates/openharmony/entry/build-profile.json5 index b9f11c6c0f..eacd4d1cab 100644 --- a/templates/openharmony/entry/build-profile.json5 +++ b/templates/openharmony/entry/build-profile.json5 @@ -3,19 +3,16 @@ "buildOption": { "externalNativeOptions": { "path": "../CMakeLists.txt", - "arguments": "-v -DOHOS_STL=c++_shared -DRES_DIR={DRES_DIR} -DCOMMON_DIR={DCOMMON_DIR} -DOPENHARMONY=1", + "arguments": "arm-linux-ohos -DOHOS_STL=c++_shared -DRES_DIR={DRES_DIR} -DCOMMON_DIR={DCOMMON_DIR} -DOPENHARMONY=1", "abiFilters": [ - "armeabi-v7a", "arm64-v8a" ], "cppFlags": "", - }, - "compileMode": "esmodule", + } }, "targets": [ { - "name": "default", - "runtimeOS": "HarmonyOS" + "name": "default" }, ] } diff --git a/templates/openharmony/entry/oh-package.json5 b/templates/openharmony/entry/oh-package.json5 index 74fb9edf16..8315ec40c0 100644 --- a/templates/openharmony/entry/oh-package.json5 +++ b/templates/openharmony/entry/oh-package.json5 @@ -3,8 +3,10 @@ "devDependencies": {}, "author": "", "name": "entry", - "description": "example description", + "description": "Please describe the basic information.", "main": "", "version": "1.0.0", - "dependencies": {} + "dependencies": { + "libcocos.so": "file:./src/main/cpp/types/libcocos" + } } \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/cpp/README.md b/templates/openharmony/entry/src/main/cpp/README.md deleted file mode 100644 index 991b84a80d..0000000000 --- a/templates/openharmony/entry/src/main/cpp/README.md +++ /dev/null @@ -1 +0,0 @@ -Need a cpp folder to fix the IDE can't compile native code for verion 3.0.0.992 \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/cpp/types/libcocos/index.d.ts b/templates/openharmony/entry/src/main/cpp/types/libcocos/index.d.ts new file mode 100644 index 0000000000..d70687261b --- /dev/null +++ b/templates/openharmony/entry/src/main/cpp/types/libcocos/index.d.ts @@ -0,0 +1,30 @@ +import { ContextType } from '../../../ets/common/Constants'; + +interface context { + onPageShow: () => void; + onPageHide: () => void; + workerInit: () => void; + postMessage: (msgType: string, msgData: string) => void; + postSyncMessage: (msgType: string, msgData: string) => Promise; + setPostMessageFunction: (postMessage: (msgType: string, msgData: string) => void) => void; + setPostSyncMessageFunction: (postSyncMessage: (msgType: string, msgData: string) => void) => void; + nativeEngineInit: () => void; + nativeEngineStart: () => void; + onTextChange: (param: string) => void; + onComplete: (param: string) => void; + onConfirm: (param: string) => void; + shouldStartLoading: (viewTag: number, url: string) => void; + finishLoading: (viewTag: number, url: string) => void; + failLoading: (viewTag: number, url: string) => void; + onBackPress: () => void; + onCreate: () => void; + onDestroy: () => void; + onShow: () => void; + onHide: () => void; + resourceManagerInit: (resourceManager: any) => void; + writablePathInit: (cacheDir: string) => void; + onVideoEvent: (param: string) => void; + registerFunction: (name:string ,fun:Function) => void; +} + +export const getContext: (type: ContextType) => context; diff --git a/templates/openharmony/entry/src/main/cpp/types/libcocos/oh-package.json5 b/templates/openharmony/entry/src/main/cpp/types/libcocos/oh-package.json5 new file mode 100644 index 0000000000..20aaf4fb86 --- /dev/null +++ b/templates/openharmony/entry/src/main/cpp/types/libcocos/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "name": "libcocos.so", + "types": "./index.d.ts", + "version": "", + "description": "Please describe the basic information." +} \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts b/templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts deleted file mode 100644 index 51b6bbd2d4..0000000000 --- a/templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ -import UIAbility from '@ohos.app.ability.UIAbility'; -import nativerender from "libcocos.so"; -import { ContextType } from "../common/Constants" -import window from '@ohos.window'; -import resourceManager from '@ohos.resourceManager'; -//import avsession from '@ohos.multimedia.avsession'; - -const nativeContext = nativerender.getContext(ContextType.ENGINE_UTILS); -const nativeAppLifecycle = nativerender.getContext(ContextType.APP_LIFECYCLE); - -export default class MainAbility extends UIAbility { - onCreate(want, launchParam) { - globalThis.abilityWant = want; - nativeAppLifecycle.onCreate(); - nativeContext.resourceManagerInit(this.context.resourceManager); - let tag = "createAudioSession"; - // TODO(qgh): This is a temporary fix for audio not continuing to play when switching from background to foreground. - // The principle of the fix is to allow the app to continue playing audio after switching background, similar to music apps. - // After a while it will be killed by the system. - // This will cause a crash on harmonyos. - // avsession.createAVSession(this.context, tag, 'audio').then(async (session) =>{ - // globalThis.avsessionManager = session; - // await globalThis.avsessionManager.activate(); - // }) - } - - onDestroy() { - nativeAppLifecycle.onDestroy(); - } - - onWindowStageCreate(windowStage) { - // Main window is created, set main page for this ability - windowStage.loadContent("pages/index", (err, data) => { - if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - return; - } - }); - // Set full screen - windowStage.getMainWindow().then((window: window.Window) => { - window.setWindowSystemBarEnable([]); - }); - nativeContext.writablePathInit(this.context.cacheDir); - } - - onWindowStageDestroy() { - } - - onForeground() { - // Ability has brought to foreground - nativeAppLifecycle.onShow(); - } - - onBackground() { - // Ability has back to background - nativeAppLifecycle.onHide(); - } -}; diff --git a/templates/openharmony/entry/src/main/ets/cocos/WorkerManager.ets b/templates/openharmony/entry/src/main/ets/cocos/WorkerManager.ets index 989b7cfd70..88b7c83498 100644 --- a/templates/openharmony/entry/src/main/ets/cocos/WorkerManager.ets +++ b/templates/openharmony/entry/src/main/ets/cocos/WorkerManager.ets @@ -21,34 +21,37 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ + ****************************************************************************/ import worker from '@ohos.worker'; -import {Constants} from '../common/Constants' +import { Constants } from '../common/Constants' export class WorkerManager { - private static instance: WorkerManager; - private cocosWorker: any; + private cocosWorker: worker.ThreadWorker; - private constructor() { - this.cocosWorker = new worker.Worker("/entry/ets/workers/cocos_worker.ts", {type:"classic", name: "CocosWorker"}); - this.cocosWorker.onerror = function (e) { - var msg = e.message; - var filename = e.filename; - var lineno = e.lineno; - var colno = e.colno; - console.error(`on Error ${msg} ${filename} ${lineno} ${colno}`); - } + private constructor() { + this.cocosWorker = new worker.ThreadWorker("entry/ets/workers/cocos_worker.ts", { + type: "classic", + name: "CocosWorker" + }); + this.cocosWorker.onerror = (e) => { + let msg = e.message; + let filename = e.filename; + let lineno = e.lineno; + let colno = e.colno; + console.error(`on Error ${msg} ${filename} ${lineno} ${colno}`); } + } - public static getInstance(): WorkerManager { - if (AppStorage.Get(Constants.APP_KEY_WORKER_MANAGER) == null) { - AppStorage.SetOrCreate(Constants.APP_KEY_WORKER_MANAGER, new WorkerManager); - } - return AppStorage.Get(Constants.APP_KEY_WORKER_MANAGER); - } - public getWorker(): any { - return this.cocosWorker; + public static getInstance(): WorkerManager { + if (AppStorage.get(Constants.APP_KEY_WORKER_MANAGER) as WorkerManager == undefined) { + AppStorage.setOrCreate(Constants.APP_KEY_WORKER_MANAGER, new WorkerManager); } + return AppStorage.get(Constants.APP_KEY_WORKER_MANAGER) as WorkerManager; + } + + public getWorker(): worker.ThreadWorker { + return this.cocosWorker; + } } diff --git a/templates/openharmony/entry/src/main/ets/cocos/game.ts b/templates/openharmony/entry/src/main/ets/cocos/game.ts index a65faf66eb..0101dd4e84 100644 --- a/templates/openharmony/entry/src/main/ets/cocos/game.ts +++ b/templates/openharmony/entry/src/main/ets/cocos/game.ts @@ -76,8 +76,7 @@ export function launchEngine (): Promise { window.global = window; // @ts-ignore window.oh = window.oh || {}; - return import('./jsb-adapter/sys-ability-polyfill.js').then(({ systemReady }) => { - return systemReady().then(() => { + return import('./oh-adapter/sys-ability-polyfill.js').then(() => { // @ts-ignore window.oh.loadModule = loadModule; return import('./jsb-adapter/web-adapter.js').then(() => { @@ -110,7 +109,6 @@ export function launchEngine (): Promise { }); }); }); - }); }).catch((e: any) => { console.error('imported failed', e.message, e.stack) }); diff --git a/templates/openharmony/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js b/templates/openharmony/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js index aa325bb753..641d0cd9a9 100644 --- a/templates/openharmony/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js +++ b/templates/openharmony/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js @@ -23,10 +23,23 @@ THE SOFTWARE. ****************************************************************************/ import display from '@ohos.display'; -import i18n from '@ohos.i18n' -import deviceInfo from '@ohos.deviceInfo' +import I18n from '@ohos.i18n'; +import deviceInfo from '@ohos.deviceInfo'; import batteryInfo from '@ohos.batteryInfo'; import sensor from '@ohos.sensor'; +import connection from '@ohos.net.connection' +import vibrator from '@ohos.vibrator'; +import { ContextType } from "../common/Constants" +import cocos from "libcocos.so"; + +const systemUtils = cocos.getContext(ContextType.SYSTEM_UTILS); + +let cutout = { + left: 0, + top: 0, + width: 0, + height: 0 +}; export function systemReady () { return new Promise(resolve => { @@ -44,13 +57,17 @@ export function systemReady () { } window.getSystemLanguage = function () { - return i18n.getSystemLanguage(); + return I18n.System.getSystemLanguage(); } window.getOSFullName = function () { return deviceInfo.osFullName; } +window.getDeviceModel = function () { + return deviceInfo.productModel; +} + window.getBatteryLevel = function () { return batteryInfo.batterySOC; } @@ -65,6 +82,19 @@ window.getPixelRation = function () { return displayClass.densityPixels; } +let onDisplayChange = (data) => { + // Monitor changes in screen orientation. + systemUtils.onDisplayChange(window.getDeviceOrientation()); + + // update screen cutout info + window.initScreenInfo(); +} + +try { + display.on("change", onDisplayChange); +} catch (exception) { + console.log('Failed to register callback. Code: ' + JSON.stringify(exception)); +} window.getDeviceOrientation = function () { var displayClass = display.getDefaultDisplaySync(); return displayClass.rotation; @@ -75,10 +105,9 @@ function radiansToDegrees(radians) { return radians * (180/pi); } - let sDeviceMotionValues = []; try { - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function (data) { + sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { sDeviceMotionValues[0] = data.x; sDeviceMotionValues[1] = data.y; sDeviceMotionValues[2] = -data.z; @@ -92,9 +121,7 @@ try { } try { - // TODO(qgh):Must pass values, macros have been renamed and can cause problems with linear sensors - //sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(data){ - sensor.on(258,function(data){ + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function(data){ sDeviceMotionValues[3] = data.x; sDeviceMotionValues[4] = data.y; sDeviceMotionValues[5] = data.z; @@ -107,7 +134,7 @@ try { sDeviceMotionValues[5] = 0; } try { - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ + sensor.on(sensor.SensorId.GYROSCOPE, function(data){ sDeviceMotionValues[6] = radiansToDegrees(data.x); sDeviceMotionValues[7] = radiansToDegrees(data.y); sDeviceMotionValues[8] = radiansToDegrees(data.z); @@ -119,48 +146,83 @@ try { sDeviceMotionValues[7] = 0; sDeviceMotionValues[8] = 0; } -// Keep this, in the master branch, this interface has been replaced. -//try { -// sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { -// sDeviceMotionValues[0] = data.x; -// sDeviceMotionValues[1] = data.y; -// sDeviceMotionValues[2] = data.z; -// }, -// { interval: 10000000000 } -// ); -//} catch (err) { -// sDeviceMotionValues[0] = 0; -// sDeviceMotionValues[1] = 0; -// sDeviceMotionValues[2] = 0; -//} -// -//try { -// sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER,function(data){ -// sDeviceMotionValues[3] = data.x; -// sDeviceMotionValues[4] = data.y; -// sDeviceMotionValues[5] = data.z; -// }, -// {interval: 10000000000} -// ); -//} catch (err) { -// sDeviceMotionValues[3] = 0; -// sDeviceMotionValues[4] = 0; -// sDeviceMotionValues[5] = 0; -//} -//try { -// sensor.on(sensor.SensorId.GYROSCOPE,function(data){ -// sDeviceMotionValues[6] = data.x; -// sDeviceMotionValues[7] = data.y; -// sDeviceMotionValues[8] = data.z; -// }, -// {interval: 10000000000} -// ); -//} catch (err) { -// sDeviceMotionValues[7] = 0; -// sDeviceMotionValues[8] = 0; -// sDeviceMotionValues[9] = 0; -//} window.getDeviceMotionValue = function () { return sDeviceMotionValues; } + +window.getNetworkType = function () { + let netHandle = connection.getDefaultNetSync(); + if(netHandle && netHandle.netId != 0) { + let result = connection.getNetCapabilitiesSync(netHandle); + if (result && result.bearerTypes) { + return result.bearerTypes[0]; + } + } + return -1; +} + +window.vibrate = function (duration) { + console.log('begin to vibrate, duration is.' + duration); + try { + vibrator.startVibration({ + type: 'time', + duration: duration * 1000 + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); + return error.code; + } + console.log('Vibration start sucessful.'); + return 0; + }); + } catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } +} + +window.initScreenInfo = function () { + display.getDefaultDisplaySync().getCutoutInfo().then((data) => { + if (data.boundingRects.length == 0) { + return; + } + + cutout.left = data.boundingRects[0].left; + cutout.top = data.boundingRects[0].top; + cutout.width = data.boundingRects[0].width; + cutout.height = data.boundingRects[0].height; + }).catch((err) => { + console.log("get cutout info error!"); + }); +}; +window.initScreenInfo(); + +window.getCutoutWidth = function () { + if(!cutout.width) { + return 0; + } + + let disPlayWidth = display.getDefaultDisplaySync().width; + if(cutout.left + cutout.width > disPlayWidth - cutout.left) { + return disPlayWidth - cutout.left; + } + return cutout.left + cutout.width; +} + +window.getCutoutHeight = function () { + if(!cutout.height) { + return 0; + } + + let orientation = globalThis.getDeviceOrientation(); + if (orientation == display.Orientation.PORTRAIT) { + return cutout.top + cutout.height; + } else if(orientation == display.Orientation.PORTRAIT_INVERTED) { + let displayHeight = display.getDefaultDisplaySync().height; + return displayHeight - cutout.top; + } + return 0; +} \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js b/templates/openharmony/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js new file mode 100644 index 0000000000..4d25256140 --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js @@ -0,0 +1,221 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +import display from '@ohos.display'; +import I18n from '@ohos.i18n'; +import deviceInfo from '@ohos.deviceInfo'; +import batteryInfo from '@ohos.batteryInfo'; +import sensor from '@ohos.sensor'; +import connection from '@ohos.net.connection' +import vibrator from '@ohos.vibrator'; +import process from '@ohos.process'; +import { ContextType } from "../../common/Constants" +import cocos from "libcocos.so"; + +const displayUtils = cocos.getContext(ContextType.DISPLAY_UTILS); + +let pro = new process.ProcessManager(); +let cutout = { + left: 0, + top: 0, + width: 0, + height: 0 +}; + +globalThis.getSystemLanguage = function () { + return I18n.System.getSystemLanguage(); +} + +globalThis.getOSFullName = function () { + return deviceInfo.osFullName; +} + +globalThis.getDeviceModel = function () { + return deviceInfo.productModel; +} + +globalThis.getBatteryLevel = function () { + return batteryInfo.batterySOC; +} + +globalThis.getDPI = function () { + var displayClass = display.getDefaultDisplaySync(); + return displayClass.densityDPI; +} + +globalThis.getPixelRation = function () { + var displayClass = display.getDefaultDisplaySync(); + return displayClass.densityPixels; +} + +let onDisplayChange = (data) => { + // Monitor changes in screen orientation. + displayUtils.onDisplayChange(globalThis.getDeviceOrientation()); + + // update screen cutout info + globalThis.initScreenInfo(); +} + +try { + display.on("change", onDisplayChange); +} catch (exception) { + console.log('Failed to register callback. Code: ' + JSON.stringify(exception)); +} + +globalThis.getDeviceOrientation = function () { + var displayClass = display.getDefaultDisplaySync(); + return displayClass.rotation; +} + +function radiansToDegrees(radians) { + var pi = Math.PI; + return radians * (180/pi); +} + +let sDeviceMotionValues = []; +try { + sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { + sDeviceMotionValues[0] = data.x; + sDeviceMotionValues[1] = data.y; + sDeviceMotionValues[2] = -data.z; + }, + { interval: 200000000 } + ); +} catch (err) { + sDeviceMotionValues[0] = 0; + sDeviceMotionValues[1] = 0; + sDeviceMotionValues[2] = 0; +} + +try { + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function(data){ + sDeviceMotionValues[3] = data.x; + sDeviceMotionValues[4] = data.y; + sDeviceMotionValues[5] = data.z; + }, + {interval: 200000000} + ); +} catch (err) { + sDeviceMotionValues[3] = 0; + sDeviceMotionValues[4] = 0; + sDeviceMotionValues[5] = 0; +} +try { + sensor.on(sensor.SensorId.GYROSCOPE, function(data){ + sDeviceMotionValues[6] = radiansToDegrees(data.x); + sDeviceMotionValues[7] = radiansToDegrees(data.y); + sDeviceMotionValues[8] = radiansToDegrees(data.z); + }, + {interval: 200000000} + ); +} catch (err) { + sDeviceMotionValues[6] = 0; + sDeviceMotionValues[7] = 0; + sDeviceMotionValues[8] = 0; +} + +globalThis.getDeviceMotionValue = function () { + return sDeviceMotionValues; +} + + +globalThis.getNetworkType = function () { + let netHandle = connection.getDefaultNetSync(); + if(netHandle && netHandle.netId != 0) { + let result = connection.getNetCapabilitiesSync(netHandle); + if (result && result.bearerTypes) { + return result.bearerTypes[0]; + } + } + return -1; +} + +globalThis.vibrate = function (duration) { + console.log('begin to vibrate, duration is.' + duration); + try { + vibrator.startVibration({ + type: 'time', + duration: duration * 1000 + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); + return error.code; + } + console.log('Vibration start sucessful.'); + return 0; + }); + } catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } +} + +globalThis.terminateProcess = function () { + pro.exit(0); +} + +globalThis.initScreenInfo = function () { + display.getDefaultDisplaySync().getCutoutInfo().then((data) => { + if (data.boundingRects.length == 0) { + return; + } + const rc = data.boundingRects[0]; + cutout.left = rc.left; + cutout.top = rc.top; + cutout.width = rc.width; + cutout.height = rc.height; + }).catch((err) => { + console.log("get cutout info error!"); + }); +}; +globalThis.initScreenInfo(); + +globalThis.getCutoutWidth = function () { + if(!cutout.width) { + return 0; + } + + let disPlayWidth = display.getDefaultDisplaySync().width; + if(cutout.left + cutout.width > disPlayWidth - cutout.left) { + return disPlayWidth - cutout.left; + } + return cutout.left + cutout.width; +} + +globalThis.getCutoutHeight = function () { + if(!cutout.height) { + return 0; + } + + let orientation = globalThis.getDeviceOrientation(); + if (orientation == display.Orientation.PORTRAIT) { + return cutout.top + cutout.height; + } else if(orientation == display.Orientation.PORTRAIT_INVERTED) { + let displayHeight = display.getDefaultDisplaySync().height; + return displayHeight - cutout.top; + } + return 0; +} diff --git a/templates/openharmony/entry/src/main/ets/common/Constants.ts b/templates/openharmony/entry/src/main/ets/common/Constants.ts index cb0e64fc7e..6247ef4030 100644 --- a/templates/openharmony/entry/src/main/ets/common/Constants.ts +++ b/templates/openharmony/entry/src/main/ets/common/Constants.ts @@ -32,8 +32,10 @@ export enum ContextType { ENGINE_UTILS, EDITBOX_UTILS, WEBVIEW_UTILS, + SYSTEM_UTILS, + DISPLAY_UTILS, UV_ASYNC_SEND, - VIDEO_UTILS, + VIDEO_UTILS } export class Constants { diff --git a/templates/openharmony/entry/src/main/ets/common/PortProxy.ts b/templates/openharmony/entry/src/main/ets/common/PortProxy.ts index a28d396f45..0c06ca5c95 100644 --- a/templates/openharmony/entry/src/main/ets/common/PortProxy.ts +++ b/templates/openharmony/entry/src/main/ets/common/PortProxy.ts @@ -21,57 +21,56 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ -import worker from '@ohos.worker'; -import {DedicatedWorkerGlobalScope} from '@ohos.worker'; -// NOTE: don't use this import all statement, because this has compile issue. -// import * as wk from '@ohos.worker'; + ****************************************************************************/ +import { ThreadWorkerGlobalScope } from '@ohos.worker'; import { MessageEvent } from '@ohos.worker'; export class PortProxy { - private autoId: number = 0; - public actionHandleMap = {} - private port :DedicatedWorkerGlobalScope = null; + private autoId: number = 0; + public actionHandleMap = {} + private port: ThreadWorkerGlobalScope = null; - public _messageHandle?:(e: MessageEvent) => void; + public _messageHandle?: (e: MessageEvent) => void; - constructor (port) { - this.port = port; - this.port.onmessage = this.onMessage.bind(this); - } + constructor(worker) { + this.port = worker; + this.port.onmessage = this.onMessage.bind(this); + } - public onMessage(e) { - let data = e['data']; - if(data.type != "syncResult" && this._messageHandle) { - this._messageHandle(e); - } else if(data.type == "syncResult") { - const {id, response} = data.data; - if (!this.actionHandleMap[id]) { - return; - } - this.actionHandleMap[id].call(this, response) - delete this.actionHandleMap[id]; - } - } - public postReturnMessage(e:any, res: any) { - if(e.type == "sync" && res != null && res != undefined) { - this.port.postMessage({type:"syncResult", data:{id:e.data.cbId, response:res}}); - } - } - public postMessage(msgName: string, msgData:any) { - this.port.postMessage({type:"async", data:{name:msgName, param:msgData}}); + public onMessage(e) { + let data = e['data']; + if (data.type != "syncResult" && this._messageHandle) { + this._messageHandle(e); + } else if (data.type == "syncResult") { + const { id, response } = data.data; + if (!this.actionHandleMap[id]) { + return; + } + this.actionHandleMap[id].call(this, response); + delete this.actionHandleMap[id]; } + } - public postSyncMessage(msgName: string, msgData:any) { - const id = this.autoId++; - return new Promise((resolve, reject) => { - const message = { - type:"sync", data:{cbId:id, name:msgName, param:msgData} - } - this.port.postMessage(message); - this.actionHandleMap[id] = (response) => { - resolve(response) - } - }) + public postReturnMessage(e: any, res: any) { + if (e.type == "sync" && res != null && res != undefined) { + this.port.postMessage({ type: "syncResult", data: { id: e.data.cbId, response: res } }); } + } + + public postMessage(msgName: string, msgData: any) { + this.port.postMessage({ type: "async", data: { name: msgName, param: msgData } }); + } + + public postSyncMessage(msgName: string, msgData: any) { + const id = this.autoId++; + return new Promise((resolve, reject) => { + const message = { + type: "sync", data: { cbId: id, name: msgName, param: msgData } + } + this.port.postMessage(message); + this.actionHandleMap[id] = (response) => { + resolve(response) + } + }) + } } \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/components/CocosVideoPlayer.ets b/templates/openharmony/entry/src/main/ets/components/CocosVideoPlayer.ets index 86d2703a62..679d4799ce 100644 --- a/templates/openharmony/entry/src/main/ets/components/CocosVideoPlayer.ets +++ b/templates/openharmony/entry/src/main/ets/components/CocosVideoPlayer.ets @@ -21,9 +21,8 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ -import { WorkerManager } from '../cocos/WorkerManager' -import { PortProxy } from '../common/PortProxy' + ****************************************************************************/ +import { PortProxy } from '../common/PortProxy'; enum EventType { PLAYING = 0, @@ -35,7 +34,13 @@ enum EventType { READY_TO_PLAY, UPDATE, QUIT_FULLSCREEN = 1000 -}; +} + +interface param { + videoTag?: number, + videoEvent?: EventType, + args?: number +} @Observed export class VideoInfo { @@ -44,22 +49,22 @@ export class VideoInfo { public w: number = 0; public h: number = 0; // url - public url: string = "" - public viewTag: string = '' - public visible: boolean = true - + public url: string | Resource = ""; + public viewTag: number = 0; + public visible: boolean = true; public duration: number = 0; public currentTime: number = 0; public isFullScreen: boolean = false; - public currentProgressRate:number | string | PlaybackSpeed; - + public currentProgressRate?: number | string | PlaybackSpeed; + public resourceType: number = 0; + public isPreparedStart: boolean = false; /** * https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-media-components-video.md#videocontroller * */ public controller: VideoController = new VideoController() - constructor(x: number, y: number, w: number, h: number, viewTag: string) { + constructor(x: number, y: number, w: number, h: number, viewTag: number) { this.x = x; this.y = y; this.w = w; @@ -68,46 +73,73 @@ export class VideoInfo { } } - @Component export struct CocosVideoPlayer { @ObjectLink videoInfo: VideoInfo; - public workPort: PortProxy; + public workPort: PortProxy | null = null; + build() { - Video({ src: this.videoInfo.url, controller: this.videoInfo.controller, currentProgressRate:this.videoInfo.currentProgressRate }) + Video({ + src: this.videoInfo.url, + controller: this.videoInfo.controller, + currentProgressRate: this.videoInfo.currentProgressRate as number | string | PlaybackSpeed + }) .position({ x: this.videoInfo.x, y: this.videoInfo.y }) .width(this.videoInfo.w) .height(this.videoInfo.h) .controls(false) - .autoPlay(true) + .autoPlay(false) .onStart(() => { - this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.PLAYING}); + this.workPort?.postMessage("onVideoEvent", { + videoTag: this.videoInfo.viewTag as number, + videoEvent: EventType.PLAYING as EventType + } as param); }) .onPause(() => { - this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.PAUSED}); + this.workPort?.postMessage("onVideoEvent", { + videoTag: this.videoInfo.viewTag as number, + videoEvent: EventType.PAUSED as EventType + } as param); }) .onFinish(() => { - this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.COMPLETED}); + this.workPort?.postMessage("onVideoEvent", { + videoTag: this.videoInfo.viewTag, + videoEvent: EventType.COMPLETED + } as param); }) - .onPrepared((event: { - duration: number; - }) => { - this.videoInfo.duration = event.duration; - this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.READY_TO_PLAY, args:event.duration}); + .onPrepared((event): void => { + this.videoInfo.isPreparedStart && this.videoInfo.controller.start(); + + this.videoInfo.duration = event?.duration as number; + this.workPort?.postMessage("onVideoEvent", { + videoTag: this.videoInfo.viewTag, + videoEvent: EventType.READY_TO_PLAY, + args: event?.duration + } as param); }) - .onUpdate((event?: { - time: number; - }) => { - this.videoInfo.currentTime = event.time - this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.UPDATE, args:event.time}); + .onClick((event): void => { + this.workPort?.postMessage("onVideoEvent", { + videoTag: this.videoInfo.viewTag, + videoEvent: EventType.CLICKED + } as param); }) - .onFullscreenChange((event?: { - fullscreen: boolean; - }) => { - if (!event.fullscreen) { - this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.QUIT_FULLSCREEN}); + .onUpdate((event) => { + this.videoInfo.currentTime = event?.time as number; + this.workPort?.postMessage("onVideoEvent", { + videoTag: this.videoInfo.viewTag, + videoEvent: EventType.UPDATE, + args: event?.time + } as param); + }) + .onFullscreenChange((event) => { + if (!event?.fullscreen) { + this.workPort?.postMessage("onVideoEvent", { + videoTag: this.videoInfo.viewTag, + videoEvent: EventType.QUIT_FULLSCREEN + } as param); } - this.videoInfo.isFullScreen = event.fullscreen + this.videoInfo.isFullScreen = event?.fullscreen as boolean; }) + .visibility(this.videoInfo.visible ? Visibility.Visible : Visibility.None) } } \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/components/CocosWebView.ets b/templates/openharmony/entry/src/main/ets/components/CocosWebView.ets index ab6448d8c6..9368735ca1 100644 --- a/templates/openharmony/entry/src/main/ets/components/CocosWebView.ets +++ b/templates/openharmony/entry/src/main/ets/components/CocosWebView.ets @@ -21,9 +21,15 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ -import { WorkerManager } from '../cocos/WorkerManager' -import { PortProxy } from '../common/PortProxy' + ****************************************************************************/ +import { PortProxy } from '../common/PortProxy'; +import web from '@ohos.web.webview'; + +interface param { + viewTag: number, + url: string, +} + @Observed export class WebViewInfo { // position @@ -33,47 +39,66 @@ export class WebViewInfo { public w: number = 0; public h: number = 0; // url - public url: string = '' + public url: string = ''; // tag - public viewTag: string = '' + public viewTag: number = 0; // Whether to display - public visible: boolean = true - + public visible: boolean = true; /* * doc : https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md#webcontroller */ - public controller: WebController = new WebController() + public controller: web.WebviewController = new web.WebviewController(); - constructor(x: number, y: number, w: number, h: number, viewTag: string) { + constructor(x: number, y: number, w: number, h: number, viewTag: number) { this.x = x; this.y = y; this.w = w; this.h = h; - this.viewTag = viewTag + this.viewTag = viewTag; + + web.once("webInited", () => { + if (this.url != '') { + this.controller.loadUrl(this.url); + } + }); } } @Component export struct CocosWebView { @ObjectLink viewInfo: WebViewInfo; - public workPort: PortProxy; + public workPort: PortProxy | null = null; + build() { Web({ src: this.viewInfo.url, controller: this.viewInfo.controller }) .position({ x: this.viewInfo.x, y: this.viewInfo.y }) .width(this.viewInfo.w) .height(this.viewInfo.h) .border({ width: 1 }) + .onControllerAttached(() => { + if (this.viewInfo.url != '') { + this.viewInfo.controller.loadUrl(this.viewInfo.url); + } + }) .onPageBegin((event) => { - this.workPort.postMessage("onPageBegin", {viewTag:this.viewInfo.viewTag, url:event.url}); + this.workPort?.postMessage("onPageBegin", { + viewTag: this.viewInfo.viewTag as number, + url: event?.url as string + } as param); }) .onPageEnd((event) => { - this.workPort.postMessage("onPageEnd", {viewTag:this.viewInfo.viewTag, url:event.url}) + this.workPort?.postMessage("onPageEnd", { viewTag: this.viewInfo.viewTag as number, url: event?.url as string } as param) }) .onErrorReceive((event) => { - this.workPort.postMessage("onErrorReceive", {viewTag:this.viewInfo.viewTag, url:this.viewInfo.url}) + this.workPort?.postMessage("onErrorReceive", { viewTag: this.viewInfo.viewTag as number, url: this.viewInfo.url as string } as param) }) .onHttpErrorReceive((event) => { - this.workPort.postMessage("onErrorReceive", {viewTag:this.viewInfo.viewTag, url:this.viewInfo.url}) + this.workPort?.postMessage("onErrorReceive", { viewTag: this.viewInfo.viewTag as number, url: this.viewInfo.url as string } as param) }) + .domStorageAccess(true)// enable DOM storage permissions + .databaseAccess(true)// enable database storage permissions + .imageAccess(true)// enable image loading permissions + .javaScriptAccess(true)// support JS code running + .visibility(this.viewInfo.visible ? Visibility.Visible : Visibility.None) } } \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/components/EditBoxDialog.ets b/templates/openharmony/entry/src/main/ets/components/EditBoxDialog.ets index 643c053212..f8f587a441 100644 --- a/templates/openharmony/entry/src/main/ets/components/EditBoxDialog.ets +++ b/templates/openharmony/entry/src/main/ets/components/EditBoxDialog.ets @@ -21,22 +21,43 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ + ****************************************************************************/ +@Observed +export class EditboxShowInfo { + public backgroundColor: number = 0xFFFFFFFF; + public enterKeyType: EnterKeyType = EnterKeyType.Done; + public type:InputType = InputType.Normal; + public maxLength: number = 65536; + public defaultMessage: string = ''; + public textAlign: TextAlign = TextAlign.Start; + public showUnderline: boolean = false; + public multiLines: boolean = false; + // API12 + public underLineColor: number = 0xFFFFFFFF; +} + @CustomDialog export struct EditBoxDialog { - private showMessage: string = '' private inputMessage: string = '' - onTextChange: (msg: string) => void - accept: (msg: string) => void - controller: CustomDialogController - cancel: () => void - confirm: () => void + @ObjectLink showInfo: EditboxShowInfo; + onTextChange?: (msg: string) => void; + accept?: (msg: string) => void; + controller?: CustomDialogController; + cancel?: () => void; + confirm?: (msg: string) => void; build() { Column() { Row() { - TextInput({ text: this.showMessage }) + TextInput({ text: this.showInfo.defaultMessage }) + .defaultFocus(true) .backgroundColor('#ffffff') + .backgroundColor(this.showInfo.backgroundColor) + .type(this.showInfo.type) + .maxLength(this.showInfo.maxLength) + .textAlign(this.showInfo.textAlign) + .showUnderline(this.showInfo.showUnderline) + .enterKeyType(this.showInfo.enterKeyType) .layoutWeight(1) .onChange((value) => { if (this.onTextChange) { @@ -45,21 +66,21 @@ export struct EditBoxDialog { this.inputMessage = value; }) .onSubmit((value) => { - if (this.accept) { - this.accept(this.inputMessage); + if(this.confirm) { + this.confirm(this.inputMessage); } - this.controller.close(); + this.controller?.close(); }) Blank(8).width(16) Button('完成').onClick(() => { if (this.accept) { this.accept(this.inputMessage); } - this.controller.close(); + this.controller?.close(); }) }.padding({ left: 8, right: 8, top: 8, bottom: 8 }) .backgroundColor(Color.Gray) - + .offset({ x : 0, y : 15 }) } .width('100%') diff --git a/templates/openharmony/entry/src/main/ets/entryability/EntryAbility.ts b/templates/openharmony/entry/src/main/ets/entryability/EntryAbility.ts new file mode 100644 index 0000000000..313242bd1b --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/entryability/EntryAbility.ts @@ -0,0 +1,89 @@ +import UIAbility from '@ohos.app.ability.UIAbility'; +import cocos from 'libcocos.so'; +import { ContextType } from '../common/Constants'; +import window from '@ohos.window'; + +const nativeContext = cocos.getContext(ContextType.ENGINE_UTILS); +const nativeAppLifecycle = cocos.getContext(ContextType.APP_LIFECYCLE); + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + globalThis.abilityWant = want; + nativeAppLifecycle.onCreate(); + nativeContext.resourceManagerInit(this.context.resourceManager); + } + + onDestroy() { + nativeAppLifecycle.onDestroy(); + } + + onWindowStageCreate(windowStage: window.WindowStage) { + nativeContext.writablePathInit(this.context.cacheDir); + + // Get the Main window instance + let windowClass = null; + windowStage.getMainWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); + + // 设置窗口为全屏布局,配合设置导航栏、状态栏是否显示,与主窗口显示保持协调一致。 + let isLayoutFullScreen = true; + windowClass.setWindowLayoutFullScreen(isLayoutFullScreen, (err) => { + if (err.code) { + console.error('Failed to set the window layout to full-screen mode. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window layout to full-screen mode.'); + }); + + // 设置状态栏和导航栏是否显示。例如,需全部显示,该参数设置为['status', 'navigation'];不设置,则默认不显示。 + let visibleBar = []; + windowClass.setWindowSystemBarEnable(visibleBar, (err) => { + if (err.code) { + console.error('Failed to set the system bar to be invisible. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar to be invisible.'); + }); + }); + + // Main window is created, set main page for this ability + windowStage.loadContent("pages/index", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + }); + windowStage.on("windowStageEvent", (data) => { + let stageEventType: window.WindowStageEventType = data; + switch (stageEventType) { + case window.WindowStageEventType.RESUMED: + nativeAppLifecycle.onShow(); + break; + case window.WindowStageEventType.PAUSED: + nativeAppLifecycle.onHide(); + break; + default: + break; + } + }); + } + + onWindowStageDestroy() { + + } + + onForeground() { + // Ability has brought to foreground + nativeAppLifecycle.onShow(); + } + + onBackground() { + // Ability has back to background + nativeAppLifecycle.onHide(); + } +} diff --git a/templates/openharmony/entry/src/main/ets/pages/index.ets b/templates/openharmony/entry/src/main/ets/pages/index.ets index a2f8944a9b..ece83ee022 100644 --- a/templates/openharmony/entry/src/main/ets/pages/index.ets +++ b/templates/openharmony/entry/src/main/ets/pages/index.ets @@ -21,221 +21,362 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ -import nativerender from "libcocos.so"; + ****************************************************************************/ +import nativerender,{context} from 'libcocos.so'; -import { WorkerManager } from '../cocos/WorkerManager' -import { ContextType } from "../common/Constants" -import featureAbility from '@ohos.ability.featureAbility' -import { EditBoxDialog } from '../components/EditBoxDialog' -import { WebViewInfo, CocosWebView } from '../components/CocosWebView' -import { VideoInfo, CocosVideoPlayer } from '../components/CocosVideoPlayer' +import { WorkerManager } from '../cocos/WorkerManager'; +import { ContextType } from '../common/Constants'; +import { EditBoxDialog, EditboxShowInfo } from '../components/EditBoxDialog'; +import { CocosWebView, WebViewInfo } from '../components/CocosWebView'; +import { CocosVideoPlayer, VideoInfo } from '../components/CocosVideoPlayer'; +import { MessageEvent } from '@ohos.worker'; +import { PortProxy } from '../common/PortProxy'; +import { common } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; -import {PortProxy} from '../common/PortProxy' -const nativePageLifecycle = nativerender.getContext(ContextType.JSPAGE_LIFECYCLE); -const engineUtils = nativerender.getContext(ContextType.ENGINE_UTILS); +const nativePageLifecycle :context = nativerender.getContext(ContextType.JSPAGE_LIFECYCLE); +const engineUtils :context = nativerender.getContext(ContextType.ENGINE_UTILS); + + +function executeNativeMethod(nativeFunc: Function, funcData: string, funCb: Function): void { + nativeFunc && nativeFunc(funcData, funCb); +} +engineUtils.registerFunction("executeNativeMethod", executeNativeMethod); + +interface WorkerMessage { + type: string; + data: data; +} + +interface data { + id: string, + name: string, + param: number | string | param +} + +interface param { + tag?: number, + url?: string, + contents?: string, + mimeType?: string, + encoding?: string, + baseUrl?: string, + jsContents?: string, + x?: number, + y?: number, + w?: number, + h?: number, + visible?: boolean, + resourceType?: number, + time?: number, + fullScreen?: boolean +} + +interface editboxShowInfo { + defaultValue?: string; + confirmType?: string; + inputType?: string; + maxLength?: number; + x?:number; + y?:number; + width?:number; + height?:number; + confirmHold?: boolean; + isMultiline?: boolean; + fontSize?: number; + fontColor?: number; + backColor?: number; + backgroundColor?: number; + isBold?: boolean; + isItalic?: boolean; + isUnderline?: boolean; + underlineColor?: number; + textAlignment?: number; +} @Entry @Component struct Index { - @State showMessage: string = '' + @State showInfo: EditboxShowInfo = new EditboxShowInfo; @State webViewArray: WebViewInfo[] = []; - @State videoArray:VideoInfo[] = []; - //private index: number = 0; - private webViewIndexMap: Map = new Map; - private videoIndexMap: Map = new Map; - - private workPort : PortProxy = new PortProxy(WorkerManager.getInstance().getWorker()); + @State videoArray: VideoInfo[] = []; + private webViewIndexMap: Map = new Map(); + private videoIndexMap: Map = new Map(); + private workPort: PortProxy = new PortProxy(WorkerManager.getInstance().getWorker()); dialogController: CustomDialogController = new CustomDialogController({ builder: EditBoxDialog({ - showMessage: this.showMessage, - onTextChange: (msg: string) => { - this.showMessage = msg; - this.workPort.postMessage('onTextInput', msg) + showInfo: this.showInfo, + onTextChange: (msg: string): void => { + this.showInfo.defaultMessage = msg; + this.workPort.postMessage('onTextInput', msg); }, - accept: (msg: string) => { - this.showMessage = msg; - this.workPort.postMessage('onComplete', msg) + accept: (msg: string): void => { + this.showInfo.defaultMessage = msg; + this.workPort.postMessage('onComplete', msg); + }, + confirm: (msg: string): void => { + this.showInfo.defaultMessage = msg; + this.workPort.postMessage('onConfirm', msg); + this.workPort.postMessage('onComplete', msg); }, }), - cancel: () => { - this.workPort.postMessage('onComplete', this.showMessage) + cancel: (): void => { + this.workPort.postMessage('onComplete', this.showInfo.defaultMessage); }, autoCancel: true, alignment: DialogAlignment.Bottom, customStyle: true, }) - aboutToAppear(): void { + aboutToAppear(): void { console.log('[LIFECYCLE-Index] cocos aboutToAppear'); - this.workPort._messageHandle = (e) => { - //let data = e['data']; - var data = e.data; - var msg = data.data; - var result; + this.workPort._messageHandle = async (e: MessageEvent): Promise => { + let data: WorkerMessage = e.data; + let msg = data.data; + let result: boolean | string | number | null = null; switch (msg.name) { // EditBox case "showEditBox": { - this.showMessage = msg.param - this.dialogController.open() + let param = msg.param as editboxShowInfo; + this.showInfo.defaultMessage = param?.defaultValue as string; + this.showInfo.backgroundColor = param?.backColor as number; + if(param?.confirmType == 'done') { + this.showInfo.enterKeyType = EnterKeyType.Done; + } else if(param?.confirmType == 'send') { + this.showInfo.enterKeyType = EnterKeyType.Send; + } else if(param?.confirmType == 'search') { + this.showInfo.enterKeyType = EnterKeyType.Search; + } else if(param?.confirmType == 'go') { + this.showInfo.enterKeyType = EnterKeyType.Go; + } else if(param?.confirmType == 'next') { + this.showInfo.enterKeyType = EnterKeyType.Next; + } else { + this.showInfo.enterKeyType = EnterKeyType.Done; + } + if(param?.inputType == 'password') { + this.showInfo.type = InputType.Password; + } else if(param?.inputType === 'email') { + this.showInfo.type = InputType.Email; + } else if(param?.inputType === 'number') { + this.showInfo.type = InputType.Number; + } else if(param?.inputType === 'digit') { + this.showInfo.type = InputType.NUMBER_DECIMAL; + } else if(param?.inputType === 'tel') { + this.showInfo.type = InputType.PhoneNumber; + } else if(param?.inputType === 'url') { + // No url support + } else { + this.showInfo.type = InputType.Normal; + } + if(param?.maxLength != undefined && param?.maxLength > 0) { + this.showInfo.maxLength = param.maxLength; + } else { + this.showInfo.maxLength = 65536; + } + + if(param?.isUnderline != undefined) { + this.showInfo.showUnderline = param?.isUnderline; + this.showInfo.underLineColor = param?.underlineColor as number; + } else { + this.showInfo.showUnderline = false; + } + + if(param?.textAlignment == 0) { + this.showInfo.textAlign = TextAlign.Start; + } else if(param?.textAlignment == 1) { + this.showInfo.textAlign = TextAlign.Center; + } else if(param?.textAlignment == 2) { + this.showInfo.textAlign = TextAlign.End; + } else { + this.showInfo.textAlign = TextAlign.Start; + } + this.dialogController.open(); break; } case "hideEditBox": { - this.showMessage = '' - this.dialogController.close() + this.showInfo.defaultMessage = ''; + this.dialogController.close(); break; } // WebView case "createWebView": { - this.webViewArray.push(new WebViewInfo(0, 0, 0, 0, msg.param)) - this.webViewIndexMap.set(msg.param, this.webViewArray.length - 1); + this.webViewArray.push(new WebViewInfo(0, 0, 0, 0, msg.param as number)); + this.webViewIndexMap.set(msg.param as number, this.webViewArray.length - 1); break; } case "removeWebView": { if (this.webViewArray.length > 0) { - this.webViewArray.splice(this.webViewIndexMap.get(msg.param), 1) + this.webViewArray.splice(this.webViewIndexMap.get(msg?.param as number) as number, 1); } break; } case "loadUrl": { - var web = msg.param; - var index = this.webViewIndexMap.get(web.tag); - this.webViewArray[index].controller.loadUrl({url: web.url}); + let web = msg.param as param; + let index = this.webViewIndexMap.get(web?.tag as number) as number; + this.webViewArray[index].url = web?.url as string; + this.webViewArray[index].controller.loadUrl(web?.url as string); break; } case "loadHTMLString": { - var web = msg.param; - var index = this.webViewIndexMap.get(web.tag); - this.webViewArray[index].controller.loadData({data: web.contents, mimeType:"text/html",encoding:"UTF-8", baseUrl:web.baseUrl}); + let web = msg.param as param; + let index = this.webViewIndexMap.get(web?.tag as number) as number; + this.webViewArray[index].controller.loadData( + web?.contents as string, + "text/html", + "UTF-8", + web?.baseUrl + ); break; } case "loadData": { - var web = msg.param; - var index = this.webViewIndexMap.get(web.tag); - this.webViewArray[index].controller.loadData({data: web.contents, mimeType:web.mimeType,encoding:web.encoding, baseUrl:web.baseUrl}); + let web = msg.param as param; + let index = this.webViewIndexMap.get(web?.tag as number) as number; + this.webViewArray[index].controller.loadData( + web?.contents as string, + web?.mimeType as string, + web?.encoding as string, + web?.baseUrl as string + ); break; } case "evaluateJS": { - var web = msg.param; - var index = this.webViewIndexMap.get(web.tag) - this.webViewArray[index].controller.runJavaScript({ - script: web.jsContents - }); + let web = msg.param as param; + let index = this.webViewIndexMap.get(web?.tag as number) as number; + this.webViewArray[index].controller.runJavaScript(web?.jsContents as string); break; } case "reload": { - var index = this.webViewIndexMap.get(msg.param); + let index = this.webViewIndexMap.get(msg.param as number) as number; this.webViewArray[index].controller.refresh(); break; } case "stopLoading": { - var index = this.webViewIndexMap.get(msg.param); + let index = this.webViewIndexMap.get(msg.param as number) as number; this.webViewArray[index].controller.stop(); break; } case "canGoForward": { - var index = this.webViewIndexMap.get(msg.param); + let index = this.webViewIndexMap.get(msg.param as number) as number; result = this.webViewArray[index].controller.accessForward(); break; } case "canGoBack": { - var index = this.webViewIndexMap.get(msg.param); + let index = this.webViewIndexMap.get(msg.param as number) as number; result = this.webViewArray[index].controller.accessBackward(); break; } case "goForward": { - var index = this.webViewIndexMap.get(msg.param); + let index = this.webViewIndexMap.get(msg.param as number) as number; this.webViewArray[index].controller.forward(); break; } case "goBack": { - var index = this.webViewIndexMap.get(msg.param); + let index = this.webViewIndexMap.get(msg.param as number) as number; this.webViewArray[index].controller.backward(); break; } case "setWebViewRect": { - var web = msg.param; - var index = this.webViewIndexMap.get(web.tag); - this.webViewArray[index].x = px2vp(web.x); - this.webViewArray[index].y = px2vp(web.y); - this.webViewArray[index].w = px2vp(web.w); - this.webViewArray[index].h = px2vp(web.h); + let web = msg.param as param + let index = this.webViewIndexMap.get(web?.tag as number) as number; + this.webViewArray[index].x = px2vp(web?.x as number) as number; + this.webViewArray[index].y = px2vp(web?.y as number) as number; + this.webViewArray[index].w = px2vp(web?.w as number) as number; + this.webViewArray[index].h = px2vp(web?.h as number) as number; + break; } - case "setVisible": - var web = msg.param; - var index = this.webViewIndexMap.get(web.tag); - this.webViewArray[index].visible = web.visible; + case "setVisible": { + let web = msg.param as param; + let index = this.webViewIndexMap.get(web?.tag as number) as number; + this.webViewArray[index].visible = web?.visible as boolean; break; - // video - case "createVideo": - this.videoArray.push(new VideoInfo(0, 0, 0, 0, msg.param)) - this.videoIndexMap.set(msg.param, this.videoArray.length - 1); + } + // video + case "createVideo": { + this.videoArray.push(new VideoInfo(0, 0, 0, 0, msg.param as number)); + this.videoIndexMap.set(msg.param as number, this.videoArray.length - 1); break; - case "removeVideo": + } + case "removeVideo": { if (this.videoArray.length > 0) { - this.videoArray.splice(this.videoIndexMap.get(msg.param), 1) + this.videoArray.splice(this.videoIndexMap.get(msg.param as number) as number, 1); } break; + } case "setVideoUrl": - var video = msg.param; - var index = this.videoIndexMap.get(video.tag); - this.videoArray[index].url = video.url; + let video = msg.param as param; + let index = this.videoIndexMap.get(video?.tag as number) as number; + let resourceType = video.resourceType; + if (resourceType == 1) { + video.url = 'Resources/' + video.url; + this.videoArray[index].url = $rawfile(video.url as string); + } else { + this.videoArray[index].url = video.url as string; + } break; case "setVideoRect": { - var video = msg.param; - var index = this.videoIndexMap.get(video.tag); - this.videoArray[index].x = px2vp(video.x); - this.videoArray[index].y = px2vp(video.y); - this.videoArray[index].w = px2vp(video.w); - this.videoArray[index].h = px2vp(video.h); + let video = msg.param as param; + let index = this.videoIndexMap.get(video?.tag as number) as number; + this.videoArray[index].x = px2vp(video?.x as number) as number; + this.videoArray[index].y = px2vp(video?.y as number) as number; + this.videoArray[index].w = px2vp(video?.w as number) as number; + this.videoArray[index].h = px2vp(video?.h as number) as number; break; } case "startVideo": { - var index = this.videoIndexMap.get(msg.param); - this.videoArray[index].controller.start(); + let index = this.videoIndexMap.get(msg.param as number) as number; + if(this.videoArray[index].duration){ + this.videoArray[index].controller.start(); + }else{ + this.videoArray[index].isPreparedStart = true; + } break; } - case "pauseVideo" : { - var index = this.videoIndexMap.get(msg.param); + case "pauseVideo": { + let index = this.videoIndexMap.get(msg.param as number) as number; this.videoArray[index].controller.pause(); break; } - case "stopVideo" : { - var index = this.videoIndexMap.get(msg.param); + case "stopVideo": { + let index = this.videoIndexMap.get(msg.param as number) as number; this.videoArray[index].controller.stop(); break; } case "resumeVideo": { - var index = this.videoIndexMap.get(msg.param); + let index = this.videoIndexMap.get(msg.param as number) as number; this.videoArray[index].controller.start(); break; } case "getVideoDuration": { - var index = this.videoIndexMap.get(msg.param); + let index = this.videoIndexMap.get(msg.param as number) as number; result = this.videoArray[index].duration; break; } - case "seekVideoTo" : { - var video = msg.param; - var index = this.videoIndexMap.get(video.tag); - this.videoArray[index].controller.setCurrentTime(video.time, SeekMode.Accurate); + case "seekVideoTo": { + let video = msg.param as param; + let index = this.videoIndexMap.get(video?.tag as number) as number; + this.videoArray[index].controller.setCurrentTime(video?.time as number, SeekMode.Accurate); break; } - case "setVideoVisible" : { - var video = msg.param; - var index = this.videoIndexMap.get(video.tag); - this.videoArray[index].visible = video.visible; + case "setVideoVisible": { + let video = msg.param as param; + let index = this.videoIndexMap.get(video?.tag as number) as number; + this.videoArray[index].visible = video.visible as boolean; break; } case "setFullScreenEnabled": { - var video = msg.param; - var index = this.videoIndexMap.get(video.tag); - this.videoArray[index].isFullScreen = video.fullScreen; + let video = msg.param as param; + let index = this.videoIndexMap.get(video?.tag as number) as number; + this.videoArray[index].isFullScreen = video.fullScreen as boolean; break; } case "currentTime": { - var index = this.videoIndexMap.get(msg.param); + let index = this.videoIndexMap.get(msg.param as number) as number; result = this.videoArray[index].currentTime; + break; + } + case "exitGame": { + this.terminateSelf(); + break; } default: { @@ -263,9 +404,36 @@ struct Index { nativePageLifecycle.onPageHide(); } + onBackPress() { + console.log("[LIFECYCLE-Page] cocos onBackPress"); + this.workPort.postMessage("backPress", ""); + // If disable system exit needed, remove comment "return true" + // return true; + } + + terminateSelf() { + try { + (getContext(this) as common.UIAbilityContext).terminateSelf((err: BusinessError) => { + if (err.code) { + console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('terminateSelf succeed'); + }); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`terminateSelf failed, code is ${code}, message is ${message}`); + } + } + build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'cocos'}) + Flex({ + direction: FlexDirection.Column, + alignItems: ItemAlign.Center, + justifyContent: FlexAlign.Center + } as FlexOptions) { + XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'cocos' }) .onLoad((context) => { // Set the cache directory in the ts layer. this.workPort.postMessage("onXCLoad", "XComponent"); @@ -274,13 +442,13 @@ struct Index { console.log('cocos onDestroy') }) - ForEach(this.webViewArray, (item: WebViewInfo, index: number) => { - CocosWebView({ viewInfo: item, workPort: this.workPort}) - }, item => item.viewTag) + ForEach(this.webViewArray, (item: WebViewInfo) => { + CocosWebView({ viewInfo: item, workPort: this.workPort }) + }, (item: WebViewInfo): string => item.viewTag.toString()) - ForEach(this.videoArray, (item: VideoInfo, index: number) => { - CocosVideoPlayer({ videoInfo: item, workPort: this.workPort}) - }, item => item.viewTag) + ForEach(this.videoArray, (item: VideoInfo) => { + CocosVideoPlayer({ videoInfo: item, workPort: this.workPort }) + }, (item: VideoInfo): string => item.viewTag.toString()) } .width('100%') .height('100%') diff --git a/templates/openharmony/entry/src/main/ets/workers/cocos_worker.ts b/templates/openharmony/entry/src/main/ets/workers/cocos_worker.ts index c37faf6c64..a6d81a3274 100644 --- a/templates/openharmony/entry/src/main/ets/workers/cocos_worker.ts +++ b/templates/openharmony/entry/src/main/ets/workers/cocos_worker.ts @@ -24,14 +24,22 @@ ****************************************************************************/ import worker from '@ohos.worker'; -import nativerender from "libcocos.so"; -import { ContextType } from "../common/Constants" -<% if(!useV8) { %> -import { launchEngine } from '../cocos/game' -<% } %> -import {PortProxy} from '../common/PortProxy' +import cocos from 'libcocos.so'; +import hilog from '@ohos.hilog'; -globalThis.oh = globalThis.oh || {}; +import { ContextType } from '../common/Constants'; +<% if(!useV8) { %> +import { launchEngine } from '../cocos/game'; +<% } %> +import { PortProxy } from '../common/PortProxy'; + +<% if(useV8) { %> + globalThis.importPolyfill = async function () { + await import('../cocos/oh-adapter/sys-ability-polyfill.js'); + } + globalThis.importPolyfill(); + globalThis.oh = {}; +<% } %> if (!(console as any).assert) { (console as any).assert = function(cond, msg) { @@ -41,76 +49,80 @@ if (!(console as any).assert) { }; } -const nativeContext = nativerender.getContext(ContextType.WORKER_INIT); -nativeContext.workerInit() +const nativeContext = cocos.getContext(ContextType.WORKER_INIT); +nativeContext.workerInit(); -const nativeEditBox = nativerender.getContext(ContextType.EDITBOX_UTILS); -const nativeWebView = nativerender.getContext(ContextType.WEBVIEW_UTILS); -const nativeVideo = nativerender.getContext(ContextType.VIDEO_UTILS); +const nativeEditBox = cocos.getContext(ContextType.EDITBOX_UTILS); +const nativeWebView = cocos.getContext(ContextType.WEBVIEW_UTILS); +const appLifecycle = cocos.getContext(ContextType.APP_LIFECYCLE); +const nativeVideo = cocos.getContext(ContextType.VIDEO_UTILS); -let uiPort = new PortProxy(worker.parentPort); -nativeContext.postMessage = function(msgType: string, msgData:string) { - uiPort.postMessage(msgType, msgData); +let uiPort = new PortProxy(worker.workerPort); + +nativeContext.postMessage = function (msgType: string, msgData: string): void { + uiPort.postMessage(msgType, msgData); } -nativeContext.postSyncMessage = async function(msgType: string, msgData:string) { - const result = await uiPort.postSyncMessage(msgType, msgData); - return result; +nativeContext.postSyncMessage = async function (msgType: string, msgData: string): Promise { + const result = await uiPort.postSyncMessage(msgType, msgData) as boolean | string | number; + return result; } // The purpose of this is to avoid being GC nativeContext.setPostMessageFunction.call(nativeContext, nativeContext.postMessage) nativeContext.setPostSyncMessageFunction.call(nativeContext, nativeContext.postSyncMessage) -var renderContext: any = undefined; -uiPort._messageHandle = function(e) { - var data = e.data; - var msg = data.data; - switch(msg.name) { - case "onXCLoad": - const renderContext = nativerender.getContext(ContextType.NATIVE_RENDER_API); - renderContext.nativeEngineInit(); - - <% if(!useV8) { %> - launchEngine().then(() => { - console.info('launch CC engine finished'); - }).catch(e => { - console.error('launch CC engine failed'); - }); - <% } %> - // @ts-ignore - globalThis.oh.postMessage = nativeContext.postMessage; - // @ts-ignore - globalThis.oh.postSyncMessage = nativeContext.postSyncMessage; - renderContext.nativeEngineStart(); - break; - case "onTextInput": - nativeEditBox.onTextChange(msg.param); - break; - case "onComplete": - nativeEditBox.onComplete(msg.param); - break; - case "onPageBegin": - nativeWebView.shouldStartLoading(msg.param.viewTag, msg.param.url); - break; - case "onPageEnd": - nativeWebView.finishLoading(msg.param.viewTag, msg.param.url); - break; - case "onErrorReceive": - nativeWebView.failLoading(msg.param.viewTag, msg.param.url); - break; - case "onVideoEvent": - // @ts-ignore - if(globalThis.oh && typeof globalThis.oh.onVideoEvent === "function") { - // @ts-ignore - globalThis.oh.onVideoEvent(msg.param.videoTag, msg.param.videoEvent, msg.param.args); - } else { - nativeVideo.onVideoEvent(msg.param.videoTag, msg.param.videoEvent, msg.param.args); - } - break; - default: - console.error("cocos worker: message type unknown"); - break; - } +globalThis.terminateProcess = function () { + uiPort.postMessage("exitGame",0); } +uiPort._messageHandle = function (e) { + var data = e.data; + var msg = data.data; + + switch (msg.name) { + case "onXCLoad": + const renderContext = cocos.getContext(ContextType.NATIVE_RENDER_API); + renderContext.nativeEngineInit(); + <% if(!useV8) { %> + launchEngine().then(() => { + console.info('launch CC engine finished'); + }).catch(e => { + console.error('launch CC engine failed'); + }); + <% } %> + // @ts-ignore + globalThis.oh.postMessage = nativeContext.postMessage; + // @ts-ignore + globalThis.oh.postSyncMessage = nativeContext.postSyncMessage; + renderContext.nativeEngineStart(); + break; + case "onTextInput": + nativeEditBox.onTextChange(msg.param); + break; + case "onComplete": + nativeEditBox.onComplete(msg.param); + break; + case "onConfirm": + nativeEditBox.onConfirm(msg.param); + break; + case "onPageBegin": + nativeWebView.shouldStartLoading(msg.param.viewTag, msg.param.url); + break; + case "onPageEnd": + nativeWebView.finishLoading(msg.param.viewTag, msg.param.url); + break; + case "onErrorReceive": + nativeWebView.failLoading(msg.param.viewTag, msg.param.url); + break; + case "onVideoEvent": + nativeVideo.onVideoEvent(JSON.stringify(msg.param)); + break; + case "backPress": + appLifecycle.onBackPress(); + break; + default: + console.error("cocos worker: message type unknown"); + break; + } +} diff --git a/templates/openharmony/entry/src/main/module.json5 b/templates/openharmony/entry/src/main/module.json5 index 4652872c67..b94a66f8ba 100644 --- a/templates/openharmony/entry/src/main/module.json5 +++ b/templates/openharmony/entry/src/main/module.json5 @@ -3,26 +3,33 @@ "name": "entry", "type": "entry", "description": "$string:entry_desc", - "mainElement": "MainAbility", + "mainElement": "EntryAbility", "deviceTypes": [ - "default", - "tablet" + "default" + ], + "requestPermissions":[ + {"name" : "ohos.permission.INTERNET"}, + {"name" : "ohos.permission.VIBRATE"}, + {"name" : "ohos.permission.GET_NETWORK_INFO"}, + {"name" : "ohos.permission.ACCELEROMETER"}, + {"name" : "ohos.permission.GYROSCOPE"} ], "deliveryWithInstall": true, "installationFree": false, "pages": "$profile:main_pages", - "uiSyntax": "ets", "abilities": [ { - "name": "MainAbility", - "srcEntrance": "./ets/MainAbility/MainAbility.ts", + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ts", "description": "$string:MainAbility_desc", "orientation": "portrait", "icon": "$media:icon", "label": "$string:MainAbility_label", "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:black", - "visible": true, + "removeMissionAfterTerminate": true, + "startWindowBackground": "$color:white", + "supportWindowMode": ["fullscreen"], + "exported": true, "skills": [ { "entities": [ @@ -34,37 +41,6 @@ } ] } - ], - "requestPermissions": [ - { - "name": 'ohos.permission.INTERNET' - }, - { - "name": "ohos.permission.ACCELEROMETER", - "reason": "$string:permissions_label", - "usedScene": { - "abilities": [ - "MainAbility" - ], - "when": "inuse" - } - }, - { - "name": "ohos.permission.GYROSCOPE", - "reason": "$string:permissions_label", - "usedScene": { - "abilities": [ - "MainAbility" - ], - "when": "inuse" - } - } - ], - "metadata": [ - { - "name": "ArkTSPartialUpdate", - "value": "true" - } ] } } \ No newline at end of file diff --git a/templates/openharmony/hvigor/hvigor-config.json5 b/templates/openharmony/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000..bb1ad53359 --- /dev/null +++ b/templates/openharmony/hvigor/hvigor-config.json5 @@ -0,0 +1,22 @@ +{ + "modelVersion": "5.0.0", + "dependencies": { + }, + "execution": { + // "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */ + // "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */ + // "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */ + // "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */ + // "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */ + }, + "logging": { + // "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */ + }, + "debugging": { + // "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */ + }, + "nodeOptions": { + // "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/ + // "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/ + } +} \ No newline at end of file diff --git a/templates/openharmony/hvigor/hvigor-wrapper.js b/templates/openharmony/hvigor/hvigor-wrapper.js deleted file mode 100644 index 994f22987b..0000000000 --- a/templates/openharmony/hvigor/hvigor-wrapper.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict";var e=require("fs"),t=require("path"),n=require("os"),r=require("crypto"),u=require("child_process"),o=require("constants"),i=require("stream"),s=require("util"),c=require("assert"),a=require("tty"),l=require("zlib"),f=require("net");function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var D=d(e),p=d(t),E=d(n),m=d(r),h=d(u),y=d(o),C=d(i),F=d(s),g=d(c),A=d(a),v=d(l),S=d(f),w="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},O={},b={},_={},B=w&&w.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0}),_.isMac=_.isLinux=_.isWindows=void 0;const P=B(E.default),k="Windows_NT",x="Linux",N="Darwin";_.isWindows=function(){return P.default.type()===k},_.isLinux=function(){return P.default.type()===x},_.isMac=function(){return P.default.type()===N};var I={},T=w&&w.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var u=Object.getOwnPropertyDescriptor(t,n);u&&!("get"in u?!t.__esModule:u.writable||u.configurable)||(u={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,u)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),R=w&&w.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),M=w&&w.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&T(t,e,n);return R(t,e),t};Object.defineProperty(I,"__esModule",{value:!0}),I.hash=void 0;const L=M(m.default);I.hash=function(e,t="md5"){return L.createHash(t).update(e,"utf-8").digest("hex")},function(e){var t=w&&w.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var u=Object.getOwnPropertyDescriptor(t,n);u&&!("get"in u?!t.__esModule:u.writable||u.configurable)||(u={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,u)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),n=w&&w.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=w&&w.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var u in e)"default"!==u&&Object.prototype.hasOwnProperty.call(e,u)&&t(r,e,u);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.HVIGOR_BOOT_JS_FILE_PATH=e.HVIGOR_PROJECT_DEPENDENCY_PACKAGE_JSON_PATH=e.HVIGOR_PROJECT_DEPENDENCIES_HOME=e.HVIGOR_PROJECT_WRAPPER_HOME=e.HVIGOR_PROJECT_NAME=e.HVIGOR_PROJECT_ROOT_DIR=e.HVIGOR_PROJECT_CACHES_HOME=e.HVIGOR_PNPM_STORE_PATH=e.HVIGOR_WRAPPER_PNPM_SCRIPT_PATH=e.HVIGOR_WRAPPER_TOOLS_HOME=e.HVIGOR_USER_HOME=e.DEFAULT_PACKAGE_JSON=e.DEFAULT_HVIGOR_CONFIG_JSON_FILE_NAME=e.PNPM=e.HVIGOR=e.NPM_TOOL=e.PNPM_TOOL=e.HVIGOR_ENGINE_PACKAGE_NAME=void 0;const u=r(p.default),o=r(E.default),i=_,s=I;e.HVIGOR_ENGINE_PACKAGE_NAME="@ohos/hvigor",e.PNPM_TOOL=(0,i.isWindows)()?"pnpm.cmd":"pnpm",e.NPM_TOOL=(0,i.isWindows)()?"npm.cmd":"npm",e.HVIGOR="hvigor",e.PNPM="pnpm",e.DEFAULT_HVIGOR_CONFIG_JSON_FILE_NAME="hvigor-config.json5",e.DEFAULT_PACKAGE_JSON="package.json",e.HVIGOR_USER_HOME=u.resolve(o.homedir(),".hvigor"),e.HVIGOR_WRAPPER_TOOLS_HOME=u.resolve(e.HVIGOR_USER_HOME,"wrapper","tools"),e.HVIGOR_WRAPPER_PNPM_SCRIPT_PATH=u.resolve(e.HVIGOR_WRAPPER_TOOLS_HOME,"node_modules",".bin",e.PNPM_TOOL),e.HVIGOR_PNPM_STORE_PATH=u.resolve(e.HVIGOR_USER_HOME,"caches"),e.HVIGOR_PROJECT_CACHES_HOME=u.resolve(e.HVIGOR_USER_HOME,"project_caches"),e.HVIGOR_PROJECT_ROOT_DIR=process.cwd(),e.HVIGOR_PROJECT_NAME=u.basename((0,s.hash)(e.HVIGOR_PROJECT_ROOT_DIR)),e.HVIGOR_PROJECT_WRAPPER_HOME=u.resolve(e.HVIGOR_PROJECT_ROOT_DIR,e.HVIGOR),e.HVIGOR_PROJECT_DEPENDENCIES_HOME=u.resolve(e.HVIGOR_PROJECT_CACHES_HOME,e.HVIGOR_PROJECT_NAME,"workspace"),e.HVIGOR_PROJECT_DEPENDENCY_PACKAGE_JSON_PATH=u.resolve(e.HVIGOR_PROJECT_DEPENDENCIES_HOME,e.DEFAULT_PACKAGE_JSON),e.HVIGOR_BOOT_JS_FILE_PATH=u.resolve(e.HVIGOR_PROJECT_DEPENDENCIES_HOME,"node_modules","@ohos","hvigor","bin","hvigor.js")}(b);var j={},$={};Object.defineProperty($,"__esModule",{value:!0}),$.logInfoPrintConsole=$.logErrorAndExit=void 0,$.logErrorAndExit=function(e){e instanceof Error?console.error(e.message):console.error(e),process.exit(-1)},$.logInfoPrintConsole=function(e){console.log(e)};var H=w&&w.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var u=Object.getOwnPropertyDescriptor(t,n);u&&!("get"in u?!t.__esModule:u.writable||u.configurable)||(u={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,u)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),J=w&&w.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),G=w&&w.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&H(t,e,n);return J(t,e),t},V=w&&w.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(j,"__esModule",{value:!0}),j.isFileExists=j.offlinePluginConversion=j.executeCommand=j.getNpmPath=j.hasNpmPackInPaths=void 0;const U=h.default,W=G(p.default),z=b,K=$,q=V(D.default);j.hasNpmPackInPaths=function(e,t){try{return require.resolve(e,{paths:[...t]}),!0}catch(e){return!1}},j.getNpmPath=function(){const e=process.execPath;return W.join(W.dirname(e),z.NPM_TOOL)},j.executeCommand=function(e,t,n){0!==(0,U.spawnSync)(e,t,n).status&&(0,K.logErrorAndExit)(`Error: ${e} ${t} execute failed.See above for details.`)},j.offlinePluginConversion=function(e,t){return t.startsWith("file:")||t.endsWith(".tgz")?W.resolve(e,z.HVIGOR,t.replace("file:","")):t},j.isFileExists=function(e){return q.default.existsSync(e)&&q.default.statSync(e).isFile()},function(e){var t=w&&w.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var u=Object.getOwnPropertyDescriptor(t,n);u&&!("get"in u?!t.__esModule:u.writable||u.configurable)||(u={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,u)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),n=w&&w.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=w&&w.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var u in e)"default"!==u&&Object.prototype.hasOwnProperty.call(e,u)&&t(r,e,u);return n(r,e),r},u=w&&w.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.executeInstallPnpm=e.isPnpmAvailable=e.environmentHandler=e.checkNpmConifg=e.PNPM_VERSION=void 0;const o=r(D.default),i=b,s=j,c=r(p.default),a=$,l=h.default,f=u(E.default);e.PNPM_VERSION="7.30.0",e.checkNpmConifg=function(){const e=c.resolve(i.HVIGOR_PROJECT_ROOT_DIR,".npmrc"),t=c.resolve(f.default.homedir(),".npmrc");if((0,s.isFileExists)(e)||(0,s.isFileExists)(t))return;const n=(0,s.getNpmPath)(),r=(0,l.spawnSync)(n,["config","get","prefix"],{cwd:i.HVIGOR_PROJECT_ROOT_DIR});if(0!==r.status||!r.stdout)return void(0,a.logErrorAndExit)("Error: The hvigor depends on the npmrc file. Configure the npmrc file first.");const u=c.resolve(`${r.stdout}`.replace(/[\r\n]/gi,""),".npmrc");(0,s.isFileExists)(u)||(0,a.logErrorAndExit)("Error: The hvigor depends on the npmrc file. Configure the npmrc file first.")},e.environmentHandler=function(){process.env["npm_config_update-notifier"]="false"},e.isPnpmAvailable=function(){return!!o.existsSync(i.HVIGOR_WRAPPER_PNPM_SCRIPT_PATH)&&(0,s.hasNpmPackInPaths)("pnpm",[i.HVIGOR_WRAPPER_TOOLS_HOME])},e.executeInstallPnpm=function(){(0,a.logInfoPrintConsole)(`Installing pnpm@${e.PNPM_VERSION}...`);const t=(0,s.getNpmPath)();!function(){const t=c.resolve(i.HVIGOR_WRAPPER_TOOLS_HOME,i.DEFAULT_PACKAGE_JSON);try{o.existsSync(i.HVIGOR_WRAPPER_TOOLS_HOME)||o.mkdirSync(i.HVIGOR_WRAPPER_TOOLS_HOME,{recursive:!0});const n={dependencies:{}};n.dependencies[i.PNPM]=e.PNPM_VERSION,o.writeFileSync(t,JSON.stringify(n))}catch(e){(0,a.logErrorAndExit)(`Error: EPERM: operation not permitted,create ${t} failed.`)}}(),(0,s.executeCommand)(t,["install","pnpm"],{cwd:i.HVIGOR_WRAPPER_TOOLS_HOME,stdio:["inherit","inherit","inherit"],env:process.env}),(0,a.logInfoPrintConsole)("Pnpm install success.")}}(O);var Y={},X={},Z={},Q={};Object.defineProperty(Q,"__esModule",{value:!0}),Q.Unicode=void 0;class ee{}Q.Unicode=ee,ee.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,ee.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,ee.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,Object.defineProperty(Z,"__esModule",{value:!0}),Z.JudgeUtil=void 0;const te=Q;Z.JudgeUtil=class{static isIgnoreChar(e){return"string"==typeof e&&("\t"===e||"\v"===e||"\f"===e||" "===e||" "===e||"\ufeff"===e||"\n"===e||"\r"===e||"\u2028"===e||"\u2029"===e)}static isSpaceSeparator(e){return"string"==typeof e&&te.Unicode.Space_Separator.test(e)}static isIdStartChar(e){return"string"==typeof e&&(e>="a"&&e<="z"||e>="A"&&e<="Z"||"$"===e||"_"===e||te.Unicode.ID_Start.test(e))}static isIdContinueChar(e){return"string"==typeof e&&(e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||"$"===e||"_"===e||"‌"===e||"‍"===e||te.Unicode.ID_Continue.test(e))}static isDigitWithoutZero(e){return/[1-9]/.test(e)}static isDigit(e){return"string"==typeof e&&/[0-9]/.test(e)}static isHexDigit(e){return"string"==typeof e&&/[0-9A-Fa-f]/.test(e)}};var ne={},re={fromCallback:function(e){return Object.defineProperty((function(...t){if("function"!=typeof t[t.length-1])return new Promise(((n,r)=>{e.call(this,...t,((e,t)=>null!=e?r(e):n(t)))}));e.apply(this,t)}),"name",{value:e.name})},fromPromise:function(e){return Object.defineProperty((function(...t){const n=t[t.length-1];if("function"!=typeof n)return e.apply(this,t);e.apply(this,t.slice(0,-1)).then((e=>n(null,e)),n)}),"name",{value:e.name})}},ue=y.default,oe=process.cwd,ie=null,se=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return ie||(ie=oe.call(process)),ie};try{process.cwd()}catch(e){}if("function"==typeof process.chdir){var ce=process.chdir;process.chdir=function(e){ie=null,ce.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,ce)}var ae=function(e){ue.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&function(e){e.lchmod=function(t,n,r){e.open(t,ue.O_WRONLY|ue.O_SYMLINK,n,(function(t,u){t?r&&r(t):e.fchmod(u,n,(function(t){e.close(u,(function(e){r&&r(t||e)}))}))}))},e.lchmodSync=function(t,n){var r,u=e.openSync(t,ue.O_WRONLY|ue.O_SYMLINK,n),o=!0;try{r=e.fchmodSync(u,n),o=!1}finally{if(o)try{e.closeSync(u)}catch(e){}else e.closeSync(u)}return r}}(e);e.lutimes||function(e){ue.hasOwnProperty("O_SYMLINK")&&e.futimes?(e.lutimes=function(t,n,r,u){e.open(t,ue.O_SYMLINK,(function(t,o){t?u&&u(t):e.futimes(o,n,r,(function(t){e.close(o,(function(e){u&&u(t||e)}))}))}))},e.lutimesSync=function(t,n,r){var u,o=e.openSync(t,ue.O_SYMLINK),i=!0;try{u=e.futimesSync(o,n,r),i=!1}finally{if(i)try{e.closeSync(o)}catch(e){}else e.closeSync(o)}return u}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}(e);e.chown=r(e.chown),e.fchown=r(e.fchown),e.lchown=r(e.lchown),e.chmod=t(e.chmod),e.fchmod=t(e.fchmod),e.lchmod=t(e.lchmod),e.chownSync=u(e.chownSync),e.fchownSync=u(e.fchownSync),e.lchownSync=u(e.lchownSync),e.chmodSync=n(e.chmodSync),e.fchmodSync=n(e.fchmodSync),e.lchmodSync=n(e.lchmodSync),e.stat=o(e.stat),e.fstat=o(e.fstat),e.lstat=o(e.lstat),e.statSync=i(e.statSync),e.fstatSync=i(e.fstatSync),e.lstatSync=i(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){});e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){});"win32"===se&&(e.rename="function"!=typeof e.rename?e.rename:function(t){function n(n,r,u){var o=Date.now(),i=0;t(n,r,(function s(c){if(c&&("EACCES"===c.code||"EPERM"===c.code||"EBUSY"===c.code)&&Date.now()-o<6e4)return setTimeout((function(){e.stat(r,(function(e,o){e&&"ENOENT"===e.code?t(n,r,s):u(c)}))}),i),void(i<100&&(i+=10));u&&u(c)}))}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n}(e.rename));function t(t){return t?function(n,r,u){return t.call(e,n,r,(function(e){s(e)&&(e=null),u&&u.apply(this,arguments)}))}:t}function n(t){return t?function(n,r){try{return t.call(e,n,r)}catch(e){if(!s(e))throw e}}:t}function r(t){return t?function(n,r,u,o){return t.call(e,n,r,u,(function(e){s(e)&&(e=null),o&&o.apply(this,arguments)}))}:t}function u(t){return t?function(n,r,u){try{return t.call(e,n,r,u)}catch(e){if(!s(e))throw e}}:t}function o(t){return t?function(n,r,u){function o(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),u&&u.apply(this,arguments)}return"function"==typeof r&&(u=r,r=null),r?t.call(e,n,r,o):t.call(e,n,o)}:t}function i(t){return t?function(n,r){var u=r?t.call(e,n,r):t.call(e,n);return u&&(u.uid<0&&(u.uid+=4294967296),u.gid<0&&(u.gid+=4294967296)),u}:t}function s(e){return!e||("ENOSYS"===e.code||!(process.getuid&&0===process.getuid()||"EINVAL"!==e.code&&"EPERM"!==e.code))}e.read="function"!=typeof e.read?e.read:function(t){function n(n,r,u,o,i,s){var c;if(s&&"function"==typeof s){var a=0;c=function(l,f,d){if(l&&"EAGAIN"===l.code&&a<10)return a++,t.call(e,n,r,u,o,i,c);s.apply(this,arguments)}}return t.call(e,n,r,u,o,i,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n}(e.read),e.readSync="function"!=typeof e.readSync?e.readSync:(c=e.readSync,function(t,n,r,u,o){for(var i=0;;)try{return c.call(e,t,n,r,u,o)}catch(e){if("EAGAIN"===e.code&&i<10){i++;continue}throw e}});var c};var le=C.default.Stream,fe=function(e){return{ReadStream:function t(n,r){if(!(this instanceof t))return new t(n,r);le.call(this);var u=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,r=r||{};for(var o=Object.keys(r),i=0,s=o.length;ithis.end)throw new Error("start must be <= end");this.pos=this.start}if(null!==this.fd)return void process.nextTick((function(){u._read()}));e.open(this.path,this.flags,this.mode,(function(e,t){if(e)return u.emit("error",e),void(u.readable=!1);u.fd=t,u.emit("open",t),u._read()}))},WriteStream:function t(n,r){if(!(this instanceof t))return new t(n,r);le.call(this),this.path=n,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,r=r||{};for(var u=Object.keys(r),o=0,i=u.length;o= zero");this.pos=this.start}this.busy=!1,this._queue=[],null===this.fd&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}};var de=function(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Object)var t={__proto__:De(e)};else t=Object.create(null);return Object.getOwnPropertyNames(e).forEach((function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))})),t},De=Object.getPrototypeOf||function(e){return e.__proto__};var pe,Ee,me=D.default,he=ae,ye=fe,Ce=de,Fe=F.default;function ge(e,t){Object.defineProperty(e,pe,{get:function(){return t}})}"function"==typeof Symbol&&"function"==typeof Symbol.for?(pe=Symbol.for("graceful-fs.queue"),Ee=Symbol.for("graceful-fs.previous")):(pe="___graceful-fs.queue",Ee="___graceful-fs.previous");var Ae=function(){};if(Fe.debuglog?Ae=Fe.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(Ae=function(){var e=Fe.format.apply(Fe,arguments);e="GFS4: "+e.split(/\n/).join("\nGFS4: "),console.error(e)}),!me[pe]){var ve=w[pe]||[];ge(me,ve),me.close=function(e){function t(t,n){return e.call(me,t,(function(e){e||_e(),"function"==typeof n&&n.apply(this,arguments)}))}return Object.defineProperty(t,Ee,{value:e}),t}(me.close),me.closeSync=function(e){function t(t){e.apply(me,arguments),_e()}return Object.defineProperty(t,Ee,{value:e}),t}(me.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",(function(){Ae(me[pe]),g.default.equal(me[pe].length,0)}))}w[pe]||ge(w,me[pe]);var Se,we=Oe(Ce(me));function Oe(e){he(e),e.gracefulify=Oe,e.createReadStream=function(t,n){return new e.ReadStream(t,n)},e.createWriteStream=function(t,n){return new e.WriteStream(t,n)};var t=e.readFile;e.readFile=function(e,n,r){"function"==typeof n&&(r=n,n=null);return function e(n,r,u,o){return t(n,r,(function(t){!t||"EMFILE"!==t.code&&"ENFILE"!==t.code?"function"==typeof u&&u.apply(this,arguments):be([e,[n,r,u],t,o||Date.now(),Date.now()])}))}(e,n,r)};var n=e.writeFile;e.writeFile=function(e,t,r,u){"function"==typeof r&&(u=r,r=null);return function e(t,r,u,o,i){return n(t,r,u,(function(n){!n||"EMFILE"!==n.code&&"ENFILE"!==n.code?"function"==typeof o&&o.apply(this,arguments):be([e,[t,r,u,o],n,i||Date.now(),Date.now()])}))}(e,t,r,u)};var r=e.appendFile;r&&(e.appendFile=function(e,t,n,u){"function"==typeof n&&(u=n,n=null);return function e(t,n,u,o,i){return r(t,n,u,(function(r){!r||"EMFILE"!==r.code&&"ENFILE"!==r.code?"function"==typeof o&&o.apply(this,arguments):be([e,[t,n,u,o],r,i||Date.now(),Date.now()])}))}(e,t,n,u)});var u=e.copyFile;u&&(e.copyFile=function(e,t,n,r){"function"==typeof n&&(r=n,n=0);return function e(t,n,r,o,i){return u(t,n,r,(function(u){!u||"EMFILE"!==u.code&&"ENFILE"!==u.code?"function"==typeof o&&o.apply(this,arguments):be([e,[t,n,r,o],u,i||Date.now(),Date.now()])}))}(e,t,n,r)});var o=e.readdir;e.readdir=function(e,t,n){"function"==typeof t&&(n=t,t=null);var r=i.test(process.version)?function(e,t,n,r){return o(e,u(e,t,n,r))}:function(e,t,n,r){return o(e,t,u(e,t,n,r))};return r(e,t,n);function u(e,t,n,u){return function(o,i){!o||"EMFILE"!==o.code&&"ENFILE"!==o.code?(i&&i.sort&&i.sort(),"function"==typeof n&&n.call(this,o,i)):be([r,[e,t,n],o,u||Date.now(),Date.now()])}}};var i=/^v[0-5]\./;if("v0.8"===process.version.substr(0,4)){var s=ye(e);d=s.ReadStream,D=s.WriteStream}var c=e.ReadStream;c&&(d.prototype=Object.create(c.prototype),d.prototype.open=function(){var e=this;E(e.path,e.flags,e.mode,(function(t,n){t?(e.autoClose&&e.destroy(),e.emit("error",t)):(e.fd=n,e.emit("open",n),e.read())}))});var a=e.WriteStream;a&&(D.prototype=Object.create(a.prototype),D.prototype.open=function(){var e=this;E(e.path,e.flags,e.mode,(function(t,n){t?(e.destroy(),e.emit("error",t)):(e.fd=n,e.emit("open",n))}))}),Object.defineProperty(e,"ReadStream",{get:function(){return d},set:function(e){d=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return D},set:function(e){D=e},enumerable:!0,configurable:!0});var l=d;Object.defineProperty(e,"FileReadStream",{get:function(){return l},set:function(e){l=e},enumerable:!0,configurable:!0});var f=D;function d(e,t){return this instanceof d?(c.apply(this,arguments),this):d.apply(Object.create(d.prototype),arguments)}function D(e,t){return this instanceof D?(a.apply(this,arguments),this):D.apply(Object.create(D.prototype),arguments)}Object.defineProperty(e,"FileWriteStream",{get:function(){return f},set:function(e){f=e},enumerable:!0,configurable:!0});var p=e.open;function E(e,t,n,r){return"function"==typeof n&&(r=n,n=null),function e(t,n,r,u,o){return p(t,n,r,(function(i,s){!i||"EMFILE"!==i.code&&"ENFILE"!==i.code?"function"==typeof u&&u.apply(this,arguments):be([e,[t,n,r,u],i,o||Date.now(),Date.now()])}))}(e,t,n,r)}return e.open=E,e}function be(e){Ae("ENQUEUE",e[0].name,e[1]),me[pe].push(e),Be()}function _e(){for(var e=Date.now(),t=0;t2&&(me[pe][t][3]=e,me[pe][t][4]=e);Be()}function Be(){if(clearTimeout(Se),Se=void 0,0!==me[pe].length){var e=me[pe].shift(),t=e[0],n=e[1],r=e[2],u=e[3],o=e[4];if(void 0===u)Ae("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-u>=6e4){Ae("TIMEOUT",t.name,n);var i=n.pop();"function"==typeof i&&i.call(null,r)}else{var s=Date.now()-o,c=Math.max(o-u,1);s>=Math.min(1.2*c,100)?(Ae("RETRY",t.name,n),t.apply(null,n.concat([u]))):me[pe].push(e)}void 0===Se&&(Se=setTimeout(Be,0))}}process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!me.__patched&&(we=Oe(me),me.__patched=!0),function(e){const t=re.fromCallback,n=we,r=["access","appendFile","chmod","chown","close","copyFile","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","lchmod","lchown","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","symlink","truncate","unlink","utimes","writeFile"].filter((e=>"function"==typeof n[e]));Object.assign(e,n),r.forEach((r=>{e[r]=t(n[r])})),e.realpath.native=t(n.realpath.native),e.exists=function(e,t){return"function"==typeof t?n.exists(e,t):new Promise((t=>n.exists(e,t)))},e.read=function(e,t,r,u,o,i){return"function"==typeof i?n.read(e,t,r,u,o,i):new Promise(((i,s)=>{n.read(e,t,r,u,o,((e,t,n)=>{if(e)return s(e);i({bytesRead:t,buffer:n})}))}))},e.write=function(e,t,...r){return"function"==typeof r[r.length-1]?n.write(e,t,...r):new Promise(((u,o)=>{n.write(e,t,...r,((e,t,n)=>{if(e)return o(e);u({bytesWritten:t,buffer:n})}))}))},"function"==typeof n.writev&&(e.writev=function(e,t,...r){return"function"==typeof r[r.length-1]?n.writev(e,t,...r):new Promise(((u,o)=>{n.writev(e,t,...r,((e,t,n)=>{if(e)return o(e);u({bytesWritten:t,buffers:n})}))}))})}(ne);var Pe={},ke={};const xe=p.default;ke.checkPath=function(e){if("win32"===process.platform){if(/[<>:"|?*]/.test(e.replace(xe.parse(e).root,""))){const t=new Error(`Path contains invalid characters: ${e}`);throw t.code="EINVAL",t}}};const Ne=ne,{checkPath:Ie}=ke,Te=e=>"number"==typeof e?e:{mode:511,...e}.mode;Pe.makeDir=async(e,t)=>(Ie(e),Ne.mkdir(e,{mode:Te(t),recursive:!0})),Pe.makeDirSync=(e,t)=>(Ie(e),Ne.mkdirSync(e,{mode:Te(t),recursive:!0}));const Re=re.fromPromise,{makeDir:Me,makeDirSync:Le}=Pe,je=Re(Me);var $e={mkdirs:je,mkdirsSync:Le,mkdirp:je,mkdirpSync:Le,ensureDir:je,ensureDirSync:Le};const He=re.fromPromise,Je=ne;var Ge={pathExists:He((function(e){return Je.access(e).then((()=>!0)).catch((()=>!1))})),pathExistsSync:Je.existsSync};const Ve=we;var Ue=function(e,t,n,r){Ve.open(e,"r+",((e,u)=>{if(e)return r(e);Ve.futimes(u,t,n,(e=>{Ve.close(u,(t=>{r&&r(e||t)}))}))}))},We=function(e,t,n){const r=Ve.openSync(e,"r+");return Ve.futimesSync(r,t,n),Ve.closeSync(r)};const ze=ne,Ke=p.default,qe=F.default;function Ye(e,t,n){const r=n.dereference?e=>ze.stat(e,{bigint:!0}):e=>ze.lstat(e,{bigint:!0});return Promise.all([r(e),r(t).catch((e=>{if("ENOENT"===e.code)return null;throw e}))]).then((([e,t])=>({srcStat:e,destStat:t})))}function Xe(e,t){return t.ino&&t.dev&&t.ino===e.ino&&t.dev===e.dev}function Ze(e,t){const n=Ke.resolve(e).split(Ke.sep).filter((e=>e)),r=Ke.resolve(t).split(Ke.sep).filter((e=>e));return n.reduce(((e,t,n)=>e&&r[n]===t),!0)}function Qe(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}var et={checkPaths:function(e,t,n,r,u){qe.callbackify(Ye)(e,t,r,((r,o)=>{if(r)return u(r);const{srcStat:i,destStat:s}=o;if(s){if(Xe(i,s)){const r=Ke.basename(e),o=Ke.basename(t);return"move"===n&&r!==o&&r.toLowerCase()===o.toLowerCase()?u(null,{srcStat:i,destStat:s,isChangingCase:!0}):u(new Error("Source and destination must not be the same."))}if(i.isDirectory()&&!s.isDirectory())return u(new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`));if(!i.isDirectory()&&s.isDirectory())return u(new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`))}return i.isDirectory()&&Ze(e,t)?u(new Error(Qe(e,t,n))):u(null,{srcStat:i,destStat:s})}))},checkPathsSync:function(e,t,n,r){const{srcStat:u,destStat:o}=function(e,t,n){let r;const u=n.dereference?e=>ze.statSync(e,{bigint:!0}):e=>ze.lstatSync(e,{bigint:!0}),o=u(e);try{r=u(t)}catch(e){if("ENOENT"===e.code)return{srcStat:o,destStat:null};throw e}return{srcStat:o,destStat:r}}(e,t,r);if(o){if(Xe(u,o)){const r=Ke.basename(e),i=Ke.basename(t);if("move"===n&&r!==i&&r.toLowerCase()===i.toLowerCase())return{srcStat:u,destStat:o,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(u.isDirectory()&&!o.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!u.isDirectory()&&o.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(u.isDirectory()&&Ze(e,t))throw new Error(Qe(e,t,n));return{srcStat:u,destStat:o}},checkParentPaths:function e(t,n,r,u,o){const i=Ke.resolve(Ke.dirname(t)),s=Ke.resolve(Ke.dirname(r));if(s===i||s===Ke.parse(s).root)return o();ze.stat(s,{bigint:!0},((i,c)=>i?"ENOENT"===i.code?o():o(i):Xe(n,c)?o(new Error(Qe(t,r,u))):e(t,n,s,u,o)))},checkParentPathsSync:function e(t,n,r,u){const o=Ke.resolve(Ke.dirname(t)),i=Ke.resolve(Ke.dirname(r));if(i===o||i===Ke.parse(i).root)return;let s;try{s=ze.statSync(i,{bigint:!0})}catch(e){if("ENOENT"===e.code)return;throw e}if(Xe(n,s))throw new Error(Qe(t,r,u));return e(t,n,i,u)},isSrcSubdir:Ze,areIdentical:Xe};const tt=we,nt=p.default,rt=$e.mkdirs,ut=Ge.pathExists,ot=Ue,it=et;function st(e,t,n,r,u){const o=nt.dirname(n);ut(o,((i,s)=>i?u(i):s?at(e,t,n,r,u):void rt(o,(o=>o?u(o):at(e,t,n,r,u)))))}function ct(e,t,n,r,u,o){Promise.resolve(u.filter(n,r)).then((i=>i?e(t,n,r,u,o):o()),(e=>o(e)))}function at(e,t,n,r,u){(r.dereference?tt.stat:tt.lstat)(t,((o,i)=>o?u(o):i.isDirectory()?function(e,t,n,r,u,o){return t?Dt(n,r,u,o):function(e,t,n,r,u){tt.mkdir(n,(o=>{if(o)return u(o);Dt(t,n,r,(t=>t?u(t):dt(n,e,u)))}))}(e.mode,n,r,u,o)}(i,e,t,n,r,u):i.isFile()||i.isCharacterDevice()||i.isBlockDevice()?function(e,t,n,r,u,o){return t?function(e,t,n,r,u){if(!r.overwrite)return r.errorOnExist?u(new Error(`'${n}' already exists`)):u();tt.unlink(n,(o=>o?u(o):lt(e,t,n,r,u)))}(e,n,r,u,o):lt(e,n,r,u,o)}(i,e,t,n,r,u):i.isSymbolicLink()?function(e,t,n,r,u){tt.readlink(t,((t,o)=>t?u(t):(r.dereference&&(o=nt.resolve(process.cwd(),o)),e?void tt.readlink(n,((t,i)=>t?"EINVAL"===t.code||"UNKNOWN"===t.code?tt.symlink(o,n,u):u(t):(r.dereference&&(i=nt.resolve(process.cwd(),i)),it.isSrcSubdir(o,i)?u(new Error(`Cannot copy '${o}' to a subdirectory of itself, '${i}'.`)):e.isDirectory()&&it.isSrcSubdir(i,o)?u(new Error(`Cannot overwrite '${i}' with '${o}'.`)):function(e,t,n){tt.unlink(t,(r=>r?n(r):tt.symlink(e,t,n)))}(o,n,u)))):tt.symlink(o,n,u))))}(e,t,n,r,u):i.isSocket()?u(new Error(`Cannot copy a socket file: ${t}`)):i.isFIFO()?u(new Error(`Cannot copy a FIFO pipe: ${t}`)):u(new Error(`Unknown file: ${t}`))))}function lt(e,t,n,r,u){tt.copyFile(t,n,(o=>o?u(o):r.preserveTimestamps?function(e,t,n,r){if(function(e){return 0==(128&e)}(e))return function(e,t,n){return dt(e,128|t,n)}(n,e,(u=>u?r(u):ft(e,t,n,r)));return ft(e,t,n,r)}(e.mode,t,n,u):dt(n,e.mode,u)))}function ft(e,t,n,r){!function(e,t,n){tt.stat(e,((e,r)=>e?n(e):ot(t,r.atime,r.mtime,n)))}(t,n,(t=>t?r(t):dt(n,e,r)))}function dt(e,t,n){return tt.chmod(e,t,n)}function Dt(e,t,n,r){tt.readdir(e,((u,o)=>u?r(u):pt(o,e,t,n,r)))}function pt(e,t,n,r,u){const o=e.pop();return o?function(e,t,n,r,u,o){const i=nt.join(n,t),s=nt.join(r,t);it.checkPaths(i,s,"copy",u,((t,c)=>{if(t)return o(t);const{destStat:a}=c;!function(e,t,n,r,u){r.filter?ct(at,e,t,n,r,u):at(e,t,n,r,u)}(a,i,s,u,(t=>t?o(t):pt(e,n,r,u,o)))}))}(e,o,t,n,r,u):u()}var Et=function(e,t,n,r){"function"!=typeof n||r?"function"==typeof n&&(n={filter:n}):(r=n,n={}),r=r||function(){},(n=n||{}).clobber=!("clobber"in n)||!!n.clobber,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&"ia32"===process.arch&&console.warn("fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n\n see https://github.com/jprichardson/node-fs-extra/issues/269"),it.checkPaths(e,t,"copy",n,((u,o)=>{if(u)return r(u);const{srcStat:i,destStat:s}=o;it.checkParentPaths(e,i,t,"copy",(u=>u?r(u):n.filter?ct(st,s,e,t,n,r):st(s,e,t,n,r)))}))};const mt=we,ht=p.default,yt=$e.mkdirsSync,Ct=We,Ft=et;function gt(e,t,n,r){const u=(r.dereference?mt.statSync:mt.lstatSync)(t);if(u.isDirectory())return function(e,t,n,r,u){return t?St(n,r,u):function(e,t,n,r){return mt.mkdirSync(n),St(t,n,r),vt(n,e)}(e.mode,n,r,u)}(u,e,t,n,r);if(u.isFile()||u.isCharacterDevice()||u.isBlockDevice())return function(e,t,n,r,u){return t?function(e,t,n,r){if(r.overwrite)return mt.unlinkSync(n),At(e,t,n,r);if(r.errorOnExist)throw new Error(`'${n}' already exists`)}(e,n,r,u):At(e,n,r,u)}(u,e,t,n,r);if(u.isSymbolicLink())return function(e,t,n,r){let u=mt.readlinkSync(t);r.dereference&&(u=ht.resolve(process.cwd(),u));if(e){let e;try{e=mt.readlinkSync(n)}catch(e){if("EINVAL"===e.code||"UNKNOWN"===e.code)return mt.symlinkSync(u,n);throw e}if(r.dereference&&(e=ht.resolve(process.cwd(),e)),Ft.isSrcSubdir(u,e))throw new Error(`Cannot copy '${u}' to a subdirectory of itself, '${e}'.`);if(mt.statSync(n).isDirectory()&&Ft.isSrcSubdir(e,u))throw new Error(`Cannot overwrite '${e}' with '${u}'.`);return function(e,t){return mt.unlinkSync(t),mt.symlinkSync(e,t)}(u,n)}return mt.symlinkSync(u,n)}(e,t,n,r);if(u.isSocket())throw new Error(`Cannot copy a socket file: ${t}`);if(u.isFIFO())throw new Error(`Cannot copy a FIFO pipe: ${t}`);throw new Error(`Unknown file: ${t}`)}function At(e,t,n,r){return mt.copyFileSync(t,n),r.preserveTimestamps&&function(e,t,n){(function(e){return 0==(128&e)})(e)&&function(e,t){vt(e,128|t)}(n,e);(function(e,t){const n=mt.statSync(e);Ct(t,n.atime,n.mtime)})(t,n)}(e.mode,t,n),vt(n,e.mode)}function vt(e,t){return mt.chmodSync(e,t)}function St(e,t,n){mt.readdirSync(e).forEach((r=>function(e,t,n,r){const u=ht.join(t,e),o=ht.join(n,e),{destStat:i}=Ft.checkPathsSync(u,o,"copy",r);return function(e,t,n,r){if(!r.filter||r.filter(t,n))return gt(e,t,n,r)}(i,u,o,r)}(r,e,t,n)))}var wt=function(e,t,n){"function"==typeof n&&(n={filter:n}),(n=n||{}).clobber=!("clobber"in n)||!!n.clobber,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&"ia32"===process.arch&&console.warn("fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n\n see https://github.com/jprichardson/node-fs-extra/issues/269");const{srcStat:r,destStat:u}=Ft.checkPathsSync(e,t,"copy",n);return Ft.checkParentPathsSync(e,r,t,"copy"),function(e,t,n,r){if(r.filter&&!r.filter(t,n))return;const u=ht.dirname(n);mt.existsSync(u)||yt(u);return gt(e,t,n,r)}(u,e,t,n)};var Ot={copy:(0,re.fromCallback)(Et),copySync:wt};const bt=we,_t=p.default,Bt=g.default,Pt="win32"===process.platform;function kt(e){["unlink","chmod","stat","lstat","rmdir","readdir"].forEach((t=>{e[t]=e[t]||bt[t],e[t+="Sync"]=e[t]||bt[t]})),e.maxBusyTries=e.maxBusyTries||3}function xt(e,t,n){let r=0;"function"==typeof t&&(n=t,t={}),Bt(e,"rimraf: missing path"),Bt.strictEqual(typeof e,"string","rimraf: path should be a string"),Bt.strictEqual(typeof n,"function","rimraf: callback function required"),Bt(t,"rimraf: invalid options argument provided"),Bt.strictEqual(typeof t,"object","rimraf: options should be object"),kt(t),Nt(e,t,(function u(o){if(o){if(("EBUSY"===o.code||"ENOTEMPTY"===o.code||"EPERM"===o.code)&&rNt(e,t,u)),100*r)}"ENOENT"===o.code&&(o=null)}n(o)}))}function Nt(e,t,n){Bt(e),Bt(t),Bt("function"==typeof n),t.lstat(e,((r,u)=>r&&"ENOENT"===r.code?n(null):r&&"EPERM"===r.code&&Pt?It(e,t,r,n):u&&u.isDirectory()?Rt(e,t,r,n):void t.unlink(e,(r=>{if(r){if("ENOENT"===r.code)return n(null);if("EPERM"===r.code)return Pt?It(e,t,r,n):Rt(e,t,r,n);if("EISDIR"===r.code)return Rt(e,t,r,n)}return n(r)}))))}function It(e,t,n,r){Bt(e),Bt(t),Bt("function"==typeof r),t.chmod(e,438,(u=>{u?r("ENOENT"===u.code?null:n):t.stat(e,((u,o)=>{u?r("ENOENT"===u.code?null:n):o.isDirectory()?Rt(e,t,n,r):t.unlink(e,r)}))}))}function Tt(e,t,n){let r;Bt(e),Bt(t);try{t.chmodSync(e,438)}catch(e){if("ENOENT"===e.code)return;throw n}try{r=t.statSync(e)}catch(e){if("ENOENT"===e.code)return;throw n}r.isDirectory()?Lt(e,t,n):t.unlinkSync(e)}function Rt(e,t,n,r){Bt(e),Bt(t),Bt("function"==typeof r),t.rmdir(e,(u=>{!u||"ENOTEMPTY"!==u.code&&"EEXIST"!==u.code&&"EPERM"!==u.code?u&&"ENOTDIR"===u.code?r(n):r(u):function(e,t,n){Bt(e),Bt(t),Bt("function"==typeof n),t.readdir(e,((r,u)=>{if(r)return n(r);let o,i=u.length;if(0===i)return t.rmdir(e,n);u.forEach((r=>{xt(_t.join(e,r),t,(r=>{if(!o)return r?n(o=r):void(0==--i&&t.rmdir(e,n))}))}))}))}(e,t,r)}))}function Mt(e,t){let n;kt(t=t||{}),Bt(e,"rimraf: missing path"),Bt.strictEqual(typeof e,"string","rimraf: path should be a string"),Bt(t,"rimraf: missing options"),Bt.strictEqual(typeof t,"object","rimraf: options should be object");try{n=t.lstatSync(e)}catch(n){if("ENOENT"===n.code)return;"EPERM"===n.code&&Pt&&Tt(e,t,n)}try{n&&n.isDirectory()?Lt(e,t,null):t.unlinkSync(e)}catch(n){if("ENOENT"===n.code)return;if("EPERM"===n.code)return Pt?Tt(e,t,n):Lt(e,t,n);if("EISDIR"!==n.code)throw n;Lt(e,t,n)}}function Lt(e,t,n){Bt(e),Bt(t);try{t.rmdirSync(e)}catch(r){if("ENOTDIR"===r.code)throw n;if("ENOTEMPTY"===r.code||"EEXIST"===r.code||"EPERM"===r.code)!function(e,t){if(Bt(e),Bt(t),t.readdirSync(e).forEach((n=>Mt(_t.join(e,n),t))),!Pt){return t.rmdirSync(e,t)}{const n=Date.now();do{try{return t.rmdirSync(e,t)}catch{}}while(Date.now()-n<500)}}(e,t);else if("ENOENT"!==r.code)throw r}}var jt=xt;xt.sync=Mt;const $t=we,Ht=re.fromCallback,Jt=jt;var Gt={remove:Ht((function(e,t){if($t.rm)return $t.rm(e,{recursive:!0,force:!0},t);Jt(e,t)})),removeSync:function(e){if($t.rmSync)return $t.rmSync(e,{recursive:!0,force:!0});Jt.sync(e)}};const Vt=re.fromPromise,Ut=ne,Wt=p.default,zt=$e,Kt=Gt,qt=Vt((async function(e){let t;try{t=await Ut.readdir(e)}catch{return zt.mkdirs(e)}return Promise.all(t.map((t=>Kt.remove(Wt.join(e,t)))))}));function Yt(e){let t;try{t=Ut.readdirSync(e)}catch{return zt.mkdirsSync(e)}t.forEach((t=>{t=Wt.join(e,t),Kt.removeSync(t)}))}var Xt={emptyDirSync:Yt,emptydirSync:Yt,emptyDir:qt,emptydir:qt};const Zt=re.fromCallback,Qt=p.default,en=we,tn=$e;var nn={createFile:Zt((function(e,t){function n(){en.writeFile(e,"",(e=>{if(e)return t(e);t()}))}en.stat(e,((r,u)=>{if(!r&&u.isFile())return t();const o=Qt.dirname(e);en.stat(o,((e,r)=>{if(e)return"ENOENT"===e.code?tn.mkdirs(o,(e=>{if(e)return t(e);n()})):t(e);r.isDirectory()?n():en.readdir(o,(e=>{if(e)return t(e)}))}))}))})),createFileSync:function(e){let t;try{t=en.statSync(e)}catch{}if(t&&t.isFile())return;const n=Qt.dirname(e);try{en.statSync(n).isDirectory()||en.readdirSync(n)}catch(e){if(!e||"ENOENT"!==e.code)throw e;tn.mkdirsSync(n)}en.writeFileSync(e,"")}};const rn=re.fromCallback,un=p.default,on=we,sn=$e,cn=Ge.pathExists,{areIdentical:an}=et;var ln={createLink:rn((function(e,t,n){function r(e,t){on.link(e,t,(e=>{if(e)return n(e);n(null)}))}on.lstat(t,((u,o)=>{on.lstat(e,((u,i)=>{if(u)return u.message=u.message.replace("lstat","ensureLink"),n(u);if(o&&an(i,o))return n(null);const s=un.dirname(t);cn(s,((u,o)=>u?n(u):o?r(e,t):void sn.mkdirs(s,(u=>{if(u)return n(u);r(e,t)}))))}))}))})),createLinkSync:function(e,t){let n;try{n=on.lstatSync(t)}catch{}try{const t=on.lstatSync(e);if(n&&an(t,n))return}catch(e){throw e.message=e.message.replace("lstat","ensureLink"),e}const r=un.dirname(t);return on.existsSync(r)||sn.mkdirsSync(r),on.linkSync(e,t)}};const fn=p.default,dn=we,Dn=Ge.pathExists;var pn={symlinkPaths:function(e,t,n){if(fn.isAbsolute(e))return dn.lstat(e,(t=>t?(t.message=t.message.replace("lstat","ensureSymlink"),n(t)):n(null,{toCwd:e,toDst:e})));{const r=fn.dirname(t),u=fn.join(r,e);return Dn(u,((t,o)=>t?n(t):o?n(null,{toCwd:u,toDst:e}):dn.lstat(e,(t=>t?(t.message=t.message.replace("lstat","ensureSymlink"),n(t)):n(null,{toCwd:e,toDst:fn.relative(r,e)})))))}},symlinkPathsSync:function(e,t){let n;if(fn.isAbsolute(e)){if(n=dn.existsSync(e),!n)throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}{const r=fn.dirname(t),u=fn.join(r,e);if(n=dn.existsSync(u),n)return{toCwd:u,toDst:e};if(n=dn.existsSync(e),!n)throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:fn.relative(r,e)}}}};const En=we;var mn={symlinkType:function(e,t,n){if(n="function"==typeof t?t:n,t="function"!=typeof t&&t)return n(null,t);En.lstat(e,((e,r)=>{if(e)return n(null,"file");t=r&&r.isDirectory()?"dir":"file",n(null,t)}))},symlinkTypeSync:function(e,t){let n;if(t)return t;try{n=En.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}};const hn=re.fromCallback,yn=p.default,Cn=ne,Fn=$e.mkdirs,gn=$e.mkdirsSync,An=pn.symlinkPaths,vn=pn.symlinkPathsSync,Sn=mn.symlinkType,wn=mn.symlinkTypeSync,On=Ge.pathExists,{areIdentical:bn}=et;function _n(e,t,n,r){An(e,t,((u,o)=>{if(u)return r(u);e=o.toDst,Sn(o.toCwd,n,((n,u)=>{if(n)return r(n);const o=yn.dirname(t);On(o,((n,i)=>n?r(n):i?Cn.symlink(e,t,u,r):void Fn(o,(n=>{if(n)return r(n);Cn.symlink(e,t,u,r)}))))}))}))}var Bn={createSymlink:hn((function(e,t,n,r){r="function"==typeof n?n:r,n="function"!=typeof n&&n,Cn.lstat(t,((u,o)=>{!u&&o.isSymbolicLink()?Promise.all([Cn.stat(e),Cn.stat(t)]).then((([u,o])=>{if(bn(u,o))return r(null);_n(e,t,n,r)})):_n(e,t,n,r)}))})),createSymlinkSync:function(e,t,n){let r;try{r=Cn.lstatSync(t)}catch{}if(r&&r.isSymbolicLink()){const n=Cn.statSync(e),r=Cn.statSync(t);if(bn(n,r))return}const u=vn(e,t);e=u.toDst,n=wn(u.toCwd,n);const o=yn.dirname(t);return Cn.existsSync(o)||gn(o),Cn.symlinkSync(e,t,n)}};const{createFile:Pn,createFileSync:kn}=nn,{createLink:xn,createLinkSync:Nn}=ln,{createSymlink:In,createSymlinkSync:Tn}=Bn;var Rn={createFile:Pn,createFileSync:kn,ensureFile:Pn,ensureFileSync:kn,createLink:xn,createLinkSync:Nn,ensureLink:xn,ensureLinkSync:Nn,createSymlink:In,createSymlinkSync:Tn,ensureSymlink:In,ensureSymlinkSync:Tn};var Mn={stringify:function(e,{EOL:t="\n",finalEOL:n=!0,replacer:r=null,spaces:u}={}){const o=n?t:"";return JSON.stringify(e,r,u).replace(/\n/g,t)+o},stripBom:function(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}};let Ln;try{Ln=we}catch(e){Ln=D.default}const jn=re,{stringify:$n,stripBom:Hn}=Mn;const Jn=jn.fromPromise((async function(e,t={}){"string"==typeof t&&(t={encoding:t});const n=t.fs||Ln,r=!("throws"in t)||t.throws;let u,o=await jn.fromCallback(n.readFile)(e,t);o=Hn(o);try{u=JSON.parse(o,t?t.reviver:null)}catch(t){if(r)throw t.message=`${e}: ${t.message}`,t;return null}return u}));const Gn=jn.fromPromise((async function(e,t,n={}){const r=n.fs||Ln,u=$n(t,n);await jn.fromCallback(r.writeFile)(e,u,n)}));const Vn={readFile:Jn,readFileSync:function(e,t={}){"string"==typeof t&&(t={encoding:t});const n=t.fs||Ln,r=!("throws"in t)||t.throws;try{let r=n.readFileSync(e,t);return r=Hn(r),JSON.parse(r,t.reviver)}catch(t){if(r)throw t.message=`${e}: ${t.message}`,t;return null}},writeFile:Gn,writeFileSync:function(e,t,n={}){const r=n.fs||Ln,u=$n(t,n);return r.writeFileSync(e,u,n)}};var Un={readJson:Vn.readFile,readJsonSync:Vn.readFileSync,writeJson:Vn.writeFile,writeJsonSync:Vn.writeFileSync};const Wn=re.fromCallback,zn=we,Kn=p.default,qn=$e,Yn=Ge.pathExists;var Xn={outputFile:Wn((function(e,t,n,r){"function"==typeof n&&(r=n,n="utf8");const u=Kn.dirname(e);Yn(u,((o,i)=>o?r(o):i?zn.writeFile(e,t,n,r):void qn.mkdirs(u,(u=>{if(u)return r(u);zn.writeFile(e,t,n,r)}))))})),outputFileSync:function(e,...t){const n=Kn.dirname(e);if(zn.existsSync(n))return zn.writeFileSync(e,...t);qn.mkdirsSync(n),zn.writeFileSync(e,...t)}};const{stringify:Zn}=Mn,{outputFile:Qn}=Xn;var er=async function(e,t,n={}){const r=Zn(t,n);await Qn(e,r,n)};const{stringify:tr}=Mn,{outputFileSync:nr}=Xn;var rr=function(e,t,n){const r=tr(t,n);nr(e,r,n)};const ur=re.fromPromise,or=Un;or.outputJson=ur(er),or.outputJsonSync=rr,or.outputJSON=or.outputJson,or.outputJSONSync=or.outputJsonSync,or.writeJSON=or.writeJson,or.writeJSONSync=or.writeJsonSync,or.readJSON=or.readJson,or.readJSONSync=or.readJsonSync;var ir=or;const sr=we,cr=p.default,ar=Ot.copy,lr=Gt.remove,fr=$e.mkdirp,dr=Ge.pathExists,Dr=et;function pr(e,t,n,r,u){return r?Er(e,t,n,u):n?lr(t,(r=>r?u(r):Er(e,t,n,u))):void dr(t,((r,o)=>r?u(r):o?u(new Error("dest already exists.")):Er(e,t,n,u)))}function Er(e,t,n,r){sr.rename(e,t,(u=>u?"EXDEV"!==u.code?r(u):function(e,t,n,r){const u={overwrite:n,errorOnExist:!0};ar(e,t,u,(t=>t?r(t):lr(e,r)))}(e,t,n,r):r()))}var mr=function(e,t,n,r){"function"==typeof n&&(r=n,n={});const u=n.overwrite||n.clobber||!1;Dr.checkPaths(e,t,"move",n,((n,o)=>{if(n)return r(n);const{srcStat:i,isChangingCase:s=!1}=o;Dr.checkParentPaths(e,i,t,"move",(n=>n?r(n):function(e){const t=cr.dirname(e);return cr.parse(t).root===t}(t)?pr(e,t,u,s,r):void fr(cr.dirname(t),(n=>n?r(n):pr(e,t,u,s,r)))))}))};const hr=we,yr=p.default,Cr=Ot.copySync,Fr=Gt.removeSync,gr=$e.mkdirpSync,Ar=et;function vr(e,t,n){try{hr.renameSync(e,t)}catch(r){if("EXDEV"!==r.code)throw r;return function(e,t,n){const r={overwrite:n,errorOnExist:!0};return Cr(e,t,r),Fr(e)}(e,t,n)}}var Sr=function(e,t,n){const r=(n=n||{}).overwrite||n.clobber||!1,{srcStat:u,isChangingCase:o=!1}=Ar.checkPathsSync(e,t,"move",n);return Ar.checkParentPathsSync(e,u,t,"move"),function(e){const t=yr.dirname(e);return yr.parse(t).root===t}(t)||gr(yr.dirname(t)),function(e,t,n,r){if(r)return vr(e,t,n);if(n)return Fr(t),vr(e,t,n);if(hr.existsSync(t))throw new Error("dest already exists.");return vr(e,t,n)}(e,t,r,o)};var wr,Or,br,_r,Br,Pr={move:(0,re.fromCallback)(mr),moveSync:Sr},kr={...ne,...Ot,...Xt,...Rn,...ir,...$e,...Pr,...Xn,...Ge,...Gt},xr={},Nr={exports:{}},Ir={exports:{}};function Tr(){if(Or)return wr;Or=1;var e=1e3,t=60*e,n=60*t,r=24*n,u=7*r,o=365.25*r;function i(e,t,n,r){var u=t>=1.5*n;return Math.round(e/n)+" "+r+(u?"s":"")}return wr=function(s,c){c=c||{};var a=typeof s;if("string"===a&&s.length>0)return function(i){if((i=String(i)).length>100)return;var s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(i);if(!s)return;var c=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*o;case"weeks":case"week":case"w":return c*u;case"days":case"day":case"d":return c*r;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(s);if("number"===a&&isFinite(s))return c.long?function(u){var o=Math.abs(u);if(o>=r)return i(u,o,r,"day");if(o>=n)return i(u,o,n,"hour");if(o>=t)return i(u,o,t,"minute");if(o>=e)return i(u,o,e,"second");return u+" ms"}(s):function(u){var o=Math.abs(u);if(o>=r)return Math.round(u/r)+"d";if(o>=n)return Math.round(u/n)+"h";if(o>=t)return Math.round(u/t)+"m";if(o>=e)return Math.round(u/e)+"s";return u+"ms"}(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))}}function Rr(){if(_r)return br;return _r=1,br=function(e){function t(e){let r,u,o,i=null;function s(...e){if(!s.enabled)return;const n=s,u=Number(new Date),o=u-(r||u);n.diff=o,n.prev=r,n.curr=u,r=u,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,u)=>{if("%%"===r)return"%";i++;const o=t.formatters[u];if("function"==typeof o){const t=e[i];r=o.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=n,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(u!==t.namespaces&&(u=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(s),s}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),u=r.length;for(n=0;n{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),u=t.indexOf("--");return-1!==r&&(-1===u||r{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if($r)return jr;$r=1;const e=E.default,t=A.default,n=Vr(),{env:r}=process;let u;function o(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function i(t,o){if(0===u)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!o&&void 0===u)return 0;const i=u||0;if("dumb"===r.TERM)return i;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in r))||"codeship"===r.CI_NAME?1:i;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if("truecolor"===r.COLORTERM)return 3;if("TERM_PROGRAM"in r){const e=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:i}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?u=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(u=1),"FORCE_COLOR"in r&&(u="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),jr={supportsColor:function(e){return o(i(e,e&&e.isTTY))},stdout:o(i(!0,t.isatty(1))),stderr:o(i(!0,t.isatty(2)))}}();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let r=process.env[t];return r=!!/^(yes|on|true|enabled)$/i.test(r)||!/^(no|off|false|disabled)$/i.test(r)&&("null"===r?null:Number(r)),e[n]=r,e}),{}),e.exports=Rr()(t);const{formatters:u}=e.exports;u.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},u.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(Gr,Gr.exports)),Gr.exports}Jr=Nr,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Jr.exports=(Br||(Br=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,u=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(u=r))})),t.splice(u,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=Rr()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Ir,Ir.exports)),Ir.exports):Jr.exports=Ur();var Wr=function(e){return(e=e||{}).circles?function(e){var t=[],n=[];return e.proto?function e(u){if("object"!=typeof u||null===u)return u;if(u instanceof Date)return new Date(u);if(Array.isArray(u))return r(u,e);if(u instanceof Map)return new Map(r(Array.from(u),e));if(u instanceof Set)return new Set(r(Array.from(u),e));var o={};for(var i in t.push(u),n.push(o),u){var s=u[i];if("object"!=typeof s||null===s)o[i]=s;else if(s instanceof Date)o[i]=new Date(s);else if(s instanceof Map)o[i]=new Map(r(Array.from(s),e));else if(s instanceof Set)o[i]=new Set(r(Array.from(s),e));else if(ArrayBuffer.isView(s))o[i]=zr(s);else{var c=t.indexOf(s);o[i]=-1!==c?n[c]:e(s)}}return t.pop(),n.pop(),o}:function e(u){if("object"!=typeof u||null===u)return u;if(u instanceof Date)return new Date(u);if(Array.isArray(u))return r(u,e);if(u instanceof Map)return new Map(r(Array.from(u),e));if(u instanceof Set)return new Set(r(Array.from(u),e));var o={};for(var i in t.push(u),n.push(o),u)if(!1!==Object.hasOwnProperty.call(u,i)){var s=u[i];if("object"!=typeof s||null===s)o[i]=s;else if(s instanceof Date)o[i]=new Date(s);else if(s instanceof Map)o[i]=new Map(r(Array.from(s),e));else if(s instanceof Set)o[i]=new Set(r(Array.from(s),e));else if(ArrayBuffer.isView(s))o[i]=zr(s);else{var c=t.indexOf(s);o[i]=-1!==c?n[c]:e(s)}}return t.pop(),n.pop(),o};function r(e,r){for(var u=Object.keys(e),o=new Array(u.length),i=0;i!e,Qr=e=>e&&"object"==typeof e&&!Array.isArray(e),eu=(e,t,n)=>{(Array.isArray(t)?t:[t]).forEach((t=>{if(t)throw new Error(`Problem with log4js configuration: (${Kr.inspect(e,{depth:5})}) - ${n}`)}))};var tu={configure:e=>{qr("New configuration to be validated: ",e),eu(e,Zr(Qr(e)),"must be an object."),qr(`Calling pre-processing listeners (${Yr.length})`),Yr.forEach((t=>t(e))),qr("Configuration pre-processing finished."),qr(`Calling configuration listeners (${Xr.length})`),Xr.forEach((t=>t(e))),qr("Configuration finished.")},addListener:e=>{Xr.push(e),qr(`Added listener, now ${Xr.length} listeners`)},addPreProcessingListener:e=>{Yr.push(e),qr(`Added pre-processing listener, now ${Yr.length} listeners`)},throwExceptionIf:eu,anObject:Qr,anInteger:e=>e&&"number"==typeof e&&Number.isInteger(e),validIdentifier:e=>/^[A-Za-z][A-Za-z0-9_]*$/g.test(e),not:Zr},nu={exports:{}};!function(e){function t(e,t){for(var n=e.toString();n.length-1?s:c,l=n(u.getHours()),f=n(u.getMinutes()),d=n(u.getSeconds()),D=t(u.getMilliseconds(),3),p=function(e){var t=Math.abs(e),n=String(Math.floor(t/60)),r=String(t%60);return n=("0"+n).slice(-2),r=("0"+r).slice(-2),0===e?"Z":(e<0?"+":"-")+n+":"+r}(u.getTimezoneOffset());return r.replace(/dd/g,o).replace(/MM/g,i).replace(/y{1,4}/g,a).replace(/hh/g,l).replace(/mm/g,f).replace(/ss/g,d).replace(/SSS/g,D).replace(/O/g,p)}function u(e,t,n,r){e["set"+(r?"":"UTC")+t](n)}e.exports=r,e.exports.asString=r,e.exports.parse=function(t,n,r){if(!t)throw new Error("pattern must be supplied");return function(t,n,r){var o=t.indexOf("O")<0,i=!1,s=[{pattern:/y{1,4}/,regexp:"\\d{1,4}",fn:function(e,t){u(e,"FullYear",t,o)}},{pattern:/MM/,regexp:"\\d{1,2}",fn:function(e,t){u(e,"Month",t-1,o),e.getMonth()!==t-1&&(i=!0)}},{pattern:/dd/,regexp:"\\d{1,2}",fn:function(e,t){i&&u(e,"Month",e.getMonth()-1,o),u(e,"Date",t,o)}},{pattern:/hh/,regexp:"\\d{1,2}",fn:function(e,t){u(e,"Hours",t,o)}},{pattern:/mm/,regexp:"\\d\\d",fn:function(e,t){u(e,"Minutes",t,o)}},{pattern:/ss/,regexp:"\\d\\d",fn:function(e,t){u(e,"Seconds",t,o)}},{pattern:/SSS/,regexp:"\\d\\d\\d",fn:function(e,t){u(e,"Milliseconds",t,o)}},{pattern:/O/,regexp:"[+-]\\d{1,2}:?\\d{2}?|Z",fn:function(e,t){t="Z"===t?0:t.replace(":","");var n=Math.abs(t),r=(t>0?-1:1)*(n%100+60*Math.floor(n/100));e.setUTCMinutes(e.getUTCMinutes()+r)}}],c=s.reduce((function(e,t){return t.pattern.test(e.regexp)?(t.index=e.regexp.match(t.pattern).index,e.regexp=e.regexp.replace(t.pattern,"("+t.regexp+")")):t.index=-1,e}),{regexp:t,index:[]}),a=s.filter((function(e){return e.index>-1}));a.sort((function(e,t){return e.index-t.index}));var l=new RegExp(c.regexp).exec(n);if(l){var f=r||e.exports.now();return a.forEach((function(e,t){e.fn(f,l[t+1])})),f}throw new Error("String '"+n+"' could not be parsed as '"+t+"'")}(t,n,r)},e.exports.now=function(){return new Date},e.exports.ISO8601_FORMAT="yyyy-MM-ddThh:mm:ss.SSS",e.exports.ISO8601_WITH_TZ_OFFSET_FORMAT="yyyy-MM-ddThh:mm:ss.SSSO",e.exports.DATETIME_FORMAT="dd MM yyyy hh:mm:ss.SSS",e.exports.ABSOLUTETIME_FORMAT="hh:mm:ss.SSS"}(nu);const ru=nu.exports,uu=E.default,ou=F.default,iu=p.default,su={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[90,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[91,39],yellow:[33,39]};function cu(e){return e?`[${su[e][0]}m`:""}function au(e){return e?`[${su[e][1]}m`:""}function lu(e,t){return n=ou.format("[%s] [%s] %s - ",ru.asString(e.startTime),e.level.toString(),e.categoryName),cu(r=t)+n+au(r);var n,r}function fu(e){return lu(e)+ou.format(...e.data)}function du(e){return lu(e,e.level.colour)+ou.format(...e.data)}function Du(e){return ou.format(...e.data)}function pu(e){return e.data[0]}function Eu(e,t){const n=/%(-?[0-9]+)?(\.?-?[0-9]+)?([[\]cdhmnprzxXyflos%])(\{([^}]+)\})?|([^%]+)/;function r(e){return e&&e.pid?e.pid.toString():process.pid.toString()}e=e||"%r %p %c - %m%n";const u={c:function(e,t){let n=e.categoryName;if(t){const e=parseInt(t,10),r=n.split(".");ee&&(n=r.slice(-e).join(iu.sep))}return n},l:function(e){return e.lineNumber?`${e.lineNumber}`:""},o:function(e){return e.columnNumber?`${e.columnNumber}`:""},s:function(e){return e.callStack||""}};function o(e,t,n){return u[e](t,n)}function i(e,t,n){let r=e;return r=function(e,t){let n;return e?(n=parseInt(e.substr(1),10),n>0?t.slice(0,n):t.slice(n)):t}(t,r),r=function(e,t){let n;if(e)if("-"===e.charAt(0))for(n=parseInt(e.substr(1),10);t.lengthDu,basic:()=>fu,colored:()=>du,coloured:()=>du,pattern:e=>Eu(e&&e.pattern,e&&e.tokens),dummy:()=>pu};var hu={basicLayout:fu,messagePassThroughLayout:Du,patternLayout:Eu,colouredLayout:du,coloredLayout:du,dummyLayout:pu,addLayout(e,t){mu[e]=t},layout:(e,t)=>mu[e]&&mu[e](t)};const yu=tu,Cu=["white","grey","black","blue","cyan","green","magenta","red","yellow"];class Fu{constructor(e,t,n){this.level=e,this.levelStr=t,this.colour=n}toString(){return this.levelStr}static getLevel(e,t){return e?e instanceof Fu?e:(e instanceof Object&&e.levelStr&&(e=e.levelStr),Fu[e.toString().toUpperCase()]||t):t}static addLevels(e){if(e){Object.keys(e).forEach((t=>{const n=t.toUpperCase();Fu[n]=new Fu(e[t].value,n,e[t].colour);const r=Fu.levels.findIndex((e=>e.levelStr===n));r>-1?Fu.levels[r]=Fu[n]:Fu.levels.push(Fu[n])})),Fu.levels.sort(((e,t)=>e.level-t.level))}}isLessThanOrEqualTo(e){return"string"==typeof e&&(e=Fu.getLevel(e)),this.level<=e.level}isGreaterThanOrEqualTo(e){return"string"==typeof e&&(e=Fu.getLevel(e)),this.level>=e.level}isEqualTo(e){return"string"==typeof e&&(e=Fu.getLevel(e)),this.level===e.level}}Fu.levels=[],Fu.addLevels({ALL:{value:Number.MIN_VALUE,colour:"grey"},TRACE:{value:5e3,colour:"blue"},DEBUG:{value:1e4,colour:"cyan"},INFO:{value:2e4,colour:"green"},WARN:{value:3e4,colour:"yellow"},ERROR:{value:4e4,colour:"red"},FATAL:{value:5e4,colour:"magenta"},MARK:{value:9007199254740992,colour:"grey"},OFF:{value:Number.MAX_VALUE,colour:"grey"}}),yu.addListener((e=>{const t=e.levels;if(t){yu.throwExceptionIf(e,yu.not(yu.anObject(t)),"levels must be an object");Object.keys(t).forEach((n=>{yu.throwExceptionIf(e,yu.not(yu.validIdentifier(n)),`level name "${n}" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)`),yu.throwExceptionIf(e,yu.not(yu.anObject(t[n])),`level "${n}" must be an object`),yu.throwExceptionIf(e,yu.not(t[n].value),`level "${n}" must have a 'value' property`),yu.throwExceptionIf(e,yu.not(yu.anInteger(t[n].value)),`level "${n}".value must have an integer value`),yu.throwExceptionIf(e,yu.not(t[n].colour),`level "${n}" must have a 'colour' property`),yu.throwExceptionIf(e,yu.not(Cu.indexOf(t[n].colour)>-1),`level "${n}".colour must be one of ${Cu.join(", ")}`)}))}})),yu.addListener((e=>{Fu.addLevels(e.levels)}));var gu=Fu,Au={exports:{}},vu={};/*! (c) 2020 Andrea Giammarchi */ -const{parse:Su,stringify:wu}=JSON,{keys:Ou}=Object,bu=String,_u="string",Bu={},Pu="object",ku=(e,t)=>t,xu=e=>e instanceof bu?bu(e):e,Nu=(e,t)=>typeof t===_u?new bu(t):t,Iu=(e,t,n,r)=>{const u=[];for(let o=Ou(n),{length:i}=o,s=0;s{const r=bu(t.push(n)-1);return e.set(n,r),r},Ru=(e,t)=>{const n=Su(e,Nu).map(xu),r=n[0],u=t||ku,o=typeof r===Pu&&r?Iu(n,new Set,r,u):r;return u.call({"":o},"",o)};vu.parse=Ru;const Mu=(e,t,n)=>{const r=t&&typeof t===Pu?(e,n)=>""===e||-1Su(Mu(e));vu.fromJSON=e=>Ru(wu(e));const Lu=vu,ju=gu;class $u{constructor(e,t,n,r,u){this.startTime=new Date,this.categoryName=e,this.data=n,this.level=t,this.context=Object.assign({},r),this.pid=process.pid,u&&(this.functionName=u.functionName,this.fileName=u.fileName,this.lineNumber=u.lineNumber,this.columnNumber=u.columnNumber,this.callStack=u.callStack)}serialise(){const e=this.data.map((e=>(e&&e.message&&e.stack&&(e=Object.assign({message:e.message,stack:e.stack},e)),e)));return this.data=e,Lu.stringify(this)}static deserialise(e){let t;try{const n=Lu.parse(e);n.data=n.data.map((e=>{if(e&&e.message&&e.stack){const t=new Error(e);Object.keys(e).forEach((n=>{t[n]=e[n]})),e=t}return e})),t=new $u(n.categoryName,ju.getLevel(n.level.levelStr),n.data,n.context),t.startTime=new Date(n.startTime),t.pid=n.pid,t.cluster=n.cluster}catch(n){t=new $u("log4js",ju.ERROR,["Unable to parse log:",e,"because: ",n])}return t}}var Hu=$u;const Ju=Nr.exports("log4js:clustering"),Gu=Hu,Vu=tu;let Uu=!1,Wu=null;try{Wu=require("cluster")}catch(e){Ju("cluster module not present"),Uu=!0}const zu=[];let Ku=!1,qu="NODE_APP_INSTANCE";const Yu=()=>Ku&&"0"===process.env[qu],Xu=()=>Uu||Wu.isMaster||Yu(),Zu=e=>{zu.forEach((t=>t(e)))},Qu=(e,t)=>{if(Ju("cluster message received from worker ",e,": ",t),e.topic&&e.data&&(t=e,e=void 0),t&&t.topic&&"log4js:message"===t.topic){Ju("received message: ",t.data);const e=Gu.deserialise(t.data);Zu(e)}};Uu||Vu.addListener((e=>{zu.length=0,({pm2:Ku,disableClustering:Uu,pm2InstanceVar:qu="NODE_APP_INSTANCE"}=e),Ju(`clustering disabled ? ${Uu}`),Ju(`cluster.isMaster ? ${Wu&&Wu.isMaster}`),Ju(`pm2 enabled ? ${Ku}`),Ju(`pm2InstanceVar = ${qu}`),Ju(`process.env[${qu}] = ${process.env[qu]}`),Ku&&process.removeListener("message",Qu),Wu&&Wu.removeListener&&Wu.removeListener("message",Qu),Uu||e.disableClustering?Ju("Not listening for cluster messages, because clustering disabled."):Yu()?(Ju("listening for PM2 broadcast messages"),process.on("message",Qu)):Wu.isMaster?(Ju("listening for cluster messages"),Wu.on("message",Qu)):Ju("not listening for messages, because we are not a master process")}));var eo={onlyOnMaster:(e,t)=>Xu()?e():t,isMaster:Xu,send:e=>{Xu()?Zu(e):(Ku||(e.cluster={workerId:Wu.worker.id,worker:process.pid}),process.send({topic:"log4js:message",data:e.serialise()}))},onMessage:e=>{zu.push(e)}},to={};function no(e){if("number"==typeof e&&Number.isInteger(e))return e;const t={K:1024,M:1048576,G:1073741824},n=Object.keys(t),r=e.substr(e.length-1).toLocaleUpperCase(),u=e.substring(0,e.length-1).trim();if(n.indexOf(r)<0||!Number.isInteger(Number(u)))throw Error(`maxLogSize: "${e}" is invalid`);return u*t[r]}function ro(e){return function(e,t){const n=Object.assign({},t);return Object.keys(e).forEach((r=>{n[r]&&(n[r]=e[r](t[r]))})),n}({maxLogSize:no},e)}const uo={file:ro,fileSync:ro};to.modifyConfig=e=>uo[e.type]?uo[e.type](e):e;var oo={};const io=console.log.bind(console);oo.configure=function(e,t){let n=t.colouredLayout;return e.layout&&(n=t.layout(e.layout.type,e.layout)),function(e,t){return n=>{io(e(n,t))}}(n,e.timezoneOffset)};var so={};so.configure=function(e,t){let n=t.colouredLayout;return e.layout&&(n=t.layout(e.layout.type,e.layout)),function(e,t){return n=>{process.stdout.write(`${e(n,t)}\n`)}}(n,e.timezoneOffset)};var co={};co.configure=function(e,t){let n=t.colouredLayout;return e.layout&&(n=t.layout(e.layout.type,e.layout)),function(e,t){return n=>{process.stderr.write(`${e(n,t)}\n`)}}(n,e.timezoneOffset)};var ao={};ao.configure=function(e,t,n,r){const u=n(e.appender);return function(e,t,n,r){const u=r.getLevel(e),o=r.getLevel(t,r.FATAL);return e=>{const t=e.level;t.isGreaterThanOrEqualTo(u)&&t.isLessThanOrEqualTo(o)&&n(e)}}(e.level,e.maxLevel,u,r)};var lo={};const fo=Nr.exports("log4js:categoryFilter");lo.configure=function(e,t,n){const r=n(e.appender);return function(e,t){return"string"==typeof e&&(e=[e]),n=>{fo(`Checking ${n.categoryName} against ${e}`),-1===e.indexOf(n.categoryName)&&(fo("Not excluded, sending to appender"),t(n))}}(e.exclude,r)};var Do={};const po=Nr.exports("log4js:noLogFilter");Do.configure=function(e,t,n){const r=n(e.appender);return function(e,t){return n=>{po(`Checking data: ${n.data} against filters: ${e}`),"string"==typeof e&&(e=[e]),e=e.filter((e=>null!=e&&""!==e));const r=new RegExp(e.join("|"),"i");(0===e.length||n.data.findIndex((e=>r.test(e)))<0)&&(po("Not excluded, sending to appender"),t(n))}}(e.exclude,r)};var Eo={},mo={exports:{}},ho={},yo={fromCallback:function(e){return Object.defineProperty((function(){if("function"!=typeof arguments[arguments.length-1])return new Promise(((t,n)=>{arguments[arguments.length]=(e,r)=>{if(e)return n(e);t(r)},arguments.length++,e.apply(this,arguments)}));e.apply(this,arguments)}),"name",{value:e.name})},fromPromise:function(e){return Object.defineProperty((function(){const t=arguments[arguments.length-1];if("function"!=typeof t)return e.apply(this,arguments);e.apply(this,arguments).then((e=>t(null,e)),t)}),"name",{value:e.name})}};!function(e){const t=yo.fromCallback,n=we,r=["access","appendFile","chmod","chown","close","copyFile","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","lchown","lchmod","link","lstat","mkdir","mkdtemp","open","readFile","readdir","readlink","realpath","rename","rmdir","stat","symlink","truncate","unlink","utimes","writeFile"].filter((e=>"function"==typeof n[e]));Object.keys(n).forEach((t=>{"promises"!==t&&(e[t]=n[t])})),r.forEach((r=>{e[r]=t(n[r])})),e.exists=function(e,t){return"function"==typeof t?n.exists(e,t):new Promise((t=>n.exists(e,t)))},e.read=function(e,t,r,u,o,i){return"function"==typeof i?n.read(e,t,r,u,o,i):new Promise(((i,s)=>{n.read(e,t,r,u,o,((e,t,n)=>{if(e)return s(e);i({bytesRead:t,buffer:n})}))}))},e.write=function(e,t,...r){return"function"==typeof r[r.length-1]?n.write(e,t,...r):new Promise(((u,o)=>{n.write(e,t,...r,((e,t,n)=>{if(e)return o(e);u({bytesWritten:t,buffer:n})}))}))},"function"==typeof n.realpath.native&&(e.realpath.native=t(n.realpath.native))}(ho);const Co=p.default;function Fo(e){return(e=Co.normalize(Co.resolve(e)).split(Co.sep)).length>0?e[0]:null}const go=/[<>:"|?*]/;var Ao=function(e){const t=Fo(e);return e=e.replace(t,""),go.test(e)};const vo=we,So=p.default,wo=Ao,Oo=parseInt("0777",8);var bo=function e(t,n,r,u){if("function"==typeof n?(r=n,n={}):n&&"object"==typeof n||(n={mode:n}),"win32"===process.platform&&wo(t)){const e=new Error(t+" contains invalid WIN32 path characters.");return e.code="EINVAL",r(e)}let o=n.mode;const i=n.fs||vo;void 0===o&&(o=Oo&~process.umask()),u||(u=null),r=r||function(){},t=So.resolve(t),i.mkdir(t,o,(o=>{if(!o)return r(null,u=u||t);if("ENOENT"===o.code){if(So.dirname(t)===t)return r(o);e(So.dirname(t),n,((u,o)=>{u?r(u,o):e(t,n,r,o)}))}else i.stat(t,((e,t)=>{e||!t.isDirectory()?r(o,u):r(null,u)}))}))};const _o=we,Bo=p.default,Po=Ao,ko=parseInt("0777",8);var xo=function e(t,n,r){n&&"object"==typeof n||(n={mode:n});let u=n.mode;const o=n.fs||_o;if("win32"===process.platform&&Po(t)){const e=new Error(t+" contains invalid WIN32 path characters.");throw e.code="EINVAL",e}void 0===u&&(u=ko&~process.umask()),r||(r=null),t=Bo.resolve(t);try{o.mkdirSync(t,u),r=r||t}catch(u){if("ENOENT"===u.code){if(Bo.dirname(t)===t)throw u;r=e(Bo.dirname(t),n,r),e(t,n,r)}else{let e;try{e=o.statSync(t)}catch(e){throw u}if(!e.isDirectory())throw u}}return r};const No=(0,yo.fromCallback)(bo);var Io={mkdirs:No,mkdirsSync:xo,mkdirp:No,mkdirpSync:xo,ensureDir:No,ensureDirSync:xo};const To=we;E.default,p.default;var Ro=function(e,t,n,r){To.open(e,"r+",((e,u)=>{if(e)return r(e);To.futimes(u,t,n,(e=>{To.close(u,(t=>{r&&r(e||t)}))}))}))},Mo=function(e,t,n){const r=To.openSync(e,"r+");return To.futimesSync(r,t,n),To.closeSync(r)};const Lo=we,jo=p.default,$o=10,Ho=5,Jo=0,Go=process.versions.node.split("."),Vo=Number.parseInt(Go[0],10),Uo=Number.parseInt(Go[1],10),Wo=Number.parseInt(Go[2],10);function zo(){if(Vo>$o)return!0;if(Vo===$o){if(Uo>Ho)return!0;if(Uo===Ho&&Wo>=Jo)return!0}return!1}function Ko(e,t){const n=jo.resolve(e).split(jo.sep).filter((e=>e)),r=jo.resolve(t).split(jo.sep).filter((e=>e));return n.reduce(((e,t,n)=>e&&r[n]===t),!0)}function qo(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}var Yo,Xo,Zo={checkPaths:function(e,t,n,r){!function(e,t,n){zo()?Lo.stat(e,{bigint:!0},((e,r)=>{if(e)return n(e);Lo.stat(t,{bigint:!0},((e,t)=>e?"ENOENT"===e.code?n(null,{srcStat:r,destStat:null}):n(e):n(null,{srcStat:r,destStat:t})))})):Lo.stat(e,((e,r)=>{if(e)return n(e);Lo.stat(t,((e,t)=>e?"ENOENT"===e.code?n(null,{srcStat:r,destStat:null}):n(e):n(null,{srcStat:r,destStat:t})))}))}(e,t,((u,o)=>{if(u)return r(u);const{srcStat:i,destStat:s}=o;return s&&s.ino&&s.dev&&s.ino===i.ino&&s.dev===i.dev?r(new Error("Source and destination must not be the same.")):i.isDirectory()&&Ko(e,t)?r(new Error(qo(e,t,n))):r(null,{srcStat:i,destStat:s})}))},checkPathsSync:function(e,t,n){const{srcStat:r,destStat:u}=function(e,t){let n,r;n=zo()?Lo.statSync(e,{bigint:!0}):Lo.statSync(e);try{r=zo()?Lo.statSync(t,{bigint:!0}):Lo.statSync(t)}catch(e){if("ENOENT"===e.code)return{srcStat:n,destStat:null};throw e}return{srcStat:n,destStat:r}}(e,t);if(u&&u.ino&&u.dev&&u.ino===r.ino&&u.dev===r.dev)throw new Error("Source and destination must not be the same.");if(r.isDirectory()&&Ko(e,t))throw new Error(qo(e,t,n));return{srcStat:r,destStat:u}},checkParentPaths:function e(t,n,r,u,o){const i=jo.resolve(jo.dirname(t)),s=jo.resolve(jo.dirname(r));if(s===i||s===jo.parse(s).root)return o();zo()?Lo.stat(s,{bigint:!0},((i,c)=>i?"ENOENT"===i.code?o():o(i):c.ino&&c.dev&&c.ino===n.ino&&c.dev===n.dev?o(new Error(qo(t,r,u))):e(t,n,s,u,o))):Lo.stat(s,((i,c)=>i?"ENOENT"===i.code?o():o(i):c.ino&&c.dev&&c.ino===n.ino&&c.dev===n.dev?o(new Error(qo(t,r,u))):e(t,n,s,u,o)))},checkParentPathsSync:function e(t,n,r,u){const o=jo.resolve(jo.dirname(t)),i=jo.resolve(jo.dirname(r));if(i===o||i===jo.parse(i).root)return;let s;try{s=zo()?Lo.statSync(i,{bigint:!0}):Lo.statSync(i)}catch(e){if("ENOENT"===e.code)return;throw e}if(s.ino&&s.dev&&s.ino===n.ino&&s.dev===n.dev)throw new Error(qo(t,r,u));return e(t,n,i,u)},isSrcSubdir:Ko};const Qo=we,ei=p.default,ti=Io.mkdirsSync,ni=Mo,ri=Zo;function ui(e,t,n,r){if(!r.filter||r.filter(t,n))return function(e,t,n,r){const u=r.dereference?Qo.statSync:Qo.lstatSync,o=u(t);if(o.isDirectory())return function(e,t,n,r,u){if(!t)return function(e,t,n,r){return Qo.mkdirSync(n),ii(t,n,r),Qo.chmodSync(n,e.mode)}(e,n,r,u);if(t&&!t.isDirectory())throw new Error(`Cannot overwrite non-directory '${r}' with directory '${n}'.`);return ii(n,r,u)}(o,e,t,n,r);if(o.isFile()||o.isCharacterDevice()||o.isBlockDevice())return function(e,t,n,r,u){return t?function(e,t,n,r){if(r.overwrite)return Qo.unlinkSync(n),oi(e,t,n,r);if(r.errorOnExist)throw new Error(`'${n}' already exists`)}(e,n,r,u):oi(e,n,r,u)}(o,e,t,n,r);if(o.isSymbolicLink())return function(e,t,n,r){let u=Qo.readlinkSync(t);r.dereference&&(u=ei.resolve(process.cwd(),u));if(e){let e;try{e=Qo.readlinkSync(n)}catch(e){if("EINVAL"===e.code||"UNKNOWN"===e.code)return Qo.symlinkSync(u,n);throw e}if(r.dereference&&(e=ei.resolve(process.cwd(),e)),ri.isSrcSubdir(u,e))throw new Error(`Cannot copy '${u}' to a subdirectory of itself, '${e}'.`);if(Qo.statSync(n).isDirectory()&&ri.isSrcSubdir(e,u))throw new Error(`Cannot overwrite '${e}' with '${u}'.`);return function(e,t){return Qo.unlinkSync(t),Qo.symlinkSync(e,t)}(u,n)}return Qo.symlinkSync(u,n)}(e,t,n,r)}(e,t,n,r)}function oi(e,t,n,r){return"function"==typeof Qo.copyFileSync?(Qo.copyFileSync(t,n),Qo.chmodSync(n,e.mode),r.preserveTimestamps?ni(n,e.atime,e.mtime):void 0):function(e,t,n,r){const u=65536,o=(Xo?Yo:(Xo=1,Yo=function(e){if("function"==typeof Buffer.allocUnsafe)try{return Buffer.allocUnsafe(e)}catch(t){return new Buffer(e)}return new Buffer(e)}))(u),i=Qo.openSync(t,"r"),s=Qo.openSync(n,"w",e.mode);let c=0;for(;cfunction(e,t,n,r){const u=ei.join(t,e),o=ei.join(n,e),{destStat:i}=ri.checkPathsSync(u,o,"copy");return ui(i,u,o,r)}(r,e,t,n)))}var si=function(e,t,n){"function"==typeof n&&(n={filter:n}),(n=n||{}).clobber=!("clobber"in n)||!!n.clobber,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&"ia32"===process.arch&&console.warn("fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n\n see https://github.com/jprichardson/node-fs-extra/issues/269");const{srcStat:r,destStat:u}=ri.checkPathsSync(e,t,"copy");return ri.checkParentPathsSync(e,r,t,"copy"),function(e,t,n,r){if(r.filter&&!r.filter(t,n))return;const u=ei.dirname(n);Qo.existsSync(u)||ti(u);return ui(e,t,n,r)}(u,e,t,n)},ci={copySync:si};const ai=yo.fromPromise,li=ho;var fi={pathExists:ai((function(e){return li.access(e).then((()=>!0)).catch((()=>!1))})),pathExistsSync:li.existsSync};const di=we,Di=p.default,pi=Io.mkdirs,Ei=fi.pathExists,mi=Ro,hi=Zo;function yi(e,t,n,r,u){const o=Di.dirname(n);Ei(o,((i,s)=>i?u(i):s?Fi(e,t,n,r,u):void pi(o,(o=>o?u(o):Fi(e,t,n,r,u)))))}function Ci(e,t,n,r,u,o){Promise.resolve(u.filter(n,r)).then((i=>i?e(t,n,r,u,o):o()),(e=>o(e)))}function Fi(e,t,n,r,u){return r.filter?Ci(gi,e,t,n,r,u):gi(e,t,n,r,u)}function gi(e,t,n,r,u){(r.dereference?di.stat:di.lstat)(t,((o,i)=>o?u(o):i.isDirectory()?function(e,t,n,r,u,o){if(!t)return function(e,t,n,r,u){di.mkdir(n,(o=>{if(o)return u(o);Si(t,n,r,(t=>t?u(t):di.chmod(n,e.mode,u)))}))}(e,n,r,u,o);if(t&&!t.isDirectory())return o(new Error(`Cannot overwrite non-directory '${r}' with directory '${n}'.`));return Si(n,r,u,o)}(i,e,t,n,r,u):i.isFile()||i.isCharacterDevice()||i.isBlockDevice()?function(e,t,n,r,u,o){return t?function(e,t,n,r,u){if(!r.overwrite)return r.errorOnExist?u(new Error(`'${n}' already exists`)):u();di.unlink(n,(o=>o?u(o):Ai(e,t,n,r,u)))}(e,n,r,u,o):Ai(e,n,r,u,o)}(i,e,t,n,r,u):i.isSymbolicLink()?function(e,t,n,r,u){di.readlink(t,((t,o)=>t?u(t):(r.dereference&&(o=Di.resolve(process.cwd(),o)),e?void di.readlink(n,((t,i)=>t?"EINVAL"===t.code||"UNKNOWN"===t.code?di.symlink(o,n,u):u(t):(r.dereference&&(i=Di.resolve(process.cwd(),i)),hi.isSrcSubdir(o,i)?u(new Error(`Cannot copy '${o}' to a subdirectory of itself, '${i}'.`)):e.isDirectory()&&hi.isSrcSubdir(i,o)?u(new Error(`Cannot overwrite '${i}' with '${o}'.`)):function(e,t,n){di.unlink(t,(r=>r?n(r):di.symlink(e,t,n)))}(o,n,u)))):di.symlink(o,n,u))))}(e,t,n,r,u):void 0))}function Ai(e,t,n,r,u){return"function"==typeof di.copyFile?di.copyFile(t,n,(t=>t?u(t):vi(e,n,r,u))):function(e,t,n,r,u){const o=di.createReadStream(t);o.on("error",(e=>u(e))).once("open",(()=>{const t=di.createWriteStream(n,{mode:e.mode});t.on("error",(e=>u(e))).on("open",(()=>o.pipe(t))).once("close",(()=>vi(e,n,r,u)))}))}(e,t,n,r,u)}function vi(e,t,n,r){di.chmod(t,e.mode,(u=>u?r(u):n.preserveTimestamps?mi(t,e.atime,e.mtime,r):r()))}function Si(e,t,n,r){di.readdir(e,((u,o)=>u?r(u):wi(o,e,t,n,r)))}function wi(e,t,n,r,u){const o=e.pop();return o?function(e,t,n,r,u,o){const i=Di.join(n,t),s=Di.join(r,t);hi.checkPaths(i,s,"copy",((t,c)=>{if(t)return o(t);const{destStat:a}=c;Fi(a,i,s,u,(t=>t?o(t):wi(e,n,r,u,o)))}))}(e,o,t,n,r,u):u()}var Oi=function(e,t,n,r){"function"!=typeof n||r?"function"==typeof n&&(n={filter:n}):(r=n,n={}),r=r||function(){},(n=n||{}).clobber=!("clobber"in n)||!!n.clobber,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&"ia32"===process.arch&&console.warn("fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n\n see https://github.com/jprichardson/node-fs-extra/issues/269"),hi.checkPaths(e,t,"copy",((u,o)=>{if(u)return r(u);const{srcStat:i,destStat:s}=o;hi.checkParentPaths(e,i,t,"copy",(u=>u?r(u):n.filter?Ci(yi,s,e,t,n,r):yi(s,e,t,n,r)))}))};var bi={copy:(0,yo.fromCallback)(Oi)};const _i=we,Bi=p.default,Pi=g.default,ki="win32"===process.platform;function xi(e){["unlink","chmod","stat","lstat","rmdir","readdir"].forEach((t=>{e[t]=e[t]||_i[t],e[t+="Sync"]=e[t]||_i[t]})),e.maxBusyTries=e.maxBusyTries||3}function Ni(e,t,n){let r=0;"function"==typeof t&&(n=t,t={}),Pi(e,"rimraf: missing path"),Pi.strictEqual(typeof e,"string","rimraf: path should be a string"),Pi.strictEqual(typeof n,"function","rimraf: callback function required"),Pi(t,"rimraf: invalid options argument provided"),Pi.strictEqual(typeof t,"object","rimraf: options should be object"),xi(t),Ii(e,t,(function u(o){if(o){if(("EBUSY"===o.code||"ENOTEMPTY"===o.code||"EPERM"===o.code)&&rIi(e,t,u)),100*r)}"ENOENT"===o.code&&(o=null)}n(o)}))}function Ii(e,t,n){Pi(e),Pi(t),Pi("function"==typeof n),t.lstat(e,((r,u)=>r&&"ENOENT"===r.code?n(null):r&&"EPERM"===r.code&&ki?Ti(e,t,r,n):u&&u.isDirectory()?Mi(e,t,r,n):void t.unlink(e,(r=>{if(r){if("ENOENT"===r.code)return n(null);if("EPERM"===r.code)return ki?Ti(e,t,r,n):Mi(e,t,r,n);if("EISDIR"===r.code)return Mi(e,t,r,n)}return n(r)}))))}function Ti(e,t,n,r){Pi(e),Pi(t),Pi("function"==typeof r),n&&Pi(n instanceof Error),t.chmod(e,438,(u=>{u?r("ENOENT"===u.code?null:n):t.stat(e,((u,o)=>{u?r("ENOENT"===u.code?null:n):o.isDirectory()?Mi(e,t,n,r):t.unlink(e,r)}))}))}function Ri(e,t,n){let r;Pi(e),Pi(t),n&&Pi(n instanceof Error);try{t.chmodSync(e,438)}catch(e){if("ENOENT"===e.code)return;throw n}try{r=t.statSync(e)}catch(e){if("ENOENT"===e.code)return;throw n}r.isDirectory()?ji(e,t,n):t.unlinkSync(e)}function Mi(e,t,n,r){Pi(e),Pi(t),n&&Pi(n instanceof Error),Pi("function"==typeof r),t.rmdir(e,(u=>{!u||"ENOTEMPTY"!==u.code&&"EEXIST"!==u.code&&"EPERM"!==u.code?u&&"ENOTDIR"===u.code?r(n):r(u):function(e,t,n){Pi(e),Pi(t),Pi("function"==typeof n),t.readdir(e,((r,u)=>{if(r)return n(r);let o,i=u.length;if(0===i)return t.rmdir(e,n);u.forEach((r=>{Ni(Bi.join(e,r),t,(r=>{if(!o)return r?n(o=r):void(0==--i&&t.rmdir(e,n))}))}))}))}(e,t,r)}))}function Li(e,t){let n;xi(t=t||{}),Pi(e,"rimraf: missing path"),Pi.strictEqual(typeof e,"string","rimraf: path should be a string"),Pi(t,"rimraf: missing options"),Pi.strictEqual(typeof t,"object","rimraf: options should be object");try{n=t.lstatSync(e)}catch(n){if("ENOENT"===n.code)return;"EPERM"===n.code&&ki&&Ri(e,t,n)}try{n&&n.isDirectory()?ji(e,t,null):t.unlinkSync(e)}catch(n){if("ENOENT"===n.code)return;if("EPERM"===n.code)return ki?Ri(e,t,n):ji(e,t,n);if("EISDIR"!==n.code)throw n;ji(e,t,n)}}function ji(e,t,n){Pi(e),Pi(t),n&&Pi(n instanceof Error);try{t.rmdirSync(e)}catch(r){if("ENOTDIR"===r.code)throw n;if("ENOTEMPTY"===r.code||"EEXIST"===r.code||"EPERM"===r.code)!function(e,t){if(Pi(e),Pi(t),t.readdirSync(e).forEach((n=>Li(Bi.join(e,n),t))),!ki){return t.rmdirSync(e,t)}{const n=Date.now();do{try{return t.rmdirSync(e,t)}catch(e){}}while(Date.now()-n<500)}}(e,t);else if("ENOENT"!==r.code)throw r}}var $i=Ni;Ni.sync=Li;const Hi=$i;var Ji={remove:(0,yo.fromCallback)(Hi),removeSync:Hi.sync};const Gi=yo.fromCallback,Vi=we,Ui=p.default,Wi=Io,zi=Ji,Ki=Gi((function(e,t){t=t||function(){},Vi.readdir(e,((n,r)=>{if(n)return Wi.mkdirs(e,t);r=r.map((t=>Ui.join(e,t))),function e(){const n=r.pop();if(!n)return t();zi.remove(n,(n=>{if(n)return t(n);e()}))}()}))}));function qi(e){let t;try{t=Vi.readdirSync(e)}catch(t){return Wi.mkdirsSync(e)}t.forEach((t=>{t=Ui.join(e,t),zi.removeSync(t)}))}var Yi={emptyDirSync:qi,emptydirSync:qi,emptyDir:Ki,emptydir:Ki};const Xi=yo.fromCallback,Zi=p.default,Qi=we,es=Io,ts=fi.pathExists;var ns={createFile:Xi((function(e,t){function n(){Qi.writeFile(e,"",(e=>{if(e)return t(e);t()}))}Qi.stat(e,((r,u)=>{if(!r&&u.isFile())return t();const o=Zi.dirname(e);ts(o,((e,r)=>e?t(e):r?n():void es.mkdirs(o,(e=>{if(e)return t(e);n()}))))}))})),createFileSync:function(e){let t;try{t=Qi.statSync(e)}catch(e){}if(t&&t.isFile())return;const n=Zi.dirname(e);Qi.existsSync(n)||es.mkdirsSync(n),Qi.writeFileSync(e,"")}};const rs=yo.fromCallback,us=p.default,os=we,is=Io,ss=fi.pathExists;var cs={createLink:rs((function(e,t,n){function r(e,t){os.link(e,t,(e=>{if(e)return n(e);n(null)}))}ss(t,((u,o)=>u?n(u):o?n(null):void os.lstat(e,(u=>{if(u)return u.message=u.message.replace("lstat","ensureLink"),n(u);const o=us.dirname(t);ss(o,((u,i)=>u?n(u):i?r(e,t):void is.mkdirs(o,(u=>{if(u)return n(u);r(e,t)}))))}))))})),createLinkSync:function(e,t){if(os.existsSync(t))return;try{os.lstatSync(e)}catch(e){throw e.message=e.message.replace("lstat","ensureLink"),e}const n=us.dirname(t);return os.existsSync(n)||is.mkdirsSync(n),os.linkSync(e,t)}};const as=p.default,ls=we,fs=fi.pathExists;var ds={symlinkPaths:function(e,t,n){if(as.isAbsolute(e))return ls.lstat(e,(t=>t?(t.message=t.message.replace("lstat","ensureSymlink"),n(t)):n(null,{toCwd:e,toDst:e})));{const r=as.dirname(t),u=as.join(r,e);return fs(u,((t,o)=>t?n(t):o?n(null,{toCwd:u,toDst:e}):ls.lstat(e,(t=>t?(t.message=t.message.replace("lstat","ensureSymlink"),n(t)):n(null,{toCwd:e,toDst:as.relative(r,e)})))))}},symlinkPathsSync:function(e,t){let n;if(as.isAbsolute(e)){if(n=ls.existsSync(e),!n)throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}{const r=as.dirname(t),u=as.join(r,e);if(n=ls.existsSync(u),n)return{toCwd:u,toDst:e};if(n=ls.existsSync(e),!n)throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:as.relative(r,e)}}}};const Ds=we;var ps={symlinkType:function(e,t,n){if(n="function"==typeof t?t:n,t="function"!=typeof t&&t)return n(null,t);Ds.lstat(e,((e,r)=>{if(e)return n(null,"file");t=r&&r.isDirectory()?"dir":"file",n(null,t)}))},symlinkTypeSync:function(e,t){let n;if(t)return t;try{n=Ds.lstatSync(e)}catch(e){return"file"}return n&&n.isDirectory()?"dir":"file"}};const Es=yo.fromCallback,ms=p.default,hs=we,ys=Io.mkdirs,Cs=Io.mkdirsSync,Fs=ds.symlinkPaths,gs=ds.symlinkPathsSync,As=ps.symlinkType,vs=ps.symlinkTypeSync,Ss=fi.pathExists;var ws={createSymlink:Es((function(e,t,n,r){r="function"==typeof n?n:r,n="function"!=typeof n&&n,Ss(t,((u,o)=>u?r(u):o?r(null):void Fs(e,t,((u,o)=>{if(u)return r(u);e=o.toDst,As(o.toCwd,n,((n,u)=>{if(n)return r(n);const o=ms.dirname(t);Ss(o,((n,i)=>n?r(n):i?hs.symlink(e,t,u,r):void ys(o,(n=>{if(n)return r(n);hs.symlink(e,t,u,r)}))))}))}))))})),createSymlinkSync:function(e,t,n){if(hs.existsSync(t))return;const r=gs(e,t);e=r.toDst,n=vs(r.toCwd,n);const u=ms.dirname(t);return hs.existsSync(u)||Cs(u),hs.symlinkSync(e,t,n)}};var Os,bs={createFile:ns.createFile,createFileSync:ns.createFileSync,ensureFile:ns.createFile,ensureFileSync:ns.createFileSync,createLink:cs.createLink,createLinkSync:cs.createLinkSync,ensureLink:cs.createLink,ensureLinkSync:cs.createLinkSync,createSymlink:ws.createSymlink,createSymlinkSync:ws.createSymlinkSync,ensureSymlink:ws.createSymlink,ensureSymlinkSync:ws.createSymlinkSync};try{Os=we}catch(e){Os=D.default}function _s(e,t){var n,r="\n";return"object"==typeof t&&null!==t&&(t.spaces&&(n=t.spaces),t.EOL&&(r=t.EOL)),JSON.stringify(e,t?t.replacer:null,n).replace(/\n/g,r)+r}function Bs(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e=e.replace(/^\uFEFF/,"")}var Ps={readFile:function(e,t,n){null==n&&(n=t,t={}),"string"==typeof t&&(t={encoding:t});var r=(t=t||{}).fs||Os,u=!0;"throws"in t&&(u=t.throws),r.readFile(e,t,(function(r,o){if(r)return n(r);var i;o=Bs(o);try{i=JSON.parse(o,t?t.reviver:null)}catch(t){return u?(t.message=e+": "+t.message,n(t)):n(null,null)}n(null,i)}))},readFileSync:function(e,t){"string"==typeof(t=t||{})&&(t={encoding:t});var n=t.fs||Os,r=!0;"throws"in t&&(r=t.throws);try{var u=n.readFileSync(e,t);return u=Bs(u),JSON.parse(u,t.reviver)}catch(t){if(r)throw t.message=e+": "+t.message,t;return null}},writeFile:function(e,t,n,r){null==r&&(r=n,n={});var u=(n=n||{}).fs||Os,o="";try{o=_s(t,n)}catch(e){return void(r&&r(e,null))}u.writeFile(e,o,n,r)},writeFileSync:function(e,t,n){var r=(n=n||{}).fs||Os,u=_s(t,n);return r.writeFileSync(e,u,n)}},ks=Ps;const xs=yo.fromCallback,Ns=ks;var Is={readJson:xs(Ns.readFile),readJsonSync:Ns.readFileSync,writeJson:xs(Ns.writeFile),writeJsonSync:Ns.writeFileSync};const Ts=p.default,Rs=Io,Ms=fi.pathExists,Ls=Is;var js=function(e,t,n,r){"function"==typeof n&&(r=n,n={});const u=Ts.dirname(e);Ms(u,((o,i)=>o?r(o):i?Ls.writeJson(e,t,n,r):void Rs.mkdirs(u,(u=>{if(u)return r(u);Ls.writeJson(e,t,n,r)}))))};const $s=we,Hs=p.default,Js=Io,Gs=Is;var Vs=function(e,t,n){const r=Hs.dirname(e);$s.existsSync(r)||Js.mkdirsSync(r),Gs.writeJsonSync(e,t,n)};const Us=yo.fromCallback,Ws=Is;Ws.outputJson=Us(js),Ws.outputJsonSync=Vs,Ws.outputJSON=Ws.outputJson,Ws.outputJSONSync=Ws.outputJsonSync,Ws.writeJSON=Ws.writeJson,Ws.writeJSONSync=Ws.writeJsonSync,Ws.readJSON=Ws.readJson,Ws.readJSONSync=Ws.readJsonSync;var zs=Ws;const Ks=we,qs=p.default,Ys=ci.copySync,Xs=Ji.removeSync,Zs=Io.mkdirpSync,Qs=Zo;function ec(e,t,n){try{Ks.renameSync(e,t)}catch(r){if("EXDEV"!==r.code)throw r;return function(e,t,n){const r={overwrite:n,errorOnExist:!0};return Ys(e,t,r),Xs(e)}(e,t,n)}}var tc=function(e,t,n){const r=(n=n||{}).overwrite||n.clobber||!1,{srcStat:u}=Qs.checkPathsSync(e,t,"move");return Qs.checkParentPathsSync(e,u,t,"move"),Zs(qs.dirname(t)),function(e,t,n){if(n)return Xs(t),ec(e,t,n);if(Ks.existsSync(t))throw new Error("dest already exists.");return ec(e,t,n)}(e,t,r)},nc={moveSync:tc};const rc=we,uc=p.default,oc=bi.copy,ic=Ji.remove,sc=Io.mkdirp,cc=fi.pathExists,ac=Zo;function lc(e,t,n,r){rc.rename(e,t,(u=>u?"EXDEV"!==u.code?r(u):function(e,t,n,r){const u={overwrite:n,errorOnExist:!0};oc(e,t,u,(t=>t?r(t):ic(e,r)))}(e,t,n,r):r()))}var fc=function(e,t,n,r){"function"==typeof n&&(r=n,n={});const u=n.overwrite||n.clobber||!1;ac.checkPaths(e,t,"move",((n,o)=>{if(n)return r(n);const{srcStat:i}=o;ac.checkParentPaths(e,i,t,"move",(n=>{if(n)return r(n);sc(uc.dirname(t),(n=>n?r(n):function(e,t,n,r){if(n)return ic(t,(u=>u?r(u):lc(e,t,n,r)));cc(t,((u,o)=>u?r(u):o?r(new Error("dest already exists.")):lc(e,t,n,r)))}(e,t,u,r)))}))}))};var dc={move:(0,yo.fromCallback)(fc)};const Dc=yo.fromCallback,pc=we,Ec=p.default,mc=Io,hc=fi.pathExists;var yc={outputFile:Dc((function(e,t,n,r){"function"==typeof n&&(r=n,n="utf8");const u=Ec.dirname(e);hc(u,((o,i)=>o?r(o):i?pc.writeFile(e,t,n,r):void mc.mkdirs(u,(u=>{if(u)return r(u);pc.writeFile(e,t,n,r)}))))})),outputFileSync:function(e,...t){const n=Ec.dirname(e);if(pc.existsSync(n))return pc.writeFileSync(e,...t);mc.mkdirsSync(n),pc.writeFileSync(e,...t)}};!function(e){e.exports=Object.assign({},ho,ci,bi,Yi,bs,zs,Io,nc,dc,yc,fi,Ji);const t=D.default;Object.getOwnPropertyDescriptor(t,"promises")&&Object.defineProperty(e.exports,"promises",{get:()=>t.promises})}(mo);const Cc=Nr.exports("streamroller:fileNameFormatter"),Fc=p.default;const gc=Nr.exports("streamroller:fileNameParser"),Ac=nu.exports;const vc=Nr.exports("streamroller:moveAndMaybeCompressFile"),Sc=mo.exports,wc=v.default;var Oc=async(e,t,n)=>{if(n=function(e){const t={mode:parseInt("0600",8),compress:!1},n=Object.assign({},t,e);return vc(`_parseOption: moveAndMaybeCompressFile called with option=${JSON.stringify(n)}`),n}(n),e!==t){if(await Sc.pathExists(e))if(vc(`moveAndMaybeCompressFile: moving file from ${e} to ${t} ${n.compress?"with":"without"} compress`),n.compress)await new Promise(((r,u)=>{let o=!1;const i=Sc.createWriteStream(t,{mode:n.mode,flags:"wx"}).on("open",(()=>{o=!0;const t=Sc.createReadStream(e).on("open",(()=>{t.pipe(wc.createGzip()).pipe(i)})).on("error",(t=>{vc(`moveAndMaybeCompressFile: error reading ${e}`,t),i.destroy(t)}))})).on("finish",(()=>{vc(`moveAndMaybeCompressFile: finished compressing ${t}, deleting ${e}`),Sc.unlink(e).then(r).catch((t=>{vc(`moveAndMaybeCompressFile: error deleting ${e}, truncating instead`,t),Sc.truncate(e).then(r).catch((t=>{vc(`moveAndMaybeCompressFile: error truncating ${e}`,t),u(t)}))}))})).on("error",(e=>{o?(vc(`moveAndMaybeCompressFile: error writing ${t}, deleting`,e),Sc.unlink(t).then((()=>{u(e)})).catch((e=>{vc(`moveAndMaybeCompressFile: error deleting ${t}`,e),u(e)}))):(vc(`moveAndMaybeCompressFile: error creating ${t}`,e),u(e))}))})).catch((()=>{}));else{vc(`moveAndMaybeCompressFile: renaming ${e} to ${t}`);try{await Sc.move(e,t,{overwrite:!0})}catch(n){if(vc(`moveAndMaybeCompressFile: error renaming ${e} to ${t}`,n),"ENOENT"!==n.code){vc("moveAndMaybeCompressFile: trying copy+truncate instead");try{await Sc.copy(e,t,{overwrite:!0}),await Sc.truncate(e)}catch(e){vc("moveAndMaybeCompressFile: error copy+truncate",e)}}}}}else vc("moveAndMaybeCompressFile: source and target are the same, not doing anything")};const bc=Nr.exports("streamroller:RollingFileWriteStream"),_c=mo.exports,Bc=p.default,Pc=E.default,kc=()=>new Date,xc=nu.exports,{Writable:Nc}=C.default,Ic=({file:e,keepFileExt:t,needsIndex:n,alwaysIncludeDate:r,compress:u,fileNameSep:o})=>{let i=o||".";const s=Fc.join(e.dir,e.name),c=t=>t+e.ext,a=(e,t,r)=>!n&&r||!t?e:e+i+t,l=(e,t,n)=>(t>0||r)&&n?e+i+n:e,f=(e,t)=>t&&u?e+".gz":e,d=t?[l,a,c,f]:[c,l,a,f];return({date:e,index:t})=>(Cc(`_formatFileName: date=${e}, index=${t}`),d.reduce(((n,r)=>r(n,t,e)),s))},Tc=({file:e,keepFileExt:t,pattern:n,fileNameSep:r})=>{let u=r||".";const o="__NOT_MATCHING__";let i=[(e,t)=>e.endsWith(".gz")?(gc("it is gzipped"),t.isCompressed=!0,e.slice(0,-1*".gz".length)):e,t?t=>t.startsWith(e.name)&&t.endsWith(e.ext)?(gc("it starts and ends with the right things"),t.slice(e.name.length+1,-1*e.ext.length)):o:t=>t.startsWith(e.base)?(gc("it starts with the right things"),t.slice(e.base.length+1)):o,n?(e,t)=>{const r=e.split(u);let o=r[r.length-1];gc("items: ",r,", indexStr: ",o);let i=e;void 0!==o&&o.match(/^\d+$/)?(i=e.slice(0,-1*(o.length+1)),gc(`dateStr is ${i}`),n&&!i&&(i=o,o="0")):o="0";try{const r=Ac.parse(n,i,new Date(0,0));return Ac.asString(n,r)!==i?e:(t.index=parseInt(o,10),t.date=i,t.timestamp=r.getTime(),"")}catch(t){return gc(`Problem parsing ${i} as ${n}, error was: `,t),e}}:(e,t)=>e.match(/^\d+$/)?(gc("it has an index"),t.index=parseInt(e,10),""):e];return e=>{let t={filename:e,index:0,isCompressed:!1};return i.reduce(((e,n)=>n(e,t)),e)?null:t}},Rc=Oc;var Mc=class extends Nc{constructor(e,t){if(bc(`constructor: creating RollingFileWriteStream. path=${e}`),"string"!=typeof e||0===e.length)throw new Error(`Invalid filename: ${e}`);if(e.endsWith(Bc.sep))throw new Error(`Filename is a directory: ${e}`);0===e.indexOf(`~${Bc.sep}`)&&(e=e.replace("~",Pc.homedir())),super(t),this.options=this._parseOption(t),this.fileObject=Bc.parse(e),""===this.fileObject.dir&&(this.fileObject=Bc.parse(Bc.join(process.cwd(),e))),this.fileFormatter=Ic({file:this.fileObject,alwaysIncludeDate:this.options.alwaysIncludePattern,needsIndex:this.options.maxSize 0`)}else delete n.maxSize;if(n.numBackups||0===n.numBackups){if(n.numBackups<0)throw new Error(`options.numBackups (${n.numBackups}) should be >= 0`);if(n.numBackups>=Number.MAX_SAFE_INTEGER)throw new Error(`options.numBackups (${n.numBackups}) should be < Number.MAX_SAFE_INTEGER`);n.numToKeep=n.numBackups+1}else if(n.numToKeep<=0)throw new Error(`options.numToKeep (${n.numToKeep}) should be > 0`);return bc(`_parseOption: creating stream with option=${JSON.stringify(n)}`),n}_final(e){this.currentFileStream.end("",this.options.encoding,e)}_write(e,t,n){this._shouldRoll().then((()=>{bc(`_write: writing chunk. file=${this.currentFileStream.path} state=${JSON.stringify(this.state)} chunk=${e}`),this.currentFileStream.write(e,t,(t=>{this.state.currentSize+=e.length,n(t)}))}))}async _shouldRoll(){(this._dateChanged()||this._tooBig())&&(bc(`_shouldRoll: rolling because dateChanged? ${this._dateChanged()} or tooBig? ${this._tooBig()}`),await this._roll())}_dateChanged(){return this.state.currentDate&&this.state.currentDate!==xc(this.options.pattern,kc())}_tooBig(){return this.state.currentSize>=this.options.maxSize}_roll(){return bc("_roll: closing the current stream"),new Promise(((e,t)=>{this.currentFileStream.end("",this.options.encoding,(()=>{this._moveOldFiles().then(e).catch(t)}))}))}async _moveOldFiles(){const e=await this._getExistingFiles();for(let t=(this.state.currentDate?e.filter((e=>e.date===this.state.currentDate)):e).length;t>=0;t--){bc(`_moveOldFiles: i = ${t}`);const e=this.fileFormatter({date:this.state.currentDate,index:t}),n=this.fileFormatter({date:this.state.currentDate,index:t+1}),r={compress:this.options.compress&&0===t,mode:this.options.mode};await Rc(e,n,r)}this.state.currentSize=0,this.state.currentDate=this.state.currentDate?xc(this.options.pattern,kc()):null,bc(`_moveOldFiles: finished rolling files. state=${JSON.stringify(this.state)}`),this._renewWriteStream(),await new Promise(((e,t)=>{this.currentFileStream.write("","utf8",(()=>{this._clean().then(e).catch(t)}))}))}async _getExistingFiles(){const e=await _c.readdir(this.fileObject.dir).catch((()=>[]));bc(`_getExistingFiles: files=${e}`);const t=e.map((e=>this.fileNameParser(e))).filter((e=>e)),n=e=>(e.timestamp?e.timestamp:kc().getTime())-e.index;return t.sort(((e,t)=>n(e)-n(t))),t}_renewWriteStream(){const e=this.fileFormatter({date:this.state.currentDate,index:0}),t=e=>{try{return _c.mkdirSync(e,{recursive:!0})}catch(n){if("ENOENT"===n.code)return t(Bc.dirname(e)),t(e);if("EEXIST"!==n.code&&"EROFS"!==n.code)throw n;try{if(_c.statSync(e).isDirectory())return e;throw n}catch(e){throw n}}};t(this.fileObject.dir);const n={flags:this.options.flags,encoding:this.options.encoding,mode:this.options.mode};var r,u;_c.appendFileSync(e,"",(r={...n},u="flags",r["flag"]=r[u],delete r[u],r)),this.currentFileStream=_c.createWriteStream(e,n),this.currentFileStream.on("error",(e=>{this.emit("error",e)}))}async _clean(){const e=await this._getExistingFiles();if(bc(`_clean: numToKeep = ${this.options.numToKeep}, existingFiles = ${e.length}`),bc("_clean: existing files are: ",e),this._tooManyFiles(e.length)){const n=e.slice(0,e.length-this.options.numToKeep).map((e=>Bc.format({dir:this.fileObject.dir,base:e.filename})));await(t=n,bc(`deleteFiles: files to delete: ${t}`),Promise.all(t.map((e=>_c.unlink(e).catch((t=>{bc(`deleteFiles: error when unlinking ${e}, ignoring. Error was ${t}`)}))))))}var t}_tooManyFiles(e){return this.options.numToKeep>0&&e>this.options.numToKeep}};const Lc=Mc;var jc=class extends Lc{constructor(e,t,n,r){r||(r={}),t&&(r.maxSize=t),r.numBackups||0===r.numBackups||(n||0===n||(n=1),r.numBackups=n),super(e,r),this.backups=r.numBackups,this.size=this.options.maxSize}get theStream(){return this.currentFileStream}};const $c=Mc;var Hc={RollingFileWriteStream:Mc,RollingFileStream:jc,DateRollingFileStream:class extends $c{constructor(e,t,n){t&&"object"==typeof t&&(n=t,t=null),n||(n={}),t||(t="yyyy-MM-dd"),n.pattern=t,n.numBackups||0===n.numBackups?n.daysToKeep=n.numBackups:(n.daysToKeep||0===n.daysToKeep?process.emitWarning("options.daysToKeep is deprecated due to the confusion it causes when used together with file size rolling. Please use options.numBackups instead.","DeprecationWarning","streamroller-DEP0001"):n.daysToKeep=1,n.numBackups=n.daysToKeep),super(e,n),this.mode=this.options.mode}get theStream(){return this.currentFileStream}}};const Jc=Nr.exports("log4js:file"),Gc=p.default,Vc=Hc,Uc=E.default.EOL;let Wc=!1;const zc=new Set;function Kc(){zc.forEach((e=>{e.sighupHandler()}))}function qc(e,t,n,r){const u=new Vc.RollingFileStream(e,t,n,r);return u.on("error",(t=>{console.error("log4js.fileAppender - Writing to file %s, error happened ",e,t)})),u.on("drain",(()=>{process.emit("log4js:pause",!1)})),u}Eo.configure=function(e,t){let n=t.basicLayout;return e.layout&&(n=t.layout(e.layout.type,e.layout)),e.mode=e.mode||384,function(e,t,n,r,u,o){e=Gc.normalize(e),Jc("Creating file appender (",e,", ",n,", ",r=r||0===r?r:5,", ",u,", ",o,")");let i=qc(e,n,r,u);const s=function(e){if(i.writable){if(!0===u.removeColor){const t=/\x1b[[0-9;]*m/g;e.data=e.data.map((e=>"string"==typeof e?e.replace(t,""):e))}i.write(t(e,o)+Uc,"utf8")||process.emit("log4js:pause",!0)}};return s.reopen=function(){i.end((()=>{i=qc(e,n,r,u)}))},s.sighupHandler=function(){Jc("SIGHUP handler called."),s.reopen()},s.shutdown=function(e){zc.delete(s),0===zc.size&&Wc&&(process.removeListener("SIGHUP",Kc),Wc=!1),i.end("","utf-8",e)},zc.add(s),Wc||(process.on("SIGHUP",Kc),Wc=!0),s}(e.filename,n,e.maxLogSize,e.backups,e,e.timezoneOffset)};var Yc={};const Xc=Hc,Zc=E.default.EOL;function Qc(e,t,n,r,u){r.maxSize=r.maxLogSize;const o=function(e,t,n){const r=new Xc.DateRollingFileStream(e,t,n);return r.on("error",(t=>{console.error("log4js.dateFileAppender - Writing to file %s, error happened ",e,t)})),r.on("drain",(()=>{process.emit("log4js:pause",!1)})),r}(e,t,r),i=function(e){o.writable&&(o.write(n(e,u)+Zc,"utf8")||process.emit("log4js:pause",!0))};return i.shutdown=function(e){o.end("","utf-8",e)},i}Yc.configure=function(e,t){let n=t.basicLayout;return e.layout&&(n=t.layout(e.layout.type,e.layout)),e.alwaysIncludePattern||(e.alwaysIncludePattern=!1),e.mode=e.mode||384,Qc(e.filename,e.pattern,n,e,e.timezoneOffset)};var ea={};const ta=Nr.exports("log4js:fileSync"),na=p.default,ra=D.default,ua=E.default.EOL||"\n";function oa(e,t){if(ra.existsSync(e))return;const n=ra.openSync(e,t.flags,t.mode);ra.closeSync(n)}class ia{constructor(e,t,n,r){ta("In RollingFileStream"),function(){if(!e||!t||t<=0)throw new Error("You must specify a filename and file size")}(),this.filename=e,this.size=t,this.backups=n,this.options=r,this.currentSize=0,this.currentSize=function(e){let t=0;try{t=ra.statSync(e).size}catch(t){oa(e,r)}return t}(this.filename)}shouldRoll(){return ta("should roll with current size %d, and max size %d",this.currentSize,this.size),this.currentSize>=this.size}roll(e){const t=this,n=new RegExp(`^${na.basename(e)}`);function r(e){return n.test(e)}function u(t){return parseInt(t.substring(`${na.basename(e)}.`.length),10)||0}function o(e,t){return u(e)>u(t)?1:u(e) ${e}.${r+1}`),ra.renameSync(na.join(na.dirname(e),n),`${e}.${r+1}`)}}ta("Rolling, rolling, rolling"),ta("Renaming the old files"),ra.readdirSync(na.dirname(e)).filter(r).sort(o).reverse().forEach(i)}write(e,t){const n=this;ta("in write"),this.shouldRoll()&&(this.currentSize=0,this.roll(this.filename)),ta("writing the chunk to the file"),n.currentSize+=e.length,ra.appendFileSync(n.filename,e)}}ea.configure=function(e,t){let n=t.basicLayout;e.layout&&(n=t.layout(e.layout.type,e.layout));const r={flags:e.flags||"a",encoding:e.encoding||"utf8",mode:e.mode||384};return function(e,t,n,r,u,o){ta("fileSync appender created");const i=function(e,t,n){let r;var u;return t?r=new ia(e,t,n,o):(oa(u=e,o),r={write(e){ra.appendFileSync(u,e)}}),r}(e=na.normalize(e),n,r=r||0===r?r:5);return e=>{i.write(t(e,u)+ua)}}(e.filename,n,e.maxLogSize,e.backups,e.timezoneOffset,r)};var sa={};const ca=Nr.exports("log4js:tcp"),aa=S.default;sa.configure=function(e,t){ca(`configure with config = ${e}`);let n=function(e){return e.serialise()};return e.layout&&(n=t.layout(e.layout.type,e.layout)),function(e,t){let n=!1;const r=[];let u,o=3,i="__LOG4JS__";function s(e){ca("Writing log event to socket"),n=u.write(`${t(e)}${i}`,"utf8")}function c(){let e;for(ca("emptying buffer");e=r.shift();)s(e)}function a(e){n?s(e):(ca("buffering log event because it cannot write at the moment"),r.push(e))}return function t(){ca(`appender creating socket to ${e.host||"localhost"}:${e.port||5e3}`),i=`${e.endMsg||"__LOG4JS__"}`,u=aa.createConnection(e.port||5e3,e.host||"localhost"),u.on("connect",(()=>{ca("socket connected"),c(),n=!0})),u.on("drain",(()=>{ca("drain event received, emptying buffer"),n=!0,c()})),u.on("timeout",u.end.bind(u)),u.on("error",(e=>{ca("connection error",e),n=!1,c()})),u.on("close",t)}(),a.shutdown=function(e){ca("shutdown called"),r.length&&o?(ca("buffer has items, waiting 100ms to empty"),o-=1,setTimeout((()=>{a.shutdown(e)}),100)):(u.removeAllListeners("close"),u.end(e))},a}(e,n)};const la=p.default,fa=Nr.exports("log4js:appenders"),da=tu,Da=eo,pa=gu,Ea=hu,ma=to,ha=new Map;ha.set("console",oo),ha.set("stdout",so),ha.set("stderr",co),ha.set("logLevelFilter",ao),ha.set("categoryFilter",lo),ha.set("noLogFilter",Do),ha.set("file",Eo),ha.set("dateFile",Yc),ha.set("fileSync",ea),ha.set("tcp",sa);const ya=new Map,Ca=(e,t)=>{fa("Loading module from ",e);try{return require(e)}catch(n){return void da.throwExceptionIf(t,"MODULE_NOT_FOUND"!==n.code,`appender "${e}" could not be loaded (error was: ${n})`)}},Fa=new Set,ga=(e,t)=>{if(ya.has(e))return ya.get(e);if(!t.appenders[e])return!1;if(Fa.has(e))throw new Error(`Dependency loop detected for appender ${e}.`);Fa.add(e),fa(`Creating appender ${e}`);const n=Aa(e,t);return Fa.delete(e),ya.set(e,n),n},Aa=(e,t)=>{const n=t.appenders[e],r=n.type.configure?n.type:((e,t)=>ha.get(e)||Ca(`./${e}`,t)||Ca(e,t)||require.main&&Ca(la.join(la.dirname(require.main.filename),e),t)||Ca(la.join(process.cwd(),e),t))(n.type,t);return da.throwExceptionIf(t,da.not(r),`appender "${e}" is not valid (type "${n.type}" could not be found)`),r.appender&&fa(`DEPRECATION: Appender ${n.type} exports an appender function.`),r.shutdown&&fa(`DEPRECATION: Appender ${n.type} exports a shutdown function.`),fa(`${e}: clustering.isMaster ? ${Da.isMaster()}`),fa(`${e}: appenderModule is ${F.default.inspect(r)}`),Da.onlyOnMaster((()=>(fa(`calling appenderModule.configure for ${e} / ${n.type}`),r.configure(ma.modifyConfig(n),Ea,(e=>ga(e,t)),pa))),(()=>{}))},va=e=>{ya.clear(),Fa.clear();const t=[];Object.values(e.categories).forEach((e=>{t.push(...e.appenders)})),Object.keys(e.appenders).forEach((n=>{(t.includes(n)||"tcp-server"===e.appenders[n].type)&&ga(n,e)}))},Sa=()=>{va({appenders:{out:{type:"stdout"}},categories:{default:{appenders:["out"],level:"trace"}}})};Sa(),da.addListener((e=>{da.throwExceptionIf(e,da.not(da.anObject(e.appenders)),'must have a property "appenders" of type object.');const t=Object.keys(e.appenders);da.throwExceptionIf(e,da.not(t.length),"must define at least one appender."),t.forEach((t=>{da.throwExceptionIf(e,da.not(e.appenders[t].type),`appender "${t}" is not valid (must be an object with property "type")`)}))})),da.addListener(va),Au.exports=ya,Au.exports.init=Sa;var wa={exports:{}};!function(e){const t=Nr.exports("log4js:categories"),n=tu,r=gu,u=Au.exports,o=new Map;function i(e,t,n){if(!1===t.inherit)return;const r=n.lastIndexOf(".");if(r<0)return;const u=n.substring(0,r);let o=e.categories[u];o||(o={inherit:!0,appenders:[]}),i(e,o,u),!e.categories[u]&&o.appenders&&o.appenders.length&&o.level&&(e.categories[u]=o),t.appenders=t.appenders||[],t.level=t.level||o.level,o.appenders.forEach((e=>{t.appenders.includes(e)||t.appenders.push(e)})),t.parent=o}function s(e){if(!e.categories)return;Object.keys(e.categories).forEach((t=>{const n=e.categories[t];i(e,n,t)}))}n.addPreProcessingListener((e=>s(e))),n.addListener((e=>{n.throwExceptionIf(e,n.not(n.anObject(e.categories)),'must have a property "categories" of type object.');const t=Object.keys(e.categories);n.throwExceptionIf(e,n.not(t.length),"must define at least one category."),t.forEach((t=>{const o=e.categories[t];n.throwExceptionIf(e,[n.not(o.appenders),n.not(o.level)],`category "${t}" is not valid (must be an object with properties "appenders" and "level")`),n.throwExceptionIf(e,n.not(Array.isArray(o.appenders)),`category "${t}" is not valid (appenders must be an array of appender names)`),n.throwExceptionIf(e,n.not(o.appenders.length),`category "${t}" is not valid (appenders must contain at least one appender name)`),Object.prototype.hasOwnProperty.call(o,"enableCallStack")&&n.throwExceptionIf(e,"boolean"!=typeof o.enableCallStack,`category "${t}" is not valid (enableCallStack must be boolean type)`),o.appenders.forEach((r=>{n.throwExceptionIf(e,n.not(u.get(r)),`category "${t}" is not valid (appender "${r}" is not defined)`)})),n.throwExceptionIf(e,n.not(r.getLevel(o.level)),`category "${t}" is not valid (level "${o.level}" not recognised; valid levels are ${r.levels.join(", ")})`)})),n.throwExceptionIf(e,n.not(e.categories.default),'must define a "default" category.')}));const c=e=>{o.clear();Object.keys(e.categories).forEach((n=>{const i=e.categories[n],s=[];i.appenders.forEach((e=>{s.push(u.get(e)),t(`Creating category ${n}`),o.set(n,{appenders:s,level:r.getLevel(i.level),enableCallStack:i.enableCallStack||!1})}))}))},a=()=>{c({categories:{default:{appenders:["out"],level:"OFF"}}})};a(),n.addListener(c);const l=e=>(t(`configForCategory: searching for config for ${e}`),o.has(e)?(t(`configForCategory: ${e} exists in config, returning it`),o.get(e)):e.indexOf(".")>0?(t(`configForCategory: ${e} has hierarchy, searching for parents`),l(e.substring(0,e.lastIndexOf(".")))):(t("configForCategory: returning config for default category"),l("default")));e.exports=o,e.exports=Object.assign(e.exports,{appendersForCategory:e=>l(e).appenders,getLevelForCategory:e=>l(e).level,setLevelForCategory:(e,n)=>{let r=o.get(e);if(t(`setLevelForCategory: found ${r} for ${e}`),!r){const n=l(e);t(`setLevelForCategory: no config found for category, found ${n} for parents of ${e}`),r={appenders:n.appenders}}r.level=n,o.set(e,r)},getEnableCallStackForCategory:e=>!0===l(e).enableCallStack,setEnableCallStackForCategory:(e,t)=>{l(e).enableCallStack=t},init:a})}(wa);const Oa=Nr.exports("log4js:logger"),ba=Hu,_a=gu,Ba=eo,Pa=wa.exports,ka=tu,xa=/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/;function Na(e,t=4){const n=e.stack.split("\n").slice(t),r=xa.exec(n[0]);return r&&6===r.length?{functionName:r[1],fileName:r[2],lineNumber:parseInt(r[3],10),columnNumber:parseInt(r[4],10),callStack:n.join("\n")}:null}class Ia{constructor(e){if(!e)throw new Error("No category provided.");this.category=e,this.context={},this.parseCallStack=Na,Oa(`Logger created (${this.category}, ${this.level})`)}get level(){return _a.getLevel(Pa.getLevelForCategory(this.category),_a.TRACE)}set level(e){Pa.setLevelForCategory(this.category,_a.getLevel(e,this.level))}get useCallStack(){return Pa.getEnableCallStackForCategory(this.category)}set useCallStack(e){Pa.setEnableCallStackForCategory(this.category,!0===e)}log(e,...t){let n=_a.getLevel(e);n||(this._log(_a.WARN,"log4js:logger.log: invalid value for log-level as first parameter given: ",e),n=_a.INFO),this.isLevelEnabled(n)&&this._log(n,t)}isLevelEnabled(e){return this.level.isLessThanOrEqualTo(e)}_log(e,t){Oa(`sending log data (${e}) to appenders`);const n=new ba(this.category,e,t,this.context,this.useCallStack&&this.parseCallStack(new Error));Ba.send(n)}addContext(e,t){this.context[e]=t}removeContext(e){delete this.context[e]}clearContext(){this.context={}}setParseCallStackFunction(e){this.parseCallStack=e}}function Ta(e){const t=_a.getLevel(e),n=t.toString().toLowerCase().replace(/_([a-z])/g,(e=>e[1].toUpperCase())),r=n[0].toUpperCase()+n.slice(1);Ia.prototype[`is${r}Enabled`]=function(){return this.isLevelEnabled(t)},Ia.prototype[n]=function(...e){this.log(t,...e)}}_a.levels.forEach(Ta),ka.addListener((()=>{_a.levels.forEach(Ta)}));var Ra=Ia;const Ma=gu;function La(e){return e.originalUrl||e.url}function ja(e,t){for(let n=0;ne.source?e.source:e));t=new RegExp(n.join("|"))}return t}(t.nolog);return(e,i,s)=>{if(e._logging)return s();if(o&&o.test(e.originalUrl))return s();if(n.isLevelEnabled(r)||"auto"===t.level){const o=new Date,{writeHead:s}=i;e._logging=!0,i.writeHead=(e,t)=>{i.writeHead=s,i.writeHead(e,t),i.__statusCode=e,i.__headers=t||{}},i.on("finish",(()=>{i.responseTime=new Date-o,i.statusCode&&"auto"===t.level&&(r=Ma.INFO,i.statusCode>=300&&(r=Ma.WARN),i.statusCode>=400&&(r=Ma.ERROR)),r=function(e,t,n){let r=t;if(n){const t=n.find((t=>{let n=!1;return n=t.from&&t.to?e>=t.from&&e<=t.to:-1!==t.codes.indexOf(e),n}));t&&(r=Ma.getLevel(t.level,r))}return r}(i.statusCode,r,t.statusRules);const s=function(e,t,n){const r=[];return r.push({token:":url",replacement:La(e)}),r.push({token:":protocol",replacement:e.protocol}),r.push({token:":hostname",replacement:e.hostname}),r.push({token:":method",replacement:e.method}),r.push({token:":status",replacement:t.__statusCode||t.statusCode}),r.push({token:":response-time",replacement:t.responseTime}),r.push({token:":date",replacement:(new Date).toUTCString()}),r.push({token:":referrer",replacement:e.headers.referer||e.headers.referrer||""}),r.push({token:":http-version",replacement:`${e.httpVersionMajor}.${e.httpVersionMinor}`}),r.push({token:":remote-addr",replacement:e.headers["x-forwarded-for"]||e.ip||e._remoteAddress||e.socket&&(e.socket.remoteAddress||e.socket.socket&&e.socket.socket.remoteAddress)}),r.push({token:":user-agent",replacement:e.headers["user-agent"]}),r.push({token:":content-length",replacement:t.getHeader("content-length")||t.__headers&&t.__headers["Content-Length"]||"-"}),r.push({token:/:req\[([^\]]+)]/g,replacement:(t,n)=>e.headers[n.toLowerCase()]}),r.push({token:/:res\[([^\]]+)]/g,replacement:(e,n)=>t.getHeader(n.toLowerCase())||t.__headers&&t.__headers[n]}),(e=>{const t=e.concat();for(let e=0;eja(e,s)));t&&n.log(r,t)}else n.log(r,ja(u,s));t.context&&n.removeContext("res")}))}return s()}},nl=Va;let rl=!1;function ul(e){if(!rl)return;Ua("Received log event ",e);Za.appendersForCategory(e.categoryName).forEach((t=>{t(e)}))}function ol(e){rl&&il();let t=e;return"string"==typeof t&&(t=function(e){Ua(`Loading configuration from ${e}`);try{return JSON.parse(Wa.readFileSync(e,"utf8"))}catch(t){throw new Error(`Problem reading config from file "${e}". Error was ${t.message}`,t)}}(e)),Ua(`Configuration is ${t}`),Ka.configure(za(t)),el.onMessage(ul),rl=!0,sl}function il(e){Ua("Shutdown called. Disabling all log writing."),rl=!1;const t=Array.from(Xa.values());Xa.init(),Za.init();const n=t.reduceRight(((e,t)=>t.shutdown?e+1:e),0);if(0===n)return Ua("No appenders with shutdown functions found."),void 0!==e&&e();let r,u=0;function o(t){r=r||t,u+=1,Ua(`Appender shutdowns complete: ${u} / ${n}`),u>=n&&(Ua("All shutdown functions completed."),e&&e(r))}return Ua(`Found ${n} appenders with shutdown functions.`),t.filter((e=>e.shutdown)).forEach((e=>e.shutdown(o))),null}const sl={getLogger:function(e){return rl||ol(process.env.LOG4JS_CONFIG||{appenders:{out:{type:"stdout"}},categories:{default:{appenders:["out"],level:"OFF"}}}),new Qa(e||"default")},configure:ol,shutdown:il,connectLogger:tl,levels:Ya,addLayout:qa.addLayout,recording:function(){return nl}};var cl=sl,al={};Object.defineProperty(al,"__esModule",{value:!0}),al.levelMap=al.getLevel=al.setCategoriesLevel=al.getConfiguration=al.setConfiguration=void 0;const ll=cl;let fl={appenders:{debug:{type:"stdout",layout:{type:"pattern",pattern:"[%d] > hvigor %p %c %[%m%]"}},info:{type:"stdout",layout:{type:"pattern",pattern:"[%d] > hvigor %[%m%]"}},"no-pattern-info":{type:"stdout",layout:{type:"pattern",pattern:"%m"}},wrong:{type:"stderr",layout:{type:"pattern",pattern:"[%d] > hvigor %[%p: %m%]"}},"just-debug":{type:"logLevelFilter",appender:"debug",level:"debug",maxLevel:"debug"},"just-info":{type:"logLevelFilter",appender:"info",level:"info",maxLevel:"info"},"just-wrong":{type:"logLevelFilter",appender:"wrong",level:"warn",maxLevel:"error"}},categories:{default:{appenders:["just-debug","just-info","just-wrong"],level:"debug"},"no-pattern-info":{appenders:["no-pattern-info"],level:"info"}}};al.setConfiguration=e=>{fl=e};al.getConfiguration=()=>fl;let dl=ll.levels.DEBUG;al.setCategoriesLevel=(e,t)=>{dl=e;const n=fl.categories;for(const r in n)(null==t?void 0:t.includes(r))||Object.prototype.hasOwnProperty.call(n,r)&&(n[r].level=e.levelStr)};al.getLevel=()=>dl,al.levelMap=new Map([["ALL",ll.levels.ALL],["MARK",ll.levels.MARK],["TRACE",ll.levels.TRACE],["DEBUG",ll.levels.DEBUG],["INFO",ll.levels.INFO],["WARN",ll.levels.WARN],["ERROR",ll.levels.ERROR],["FATAL",ll.levels.FATAL],["OFF",ll.levels.OFF]]);var Dl=w&&w.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var u=Object.getOwnPropertyDescriptor(t,n);u&&!("get"in u?!t.__esModule:u.writable||u.configurable)||(u={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,u)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),pl=w&&w.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),El=w&&w.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&Dl(t,e,n);return pl(t,e),t};Object.defineProperty(xr,"__esModule",{value:!0}),xr.evaluateLogLevel=xr.HvigorLogger=void 0;const ml=El(cl),hl=cl,yl=El(F.default),Cl=al;class Fl{constructor(e){ml.configure((0,Cl.getConfiguration)()),this._logger=ml.getLogger(e),this._logger.level=(0,Cl.getLevel)()}static getLogger(e){return new Fl(e)}log(e,...t){this._logger.log(e,...t)}debug(e,...t){this._logger.debug(e,...t)}info(e,...t){this._logger.info(e,...t)}warn(e,...t){void 0!==e&&""!==e&&this._logger.warn(e,...t)}error(e,...t){this._logger.error(e,...t)}_printTaskExecuteInfo(e,t){this.info(`Finished :${e}... after ${t}`)}_printFailedTaskInfo(e){this.error(`Failed :${e}... `)}_printDisabledTaskInfo(e){this.info(`Disabled :${e}... `)}_printUpToDateTaskInfo(e){this.info(`UP-TO-DATE :${e}... `)}errorMessageExit(e,...t){throw new Error(yl.format(e,...t))}errorExit(e,t,...n){t&&this._logger.error(t,n),this._logger.error(e.stack)}setLevel(e,t){(0,Cl.setCategoriesLevel)(e,t),ml.shutdown(),ml.configure((0,Cl.getConfiguration)())}getLevel(){return this._logger.level}configure(e){const t=(0,Cl.getConfiguration)(),n={appenders:{...t.appenders,...e.appenders},categories:{...t.categories,...e.categories}};(0,Cl.setConfiguration)(n),ml.shutdown(),ml.configure(n)}}xr.HvigorLogger=Fl,xr.evaluateLogLevel=function(e,t){t.debug?e.setLevel(hl.levels.DEBUG):t.warn?e.setLevel(hl.levels.WARN):t.error?e.setLevel(hl.levels.ERROR):e.setLevel(hl.levels.INFO)};var gl=w&&w.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(X,"__esModule",{value:!0}),X.parseJsonText=X.parseJsonFile=void 0;const Al=Z,vl=gl(kr),Sl=gl(p.default),wl=gl(E.default),Ol=xr.HvigorLogger.getLogger("parse-json-util");var bl;!function(e){e[e.Char=0]="Char",e[e.EOF=1]="EOF",e[e.Identifier=2]="Identifier"}(bl||(bl={}));let _l,Bl,Pl,kl,xl,Nl,Il="start",Tl=[],Rl=0,Ml=1,Ll=0,jl=!1,$l="default",Hl="'",Jl=1;function Gl(e,t=!1){Bl=String(e),Il="start",Tl=[],Rl=0,Ml=1,Ll=0,kl=void 0,jl=t;do{_l=Vl(),Xl[Il]()}while("eof"!==_l.type);return kl}function Vl(){for($l="default",xl="",Hl="'",Jl=1;;){Nl=Ul();const e=zl[$l]();if(e)return e}}function Ul(){if(Bl[Rl])return String.fromCodePoint(Bl.codePointAt(Rl))}function Wl(){const e=Ul();return"\n"===e?(Ml++,Ll=0):e?Ll+=e.length:Ll++,e&&(Rl+=e.length),e}X.parseJsonFile=function(e,t=!1,n="utf-8"){const r=vl.default.readFileSync(Sl.default.resolve(e),{encoding:n});try{return Gl(r,t)}catch(t){if(t instanceof SyntaxError){const n=t.message.split("at");2===n.length&&Ol.errorMessageExit(`${n[0].trim()}${wl.default.EOL}\t at ${e}:${n[1].trim()}`)}Ol.errorMessageExit(`${e} is not in valid JSON/JSON5 format.`)}},X.parseJsonText=Gl;const zl={default(){switch(Nl){case"/":return Wl(),void($l="comment");case void 0:return Wl(),Kl("eof")}if(!Al.JudgeUtil.isIgnoreChar(Nl)&&!Al.JudgeUtil.isSpaceSeparator(Nl))return zl[Il]();Wl()},start(){$l="value"},beforePropertyName(){switch(Nl){case"$":case"_":return xl=Wl(),void($l="identifierName");case"\\":return Wl(),void($l="identifierNameStartEscape");case"}":return Kl("punctuator",Wl());case'"':case"'":return Hl=Nl,Wl(),void($l="string")}if(Al.JudgeUtil.isIdStartChar(Nl))return xl+=Wl(),void($l="identifierName");throw tf(bl.Char,Wl())},afterPropertyName(){if(":"===Nl)return Kl("punctuator",Wl());throw tf(bl.Char,Wl())},beforePropertyValue(){$l="value"},afterPropertyValue(){switch(Nl){case",":case"}":return Kl("punctuator",Wl())}throw tf(bl.Char,Wl())},beforeArrayValue(){if("]"===Nl)return Kl("punctuator",Wl());$l="value"},afterArrayValue(){switch(Nl){case",":case"]":return Kl("punctuator",Wl())}throw tf(bl.Char,Wl())},end(){throw tf(bl.Char,Wl())},comment(){switch(Nl){case"*":return Wl(),void($l="multiLineComment");case"/":return Wl(),void($l="singleLineComment")}throw tf(bl.Char,Wl())},multiLineComment(){switch(Nl){case"*":return Wl(),void($l="multiLineCommentAsterisk");case void 0:throw tf(bl.Char,Wl())}Wl()},multiLineCommentAsterisk(){switch(Nl){case"*":return void Wl();case"/":return Wl(),void($l="default");case void 0:throw tf(bl.Char,Wl())}Wl(),$l="multiLineComment"},singleLineComment(){switch(Nl){case"\n":case"\r":case"\u2028":case"\u2029":return Wl(),void($l="default");case void 0:return Wl(),Kl("eof")}Wl()},value(){switch(Nl){case"{":case"[":return Kl("punctuator",Wl());case"n":return Wl(),ql("ull"),Kl("null",null);case"t":return Wl(),ql("rue"),Kl("boolean",!0);case"f":return Wl(),ql("alse"),Kl("boolean",!1);case"-":case"+":return"-"===Wl()&&(Jl=-1),void($l="numerical");case".":case"0":case"I":case"N":return void($l="numerical");case'"':case"'":return Hl=Nl,Wl(),xl="",void($l="string")}if(void 0===Nl||!Al.JudgeUtil.isDigitWithoutZero(Nl))throw tf(bl.Char,Wl());$l="numerical"},numerical(){switch(Nl){case".":return xl=Wl(),void($l="decimalPointLeading");case"0":return xl=Wl(),void($l="zero");case"I":return Wl(),ql("nfinity"),Kl("numeric",Jl*(1/0));case"N":return Wl(),ql("aN"),Kl("numeric",NaN)}if(void 0!==Nl&&Al.JudgeUtil.isDigitWithoutZero(Nl))return xl=Wl(),void($l="decimalInteger");throw tf(bl.Char,Wl())},zero(){switch(Nl){case".":case"e":case"E":return void($l="decimal");case"x":case"X":return xl+=Wl(),void($l="hexadecimal")}return Kl("numeric",0)},decimalInteger(){switch(Nl){case".":case"e":case"E":return void($l="decimal")}if(!Al.JudgeUtil.isDigit(Nl))return Kl("numeric",Jl*Number(xl));xl+=Wl()},decimal(){switch(Nl){case".":xl+=Wl(),$l="decimalFraction";break;case"e":case"E":xl+=Wl(),$l="decimalExponent"}},decimalPointLeading(){if(Al.JudgeUtil.isDigit(Nl))return xl+=Wl(),void($l="decimalFraction");throw tf(bl.Char,Wl())},decimalFraction(){switch(Nl){case"e":case"E":return xl+=Wl(),void($l="decimalExponent")}if(!Al.JudgeUtil.isDigit(Nl))return Kl("numeric",Jl*Number(xl));xl+=Wl()},decimalExponent(){switch(Nl){case"+":case"-":return xl+=Wl(),void($l="decimalExponentSign")}if(Al.JudgeUtil.isDigit(Nl))return xl+=Wl(),void($l="decimalExponentInteger");throw tf(bl.Char,Wl())},decimalExponentSign(){if(Al.JudgeUtil.isDigit(Nl))return xl+=Wl(),void($l="decimalExponentInteger");throw tf(bl.Char,Wl())},decimalExponentInteger(){if(!Al.JudgeUtil.isDigit(Nl))return Kl("numeric",Jl*Number(xl));xl+=Wl()},hexadecimal(){if(Al.JudgeUtil.isHexDigit(Nl))return xl+=Wl(),void($l="hexadecimalInteger");throw tf(bl.Char,Wl())},hexadecimalInteger(){if(!Al.JudgeUtil.isHexDigit(Nl))return Kl("numeric",Jl*Number(xl));xl+=Wl()},identifierNameStartEscape(){if("u"!==Nl)throw tf(bl.Char,Wl());Wl();const e=Yl();switch(e){case"$":case"_":break;default:if(!Al.JudgeUtil.isIdStartChar(e))throw tf(bl.Identifier)}xl+=e,$l="identifierName"},identifierName(){switch(Nl){case"$":case"_":case"‌":case"‍":return void(xl+=Wl());case"\\":return Wl(),void($l="identifierNameEscape")}if(!Al.JudgeUtil.isIdContinueChar(Nl))return Kl("identifier",xl);xl+=Wl()},identifierNameEscape(){if("u"!==Nl)throw tf(bl.Char,Wl());Wl();const e=Yl();switch(e){case"$":case"_":case"‌":case"‍":break;default:if(!Al.JudgeUtil.isIdContinueChar(e))throw tf(bl.Identifier)}xl+=e,$l="identifierName"},string(){switch(Nl){case"\\":return Wl(),void(xl+=function(){const e=Ul(),t=function(){switch(Ul()){case"b":return Wl(),"\b";case"f":return Wl(),"\f";case"n":return Wl(),"\n";case"r":return Wl(),"\r";case"t":return Wl(),"\t";case"v":return Wl(),"\v"}return}();if(t)return t;switch(e){case"0":if(Wl(),Al.JudgeUtil.isDigit(Ul()))throw tf(bl.Char,Wl());return"\0";case"x":return Wl(),function(){let e="",t=Ul();if(!Al.JudgeUtil.isHexDigit(t))throw tf(bl.Char,Wl());if(e+=Wl(),t=Ul(),!Al.JudgeUtil.isHexDigit(t))throw tf(bl.Char,Wl());return e+=Wl(),String.fromCodePoint(parseInt(e,16))}();case"u":return Wl(),Yl();case"\n":case"\u2028":case"\u2029":return Wl(),"";case"\r":return Wl(),"\n"===Ul()&&Wl(),""}if(void 0===e||Al.JudgeUtil.isDigitWithoutZero(e))throw tf(bl.Char,Wl());return Wl()}());case'"':case"'":if(Nl===Hl){const e=Kl("string",xl);return Wl(),e}return void(xl+=Wl());case"\n":case"\r":case void 0:throw tf(bl.Char,Wl());case"\u2028":case"\u2029":!function(e){Ol.warn(`JSON5: '${ef(e)}' in strings is not valid ECMAScript; consider escaping.`)}(Nl)}xl+=Wl()}};function Kl(e,t){return{type:e,value:t,line:Ml,column:Ll}}function ql(e){for(const t of e){if(Ul()!==t)throw tf(bl.Char,Wl());Wl()}}function Yl(){let e="",t=4;for(;t-- >0;){const t=Ul();if(!Al.JudgeUtil.isHexDigit(t))throw tf(bl.Char,Wl());e+=Wl()}return String.fromCodePoint(parseInt(e,16))}const Xl={start(){if("eof"===_l.type)throw tf(bl.EOF);Zl()},beforePropertyName(){switch(_l.type){case"identifier":case"string":return Pl=_l.value,void(Il="afterPropertyName");case"punctuator":return void Ql();case"eof":throw tf(bl.EOF)}},afterPropertyName(){if("eof"===_l.type)throw tf(bl.EOF);Il="beforePropertyValue"},beforePropertyValue(){if("eof"===_l.type)throw tf(bl.EOF);Zl()},afterPropertyValue(){if("eof"===_l.type)throw tf(bl.EOF);switch(_l.value){case",":return void(Il="beforePropertyName");case"}":Ql()}},beforeArrayValue(){if("eof"===_l.type)throw tf(bl.EOF);"punctuator"!==_l.type||"]"!==_l.value?Zl():Ql()},afterArrayValue(){if("eof"===_l.type)throw tf(bl.EOF);switch(_l.value){case",":return void(Il="beforeArrayValue");case"]":Ql()}},end(){}};function Zl(){const e=function(){let e;switch(_l.type){case"punctuator":switch(_l.value){case"{":e={};break;case"[":e=[]}break;case"null":case"boolean":case"numeric":case"string":e=_l.value}return e}();if(jl&&"object"==typeof e&&(e._line=Ml,e._column=Ll),void 0===kl)kl=e;else{const t=Tl[Tl.length-1];Array.isArray(t)?jl&&"object"!=typeof e?t.push({value:e,_line:Ml,_column:Ll}):t.push(e):t[Pl]=jl&&"object"!=typeof e?{value:e,_line:Ml,_column:Ll}:e}!function(e){if(e&&"object"==typeof e)Tl.push(e),Il=Array.isArray(e)?"beforeArrayValue":"beforePropertyName";else{const e=Tl[Tl.length-1];Il=e?Array.isArray(e)?"afterArrayValue":"afterPropertyValue":"end"}}(e)}function Ql(){Tl.pop();const e=Tl[Tl.length-1];Il=e?Array.isArray(e)?"afterArrayValue":"afterPropertyValue":"end"}function ef(e){const t={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(t[e])return t[e];if(e<" "){const t=e.charCodeAt(0).toString(16);return`\\x${`00${t}`.substring(t.length)}`}return e}function tf(e,t){let n="";switch(e){case bl.Char:n=void 0===t?`JSON5: invalid end of input at ${Ml}:${Ll}`:`JSON5: invalid character '${ef(t)}' at ${Ml}:${Ll}`;break;case bl.EOF:n=`JSON5: invalid end of input at ${Ml}:${Ll}`;break;case bl.Identifier:Ll-=5,n=`JSON5: invalid identifier character at ${Ml}:${Ll}`}const r=new nf(n);return r.lineNumber=Ml,r.columnNumber=Ll,r}class nf extends SyntaxError{}var rf=w&&w.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var u=Object.getOwnPropertyDescriptor(t,n);u&&!("get"in u?!t.__esModule:u.writable||u.configurable)||(u={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,u)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),uf=w&&w.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),of=w&&w.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&rf(t,e,n);return uf(t,e),t};Object.defineProperty(Y,"__esModule",{value:!0});var sf=Y.cleanWorkSpace=Ff=Y.executeInstallHvigor=yf=Y.isHvigorInstalled=mf=Y.isAllDependenciesInstalled=void 0;const cf=of(D.default),af=of(p.default),lf=b,ff=j,df=$,Df=X;let pf,Ef;var mf=Y.isAllDependenciesInstalled=function(){function e(e){const t=null==e?void 0:e.dependencies;return void 0===t?0:Object.getOwnPropertyNames(t).length}if(pf=gf(),Ef=Af(),e(pf)+1!==e(Ef))return!1;for(const e in null==pf?void 0:pf.dependencies)if(!(0,ff.hasNpmPackInPaths)(e,[lf.HVIGOR_PROJECT_DEPENDENCIES_HOME])||!hf(e,pf,Ef))return!1;return!0};function hf(e,t,n){return void 0!==n.dependencies&&(0,ff.offlinePluginConversion)(lf.HVIGOR_PROJECT_ROOT_DIR,t.dependencies[e])===n.dependencies[e]}var yf=Y.isHvigorInstalled=function(){return pf=gf(),Ef=Af(),(0,ff.hasNpmPackInPaths)(lf.HVIGOR_ENGINE_PACKAGE_NAME,[lf.HVIGOR_PROJECT_DEPENDENCIES_HOME])&&(0,ff.offlinePluginConversion)(lf.HVIGOR_PROJECT_ROOT_DIR,pf.hvigorVersion)===Ef.dependencies[lf.HVIGOR_ENGINE_PACKAGE_NAME]};const Cf={cwd:lf.HVIGOR_PROJECT_DEPENDENCIES_HOME,stdio:["inherit","inherit","inherit"]};var Ff=Y.executeInstallHvigor=function(){(0,df.logInfoPrintConsole)("Hvigor installing...");const e={dependencies:{}};e.dependencies[lf.HVIGOR_ENGINE_PACKAGE_NAME]=(0,ff.offlinePluginConversion)(lf.HVIGOR_PROJECT_ROOT_DIR,pf.hvigorVersion);try{cf.mkdirSync(lf.HVIGOR_PROJECT_DEPENDENCIES_HOME,{recursive:!0});const t=af.resolve(lf.HVIGOR_PROJECT_DEPENDENCIES_HOME,lf.DEFAULT_PACKAGE_JSON);cf.writeFileSync(t,JSON.stringify(e))}catch(e){(0,df.logErrorAndExit)(e)}!function(){const e=["config","set","store-dir",lf.HVIGOR_PNPM_STORE_PATH];(0,ff.executeCommand)(lf.HVIGOR_WRAPPER_PNPM_SCRIPT_PATH,e,Cf)}(),(0,ff.executeCommand)(lf.HVIGOR_WRAPPER_PNPM_SCRIPT_PATH,["install"],Cf)};function gf(){const e=af.resolve(lf.HVIGOR_PROJECT_WRAPPER_HOME,lf.DEFAULT_HVIGOR_CONFIG_JSON_FILE_NAME);return cf.existsSync(e)||(0,df.logErrorAndExit)(`Error: Hvigor config file ${e} does not exist.`),(0,Df.parseJsonFile)(e)}function Af(){return cf.existsSync(lf.HVIGOR_PROJECT_DEPENDENCY_PACKAGE_JSON_PATH)?(0,Df.parseJsonFile)(lf.HVIGOR_PROJECT_DEPENDENCY_PACKAGE_JSON_PATH):{dependencies:{}}}sf=Y.cleanWorkSpace=function(){if((0,df.logInfoPrintConsole)("Hvigor cleaning..."),!cf.existsSync(lf.HVIGOR_PROJECT_DEPENDENCIES_HOME))return;const e=cf.readdirSync(lf.HVIGOR_PROJECT_DEPENDENCIES_HOME);if(e&&0!==e.length){cf.existsSync(lf.HVIGOR_BOOT_JS_FILE_PATH)&&(0,ff.executeCommand)(process.argv[0],[lf.HVIGOR_BOOT_JS_FILE_PATH,"--stop-daemon"],{});try{e.forEach((e=>{cf.rmSync(af.resolve(lf.HVIGOR_PROJECT_DEPENDENCIES_HOME,e),{recursive:!0})}))}catch(e){(0,df.logErrorAndExit)(`The hvigor build tool cannot be installed. Please manually clear the workspace directory and synchronize the project again.\n\n Workspace Path: ${lf.HVIGOR_PROJECT_DEPENDENCIES_HOME}.`)}}};var vf={},Sf=w&&w.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var u=Object.getOwnPropertyDescriptor(t,n);u&&!("get"in u?!t.__esModule:u.writable||u.configurable)||(u={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,u)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),wf=w&&w.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Of=w&&w.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&Sf(t,e,n);return wf(t,e),t};Object.defineProperty(vf,"__esModule",{value:!0});var bf=vf.executeBuild=void 0;const _f=b,Bf=Of(D.default),Pf=Of(p.default),kf=$;bf=vf.executeBuild=function(){const e=Pf.resolve(_f.HVIGOR_PROJECT_DEPENDENCIES_HOME,"node_modules","@ohos","hvigor","bin","hvigor.js");try{const t=Bf.realpathSync(e);require(t)}catch(t){(0,kf.logErrorAndExit)(`Error: ENOENT: no such file ${e},delete ${_f.HVIGOR_PROJECT_DEPENDENCIES_HOME} and retry.`)}},function(){if(O.checkNpmConifg(),O.environmentHandler(),O.isPnpmAvailable()||O.executeInstallPnpm(),yf()&&mf())bf();else{sf();try{Ff()}catch(e){return void sf()}bf()}}(); \ No newline at end of file diff --git a/templates/openharmony/hvigorfile.ts b/templates/openharmony/hvigorfile.ts index 6478186902..f3cb9f1a87 100644 --- a/templates/openharmony/hvigorfile.ts +++ b/templates/openharmony/hvigorfile.ts @@ -1,2 +1,6 @@ -// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. -export { appTasks } from '@ohos/hvigor-ohos-plugin'; \ No newline at end of file +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/templates/openharmony/hvigorw b/templates/openharmony/hvigorw deleted file mode 100755 index 54aadd226b..0000000000 --- a/templates/openharmony/hvigorw +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash - -# ---------------------------------------------------------------------------- -# Hvigor startup script, version 1.0.0 -# -# Required ENV vars: -# ------------------ -# NODE_HOME - location of a Node home dir -# or -# Add /usr/local/nodejs/bin to the PATH environment variable -# ---------------------------------------------------------------------------- - -HVIGOR_APP_HOME=$(dirname $(readlink -f $0)) -HVIGOR_WRAPPER_SCRIPT=${HVIGOR_APP_HOME}/hvigor/hvigor-wrapper.js -warn() { - echo "" - echo -e "\033[1;33m`date '+[%Y-%m-%d %H:%M:%S]'`$@\033[0m" -} - -error() { - echo "" - echo -e "\033[1;31m`date '+[%Y-%m-%d %H:%M:%S]'`$@\033[0m" -} - -fail() { - error "$@" - exit 1 -} - -# Determine node to start hvigor wrapper script -if [ -n "${NODE_HOME}" ];then - EXECUTABLE_NODE="${NODE_HOME}/bin/node" - if [ ! -x "$EXECUTABLE_NODE" ];then - fail "ERROR: NODE_HOME is set to an invalid directory,check $NODE_HOME\n\nPlease set NODE_HOME in your environment to the location where your nodejs installed" - fi -else - EXECUTABLE_NODE="node" - which ${EXECUTABLE_NODE} > /dev/null 2>&1 || fail "ERROR: NODE_HOME is not set and not 'node' command found in your path" -fi - -# Check hvigor wrapper script -if [ ! -r "$HVIGOR_WRAPPER_SCRIPT" ];then - fail "ERROR: Couldn't find hvigor/hvigor-wrapper.js in ${HVIGOR_APP_HOME}" -fi - -# start hvigor-wrapper script -exec "${EXECUTABLE_NODE}" \ - "${HVIGOR_WRAPPER_SCRIPT}" "$@" diff --git a/templates/openharmony/hvigorw.bat b/templates/openharmony/hvigorw.bat deleted file mode 100644 index 6861293e47..0000000000 --- a/templates/openharmony/hvigorw.bat +++ /dev/null @@ -1,64 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Hvigor startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -set WRAPPER_MODULE_PATH=%APP_HOME%\hvigor\hvigor-wrapper.js -set NODE_EXE=node.exe - -goto start - -:start -@rem Find node.exe -if defined NODE_HOME goto findNodeFromNodeHome - -%NODE_EXE% --version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: NODE_HOME is not set and no 'node' command could be found in your PATH. -echo. -echo Please set the NODE_HOME variable in your environment to match the -echo location of your NodeJs installation. - -goto fail - -:findNodeFromNodeHome -set NODE_HOME=%NODE_HOME:"=% -set NODE_EXE_PATH=%NODE_HOME%/%NODE_EXE% - -if exist "%NODE_EXE_PATH%" goto execute -echo. -echo ERROR: NODE_HOME is not set and no 'node' command could be found in your PATH. -echo. -echo Please set the NODE_HOME variable in your environment to match the -echo location of your NodeJs installation. - -goto fail - -:execute -@rem Execute hvigor -"%NODE_EXE%" %WRAPPER_MODULE_PATH% %* - -if "%ERRORLEVEL%" == "0" goto hvigorwEnd - -:fail -exit /b 1 - -:hvigorwEnd -if "%OS%" == "Windows_NT" endlocal - -:end diff --git a/templates/openharmony/oh-package-lock.json5 b/templates/openharmony/oh-package-lock.json5 deleted file mode 100644 index 12dbc42214..0000000000 --- a/templates/openharmony/oh-package-lock.json5 +++ /dev/null @@ -1,14 +0,0 @@ -{ - "lockfileVersion": 1, - "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", - "specifiers": { - "@ohos/hypium@1.0.6": "@ohos/hypium@1.0.6", - "@ohos/hypium@^1.0.6": "@ohos/hypium@1.0.6" - }, - "packages": { - "@ohos/hypium@1.0.6": { - "resolved": "https://repo.harmonyos.com/ohpm/@ohos/hypium/-/hypium-1.0.6.tgz", - "integrity": "sha512-bb3DWeWhYrFqj9mPFV3yZQpkm36kbcK+YYaeY9g292QKSjOdmhEIQR2ULPvyMsgSR4usOBf5nnYrDmaCCXirgQ==" - } - } -} \ No newline at end of file diff --git a/templates/openharmony/oh-package.json5 b/templates/openharmony/oh-package.json5 index b794907fe7..4196319b7d 100644 --- a/templates/openharmony/oh-package.json5 +++ b/templates/openharmony/oh-package.json5 @@ -1,7 +1,8 @@ { - "license": "", + "modelVersion": "5.0.0", "devDependencies": { - "@ohos/hypium": "1.0.6" + "@ohos/hypium": "1.0.18", + "@ohos/hamock": "1.0.0" }, "author": "", "name": "test-cases",