using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using Jint; using Jint.Native; using Jint.Native.Object; using Jint.Runtime.Interop; using Jint.Runtime.Modules; namespace durable_pi_omg; public sealed partial class NodeModuleLoader : ModuleLoader { private readonly string _basePath; private readonly HashSet _conditions; private readonly HashSet _cjsConditions = new(["require", "node", "default"], StringComparer.Ordinal); private readonly Dictionary _cjsCache = new(StringComparer.Ordinal); private readonly Dictionary _packageTypeCache = new(StringComparer.Ordinal); private static readonly HashSet ReservedWords = new(StringComparer.Ordinal) { "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with", "yield", "let", "static", "implements", "interface", "package", "private", "protected", "public", "await" }; [GeneratedRegex(@"^\s*(?:import|export)\s", RegexOptions.Multiline)] private static partial Regex EsmSyntaxRegex(); [GeneratedRegex(@"^[A-Za-z_$][A-Za-z0-9_$]*$")] private static partial Regex ValidIdentifierRegex(); public NodeModuleLoader(string basePath, IEnumerable? conditions = null) { _basePath = Path.GetFullPath(basePath); _conditions = new HashSet( conditions ?? ["import", "module", "default", "node"], StringComparer.Ordinal); } public override ResolvedSpecifier Resolve(string? referencingModuleLocation, ModuleRequest moduleRequest) { var specifier = moduleRequest.Specifier; if (string.IsNullOrEmpty(specifier)) { throw new ArgumentException("Module specifier cannot be empty.", nameof(moduleRequest)); } // Preserve built-in / virtual / node: specifiers if registered via Engine.Modules.Add(...) if (specifier.StartsWith("node:", StringComparison.Ordinal)) { return new ResolvedSpecifier(moduleRequest, specifier, null, SpecifierType.Bare); } string? resolvedPath; if (specifier.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) { var fileUri = new Uri(specifier); resolvedPath = ResolveFilePath(fileUri.LocalPath); } else if (specifier.StartsWith("./", StringComparison.Ordinal) || specifier.StartsWith("../", StringComparison.Ordinal) || specifier.StartsWith("/", StringComparison.Ordinal) || specifier is "." or "..") { var baseDir = GetBaseDirectory(referencingModuleLocation); var candidate = Path.GetFullPath(Path.Combine(baseDir, specifier)); resolvedPath = ResolveFilePath(candidate); } else if (specifier.StartsWith('#')) { var baseDir = GetBaseDirectory(referencingModuleLocation); resolvedPath = ResolvePackageImport(specifier, baseDir); } else { var baseDir = GetBaseDirectory(referencingModuleLocation); resolvedPath = ResolveBareSpecifier(specifier, baseDir); } if (resolvedPath is null) { // Fall back to Bare so Jint can check modules registered with Engine.Modules.Add() return new ResolvedSpecifier(moduleRequest, specifier, null, SpecifierType.Bare); } var fullPath = Path.GetFullPath(resolvedPath); var uri = new Uri(fullPath); return new ResolvedSpecifier(moduleRequest, fullPath, uri, SpecifierType.RelativeOrAbsolute); } protected override string LoadModuleContents(Engine engine, ResolvedSpecifier resolved) { if (resolved.Uri is null || !resolved.Uri.IsFile) { throw new FileNotFoundException( $"Could not resolve module '{resolved.ModuleRequest.Specifier}'."); } var path = resolved.Uri.LocalPath; if (!File.Exists(path)) { throw new FileNotFoundException($"Module file not found: '{path}'.", path); } var content = File.ReadAllText(path); if (IsCommonJs(path, content)) { return WrapCommonJsAsEsm(engine, path); } return content; } private bool IsCommonJs(string filePath, string content) { if (filePath.EndsWith(".mjs", StringComparison.OrdinalIgnoreCase)) { return false; } if (filePath.EndsWith(".cjs", StringComparison.OrdinalIgnoreCase)) { return true; } if (!filePath.EndsWith(".js", StringComparison.OrdinalIgnoreCase)) { return false; } var pkgType = GetNearestPackageType(Path.GetDirectoryName(filePath)); if (string.Equals(pkgType, "module", StringComparison.Ordinal)) { return false; } // Some packages omit "type": "module" but ship ESM via "module" field return !EsmSyntaxRegex().IsMatch(content); } private string? GetNearestPackageType(string? startDir) { var dir = startDir; while (!string.IsNullOrEmpty(dir)) { if (_packageTypeCache.TryGetValue(dir, out var cached)) { return cached; } var pkgJsonPath = Path.Combine(dir, "package.json"); if (File.Exists(pkgJsonPath)) { string? type = null; using var doc = JsonDocument.Parse(File.ReadAllText(pkgJsonPath)); if (doc.RootElement.TryGetProperty("type", out var typeEl) && typeEl.ValueKind == JsonValueKind.String) { type = typeEl.GetString(); } _packageTypeCache[dir] = type; return type; } var parent = Path.GetDirectoryName(dir); if (parent == dir) { break; } dir = parent; } return null; } private string WrapCommonJsAsEsm(Engine engine, string filePath) { var exportsVal = LoadCommonJs(engine, filePath); engine.SetValue("__jintGetCjsExports", new Func(p => _cjsCache[p])); var sb = new StringBuilder(); sb.Append("const __cjs = globalThis.__jintGetCjsExports("); sb.Append(JsonSerializer.Serialize(filePath)); sb.AppendLine(");"); sb.AppendLine("export default __cjs;"); if (exportsVal is ObjectInstance obj) { foreach (var key in obj.GetOwnPropertyKeys(Jint.Runtime.Types.String)) { var name = key.AsString(); if (ValidIdentifierRegex().IsMatch(name) && !ReservedWords.Contains(name)) { sb.Append("export const "); sb.Append(name); sb.Append(" = __cjs["); sb.Append(JsonSerializer.Serialize(name)); sb.AppendLine("];"); } } } return sb.ToString(); } private JsValue LoadCommonJs(Engine engine, string filePath) { var fullPath = Path.GetFullPath(filePath); if (_cjsCache.TryGetValue(fullPath, out var cached)) { return cached; } if (fullPath.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) { var json = File.ReadAllText(fullPath); var parsed = engine.Evaluate($"({json})"); _cjsCache[fullPath] = parsed; return parsed; } var moduleObj = new JsObject(engine); var exportsObj = new JsObject(engine); moduleObj.Set("exports", exportsObj); _cjsCache[fullPath] = exportsObj; var dirName = Path.GetDirectoryName(fullPath) ?? _basePath; var requireFn = new ClrFunction(engine, "require", (_, args) => { var spec = args.Length > 0 ? args[0].ToString() : string.Empty; var resolved = ResolveSpecForCjs(spec, dirName) ?? throw new FileNotFoundException($"CommonJS module not found: '{spec}' (from '{fullPath}')."); return LoadCommonJs(engine, resolved); }); var code = File.ReadAllText(fullPath); var wrapped = $"(function(exports, require, module, __filename, __dirname) {{\n{code}\n}})"; var factory = engine.Evaluate(wrapped, fullPath); engine.Invoke(factory, exportsObj, requireFn, moduleObj, fullPath, dirName); var finalExports = moduleObj.Get("exports"); _cjsCache[fullPath] = finalExports; return finalExports; } private string? ResolveSpecForCjs(string specifier, string baseDir) { if (specifier.StartsWith("./", StringComparison.Ordinal) || specifier.StartsWith("../", StringComparison.Ordinal) || specifier.StartsWith("/", StringComparison.Ordinal) || specifier is "." or "..") { var candidate = Path.GetFullPath(Path.Combine(baseDir, specifier)); return ResolveFilePath(candidate); } return ResolveBareSpecifier(specifier, baseDir, _cjsConditions); } private string GetBaseDirectory(string? referencingModuleLocation) { if (string.IsNullOrEmpty(referencingModuleLocation)) { return _basePath; } if (Uri.TryCreate(referencingModuleLocation, UriKind.Absolute, out var uri) && uri.IsFile) { referencingModuleLocation = uri.LocalPath; } return Directory.Exists(referencingModuleLocation) ? referencingModuleLocation : Path.GetDirectoryName(referencingModuleLocation) ?? _basePath; } private string? ResolveBareSpecifier(string specifier, string startDir, HashSet? conditions = null) { var activeConditions = conditions ?? _conditions; var (packageName, subpath) = SplitPackageSpecifier(specifier); var dir = startDir; while (!string.IsNullOrEmpty(dir)) { var pkgDir = Path.Combine(dir, "node_modules", packageName); if (Directory.Exists(pkgDir)) { var resolved = ResolveInPackage(pkgDir, subpath, activeConditions); if (resolved is not null) { return resolved; } } var parent = Path.GetDirectoryName(dir); if (parent == dir) { break; } dir = parent; } return null; } private string? ResolvePackageImport(string specifier, string startDir) { var dir = startDir; while (!string.IsNullOrEmpty(dir)) { var pkgJsonPath = Path.Combine(dir, "package.json"); if (File.Exists(pkgJsonPath)) { using var doc = JsonDocument.Parse(File.ReadAllText(pkgJsonPath)); if (doc.RootElement.TryGetProperty("imports", out var importsEl)) { var target = MatchExportsOrImports(importsEl, specifier); if (target is not null) { return target.StartsWith("./", StringComparison.Ordinal) || target.StartsWith("../", StringComparison.Ordinal) ? ResolveFilePath(Path.GetFullPath(Path.Combine(dir, target))) : ResolveBareSpecifier(target, dir); } } break; } var parent = Path.GetDirectoryName(dir); if (parent == dir) { break; } dir = parent; } return null; } private string? ResolveInPackage(string pkgDir, string subpath, HashSet conditions) { var pkgJsonPath = Path.Combine(pkgDir, "package.json"); if (File.Exists(pkgJsonPath)) { using var doc = JsonDocument.Parse(File.ReadAllText(pkgJsonPath)); var root = doc.RootElement; if (root.TryGetProperty("exports", out var exportsEl)) { var target = MatchExportsOrImports(exportsEl, subpath, conditions); if (target is not null) { var fullTarget = Path.GetFullPath(Path.Combine(pkgDir, target)); return ResolveFilePath(fullTarget); } // If exports is defined and doesn't match, still allow package.json if (subpath == "./package.json") { return pkgJsonPath; } return null; } if (subpath == ".") { if (root.TryGetProperty("module", out var moduleEl) && moduleEl.ValueKind == JsonValueKind.String) { var modulePath = ResolveFilePath(Path.GetFullPath(Path.Combine(pkgDir, moduleEl.GetString()!))); if (modulePath is not null) return modulePath; } if (root.TryGetProperty("main", out var mainEl) && mainEl.ValueKind == JsonValueKind.String) { var mainPath = ResolveFilePath(Path.GetFullPath(Path.Combine(pkgDir, mainEl.GetString()!))); if (mainPath is not null) return mainPath; } return ResolveFilePath(Path.Combine(pkgDir, "index.js")); } } var relativeSubpath = subpath == "." ? "index.js" : subpath.StartsWith("./", StringComparison.Ordinal) ? subpath[2..] : subpath; return ResolveFilePath(Path.GetFullPath(Path.Combine(pkgDir, relativeSubpath))); } private string? MatchExportsOrImports(JsonElement exportsEl, string subpath, HashSet? conditions = null) { var activeConditions = conditions ?? _conditions; if (exportsEl.ValueKind == JsonValueKind.String) { return subpath == "." ? exportsEl.GetString() : null; } if (exportsEl.ValueKind == JsonValueKind.Array) { foreach (var item in exportsEl.EnumerateArray()) { var resolved = MatchExportsOrImports(item, subpath, activeConditions); if (resolved is not null) return resolved; } return null; } if (exportsEl.ValueKind != JsonValueKind.Object) { return null; } // Check if object is a subpath map (keys start with "." or "#") or a condition map var isSubpathMap = false; foreach (var prop in exportsEl.EnumerateObject()) { if (prop.Name.StartsWith('.') || prop.Name.StartsWith('#')) { isSubpathMap = true; break; } } if (!isSubpathMap) { return subpath == "." ? ResolveConditionObject(exportsEl, activeConditions) : null; } // 1. Exact match if (exportsEl.TryGetProperty(subpath, out var exactTarget)) { return ResolveTarget(exactTarget, null, activeConditions); } // 2. Wildcard pattern match (longest prefix wins per Node spec) string? bestKey = null; JsonElement bestTarget = default; string? bestMatch = null; foreach (var prop in exportsEl.EnumerateObject()) { var starIndex = prop.Name.IndexOf('*'); if (starIndex < 0) continue; var prefix = prop.Name[..starIndex]; var suffix = prop.Name[(starIndex + 1)..]; if (subpath.Length >= prefix.Length + suffix.Length && subpath.StartsWith(prefix, StringComparison.Ordinal) && subpath.EndsWith(suffix, StringComparison.Ordinal)) { if (bestKey is null || prefix.Length > bestKey.IndexOf('*')) { bestKey = prop.Name; bestTarget = prop.Value; bestMatch = subpath[prefix.Length..(subpath.Length - suffix.Length)]; } } } if (bestKey is not null) { return ResolveTarget(bestTarget, bestMatch, activeConditions); } return null; } private string? ResolveTarget(JsonElement target, string? patternMatch, HashSet conditions) { switch (target.ValueKind) { case JsonValueKind.String: var s = target.GetString(); if (s is null) return null; return patternMatch is not null ? s.Replace("*", patternMatch, StringComparison.Ordinal) : s; case JsonValueKind.Array: foreach (var item in target.EnumerateArray()) { var resolved = ResolveTarget(item, patternMatch, conditions); if (resolved is not null) return resolved; } return null; case JsonValueKind.Object: return ResolveConditionObject(target, conditions, patternMatch); default: return null; } } private string? ResolveConditionObject(JsonElement obj, HashSet conditions, string? patternMatch = null) { foreach (var prop in obj.EnumerateObject()) { if (conditions.Contains(prop.Name)) { var resolved = ResolveTarget(prop.Value, patternMatch, conditions); if (resolved is not null) { return resolved; } } } return null; } private static (string PackageName, string Subpath) SplitPackageSpecifier(string specifier) { if (specifier.StartsWith('@')) { var firstSlash = specifier.IndexOf('/'); if (firstSlash < 0) { return (specifier, "."); } var secondSlash = specifier.IndexOf('/', firstSlash + 1); if (secondSlash < 0) { return (specifier, "."); } return (specifier[..secondSlash], "./" + specifier[(secondSlash + 1)..]); } else { var firstSlash = specifier.IndexOf('/'); if (firstSlash < 0) { return (specifier, "."); } return (specifier[..firstSlash], "./" + specifier[(firstSlash + 1)..]); } } private static string? ResolveFilePath(string candidate) { if (File.Exists(candidate)) { return candidate; } string[] extensions = [".mjs", ".js", ".cjs", ".json"]; foreach (var ext in extensions) { var withExt = candidate + ext; if (File.Exists(withExt)) { return withExt; } } if (Directory.Exists(candidate)) { foreach (var ext in extensions) { var indexFile = Path.Combine(candidate, "index" + ext); if (File.Exists(indexFile)) { return indexFile; } } } return null; } }