using Jint.Native;
using Jint.Native.Json;
namespace Jint.Runtime.Modules;
///
/// Factory which creates a single runtime from a given source.
///
public static class ModuleFactory
{
///
/// Creates a for the usage within the given
/// from the provided javascript .
///
///
/// The returned modules location (see ) points to
/// if is not null. If
/// is null, the modules location source will be null as well.
///
/// Is thrown if the provided can not be parsed.
/// Is thrown if an error occured when parsing .
public static Module BuildSourceTextModule(Engine engine, ResolvedSpecifier resolved, string code, ModuleParsingOptions? parsingOptions = null)
{
var source = resolved.Uri?.LocalPath ?? resolved.Key;
AstModule module;
var parserOptions = (parsingOptions ?? ModuleParsingOptions.Default).GetParserOptions();
var parser = new Parser(parserOptions);
try
{
module = parser.ParseModule(code, source);
}
catch (ParseErrorException ex)
{
ExceptionHelper.ThrowSyntaxError(engine.Realm, $"Error while loading module: error in module '{source}': {ex.Error}");
module = null;
}
catch (Exception)
{
ExceptionHelper.ThrowJavaScriptException(engine, $"Could not load module {source}", (SourceLocation) default);
module = null;
}
return BuildSourceTextModule(engine, new Prepared(module, parserOptions));
}
///
/// Creates a for the usage within the given
/// from the parsed .
///
///
/// The returned modules location (see ) will be set
/// to of the .
///
public static Module BuildSourceTextModule(Engine engine, Prepared preparedModule)
{
if (!preparedModule.IsValid)
{
ExceptionHelper.ThrowInvalidPreparedModuleArgumentException(nameof(preparedModule));
}
return new SourceTextModule(engine, engine.Realm, preparedModule, preparedModule.Program!.Location.Source, async: false);
}
///
/// Creates a for the usage within the given for the
/// provided JSON module .
///
///
/// The returned modules location (see ) points to
/// if is not null. If
/// is null, the modules location source will be null as well.
///
/// Is thrown if an error occured when parsing .
public static Module BuildJsonModule(Engine engine, ResolvedSpecifier resolved, string jsonString)
{
var source = resolved.Uri?.LocalPath;
JsValue module;
try
{
module = new JsonParser(engine).Parse(jsonString);
}
catch (Exception)
{
ExceptionHelper.ThrowJavaScriptException(engine, $"Could not load module {source}", (SourceLocation) default);
module = null;
}
return BuildJsonModule(engine, module, resolved.Uri?.LocalPath);
}
///
/// Creates a for the usage within the given
/// from the parsed JSON provided in .
///
///
/// The returned modules location (see ) will be set
/// to .
///
public static Module BuildJsonModule(Engine engine, JsValue parsedJson, string? location)
{
return new SyntheticModule(engine, engine.Realm, parsedJson, location);
}
}