DefaultModuleLoader.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. using Esprima;
  2. using Esprima.Ast;
  3. namespace Jint.Runtime.Modules;
  4. public sealed class DefaultModuleLoader : IModuleLoader
  5. {
  6. private readonly Uri _basePath;
  7. private readonly bool _restrictToBasePath;
  8. public DefaultModuleLoader(string basePath) : this(basePath, true)
  9. {
  10. }
  11. public DefaultModuleLoader(string basePath, bool restrictToBasePath)
  12. {
  13. if (string.IsNullOrWhiteSpace(basePath))
  14. {
  15. ExceptionHelper.ThrowArgumentException("Value cannot be null or whitespace.", nameof(basePath));
  16. }
  17. _restrictToBasePath = restrictToBasePath;
  18. if (!Uri.TryCreate(basePath, UriKind.Absolute, out var temp))
  19. {
  20. if (!Path.IsPathRooted(basePath))
  21. {
  22. ExceptionHelper.ThrowArgumentException("Path must be rooted", nameof(basePath));
  23. }
  24. basePath = Path.GetFullPath(basePath);
  25. _basePath = new Uri(basePath, UriKind.Absolute);
  26. }
  27. else
  28. {
  29. _basePath = temp;
  30. }
  31. if (_basePath.AbsolutePath[_basePath.AbsolutePath.Length - 1] != '/')
  32. {
  33. var uriBuilder = new UriBuilder(_basePath);
  34. uriBuilder.Path += '/';
  35. _basePath = uriBuilder.Uri;
  36. }
  37. }
  38. public ResolvedSpecifier Resolve(string? referencingModuleLocation, string specifier)
  39. {
  40. if (string.IsNullOrEmpty(specifier))
  41. {
  42. ExceptionHelper.ThrowModuleResolutionException("Invalid Module Specifier", specifier, referencingModuleLocation);
  43. return default;
  44. }
  45. // Specifications from ESM_RESOLVE Algorithm: https://nodejs.org/api/esm.html#resolution-algorithm
  46. Uri resolved;
  47. if (Uri.TryCreate(specifier, UriKind.Absolute, out var uri))
  48. {
  49. resolved = uri;
  50. }
  51. else if (IsRelative(specifier))
  52. {
  53. resolved = new Uri(referencingModuleLocation != null ? new Uri(referencingModuleLocation, UriKind.Absolute) : _basePath, specifier);
  54. }
  55. else if (specifier[0] == '#')
  56. {
  57. ExceptionHelper.ThrowNotSupportedException($"PACKAGE_IMPORTS_RESOLVE is not supported: '{specifier}'");
  58. return default;
  59. }
  60. else
  61. {
  62. return new ResolvedSpecifier(
  63. specifier,
  64. specifier,
  65. null,
  66. SpecifierType.Bare
  67. );
  68. }
  69. if (resolved.IsFile)
  70. {
  71. if (resolved.UserEscaped)
  72. {
  73. ExceptionHelper.ThrowModuleResolutionException("Invalid Module Specifier", specifier, referencingModuleLocation);
  74. return default;
  75. }
  76. if (!Path.HasExtension(resolved.LocalPath))
  77. {
  78. ExceptionHelper.ThrowModuleResolutionException("Unsupported Directory Import", specifier, referencingModuleLocation);
  79. return default;
  80. }
  81. }
  82. if (_restrictToBasePath && !_basePath.IsBaseOf(resolved))
  83. {
  84. ExceptionHelper.ThrowModuleResolutionException($"Unauthorized Module Path", specifier, referencingModuleLocation);
  85. return default;
  86. }
  87. return new ResolvedSpecifier(
  88. specifier,
  89. resolved.AbsoluteUri,
  90. resolved,
  91. SpecifierType.RelativeOrAbsolute
  92. );
  93. }
  94. public Module LoadModule(Engine engine, ResolvedSpecifier resolved)
  95. {
  96. if (resolved.Type != SpecifierType.RelativeOrAbsolute)
  97. {
  98. ExceptionHelper.ThrowNotSupportedException($"The default module loader can only resolve files. You can define modules directly to allow imports using {nameof(Engine)}.{nameof(Engine.AddModule)}(). Attempted to resolve: '{resolved.Specifier}'.");
  99. return default;
  100. }
  101. if (resolved.Uri == null)
  102. {
  103. ExceptionHelper.ThrowInvalidOperationException($"Module '{resolved.Specifier}' of type '{resolved.Type}' has no resolved URI.");
  104. }
  105. var fileName = Uri.UnescapeDataString(resolved.Uri.AbsolutePath);
  106. if (!File.Exists(fileName))
  107. {
  108. ExceptionHelper.ThrowArgumentException("Module Not Found: ", resolved.Specifier);
  109. return default;
  110. }
  111. var code = File.ReadAllText(fileName);
  112. var source = resolved.Uri.LocalPath;
  113. Module module;
  114. try
  115. {
  116. module = new JavaScriptParser().ParseModule(code, source);
  117. }
  118. catch (ParserException ex)
  119. {
  120. ExceptionHelper.ThrowSyntaxError(engine.Realm, $"Error while loading module: error in module '{source}': {ex.Error}");
  121. module = null;
  122. }
  123. catch (Exception)
  124. {
  125. ExceptionHelper.ThrowJavaScriptException(engine, $"Could not load module {source}", (Location) default);
  126. module = null;
  127. }
  128. return module;
  129. }
  130. private static bool IsRelative(string specifier)
  131. {
  132. return specifier.StartsWith(".") || specifier.StartsWith("/");
  133. }
  134. }