Skip to content

Commit f7c7757

Browse files
committed
refactor: clean up whitespace and improve script execution in NodeBridge
1 parent 4f6a294 commit f7c7757

File tree

1 file changed

+23
-24
lines changed

1 file changed

+23
-24
lines changed

src/vortex_sdk/bridge.py

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,13 @@
1414

1515
class NodeBridge:
1616
"""Bridge to execute Vortex SDK via Node.js subprocess."""
17-
17+
1818
def __init__(self, sdk_config: Dict[str, Any]):
1919
"""Initialize the Node.js bridge."""
2020
self.sdk_config = sdk_config
2121
self._verify_node()
2222
self._find_sdk()
23-
23+
2424
def _verify_node(self) -> None:
2525
"""Verify Node.js is available."""
2626
try:
@@ -40,15 +40,15 @@ def _verify_node(self) -> None:
4040
"Node.js 18+ is required but not found. "
4141
"Install from https://nodejs.org/"
4242
)
43-
43+
4444
def _find_sdk(self) -> None:
4545
"""Find the npm-installed SDK (local or global)."""
4646
# First check local node_modules in current working directory
4747
sdk_path = Path.cwd() / "node_modules" / "@vortexfi" / "sdk"
48-
48+
4949
if sdk_path.exists():
5050
return # Local installation found
51-
51+
5252
# Check if Node.js can require it (works for global installs too)
5353
try:
5454
test_script = """
@@ -69,38 +69,37 @@ def _find_sdk(self) -> None:
6969
return # SDK is accessible to Node.js (global or local)
7070
except Exception:
7171
pass
72-
72+
7373
# SDK not found anywhere
7474
raise VortexSDKError(
7575
"@vortexfi/sdk not found. Install it with:\n"
7676
" npm install @vortexfi/sdk (local install)\n"
7777
" npm install -g @vortexfi/sdk (global install)"
7878
)
79-
79+
8080
def call_method(self, method: str, *args, timeout: int = 60) -> Any:
8181
"""Call a SDK method via Node.js.
82-
82+
8383
Args:
8484
method: SDK method name
8585
*args: Method arguments
8686
timeout: Timeout in seconds (default 60, use higher for registerRamp)
8787
"""
8888
script = f"""
89+
import {{ VortexSdk }} from "@vortexfi/sdk";
8990
(async () => {{
9091
try {{
9192
// Redirect console.log to stderr to keep stdout clean for JSON only
9293
const originalLog = console.log;
9394
console.log = (...args) => console.error(...args);
94-
95-
const {{ VortexSdk }} = require('@vortexfi/sdk');
96-
95+
9796
const config = {json.dumps(self.sdk_config)};
9897
const sdk = new VortexSdk(config);
99-
98+
10099
const methodArgs = {json.dumps(args)};
101-
100+
102101
const result = await sdk.{method}(...methodArgs);
103-
102+
104103
// Restore console.log and output JSON to stdout
105104
console.log = originalLog;
106105
console.log(JSON.stringify({{ success: true, result }}));
@@ -115,17 +114,17 @@ def call_method(self, method: str, *args, timeout: int = 60) -> Any:
115114
}}
116115
}})();
117116
"""
118-
117+
119118
try:
120119
result = subprocess.run(
121-
["node", "-e", script],
120+
["node", "--input-type=module", "-e", script],
122121
capture_output=True,
123122
text=True,
124123
check=False,
125124
cwd=str(Path.cwd()),
126125
timeout=timeout
127126
)
128-
127+
129128
# Check for errors in stderr
130129
if result.stderr:
131130
# Try to parse as JSON error first
@@ -143,42 +142,42 @@ def call_method(self, method: str, *args, timeout: int = 60) -> Any:
143142
)
144143
except json.JSONDecodeError:
145144
pass
146-
145+
147146
# If returncode is non-zero, treat stderr as error
148147
if result.returncode != 0:
149148
raise VortexSDKError(
150149
f"Node.js process failed (exit code {result.returncode}):\n{result.stderr}"
151150
)
152-
151+
153152
if not result.stdout:
154153
raise VortexSDKError(
155154
f"No output from Node.js process.\n"
156155
f"Exit code: {result.returncode}\n"
157156
f"stderr output:\n{result.stderr or '(empty)'}"
158157
)
159-
158+
160159
# Try to find JSON in stdout (last line that starts with {)
161160
stdout_lines = result.stdout.strip().split('\n')
162161
json_line = None
163162
for line in reversed(stdout_lines):
164163
if line.strip().startswith('{'):
165164
json_line = line
166165
break
167-
166+
168167
if not json_line:
169168
raise VortexSDKError(
170169
f"No JSON response found in stdout.\n"
171170
f"stdout output:\n{result.stdout[:1000]}\n"
172171
f"stderr output:\n{result.stderr[:500] if result.stderr else '(empty)'}"
173172
)
174-
173+
175174
response = json.loads(json_line)
176175
if not response.get('success'):
177176
error_msg = response.get('error', 'Unknown error')
178177
raise VortexSDKError(f"SDK error: {error_msg}")
179-
178+
180179
return response['result']
181-
180+
182181
except subprocess.TimeoutExpired:
183182
raise VortexSDKError(
184183
f"SDK call '{method}' timed out after {timeout}s. "

0 commit comments

Comments
 (0)