DefaultModuleLoader.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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 _basePath))
  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. if (_basePath.AbsolutePath[_basePath.AbsolutePath.Length - 1] != '/')
  28. {
  29. var uriBuilder = new UriBuilder(_basePath);
  30. uriBuilder.Path += '/';
  31. _basePath = uriBuilder.Uri;
  32. }
  33. }
  34. public ResolvedSpecifier Resolve(string? referencingModuleLocation, string specifier)
  35. {
  36. if (string.IsNullOrEmpty(specifier))
  37. {
  38. ExceptionHelper.ThrowModuleResolutionException("Invalid Module Specifier", specifier, referencingModuleLocation);
  39. return default;
  40. }
  41. // Specifications from ESM_RESOLVE Algorithm: https://nodejs.org/api/esm.html#resolution-algorithm
  42. Uri resolved;
  43. if (Uri.TryCreate(specifier, UriKind.Absolute, out var uri))
  44. {
  45. resolved = uri;
  46. }
  47. else if (IsRelative(specifier))
  48. {
  49. resolved = new Uri(referencingModuleLocation != null ? new Uri(referencingModuleLocation, UriKind.Absolute) : _basePath, specifier);
  50. }
  51. else if (specifier[0] == '#')
  52. {
  53. ExceptionHelper.ThrowNotSupportedException($"PACKAGE_IMPORTS_RESOLVE is not supported: '{specifier}'");
  54. return default;
  55. }
  56. else
  57. {
  58. return new ResolvedSpecifier(
  59. specifier,
  60. specifier,
  61. null,
  62. SpecifierType.Bare
  63. );
  64. }
  65. if (resolved.IsFile)
  66. {
  67. if (resolved.UserEscaped)
  68. {
  69. ExceptionHelper.ThrowModuleResolutionException("Invalid Module Specifier", specifier, referencingModuleLocation);
  70. return default;
  71. }
  72. if (!Path.HasExtension(resolved.LocalPath))
  73. {
  74. ExceptionHelper.ThrowModuleResolutionException("Unsupported Directory Import", specifier, referencingModuleLocation);
  75. return default;
  76. }
  77. }
  78. if (_restrictToBasePath && !_basePath.IsBaseOf(resolved))
  79. {
  80. ExceptionHelper.ThrowModuleResolutionException($"Unauthorized Module Path", specifier, referencingModuleLocation);
  81. return default;
  82. }
  83. return new ResolvedSpecifier(
  84. specifier,
  85. resolved.AbsoluteUri,
  86. resolved,
  87. SpecifierType.RelativeOrAbsolute
  88. );
  89. }
  90. public Module LoadModule(Engine engine, ResolvedSpecifier resolved)
  91. {
  92. if (resolved.Type != SpecifierType.RelativeOrAbsolute)
  93. {
  94. 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}'.");
  95. return default;
  96. }
  97. if (resolved.Uri == null)
  98. {
  99. ExceptionHelper.ThrowInvalidOperationException($"Module '{resolved.Specifier}' of type '{resolved.Type}' has no resolved URI.");
  100. }
  101. var fileName = Uri.UnescapeDataString(resolved.Uri.AbsolutePath);
  102. if (!File.Exists(fileName))
  103. {
  104. ExceptionHelper.ThrowArgumentException("Module Not Found: ", resolved.Specifier);
  105. return default;
  106. }
  107. var code = File.ReadAllText(fileName);
  108. Module module;
  109. try
  110. {
  111. module = new JavaScriptParser().ParseModule(code, source: resolved.Uri.LocalPath);
  112. }
  113. catch (ParserException ex)
  114. {
  115. ExceptionHelper.ThrowSyntaxError(engine.Realm, $"Error while loading module: error in module '{resolved.Uri.LocalPath}': {ex.Error}");
  116. module = null;
  117. }
  118. catch (Exception)
  119. {
  120. ExceptionHelper.ThrowJavaScriptException(engine, $"Could not load module {resolved.Uri?.LocalPath}", (Location) default);
  121. module = null;
  122. }
  123. return module;
  124. }
  125. private static bool IsRelative(string specifier)
  126. {
  127. return specifier.StartsWith(".") || specifier.StartsWith("/");
  128. }
  129. }