DefaultModuleLoader.cs 4.9 KB

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