|
1 | 1 | using Jering.Javascript.NodeJS; |
2 | 2 | using System; |
3 | 3 | using System.Collections.Generic; |
| 4 | +using System.IO; |
4 | 5 | using System.Linq; |
5 | 6 | using System.Text.Json; |
6 | 7 | using System.Text.RegularExpressions; |
@@ -115,4 +116,51 @@ public async Task InvokeNode_NoOutputs_ReturnNothing() |
115 | 116 | var result = await StaticNodeJSService.InvokeFromStringAsync<JsonElement>(script, null, null, [3, 5], TestCancellationToken); |
116 | 117 | Assert.Throws<KeyNotFoundException>(() => result.GetProperty("result")); |
117 | 118 | } |
| 119 | + |
| 120 | + [Fact] |
| 121 | + public async Task InvokeNode_WithCreateRequire_ResolvesDependencyFromScriptsNodeModules() |
| 122 | + { |
| 123 | + var tempRoot = Path.Combine(Path.GetTempPath(), $"{nameof(NodeJsTests)}-{Guid.NewGuid():N}"); |
| 124 | + var scriptsPath = Path.Combine(tempRoot, "Scripts"); |
| 125 | + var dependencyPath = Path.Combine(scriptsPath, "node_modules", "ob2-test-dependency"); |
| 126 | + |
| 127 | + Directory.CreateDirectory(dependencyPath); |
| 128 | + await File.WriteAllTextAsync( |
| 129 | + Path.Combine(dependencyPath, "index.js"), |
| 130 | + "module.exports = { getValue: () => 'resolved from Scripts/node_modules' };", |
| 131 | + TestCancellationToken); |
| 132 | + |
| 133 | + var virtualScriptPath = Path.Combine(scriptsPath, "__ob2_virtual__.js"); |
| 134 | + var escapedVirtualScriptPath = JsonSerializer.Serialize(virtualScriptPath); |
| 135 | + var script = $$""" |
| 136 | + module.exports = async () => { |
| 137 | + const { createRequire } = require('module'); |
| 138 | + const obRequire = createRequire({{escapedVirtualScriptPath}}); |
| 139 | + return await (async (require) => { |
| 140 | + const dependency = require('ob2-test-dependency'); |
| 141 | + var result = dependency.getValue(); |
| 142 | + var noderesult = { |
| 143 | + 'result': result, |
| 144 | + }; |
| 145 | + return noderesult; |
| 146 | + })(obRequire); |
| 147 | + } |
| 148 | + """; |
| 149 | + |
| 150 | + try |
| 151 | + { |
| 152 | + var result = await StaticNodeJSService.InvokeFromStringAsync<JsonElement>( |
| 153 | + script, |
| 154 | + null, |
| 155 | + null, |
| 156 | + [], |
| 157 | + TestCancellationToken); |
| 158 | + |
| 159 | + Assert.Equal("resolved from Scripts/node_modules", result.GetProperty("result").GetString()); |
| 160 | + } |
| 161 | + finally |
| 162 | + { |
| 163 | + Directory.Delete(tempRoot, recursive: true); |
| 164 | + } |
| 165 | + } |
118 | 166 | } |
0 commit comments