forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionRunner.tsx
More file actions
345 lines (318 loc) · 17.4 KB
/
Copy pathCollectionRunner.tsx
File metadata and controls
345 lines (318 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import React, { useState, useMemo, useRef } from 'react';
import { Play, Pause, RotateCcw, CheckCircle2, XCircle, Clock, AlertTriangle, FileText, ArrowRight, Square } from 'lucide-react';
import { useAppStore } from '@/lib/store';
import { useWallet } from '@/wallet';
import { AssertionResult, CollectionNode, RequestItem, RequestType } from '../types';
import { executeSuiRpc, simulateMoveCall, SuiRpcError } from '../services/suiService';
import { evaluateAssertions } from '@/lib/assertionsEngine';
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000000000000000000000000000';
const resolveVariables = (raw: string, vars: { key: string; value: string }[]): string =>
vars.reduce((str, v) => str.replaceAll(`{{${v.key}}}`, v.value), raw);
const resolveRequestVars = (request: RequestItem, vars: { key: string; value: string }[]): RequestItem => {
if (!vars.length) return request;
try {
if (request.type === RequestType.RPC) {
const raw = JSON.stringify(request.rpcParams.params);
const resolved = resolveVariables(raw, vars);
return {
...request,
rpcParams: {
...request.rpcParams,
method: resolveVariables(request.rpcParams.method, vars),
params: JSON.parse(resolved),
},
};
}
const mp = request.moveParams;
return {
...request,
moveParams: {
...mp,
packageId: resolveVariables(mp.packageId, vars),
module: resolveVariables(mp.module, vars),
function: resolveVariables(mp.function, vars),
typeArguments: mp.typeArguments.map((t: string) => resolveVariables(t, vars)),
arguments: mp.arguments.map((a) => ({
...a,
value: resolveVariables(String(a.value), vars),
})),
},
};
} catch {
return request;
}
};
interface CollectionRunnerProps {
collectionId?: string;
}
export const CollectionRunner: React.FC<CollectionRunnerProps> = ({ collectionId }) => {
const { collections, currentWorkspaceId, network, envVariables } = useAppStore();
const { currentWallet } = useWallet();
const connectedAddress = currentWallet?.family === 'sui' ? currentWallet.address : null;
const [isRunning, setIsRunning] = useState(false);
const [progress, setProgress] = useState(0);
const [currentReqIndex, setCurrentReqIndex] = useState(-1);
const abortRef = useRef(false);
// Filter collections by current workspace
const workspaceCollections = useMemo(() => {
return collections.filter(c => !c.workspaceId || c.workspaceId === currentWorkspaceId);
}, [collections, currentWorkspaceId]);
// Helper to find collection by ID recursively within filtered list
const findCollection = (nodes: CollectionNode[], id: string): CollectionNode | null => {
for (const node of nodes) {
if (node.id === id) return node;
if (node.children) {
const found = findCollection(node.children, id);
if (found) return found;
}
}
return null;
};
// Flatten requests from collection hierarchy
const getRequests = (node: CollectionNode): any[] => {
let reqs: any[] = [];
if (node.type === 'request' && node.requestData) {
reqs.push({ ...node.requestData, status: 'pending', duration: 0 });
}
if (node.children) {
node.children.forEach(c => reqs = [...reqs, ...getRequests(c)]);
}
return reqs;
};
const targetCollection = collectionId ? findCollection(workspaceCollections, collectionId) : null;
// Default to first collection if none specified
const runSource = targetCollection || (!collectionId && workspaceCollections.length > 0 ? workspaceCollections[0] : null);
const [runList, setRunList] = useState<any[]>(runSource ? getRequests(runSource) : []);
const [prevRunSource, setPrevRunSource] = useState(runSource);
// Re-initialize the run list whenever the targeted collection changes
if (runSource !== prevRunSource) {
setPrevRunSource(runSource);
setRunList(runSource ? getRequests(runSource) : []);
}
const handleRun = async () => {
abortRef.current = false;
setIsRunning(true);
setProgress(0);
setCurrentReqIndex(0);
// Snapshot the run list at start so mutations don't shift indices
const snapshot = [...runList];
const activeEnvVars = envVariables.filter(
v => v.enabled && (!v.network || v.network === 'all' || v.network === network)
);
for (let idx = 0; idx < snapshot.length; idx++) {
if (abortRef.current) break;
setCurrentReqIndex(idx);
const req = snapshot[idx] as RequestItem;
const resolved = resolveRequestVars(req, activeEnvVars);
const startTime = performance.now();
try {
if (resolved.type === RequestType.TRANSACTION) {
const { packageId, module, function: func, typeArguments, arguments: args } = resolved.moveParams;
const simulationSender = connectedAddress || ZERO_ADDRESS;
const { result, status, duration } = await simulateMoveCall(
network,
simulationSender,
packageId,
module,
func,
typeArguments,
args,
);
const testResults = evaluateAssertions(req.tests, {
requestType: resolved.type,
httpStatus: status,
duration,
result,
sender: simulationSender,
});
setRunList((prev) =>
abortRef.current
? prev
: prev.map((r, i) => (i === idx ? { ...r, status: 'success' as const, duration, httpStatus: status, testResults } : r)),
);
} else {
const { result, status, duration } = await executeSuiRpc(
network,
resolved.rpcParams.method,
resolved.rpcParams.params,
);
const testResults = evaluateAssertions(req.tests, {
requestType: resolved.type,
httpStatus: status,
duration,
result,
});
setRunList((prev) =>
abortRef.current
? prev
: prev.map((r, i) =>
i === idx ? { ...r, status: 'success' as const, duration, httpStatus: status, response: result, testResults } : r,
),
);
}
} catch (error) {
const duration = Math.round(performance.now() - startTime);
const rpcError = error instanceof SuiRpcError ? error : null;
const errorMessage = error instanceof Error && error.message.trim() ? error.message : 'Request failed';
const testResults = evaluateAssertions(req.tests, {
requestType: resolved.type,
httpStatus: rpcError?.status ?? 0,
duration,
error: errorMessage,
});
setRunList((prev) =>
abortRef.current
? prev
: prev.map((r, i) =>
i === idx
? {
...r,
status: 'error' as const,
duration,
httpStatus: rpcError?.status ?? 0,
errorMessage,
testResults,
}
: r,
),
);
}
setProgress(((idx + 1) / snapshot.length) * 100);
}
setIsRunning(false);
setCurrentReqIndex(-1);
};
const handleStop = () => {
abortRef.current = true;
};
const handleReset = () => {
abortRef.current = true;
setRunList((prev) => prev.map((r) => ({ ...r, status: 'pending', duration: 0, testResults: undefined })));
setProgress(0);
setCurrentReqIndex(-1);
};
if (!targetCollection && !collectionId && workspaceCollections.length === 0) {
return <div className="p-10 text-slate-500">No collections found in this workspace. Create one in the sidebar to start running.</div>;
}
const collectionName = targetCollection ? targetCollection.name : (workspaceCollections[0]?.name || "Collection");
return (
<div className="h-full bg-near-black flex flex-col font-sans">
{/* Header */}
<div className="border-b border-white/5 bg-dark-indigo-glow/50 p-6">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-xl font-bold text-white mb-1 flex items-center gap-2">
<Play size={20} className="text-electric-violet"/> Collection Runner
</h1>
<p className="text-xs text-slate-400">Executing sequence: <span className="text-white font-bold">{collectionName}</span></p>
</div>
<div className="flex gap-3">
{isRunning && (
<button onClick={handleStop} className="px-4 py-2 bg-red-900/30 hover:bg-red-900/50 text-red-400 text-xs font-bold rounded flex items-center gap-2 transition-colors border border-red-900/30">
<Square size={14}/> Stop
</button>
)}
<button onClick={handleReset} className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-bold rounded flex items-center gap-2 transition-colors">
<RotateCcw size={14}/> Reset
</button>
<button
onClick={handleRun}
disabled={isRunning || runList.length === 0}
className={`px-6 py-2 bg-electric-violet hover:bg-electric-violet text-white text-xs font-bold rounded shadow-lg shadow-sui-900/20 flex items-center gap-2 transition-all ${isRunning ? 'opacity-50 cursor-not-allowed' : ''}`}
>
{isRunning ? <Pause size={14}/> : <Play size={14}/>}
{isRunning ? 'Running...' : 'Run Collection'}
</button>
</div>
</div>
{/* Progress Bar */}
<div className="h-2 bg-slate-800 rounded-full overflow-hidden mb-2">
<div
className="h-full bg-electric-violet transition-all duration-300 ease-out relative"
style={{ width: `${progress}%` }}
>
<div className="absolute right-0 top-0 bottom-0 w-2 bg-white/50 animate-pulse"></div>
</div>
</div>
<div className="flex justify-between text-[10px] font-bold text-slate-500 uppercase tracking-wider">
<span>
{runList.filter(r => r.status === 'success').length} / {runList.length} Completed
{runList.some(r => r.status === 'error') && (
<span className="text-red-400 ml-2">· {runList.filter(r => r.status === 'error').length} Failed</span>
)}
</span>
<span>{Math.round(progress)}%</span>
</div>
</div>
{/* List */}
<div className="flex-1 overflow-y-auto p-6 custom-scrollbar">
<div className="border border-white/5 rounded-xl bg-dark-indigo-glow overflow-hidden shadow-xl">
<table className="w-full text-left">
<thead className="bg-near-black text-[10px] font-black uppercase text-slate-500 tracking-widest border-b border-white/5">
<tr>
<th className="px-6 py-3 w-12">#</th>
<th className="px-6 py-3">Request Name</th>
<th className="px-6 py-3">Method</th>
<th className="px-6 py-3">Status</th>
<th className="px-6 py-3">Tests</th>
<th className="px-6 py-3">Time</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-800 text-sm">
{runList.map((req, i) => (
<tr key={i} className={`transition-colors ${i === currentReqIndex ? 'bg-sui-900/10' : 'hover:bg-white/5'}`}>
<td className="px-6 py-4 text-slate-600 font-mono text-xs">{i + 1}</td>
<td className="px-6 py-4 font-bold text-slate-300 flex items-center gap-2">
{req.name}
</td>
<td className="px-6 py-4 font-mono text-xs text-slate-500">{req.rpcParams?.method || req.txType || 'Transaction'}</td>
<td className="px-6 py-4">
{req.status === 'error' ? (
<span className="inline-flex items-center gap-1.5 text-red-400 text-xs font-bold bg-red-900/10 px-2 py-1 rounded border border-red-900/20" title={req.errorMessage}>
<XCircle size={14}/> {req.httpStatus || 'ERR'}
</span>
) : req.status === 'success' ? (
<span className="inline-flex items-center gap-1.5 text-emerald-400 text-xs font-bold bg-emerald-900/10 px-2 py-1 rounded border border-emerald-900/20">
<CheckCircle2 size={14}/> {req.httpStatus || 200} OK
</span>
) : i === currentReqIndex ? (
<span className="inline-flex items-center gap-1.5 text-amber-400 text-xs font-bold bg-amber-900/10 px-2 py-1 rounded border border-amber-900/20">
<Clock size={14} className="animate-spin"/> Running
</span>
) : (
<span className="text-slate-600 text-xs italic flex items-center gap-1"><Clock size={12}/> Pending</span>
)}
</td>
<td className="px-6 py-4">
{req.testResults && req.testResults.length > 0 ? (
<span
className={`inline-flex items-center gap-1.5 text-xs font-bold px-2 py-1 rounded border ${
req.testResults.every((r: AssertionResult) => r.passed)
? 'text-emerald-400 bg-emerald-900/10 border-emerald-900/20'
: 'text-red-400 bg-red-900/10 border-red-900/20'
}`}
title={req.testResults.map((r: AssertionResult) => r.message).join('\n')}
>
{req.testResults.filter((r: AssertionResult) => r.passed).length}/{req.testResults.length}
</span>
) : (
<span className="text-slate-600 text-xs italic">—</span>
)}
</td>
<td className="px-6 py-4 font-mono text-xs text-slate-400">
{req.duration > 0 ? `${req.duration}ms` : '-'}
</td>
</tr>
))}
</tbody>
</table>
{runList.length === 0 && (
<div className="p-8 text-center text-slate-500 text-sm italic">
Empty collection. Add requests to "{collectionName}" to see them here.
</div>
)}
</div>
</div>
</div>
);
};