LCOV - code coverage report
Current view: top level - source/scriptinterface - ModuleLoader.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 261 293 89.1 %
Date: 2026-12-03 01:19:39 Functions: 36 44 81.8 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "ModuleLoader.h"
      21             : 
      22             : #include "js/Modules.h"
      23             : #include "lib/file/file_system.h"
      24             : #include "lib/file/vfs/vfs.h"
      25             : #include "lib/os_path.h"
      26             : #include "lib/status.h"
      27             : #include "ps/CLogger.h"
      28             : #include "ps/CStr.h"
      29             : #include "ps/Errors.h"
      30             : #include "ps/Filesystem.h"
      31             : #include "scriptinterface/FunctionWrapper.h"
      32             : #include "scriptinterface/Object.h"
      33             : #include "scriptinterface/Conversions.h"
      34             : #include "scriptinterface/Exceptions.h"
      35             : #include "scriptinterface/Interface.h"
      36             : #include "scriptinterface/Request.h"
      37             : 
      38             : #include <algorithm>
      39             : #include <filesystem>
      40             : #include <fmt/format.h>
      41             : #include <js/CallArgs.h>
      42             : #include <js/Class.h>
      43             : #include <js/CompileOptions.h>
      44             : #include <js/Object.h>
      45             : #include <js/Promise.h>
      46             : #include <js/SourceText.h>
      47             : #include <js/Value.h>
      48             : #include <jsapi.h>
      49             : #include <numeric>
      50             : #include <stdexcept>
      51             : #include <string>
      52             : #include <string_view>
      53             : 
      54             : class JSObject;
      55             : namespace mozilla { union Utf8Unit; }
      56             : struct JSContext;
      57             : 
      58             : namespace Script
      59             : {
      60             : namespace
      61             : {
      62             : /**
      63             :  * When provided with an appendix name (containing a "~" and ending with
      64             :  * ".append.js") the name of the base file is returned. When it's not an
      65             :  * appendix name an empty string is returned. E.g.
      66             :  * "base_file~mod_name.append.js" -> "base_file.js"
      67             :  * "base-name~0.append.js" -> "base-name.js"
      68             :  * "base_file~mod_name.js" -> ""
      69             :  * "base_file_mod_name.append.js" -> ""
      70             :  */
      71        1166 : VfsPath GetBaseFilename(const VfsPath& filename)
      72             : {
      73        1166 :     constexpr std::string_view appendixExtension{".append.js"};
      74        1166 :     const std::string nameString{filename.string8()};
      75        1166 :     if (nameString.size() < appendixExtension.size())
      76         289 :         return {};
      77             : 
      78        1754 :     if (nameString.substr(nameString.size() - appendixExtension.size()) != appendixExtension)
      79         833 :         return {};
      80             : 
      81          44 :     const size_t pos{nameString.find('~')};
      82          44 :     if (pos == std::string::npos)
      83           1 :         return {};
      84             : 
      85         129 :     return nameString.substr(0, pos) + ".js";
      86        1166 : }
      87             : 
      88         112 : [[nodiscard]] std::vector<VfsPath> GetAppendices(const VfsPath& baseFilepath)
      89             : {
      90         112 :     const VfsPath directory{baseFilepath.Parent()};
      91         112 :     CFileInfos fileInfos;
      92         112 :     if (g_VFS->GetDirectoryEntries(baseFilepath, &fileInfos, nullptr) != INFO::OK)
      93             :     {
      94           0 :         throw std::runtime_error{fmt::format("Unable to load files in directory: \"{}\"",
      95           0 :             directory.string8())};
      96             :     }
      97             : 
      98         112 :     std::vector<VfsPath> filenames;
      99         112 :     std::transform(fileInfos.begin(), fileInfos.end(), std::back_inserter(filenames),
     100        1157 :         [](const CFileInfo fileInfo)
     101             :         {
     102        1157 :             return fileInfo.Name();
     103             :         });
     104             : 
     105         112 :     const VfsPath baseFilename{baseFilepath.Filename()};
     106         112 :     const auto endPoint = std::remove_if(filenames.begin(), filenames.end(), [&](const VfsPath& filename)
     107             :     {
     108        1157 :         const VfsPath base{GetBaseFilename(filename)};
     109        1157 :         return base != baseFilename;
     110        1157 :     });
     111         112 :     filenames.erase(endPoint, filenames.end());
     112             : 
     113         128 :     for (VfsPath& filename : filenames)
     114          48 :         filename = directory / filename;
     115         112 :     return filenames;
     116         295 : }
     117             : 
     118         127 : [[nodiscard]] std::string GetCode(const ModuleLoader::AllowModuleFunc& allowModule,
     119             :     const VfsPath& filePath)
     120             : {
     121         253 :     if (!allowModule || !allowModule(filePath))
     122             :     {
     123          10 :         throw std::runtime_error{fmt::format("Importing file \"{}\" is disallowed.",
     124          10 :             filePath.string8())};
     125             :     }
     126         122 :     if (!VfsFileExists(filePath))
     127           3 :         throw std::runtime_error{fmt::format("The file \"{}\" does not exist.", filePath.string8())};
     128             : 
     129         121 :     if (filePath.Extension() != L".js")
     130             :     {
     131           0 :         throw std::runtime_error{fmt::format("The file \"{}\" is not a JavaScript module.",
     132           0 :             filePath.string8())};
     133             :     }
     134             : 
     135         121 :     CVFSFile file;
     136         121 :     const PSRETURN ret{file.Load(g_VFS, filePath)};
     137         121 :     if (ret != PSRETURN_OK)
     138             :     {
     139           0 :         throw std::runtime_error{fmt::format("Failed to load file \"{}\": {}.", filePath.string8(),
     140           0 :             GetErrorString(ret))};
     141             :     }
     142             : 
     143         242 :     return file.DecodeUTF8();
     144         121 : }
     145             : 
     146             : template<typename Requester>
     147         383 : [[nodiscard]] JSObject* CompileModule(const Script::Request& rq,
     148             :     const ModuleLoader::AllowModuleFunc& allowModule, ModuleLoader::RegistryType& registry,
     149             :     const VfsPath& filePath, Requester&& requester)
     150             : {
     151        1149 :     const VfsPath normalizedPath{filePath.fileSystemPath().lexically_normal().generic_string()};
     152         375 :     const auto insertResult = registry.try_emplace(normalizedPath, rq, allowModule, normalizedPath);
     153         375 :     ModuleLoader::CompiledModule& compiledModule{std::get<1>(*std::get<0>(insertResult))};
     154         378 :     compiledModule.AddRequester(std::forward<Requester>(requester));
     155         435 :     return compiledModule.m_ModuleObject;
     156         375 : }
     157         318 : [[nodiscard]] JSObject* Resolve(const Script::Request& rq, const ModuleLoader::AllowModuleFunc& allowModule,
     158             :     ModuleLoader::RegistryType& registry, JS::HandleValue referencingModule,
     159             :     JS::HandleObject moduleRequest)
     160             : {
     161         318 :     std::string includeString;
     162         318 :     const JS::RootedValue pathValue{rq.cx,
     163         318 :         JS::StringValue(JS::GetModuleRequestSpecifier(rq.cx, moduleRequest))};
     164         321 :     if (!Script::FromJSVal(rq, pathValue, includeString))
     165           0 :         throw std::logic_error{"The module-name to import isn't a string."};
     166             : 
     167         318 :     std::string includingModule;
     168         318 :     if (!Script::FromJSProperty(rq, referencingModule, "path", includingModule))
     169           0 :         throw std::logic_error{"The importing module doesn't have a \"path\" property."};
     170             : 
     171         636 :     return CompileModule(rq, allowModule, registry, includeString, includingModule);
     172         607 : }
     173             : 
     174          61 : [[nodiscard]] JSObject* Evaluate(const Script::Request& rq, JS::HandleObject mod)
     175             : {
     176          61 :     if (!JS::ModuleLink(rq.cx, mod))
     177             :     {
     178           2 :         Script::Exception::CatchPending(rq);
     179           2 :         throw std::invalid_argument{"Unable to link module."};
     180             :     }
     181             : 
     182          59 :     JS::RootedValue val{rq.cx};
     183          59 :     if (!JS::ModuleEvaluate(rq.cx, mod, &val) || !val.isObject())
     184             :     {
     185           0 :         Script::Exception::CatchPending(rq);
     186           0 :         throw std::invalid_argument{"Unable to evaluate module."};
     187             :     }
     188             : 
     189          59 :     return &val.toObject();
     190          59 : }
     191             : 
     192           9 : Status FileChangedHook(void* param, const VfsPath& changedFile)
     193             : {
     194           9 :     ModuleLoader::RegistryType& registry{*static_cast<ModuleLoader::RegistryType*>(param)};
     195             : 
     196           9 :     const VfsPath proposedBasePath{GetBaseFilename(changedFile)};
     197             : 
     198          18 :     std::vector<VfsPath> modulesToErase{proposedBasePath.empty() ? changedFile : proposedBasePath};
     199           9 :     std::vector<std::reference_wrapper<ModuleLoader::Result>> queries;
     200          25 :     while (!modulesToErase.empty())
     201             :     {
     202          16 :         const VfsPath path{modulesToErase.back()};
     203          16 :         modulesToErase.pop_back();
     204          16 :         const VfsPath pathWithExtension{path.ChangeExtension(".js")};
     205          16 :         const auto it = registry.find(pathWithExtension);
     206          16 :         if (it == registry.end())
     207           6 :             continue;
     208             : 
     209          10 :         ModuleLoader::CompiledModule compiledModule{std::move(std::get<1>(*it))};
     210          10 :         registry.erase(it);
     211             : 
     212          10 :         const auto [additionalModules, callbacks] = compiledModule.GetRequesters();
     213          10 :         modulesToErase.insert(modulesToErase.end(),
     214             :             additionalModules.begin(), additionalModules.end());
     215             : 
     216          10 :         queries.insert(queries.end(), callbacks.begin(), callbacks.end());
     217          42 :     }
     218             : 
     219          16 :     for (ModuleLoader::Result& result : queries)
     220           7 :         result.Resume();
     221             : 
     222           9 :     return INFO::OK;
     223          20 : }
     224             : 
     225             : template<bool reject>
     226          56 : bool Call(JSContext* cx, const unsigned argc, JS::Value* vp)
     227             : {
     228          56 :     JS::CallArgs args{JS::CallArgsFromVp(argc, vp)};
     229          56 :     const Script::Request rq{cx};
     230             : 
     231         101 :     const auto statusPtr{JS::GetMaybePtrFromReservedSlot<ModuleLoader::Future::Status>(
     232          56 :         &args.callee(), 0)};
     233          45 :     if (!statusPtr)
     234             :         return true;
     235             : 
     236          45 :     auto& status = *statusPtr;
     237             : 
     238             :     if (reject)
     239             :     {
     240           2 :         JS::HandleValue error{args.get(0)};
     241           2 :         std::string asString;
     242           2 :         Script::Function::Call(rq, error, "toString", asString);
     243           2 :         std::string stack;
     244           2 :         Script::GetProperty(rq, error, "stack", stack);
     245           7 :         status = ModuleLoader::Future::Rejected{std::make_exception_ptr(std::runtime_error{
     246             :             asString + '\n' + stack})};
     247           2 :         return true;
     248           3 :     }
     249             : 
     250          43 :     const auto evaluatingStatus{std::get_if<ModuleLoader::Future::Evaluating>(&status)};
     251             :     if (!evaluatingStatus)
     252             :     {
     253           0 :         status = ModuleLoader::Future::Rejected{std::make_exception_ptr(std::runtime_error{
     254             :             "Future is not Pending."})};
     255           0 :         return true;
     256             :     }
     257          43 :     status = ModuleLoader::Future::Fulfilled{evaluatingStatus->moduleNamespace};
     258          43 :     return true;
     259         101 : }
     260             : 
     261             : template<bool reject>
     262             : constexpr JSClassOps callbackClassOps{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
     263             :     /*call =*/Call<reject>, nullptr, nullptr};
     264             : 
     265             : template<bool reject>
     266             : constexpr JSClass callbackClass{"Callback", JSCLASS_HAS_RESERVED_SLOTS(1), &callbackClassOps<reject>};
     267             : } // anonymous namespace
     268             : 
     269         112 : ModuleLoader::CompiledModule::CompiledModule(const Script::Request& rq, const AllowModuleFunc& allowModule,
     270         112 :     const VfsPath& filePath):
     271         112 :     m_ModuleObject(rq.cx)
     272             : {
     273         112 :     const std::vector<VfsPath> appendices{GetAppendices(filePath)};
     274         112 :     const std::string code{std::accumulate(appendices.begin(), appendices.end(),
     275           0 :         GetCode(allowModule, filePath),
     276          15 :         [&](std::string code, const VfsPath& fileToAppend)
     277             :         {
     278          30 :             return std::move(code) + GetCode(allowModule, fileToAppend);
     279         112 :         })};
     280             : 
     281         106 :     JS::CompileOptions options{rq.cx};
     282         106 :     const std::string filePathStr{filePath.string8()};
     283         106 :     options.setFileAndLine(filePathStr.c_str(), 1);
     284             : 
     285         106 :     JS::SourceText<mozilla::Utf8Unit> src;
     286         106 :     if (!src.init(rq.cx, code.c_str(), code.length(), JS::SourceOwnership::Borrowed))
     287           0 :         throw std::invalid_argument{fmt::format("Unable to read code file: \"{}\".", filePathStr)};
     288             : 
     289         106 :     m_ModuleObject = JS::CompileModule(rq.cx, options, src);
     290             : 
     291         106 :     if (!m_ModuleObject)
     292             :     {
     293           2 :         Script::Exception::CatchPending(rq);
     294           2 :         throw std::invalid_argument{fmt::format("Unable to compile module: \"{}\".",
     295           4 :             filePathStr)};
     296             :     }
     297             : 
     298         104 :     JS::RootedValue modInfo{rq.cx};
     299         104 :     Script::CreateObject(rq, &modInfo, "path", filePathStr);
     300         104 :     JS::SetModulePrivate(m_ModuleObject, modInfo);
     301         294 : }
     302             : 
     303             : [[nodiscard]] std::tuple<const std::vector<VfsPath>&,
     304             :     const std::vector<std::reference_wrapper<ModuleLoader::Result>>&>
     305          10 :     ModuleLoader::CompiledModule::GetRequesters() const
     306             : {
     307          10 :     return {m_Importer, m_Callbacks};
     308             : }
     309             : 
     310         315 : void ModuleLoader::CompiledModule::AddRequester(VfsPath importer)
     311             : {
     312         630 :     m_Importer.push_back(std::move(importer));
     313         315 : }
     314             : 
     315          60 : void ModuleLoader::CompiledModule::AddRequester(Result& callback)
     316             : {
     317          60 :     m_Callbacks.push_back(callback);
     318           0 : }
     319             : 
     320          51 : void ModuleLoader::CompiledModule::RemoveRequester(Result* toErase)
     321             : {
     322          51 :     m_Callbacks.erase(std::remove_if(m_Callbacks.begin(), m_Callbacks.end(),
     323          51 :         [&](Result& elem)
     324             :         {
     325          51 :             return &elem == toErase;
     326          51 :         }), m_Callbacks.end());
     327          51 : }
     328             : 
     329          65 : ModuleLoader::Future::Future(const Script::Request& rq, ModuleLoader& loader, Result& result,
     330          65 :     VfsPath modulePath):
     331         130 :     m_Status{Evaluating{{rq.cx, nullptr}, {rq.cx, JS_NewObject(rq.cx, &callbackClass<false>)},
     332          65 :         {rq.cx, JS_NewObject(rq.cx, &callbackClass<true>)}}}
     333             : {
     334             :     // It's possible to access exported values before the complete module is evaluated (whenever
     335             :     // something is `export`-ed before a top-level `await`).
     336             :     // Those "partial" module namespaces are not exposed for the following reasons:
     337             :     // - The use case for them is too limited.
     338             :     // - JS developers are used to getting either a complete namespace or nothing.
     339             :     // - Accessing values which are not yet exported results in an error. These errors might implicitly be
     340             :     //  dropped.
     341             : 
     342          65 :     try
     343             :     {
     344          60 :         JS::RootedObject mod{rq.cx, CompileModule(rq, loader.m_AllowModule, loader.m_Registry, modulePath,
     345          60 :             result)};
     346          60 :         JS::RootedObject promise{rq.cx, Evaluate(rq, mod)};
     347          58 :         Evaluating& evaluatingStatus{std::get<Evaluating>(m_Status)};
     348          58 :         evaluatingStatus.moduleNamespace = JS::GetModuleNamespace(rq.cx, mod);
     349             : 
     350          58 :         SetReservedSlot(JS::PrivateValue(static_cast<void*>(&m_Status)));
     351             : 
     352          58 :         if (!JS::AddPromiseReactions(rq.cx, promise, evaluatingStatus.fulfill, evaluatingStatus.reject))
     353           0 :             throw std::runtime_error{"Failed adding promise reaction."};
     354          60 :     }
     355           7 :     catch(...)
     356             :     {
     357           7 :         if (std::holds_alternative<Evaluating>(m_Status))
     358           7 :             m_Status = Rejected{std::current_exception()};
     359           7 :     }
     360         332 : }
     361             : 
     362           4 : ModuleLoader::Future::Future(Future&& other) noexcept:
     363           4 :     m_Status{std::exchange(other.m_Status, Invalid{})}
     364             : {
     365           4 :     SetReservedSlot(JS::PrivateValue(static_cast<void*>(&m_Status)));
     366           4 : }
     367             : 
     368          10 : ModuleLoader::Future& ModuleLoader::Future::operator=(Future&& other) noexcept
     369             : {
     370          10 :     SetReservedSlot(JS::UndefinedValue());
     371          10 :     m_Status = std::exchange(other.m_Status, Invalid{});
     372          10 :     SetReservedSlot(JS::PrivateValue(static_cast<void*>(&m_Status)));
     373             : 
     374          10 :     return *this;
     375             : }
     376             : 
     377          71 : ModuleLoader::Future::~Future()
     378             : {
     379          71 :     SetReservedSlot(JS::UndefinedValue());
     380          71 : }
     381             : 
     382          47 : [[nodiscard]] bool ModuleLoader::Future::IsDone() const noexcept
     383             : {
     384          47 :     return std::holds_alternative<Fulfilled>(m_Status) || std::holds_alternative<Rejected>(m_Status);
     385             : }
     386             : 
     387          38 : [[nodiscard]] JSObject* ModuleLoader::Future::Get()
     388             : {
     389          38 :     if (std::holds_alternative<Fulfilled>(m_Status))
     390          27 :         return std::get<Fulfilled>(std::exchange(m_Status, Invalid{})).moduleNamespace;
     391          11 :     std::exception_ptr error{std::move(std::get<Rejected>(m_Status).error)};
     392           9 :     m_Status = Invalid{};
     393          18 :     std::rethrow_exception(std::move(error));
     394           9 : }
     395             : 
     396           7 : [[nodiscard]] bool ModuleLoader::Future::IsWaiting() const noexcept
     397             : {
     398           7 :     return std::holds_alternative<WaitingForFileChange>(m_Status);
     399             : }
     400             : 
     401           7 : void ModuleLoader::Future::SetWaiting() noexcept
     402             : {
     403           0 :     m_Status.emplace<WaitingForFileChange>();
     404           0 : }
     405             : 
     406         153 : void ModuleLoader::Future::SetReservedSlot(JS::Value privateValue) noexcept
     407             : {
     408         153 :     Evaluating* evaluatingStatus{std::get_if<Evaluating>(&m_Status)};
     409          83 :     if (!evaluatingStatus)
     410             :         return;
     411          83 :     if (evaluatingStatus->fulfill)
     412          83 :         JS::SetReservedSlot(evaluatingStatus->fulfill, 0, privateValue);
     413          83 :     if (evaluatingStatus->reject)
     414          83 :         JS::SetReservedSlot(evaluatingStatus->reject, 0, privateValue);
     415             : }
     416             : 
     417          50 : ModuleLoader::Result::iterator::iterator(Result& backReference):
     418           0 :     backRef{&backReference}
     419           0 : {}
     420             : 
     421          56 : [[nodiscard]] ModuleLoader::Future& ModuleLoader::Result::iterator::operator*() const
     422             : {
     423          56 :     return backRef->m_Storage;
     424             : }
     425             : 
     426          16 : [[nodiscard]] ModuleLoader::Future* ModuleLoader::Result::iterator::operator->() const
     427             : {
     428          16 :     return &(**this);
     429             : }
     430             : 
     431           7 : ModuleLoader::Result::iterator& ModuleLoader::Result::iterator::operator++()
     432             : {
     433           7 :     backRef->m_Storage.SetWaiting();
     434           7 :     return *this;
     435             : }
     436             : 
     437           0 : ModuleLoader::Result::iterator& ModuleLoader::Result::iterator::operator++(int)
     438             : {
     439           0 :     ++(*this);
     440             :     // All iterator of this `LoadModuleResult` refere to the same `LoadModuleResult`.
     441           0 :     return *this;
     442             : }
     443             : 
     444           0 : [[nodiscard]] bool ModuleLoader::Result::iterator::operator==(const iterator&) const
     445             : {
     446           0 :     return false;
     447             : }
     448             : 
     449           3 : [[nodiscard]] bool ModuleLoader::Result::iterator::operator!=(const iterator&) const
     450             : {
     451           3 :     return true;
     452             : }
     453             : 
     454          59 : ModuleLoader::Result::Result(const Script::Request& rq, const VfsPath& modulePath):
     455          59 :     m_Script{rq.GetScriptInterface()},
     456          59 :     m_ModulePath{modulePath},
     457          59 :     m_Storage{rq, m_Script.GetModuleLoader(), *this, m_ModulePath}
     458             : {
     459          59 : }
     460             : 
     461         110 : ModuleLoader::Result::~Result()
     462             : {
     463          59 :     ModuleLoader::RegistryType& registry{m_Script.GetModuleLoader().m_Registry};
     464          59 :     const auto modIter = registry.find(m_ModulePath);
     465          59 :     if (modIter == registry.end())
     466           8 :         return;
     467             : 
     468          51 :     std::get<1>(*modIter).RemoveRequester(this);
     469         118 : }
     470             : 
     471          50 : [[nodiscard]] ModuleLoader::Result::iterator ModuleLoader::Result::begin() noexcept
     472             : {
     473          50 :     return ModuleLoader::Result::iterator{*this};
     474             : }
     475             : 
     476           1 : [[nodiscard]] ModuleLoader::Result::iterator ModuleLoader::Result::end() const noexcept
     477             : {
     478           1 :     return ModuleLoader::Result::iterator{};
     479             : }
     480             : 
     481           7 : void ModuleLoader::Result::Resume()
     482             : {
     483           7 :     if (m_Storage.IsWaiting())
     484          12 :         m_Storage = ModuleLoader::Future{m_Script, m_Script.GetModuleLoader(), *this, m_ModulePath};
     485           7 : }
     486             : 
     487         377 : ModuleLoader::ModuleLoader(ModuleLoader::AllowModuleFunc allowModule):
     488         457 :     m_AllowModule{std::move(allowModule)}
     489             : {
     490         377 :     RegisterFileReloadFunc(FileChangedHook, static_cast<void*>(&m_Registry));
     491         377 : }
     492             : 
     493         377 : ModuleLoader::~ModuleLoader()
     494             : {
     495         377 :     UnregisterFileReloadFunc(FileChangedHook, static_cast<void*>(&m_Registry));
     496         377 : }
     497             : 
     498          57 : [[nodiscard]] ModuleLoader::Result ModuleLoader::LoadModule(const Script::Request& rq,
     499             :     const VfsPath& modulePath)
     500             : {
     501          57 :     return Result{rq, modulePath};
     502             : }
     503             : 
     504             : /**
     505             :  * This is only executed once per module. Following accesses of `import.meta`
     506             :  * evaluate to the same object.
     507             :  */
     508           2 : [[nodiscard]] bool ModuleLoader::MetadataHook(JSContext* cx, JS::HandleValue privateValue,
     509             :     JS::HandleObject metaObject) noexcept
     510             : {
     511           2 :     const Script::Request rq{cx};
     512             : 
     513           2 :     JS::RootedValue path{cx};
     514           2 :     if (!Script::GetProperty(rq, privateValue, "path", &path))
     515             :         return false;
     516             : 
     517           2 :     JS::RootedValue metaValue{cx, JS::ObjectValue(*metaObject)};
     518           2 :     if (!Script::SetProperty(rq, metaValue, "path", path))
     519             :         return false;
     520             : 
     521             :     return true;
     522           2 : }
     523             : 
     524         316 : [[nodiscard]] JSObject* ModuleLoader::ResolveHook(JSContext* cx, JS::HandleValue referencingPrivate,
     525             :     JS::HandleObject request) noexcept
     526             : {
     527         316 :     try
     528             :     {
     529         316 :         const Script::Request rq{cx};
     530         316 :         ModuleLoader& loader{rq.GetScriptInterface().GetModuleLoader()};
     531         316 :         return Resolve(rq, loader.m_AllowModule, loader.m_Registry, referencingPrivate, request);
     532         316 :     }
     533           2 :     catch (const std::exception& e)
     534             :     {
     535           4 :         LOGERROR("{}", e.what());
     536           2 :         return nullptr;
     537           2 :     }
     538           0 :     catch (...)
     539             :     {
     540           0 :         LOGERROR("Error compiling module.");
     541           0 :         return nullptr;
     542           0 :     }
     543             : }
     544             : 
     545           2 : [[nodiscard]] bool ModuleLoader::DynamicImportHook(JSContext* cx, JS::HandleValue referencingPrivate,
     546             :     JS::HandleObject moduleRequest, JS::HandleObject promise) noexcept
     547             : {
     548           2 :     const Script::Request rq{cx};
     549           2 :     try
     550             :     {
     551           2 :         ModuleLoader& loader{rq.GetScriptInterface().GetModuleLoader()};
     552           2 :         JS::RootedObject mod{rq.cx, Resolve(rq, loader.m_AllowModule, loader.m_Registry,
     553           1 :             referencingPrivate, moduleRequest)};
     554           1 :         JS::RootedObject evaluationPromise{rq.cx, Evaluate(rq, mod)};
     555           1 :         return JS::FinishDynamicModuleImport(rq.cx, evaluationPromise, referencingPrivate,
     556             :             moduleRequest, promise);
     557           1 :     }
     558           1 :     catch (const std::exception& e)
     559             :     {
     560           2 :         LOGERROR("{}", e.what());
     561           1 :         return JS::FinishDynamicModuleImport(rq.cx, nullptr, referencingPrivate, moduleRequest,
     562             :             promise);
     563           1 :     }
     564           0 :     catch (...)
     565             :     {
     566           0 :         return JS::FinishDynamicModuleImport(rq.cx, nullptr, referencingPrivate, moduleRequest,
     567             :             promise);
     568           0 :     }
     569           2 : }
     570             : } // namespace Script

Generated by: LCOV version 1.16