@tracecode/harness 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/LICENSE +674 -0
  3. package/README.md +266 -0
  4. package/dist/browser.cjs +1352 -0
  5. package/dist/browser.cjs.map +1 -0
  6. package/dist/browser.d.cts +49 -0
  7. package/dist/browser.d.ts +49 -0
  8. package/dist/browser.js +1317 -0
  9. package/dist/browser.js.map +1 -0
  10. package/dist/cli.cjs +70 -0
  11. package/dist/cli.cjs.map +1 -0
  12. package/dist/cli.d.cts +1 -0
  13. package/dist/cli.d.ts +1 -0
  14. package/dist/cli.js +70 -0
  15. package/dist/cli.js.map +1 -0
  16. package/dist/core.cjs +286 -0
  17. package/dist/core.cjs.map +1 -0
  18. package/dist/core.d.cts +69 -0
  19. package/dist/core.d.ts +69 -0
  20. package/dist/core.js +254 -0
  21. package/dist/core.js.map +1 -0
  22. package/dist/index.cjs +2603 -0
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.cts +6 -0
  25. package/dist/index.d.ts +6 -0
  26. package/dist/index.js +2538 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/internal/browser.cjs +647 -0
  29. package/dist/internal/browser.cjs.map +1 -0
  30. package/dist/internal/browser.d.cts +143 -0
  31. package/dist/internal/browser.d.ts +143 -0
  32. package/dist/internal/browser.js +617 -0
  33. package/dist/internal/browser.js.map +1 -0
  34. package/dist/javascript.cjs +549 -0
  35. package/dist/javascript.cjs.map +1 -0
  36. package/dist/javascript.d.cts +11 -0
  37. package/dist/javascript.d.ts +11 -0
  38. package/dist/javascript.js +518 -0
  39. package/dist/javascript.js.map +1 -0
  40. package/dist/python.cjs +744 -0
  41. package/dist/python.cjs.map +1 -0
  42. package/dist/python.d.cts +97 -0
  43. package/dist/python.d.ts +97 -0
  44. package/dist/python.js +698 -0
  45. package/dist/python.js.map +1 -0
  46. package/dist/runtime-types-C7d1LFbx.d.ts +85 -0
  47. package/dist/runtime-types-Dvgn07z9.d.cts +85 -0
  48. package/dist/types-Bzr1Ohcf.d.cts +96 -0
  49. package/dist/types-Bzr1Ohcf.d.ts +96 -0
  50. package/package.json +89 -0
  51. package/workers/javascript/javascript-worker.js +2918 -0
  52. package/workers/python/generated-python-harness-snippets.js +20 -0
  53. package/workers/python/pyodide-worker.js +1197 -0
  54. package/workers/python/runtime-core.js +1529 -0
  55. package/workers/vendor/typescript.js +200276 -0
@@ -0,0 +1,1317 @@
1
+ // packages/harness-browser/src/javascript-worker-client.ts
2
+ var EXECUTION_TIMEOUT_MS = 7e3;
3
+ var INTERVIEW_MODE_TIMEOUT_MS = 5e3;
4
+ var TRACING_TIMEOUT_MS = 7e3;
5
+ var INIT_TIMEOUT_MS = 1e4;
6
+ var MESSAGE_TIMEOUT_MS = 12e3;
7
+ var WORKER_READY_TIMEOUT_MS = 1e4;
8
+ var JavaScriptWorkerClient = class {
9
+ constructor(options) {
10
+ this.options = options;
11
+ this.debug = options.debug ?? process.env.NODE_ENV === "development";
12
+ }
13
+ worker = null;
14
+ pendingMessages = /* @__PURE__ */ new Map();
15
+ messageId = 0;
16
+ isInitializing = false;
17
+ initPromise = null;
18
+ workerReadyPromise = null;
19
+ workerReadyResolve = null;
20
+ workerReadyReject = null;
21
+ debug;
22
+ isSupported() {
23
+ return typeof Worker !== "undefined";
24
+ }
25
+ getWorker() {
26
+ if (this.worker) return this.worker;
27
+ if (!this.isSupported()) {
28
+ throw new Error("Web Workers are not supported in this environment");
29
+ }
30
+ this.workerReadyPromise = new Promise((resolve, reject) => {
31
+ this.workerReadyResolve = resolve;
32
+ this.workerReadyReject = (error) => reject(error);
33
+ });
34
+ const workerUrl = this.debug && !this.options.workerUrl.includes("?") ? `${this.options.workerUrl}?dev=${Date.now()}` : this.options.workerUrl;
35
+ this.worker = new Worker(workerUrl);
36
+ this.worker.onmessage = (event) => {
37
+ const { id, type, payload } = event.data;
38
+ if (type === "worker-ready") {
39
+ this.workerReadyResolve?.();
40
+ this.workerReadyResolve = null;
41
+ this.workerReadyReject = null;
42
+ if (this.debug) console.log("[JavaScriptWorkerClient] worker-ready");
43
+ return;
44
+ }
45
+ if (id) {
46
+ const pending = this.pendingMessages.get(id);
47
+ if (!pending) return;
48
+ this.pendingMessages.delete(id);
49
+ if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);
50
+ if (type === "error") {
51
+ pending.reject(new Error(payload.error));
52
+ return;
53
+ }
54
+ pending.resolve(payload);
55
+ }
56
+ };
57
+ this.worker.onerror = (error) => {
58
+ console.error("[JavaScriptWorkerClient] Worker error:", error);
59
+ const workerError = new Error("Worker error");
60
+ this.workerReadyReject?.(workerError);
61
+ this.workerReadyResolve = null;
62
+ this.workerReadyReject = null;
63
+ for (const [id, pending] of this.pendingMessages) {
64
+ if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);
65
+ pending.reject(workerError);
66
+ this.pendingMessages.delete(id);
67
+ }
68
+ };
69
+ return this.worker;
70
+ }
71
+ async waitForWorkerReady() {
72
+ const readyPromise = this.workerReadyPromise;
73
+ if (!readyPromise) return;
74
+ await new Promise((resolve, reject) => {
75
+ let settled = false;
76
+ const timeoutId = globalThis.setTimeout(() => {
77
+ if (settled) return;
78
+ settled = true;
79
+ const timeoutError = new Error(
80
+ `JavaScript worker failed to initialize in time (${Math.round(WORKER_READY_TIMEOUT_MS / 1e3)}s)`
81
+ );
82
+ this.terminateAndReset(timeoutError);
83
+ reject(timeoutError);
84
+ }, WORKER_READY_TIMEOUT_MS);
85
+ readyPromise.then(() => {
86
+ if (settled) return;
87
+ settled = true;
88
+ globalThis.clearTimeout(timeoutId);
89
+ resolve();
90
+ }).catch((error) => {
91
+ if (settled) return;
92
+ settled = true;
93
+ globalThis.clearTimeout(timeoutId);
94
+ reject(error instanceof Error ? error : new Error(String(error)));
95
+ });
96
+ });
97
+ }
98
+ async sendMessage(type, payload, timeoutMs = MESSAGE_TIMEOUT_MS) {
99
+ const worker = this.getWorker();
100
+ await this.waitForWorkerReady();
101
+ const id = String(++this.messageId);
102
+ return new Promise((resolve, reject) => {
103
+ this.pendingMessages.set(id, {
104
+ resolve,
105
+ reject
106
+ });
107
+ const timeoutId = globalThis.setTimeout(() => {
108
+ const pending2 = this.pendingMessages.get(id);
109
+ if (!pending2) return;
110
+ this.pendingMessages.delete(id);
111
+ pending2.reject(new Error(`Worker request timed out: ${type}`));
112
+ }, timeoutMs);
113
+ const pending = this.pendingMessages.get(id);
114
+ if (pending) pending.timeoutId = timeoutId;
115
+ worker.postMessage({ id, type, payload });
116
+ });
117
+ }
118
+ async executeWithTimeout(executor, timeoutMs) {
119
+ return new Promise((resolve, reject) => {
120
+ let settled = false;
121
+ const timeoutId = globalThis.setTimeout(() => {
122
+ if (settled) return;
123
+ settled = true;
124
+ this.terminateAndReset();
125
+ reject(
126
+ new Error(
127
+ `Execution timed out (possible infinite loop). Code execution was stopped after ${Math.round(timeoutMs / 1e3)} seconds.`
128
+ )
129
+ );
130
+ }, timeoutMs);
131
+ executor().then((result) => {
132
+ if (settled) return;
133
+ settled = true;
134
+ globalThis.clearTimeout(timeoutId);
135
+ resolve(result);
136
+ }).catch((error) => {
137
+ if (settled) return;
138
+ settled = true;
139
+ globalThis.clearTimeout(timeoutId);
140
+ reject(error);
141
+ });
142
+ });
143
+ }
144
+ terminateAndReset(reason = new Error("Worker was terminated")) {
145
+ this.workerReadyReject?.(reason);
146
+ if (this.worker) {
147
+ this.worker.terminate();
148
+ this.worker = null;
149
+ }
150
+ this.initPromise = null;
151
+ this.isInitializing = false;
152
+ this.workerReadyPromise = null;
153
+ this.workerReadyResolve = null;
154
+ this.workerReadyReject = null;
155
+ for (const [, pending] of this.pendingMessages) {
156
+ if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);
157
+ pending.reject(reason);
158
+ }
159
+ this.pendingMessages.clear();
160
+ }
161
+ async init() {
162
+ if (this.initPromise) return this.initPromise;
163
+ if (this.isInitializing) {
164
+ await new Promise((resolve) => globalThis.setTimeout(resolve, 100));
165
+ return this.init();
166
+ }
167
+ this.isInitializing = true;
168
+ this.initPromise = this.sendMessage("init", void 0, INIT_TIMEOUT_MS);
169
+ try {
170
+ return await this.initPromise;
171
+ } catch (error) {
172
+ this.initPromise = null;
173
+ throw error;
174
+ } finally {
175
+ this.isInitializing = false;
176
+ }
177
+ }
178
+ async executeWithTracing(code, functionName, inputs, options, executionStyle = "function", language = "javascript") {
179
+ await this.init();
180
+ return this.executeWithTimeout(
181
+ () => this.sendMessage(
182
+ "execute-with-tracing",
183
+ {
184
+ code,
185
+ functionName,
186
+ inputs,
187
+ options,
188
+ executionStyle,
189
+ language
190
+ },
191
+ TRACING_TIMEOUT_MS + 2e3
192
+ ),
193
+ TRACING_TIMEOUT_MS
194
+ );
195
+ }
196
+ async executeCode(code, functionName, inputs, executionStyle = "function", language = "javascript") {
197
+ await this.init();
198
+ return this.executeWithTimeout(
199
+ () => this.sendMessage(
200
+ "execute-code",
201
+ {
202
+ code,
203
+ functionName,
204
+ inputs,
205
+ executionStyle,
206
+ language
207
+ },
208
+ EXECUTION_TIMEOUT_MS + 2e3
209
+ ),
210
+ EXECUTION_TIMEOUT_MS
211
+ );
212
+ }
213
+ async executeCodeInterviewMode(code, functionName, inputs, executionStyle = "function", language = "javascript") {
214
+ await this.init();
215
+ try {
216
+ const result = await this.executeWithTimeout(
217
+ () => this.sendMessage(
218
+ "execute-code-interview",
219
+ {
220
+ code,
221
+ functionName,
222
+ inputs,
223
+ executionStyle,
224
+ language
225
+ },
226
+ INTERVIEW_MODE_TIMEOUT_MS + 2e3
227
+ ),
228
+ INTERVIEW_MODE_TIMEOUT_MS
229
+ );
230
+ if (!result.success && result.error) {
231
+ const normalized = result.error.toLowerCase();
232
+ const isTimeoutOrResourceLimit = normalized.includes("timed out") || normalized.includes("infinite loop") || normalized.includes("line-limit") || normalized.includes("single-line-limit") || normalized.includes("recursion-limit") || normalized.includes("trace-limit") || normalized.includes("line events") || normalized.includes("trace steps") || normalized.includes("call depth");
233
+ if (isTimeoutOrResourceLimit) {
234
+ return {
235
+ success: false,
236
+ output: null,
237
+ error: "Time Limit Exceeded",
238
+ consoleOutput: result.consoleOutput ?? []
239
+ };
240
+ }
241
+ }
242
+ return result;
243
+ } catch {
244
+ return {
245
+ success: false,
246
+ output: null,
247
+ error: "Time Limit Exceeded",
248
+ consoleOutput: []
249
+ };
250
+ }
251
+ }
252
+ terminate() {
253
+ this.terminateAndReset();
254
+ }
255
+ };
256
+
257
+ // packages/harness-core/src/trace-contract.ts
258
+ var RUNTIME_TRACE_CONTRACT_SCHEMA_VERSION = "2026-03-07";
259
+ var TRACE_EVENTS = /* @__PURE__ */ new Set([
260
+ "line",
261
+ "call",
262
+ "return",
263
+ "exception",
264
+ "timeout",
265
+ "stdout"
266
+ ]);
267
+ var TRACE_ACCESS_KINDS = /* @__PURE__ */ new Set([
268
+ "indexed-read",
269
+ "indexed-write",
270
+ "cell-read",
271
+ "cell-write",
272
+ "mutating-call"
273
+ ]);
274
+ function normalizeLineNumber(value, fallback = 1) {
275
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
276
+ const normalized = Math.floor(value);
277
+ return normalized > 0 ? normalized : fallback;
278
+ }
279
+ function normalizeOutputLineCount(value) {
280
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
281
+ const normalized = Math.floor(value);
282
+ return normalized >= 0 ? normalized : void 0;
283
+ }
284
+ function normalizeEvent(value) {
285
+ if (typeof value === "string" && TRACE_EVENTS.has(value)) {
286
+ return value;
287
+ }
288
+ return "line";
289
+ }
290
+ function normalizeAccessKind(value) {
291
+ if (typeof value === "string" && TRACE_ACCESS_KINDS.has(value)) {
292
+ return value;
293
+ }
294
+ return null;
295
+ }
296
+ function normalizeFunctionName(value) {
297
+ if (typeof value === "string" && value.length > 0) return value;
298
+ return "<module>";
299
+ }
300
+ function normalizeKind(value) {
301
+ if (value === "map" || value === "set" || value === "hashmap") {
302
+ return value;
303
+ }
304
+ return "hashmap";
305
+ }
306
+ function normalizeObjectKind(value) {
307
+ if (value === "hashmap" || value === "map" || value === "set" || value === "tree" || value === "linked-list" || value === "graph-adjacency") {
308
+ return value;
309
+ }
310
+ return null;
311
+ }
312
+ function normalizeScalar(value) {
313
+ if (value === null || value === void 0) return value;
314
+ if (typeof value === "string" || typeof value === "boolean") return value;
315
+ if (typeof value === "number") return Number.isFinite(value) ? value : String(value);
316
+ if (typeof value === "bigint") {
317
+ const asNumber = Number(value);
318
+ return Number.isSafeInteger(asNumber) ? asNumber : String(value);
319
+ }
320
+ if (typeof value === "function") return "<function>";
321
+ return null;
322
+ }
323
+ function normalizeUnknown(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
324
+ if (depth > 48) return "<max depth>";
325
+ const scalar = normalizeScalar(value);
326
+ if (scalar !== null || value === null || value === void 0) {
327
+ return scalar;
328
+ }
329
+ if (Array.isArray(value)) {
330
+ return value.map((item) => {
331
+ if (item === void 0) return null;
332
+ return normalizeUnknown(item, depth + 1, seen);
333
+ });
334
+ }
335
+ if (typeof value === "object" && value) {
336
+ if (seen.has(value)) return "<cycle>";
337
+ seen.add(value);
338
+ const normalized = {};
339
+ for (const key of Object.keys(value).sort()) {
340
+ const child = value[key];
341
+ if (child === void 0) continue;
342
+ normalized[key] = normalizeUnknown(child, depth + 1, seen);
343
+ }
344
+ seen.delete(value);
345
+ return normalized;
346
+ }
347
+ return String(value);
348
+ }
349
+ function normalizeAccesses(accesses) {
350
+ if (!Array.isArray(accesses) || accesses.length === 0) {
351
+ return void 0;
352
+ }
353
+ const normalized = accesses.map((access) => {
354
+ const variable = typeof access?.variable === "string" && access.variable.length > 0 ? access.variable : "";
355
+ const kind = normalizeAccessKind(access?.kind);
356
+ if (!variable || !kind) {
357
+ return null;
358
+ }
359
+ const indices = Array.isArray(access?.indices) ? access.indices.map(
360
+ (index) => typeof index === "number" && Number.isFinite(index) ? Math.floor(index) : null
361
+ ).filter((index) => index !== null) : void 0;
362
+ const pathDepth = access?.pathDepth === 1 || access?.pathDepth === 2 ? access.pathDepth : void 0;
363
+ const method = typeof access?.method === "string" && access.method.length > 0 ? access.method : void 0;
364
+ const payload = {
365
+ variable,
366
+ kind
367
+ };
368
+ if (indices && indices.length > 0) {
369
+ payload.indices = indices;
370
+ }
371
+ if (pathDepth !== void 0) {
372
+ payload.pathDepth = pathDepth;
373
+ }
374
+ if (method) {
375
+ payload.method = method;
376
+ }
377
+ return payload;
378
+ }).filter((access) => access !== null);
379
+ return normalized.length > 0 ? normalized : void 0;
380
+ }
381
+ function normalizeRecord(value) {
382
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
383
+ return normalizeUnknown(value);
384
+ }
385
+ function normalizeCallStackFrame(frame) {
386
+ return {
387
+ function: normalizeFunctionName(frame?.function),
388
+ line: normalizeLineNumber(frame?.line, 1),
389
+ args: normalizeRecord(frame?.args)
390
+ };
391
+ }
392
+ function normalizeVisualizationPayload(payload) {
393
+ const hashMaps = Array.isArray(payload?.hashMaps) ? payload.hashMaps.map((entry) => ({
394
+ name: typeof entry?.name === "string" ? entry.name : "",
395
+ kind: normalizeKind(entry?.kind),
396
+ entries: Array.isArray(entry?.entries) ? entry.entries.map((item) => ({
397
+ key: normalizeUnknown(item?.key),
398
+ value: normalizeUnknown(item?.value),
399
+ ...item?.highlight ? { highlight: true } : {}
400
+ })) : [],
401
+ ...entry?.highlightedKey !== void 0 ? { highlightedKey: normalizeUnknown(entry.highlightedKey) } : {},
402
+ ...entry?.deletedKey !== void 0 ? { deletedKey: normalizeUnknown(entry.deletedKey) } : {}
403
+ })).sort((a, b) => `${a.name}:${a.kind}`.localeCompare(`${b.name}:${b.kind}`)) : [];
404
+ const objectKinds = payload?.objectKinds && typeof payload.objectKinds === "object" ? Object.fromEntries(
405
+ Object.entries(payload.objectKinds).filter(([name]) => typeof name === "string" && name.length > 0).map(([name, kind]) => [name, normalizeObjectKind(kind)]).filter((entry) => entry[1] !== null).sort((a, b) => a[0].localeCompare(b[0]))
406
+ ) : void 0;
407
+ if (hashMaps.length === 0 && (!objectKinds || Object.keys(objectKinds).length === 0)) {
408
+ return void 0;
409
+ }
410
+ return {
411
+ ...hashMaps.length > 0 ? { hashMaps } : {},
412
+ ...objectKinds && Object.keys(objectKinds).length > 0 ? { objectKinds } : {}
413
+ };
414
+ }
415
+ function normalizeTraceStep(step) {
416
+ const normalizedStdoutCount = normalizeOutputLineCount(step?.stdoutLineCount);
417
+ const normalizedVisualization = normalizeVisualizationPayload(step?.visualization);
418
+ const normalizedAccesses = normalizeAccesses(step?.accesses);
419
+ return {
420
+ event: normalizeEvent(step?.event),
421
+ line: normalizeLineNumber(step?.line, 1),
422
+ function: normalizeFunctionName(step?.function),
423
+ variables: normalizeRecord(step?.variables),
424
+ ...Array.isArray(step?.callStack) && step.callStack.length > 0 ? { callStack: step.callStack.map(normalizeCallStackFrame) } : {},
425
+ ...normalizedAccesses ? { accesses: normalizedAccesses } : {},
426
+ ...step?.returnValue !== void 0 ? { returnValue: normalizeUnknown(step.returnValue) } : {},
427
+ ...normalizedStdoutCount !== void 0 ? { stdoutLineCount: normalizedStdoutCount } : {},
428
+ ...normalizedVisualization ? { visualization: normalizedVisualization } : {}
429
+ };
430
+ }
431
+ function normalizeRuntimeTraceContract(language, result) {
432
+ const normalizedTrace = Array.isArray(result.trace) ? result.trace.map(normalizeTraceStep) : [];
433
+ const lineEventCount = typeof result.lineEventCount === "number" && Number.isFinite(result.lineEventCount) ? Math.floor(result.lineEventCount) : normalizedTrace.filter((step) => step.event === "line").length;
434
+ const normalizedConsole = Array.isArray(result.consoleOutput) ? result.consoleOutput.map((line) => String(line)) : [];
435
+ return {
436
+ schemaVersion: RUNTIME_TRACE_CONTRACT_SCHEMA_VERSION,
437
+ language,
438
+ success: Boolean(result.success),
439
+ ...Object.prototype.hasOwnProperty.call(result, "output") ? { output: normalizeUnknown(result.output) } : {},
440
+ ...typeof result.error === "string" && result.error.length > 0 ? { error: result.error } : {},
441
+ ...typeof result.errorLine === "number" && Number.isFinite(result.errorLine) ? { errorLine: Math.floor(result.errorLine) } : {},
442
+ consoleOutput: normalizedConsole,
443
+ trace: normalizedTrace,
444
+ ...result.traceLimitExceeded !== void 0 ? { traceLimitExceeded: Boolean(result.traceLimitExceeded) } : {},
445
+ ...typeof result.timeoutReason === "string" && result.timeoutReason.length > 0 ? { timeoutReason: result.timeoutReason } : {},
446
+ lineEventCount: Math.max(0, lineEventCount),
447
+ traceStepCount: normalizedTrace.length
448
+ };
449
+ }
450
+
451
+ // packages/harness-core/src/trace-adapters/shared.ts
452
+ function denormalizeCallStackFrame(frame) {
453
+ return {
454
+ function: frame.function,
455
+ line: frame.line,
456
+ args: frame.args
457
+ };
458
+ }
459
+ function denormalizeTraceStep(step) {
460
+ return {
461
+ line: step.line,
462
+ event: step.event,
463
+ variables: step.variables,
464
+ function: step.function,
465
+ ...step.callStack ? { callStack: step.callStack.map(denormalizeCallStackFrame) } : {},
466
+ ...step.accesses ? { accesses: step.accesses } : {},
467
+ ...step.returnValue !== void 0 ? { returnValue: step.returnValue } : {},
468
+ ...step.stdoutLineCount !== void 0 ? { stdoutLineCount: step.stdoutLineCount } : {},
469
+ ...step.visualization ? { visualization: step.visualization } : {}
470
+ };
471
+ }
472
+ function adaptTraceExecutionResult(language, result) {
473
+ const normalized = normalizeRuntimeTraceContract(language, result);
474
+ const adaptedTrace = normalized.trace.map(denormalizeTraceStep);
475
+ return {
476
+ success: normalized.success,
477
+ ...Object.prototype.hasOwnProperty.call(normalized, "output") ? { output: normalized.output } : {},
478
+ ...normalized.error ? { error: normalized.error } : {},
479
+ ...normalized.errorLine !== void 0 ? { errorLine: normalized.errorLine } : {},
480
+ trace: adaptedTrace,
481
+ executionTimeMs: typeof result.executionTimeMs === "number" && Number.isFinite(result.executionTimeMs) ? result.executionTimeMs : 0,
482
+ consoleOutput: normalized.consoleOutput,
483
+ ...normalized.traceLimitExceeded !== void 0 ? { traceLimitExceeded: normalized.traceLimitExceeded } : {},
484
+ ...normalized.timeoutReason ? { timeoutReason: normalized.timeoutReason } : {},
485
+ lineEventCount: normalized.lineEventCount,
486
+ traceStepCount: adaptedTrace.length
487
+ };
488
+ }
489
+
490
+ // packages/harness-core/src/trace-adapters/javascript.ts
491
+ function adaptJavaScriptTraceExecutionResult(language, result) {
492
+ return adaptTraceExecutionResult(language, result);
493
+ }
494
+
495
+ // packages/harness-browser/src/runtime-capability-guards.ts
496
+ function isScriptRequest(functionName) {
497
+ if (functionName == null) return true;
498
+ return functionName.trim().length === 0;
499
+ }
500
+ function executionStyleLabel(executionStyle) {
501
+ if (executionStyle === "solution-method") return "solution-method";
502
+ if (executionStyle === "ops-class") return "ops-class";
503
+ return "function";
504
+ }
505
+ function isExecutionStyleSupported(profile, executionStyle) {
506
+ const styles = profile.capabilities.execution.styles;
507
+ if (executionStyle === "solution-method") return styles.solutionMethod;
508
+ if (executionStyle === "ops-class") return styles.opsClass;
509
+ return styles.function;
510
+ }
511
+ function describeRequest(request) {
512
+ if (request === "trace") return "tracing";
513
+ if (request === "interview") return "interview execution";
514
+ return "execution";
515
+ }
516
+ function assertRuntimeRequestSupported(profile, options) {
517
+ if (options.request === "trace" && !profile.capabilities.tracing.supported) {
518
+ throw new Error(`Runtime "${profile.language}" does not support tracing.`);
519
+ }
520
+ if (options.request === "interview" && !profile.capabilities.execution.styles.interviewMode) {
521
+ throw new Error(`Runtime "${profile.language}" does not support interview execution.`);
522
+ }
523
+ if (!isExecutionStyleSupported(profile, options.executionStyle)) {
524
+ throw new Error(
525
+ `Runtime "${profile.language}" does not support execution style "${executionStyleLabel(options.executionStyle)}".`
526
+ );
527
+ }
528
+ if (isScriptRequest(options.functionName) && !profile.capabilities.execution.styles.script) {
529
+ throw new Error(`Runtime "${profile.language}" does not support script mode ${describeRequest(options.request)}.`);
530
+ }
531
+ }
532
+
533
+ // packages/harness-browser/src/runtime-profiles.ts
534
+ var PYTHON_RUNTIME_PROFILE = {
535
+ language: "python",
536
+ maturity: "stable",
537
+ capabilities: {
538
+ execution: {
539
+ styles: {
540
+ function: true,
541
+ solutionMethod: true,
542
+ opsClass: true,
543
+ script: true,
544
+ interviewMode: true
545
+ },
546
+ timeouts: {
547
+ clientTimeouts: true,
548
+ runtimeTimeouts: true
549
+ }
550
+ },
551
+ tracing: {
552
+ supported: true,
553
+ events: {
554
+ line: true,
555
+ call: true,
556
+ return: true,
557
+ exception: true,
558
+ stdout: true,
559
+ timeout: true
560
+ },
561
+ controls: {
562
+ maxTraceSteps: true,
563
+ maxLineEvents: true,
564
+ maxSingleLineHits: true,
565
+ minimalTrace: true
566
+ },
567
+ fidelity: {
568
+ preciseLineMapping: true,
569
+ stableFunctionNames: true,
570
+ callStack: true
571
+ }
572
+ },
573
+ diagnostics: {
574
+ compileErrors: false,
575
+ runtimeErrors: true,
576
+ mappedErrorLines: true,
577
+ stackTraces: false
578
+ },
579
+ structures: {
580
+ treeNodeRefs: true,
581
+ listNodeRefs: true,
582
+ mapSerialization: true,
583
+ setSerialization: true,
584
+ graphSerialization: true,
585
+ cycleReferences: true
586
+ },
587
+ visualization: {
588
+ runtimePayloads: true,
589
+ objectKinds: true,
590
+ hashMaps: true,
591
+ stepVisualization: true
592
+ }
593
+ }
594
+ };
595
+ var JAVASCRIPT_RUNTIME_PROFILE = {
596
+ language: "javascript",
597
+ maturity: "stable",
598
+ capabilities: {
599
+ execution: {
600
+ styles: {
601
+ function: true,
602
+ solutionMethod: true,
603
+ opsClass: true,
604
+ script: true,
605
+ interviewMode: true
606
+ },
607
+ timeouts: {
608
+ clientTimeouts: true,
609
+ runtimeTimeouts: false
610
+ }
611
+ },
612
+ tracing: {
613
+ supported: true,
614
+ events: {
615
+ line: true,
616
+ call: true,
617
+ return: true,
618
+ exception: true,
619
+ stdout: false,
620
+ timeout: true
621
+ },
622
+ controls: {
623
+ maxTraceSteps: true,
624
+ maxLineEvents: true,
625
+ maxSingleLineHits: true,
626
+ minimalTrace: true
627
+ },
628
+ fidelity: {
629
+ preciseLineMapping: true,
630
+ stableFunctionNames: true,
631
+ callStack: true
632
+ }
633
+ },
634
+ diagnostics: {
635
+ compileErrors: false,
636
+ runtimeErrors: true,
637
+ mappedErrorLines: false,
638
+ stackTraces: false
639
+ },
640
+ structures: {
641
+ treeNodeRefs: true,
642
+ listNodeRefs: true,
643
+ mapSerialization: true,
644
+ setSerialization: true,
645
+ graphSerialization: true,
646
+ cycleReferences: true
647
+ },
648
+ visualization: {
649
+ runtimePayloads: true,
650
+ objectKinds: true,
651
+ hashMaps: true,
652
+ stepVisualization: true
653
+ }
654
+ }
655
+ };
656
+ var TYPESCRIPT_RUNTIME_PROFILE = {
657
+ language: "typescript",
658
+ maturity: "stable",
659
+ capabilities: {
660
+ execution: {
661
+ styles: {
662
+ function: true,
663
+ solutionMethod: true,
664
+ opsClass: true,
665
+ script: true,
666
+ interviewMode: true
667
+ },
668
+ timeouts: {
669
+ clientTimeouts: true,
670
+ runtimeTimeouts: false
671
+ }
672
+ },
673
+ tracing: {
674
+ supported: true,
675
+ events: {
676
+ line: true,
677
+ call: true,
678
+ return: true,
679
+ exception: true,
680
+ stdout: false,
681
+ timeout: true
682
+ },
683
+ controls: {
684
+ maxTraceSteps: true,
685
+ maxLineEvents: true,
686
+ maxSingleLineHits: true,
687
+ minimalTrace: true
688
+ },
689
+ fidelity: {
690
+ preciseLineMapping: true,
691
+ stableFunctionNames: true,
692
+ callStack: true
693
+ }
694
+ },
695
+ diagnostics: {
696
+ compileErrors: true,
697
+ runtimeErrors: true,
698
+ mappedErrorLines: true,
699
+ stackTraces: false
700
+ },
701
+ structures: {
702
+ treeNodeRefs: true,
703
+ listNodeRefs: true,
704
+ mapSerialization: true,
705
+ setSerialization: true,
706
+ graphSerialization: true,
707
+ cycleReferences: true
708
+ },
709
+ visualization: {
710
+ runtimePayloads: true,
711
+ objectKinds: true,
712
+ hashMaps: true,
713
+ stepVisualization: true
714
+ }
715
+ }
716
+ };
717
+ var LANGUAGE_RUNTIME_PROFILES = {
718
+ python: PYTHON_RUNTIME_PROFILE,
719
+ javascript: JAVASCRIPT_RUNTIME_PROFILE,
720
+ typescript: TYPESCRIPT_RUNTIME_PROFILE
721
+ };
722
+ var SUPPORTED_LANGUAGES = Object.freeze(
723
+ Object.keys(LANGUAGE_RUNTIME_PROFILES)
724
+ );
725
+ function getLanguageRuntimeProfile(language) {
726
+ const profile = LANGUAGE_RUNTIME_PROFILES[language];
727
+ if (!profile) {
728
+ throw new Error(`Runtime profile for language "${language}" is not implemented yet.`);
729
+ }
730
+ return profile;
731
+ }
732
+ function getSupportedLanguageProfiles() {
733
+ return SUPPORTED_LANGUAGES.map((language) => LANGUAGE_RUNTIME_PROFILES[language]);
734
+ }
735
+ function isLanguageSupported(language) {
736
+ return SUPPORTED_LANGUAGES.includes(language);
737
+ }
738
+
739
+ // packages/harness-browser/src/javascript-runtime-client.ts
740
+ var JavaScriptRuntimeClient = class {
741
+ constructor(runtimeLanguage, workerClient) {
742
+ this.runtimeLanguage = runtimeLanguage;
743
+ this.workerClient = workerClient;
744
+ }
745
+ async init() {
746
+ return this.workerClient.init();
747
+ }
748
+ async executeWithTracing(code, functionName, inputs, options, executionStyle = "function") {
749
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile(this.runtimeLanguage), {
750
+ request: "trace",
751
+ executionStyle,
752
+ functionName
753
+ });
754
+ const rawResult = await this.workerClient.executeWithTracing(
755
+ code,
756
+ functionName,
757
+ inputs,
758
+ options,
759
+ executionStyle,
760
+ this.runtimeLanguage
761
+ );
762
+ return adaptJavaScriptTraceExecutionResult(this.runtimeLanguage, rawResult);
763
+ }
764
+ async executeCode(code, functionName, inputs, executionStyle = "function") {
765
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile(this.runtimeLanguage), {
766
+ request: "execute",
767
+ executionStyle,
768
+ functionName
769
+ });
770
+ return this.workerClient.executeCode(
771
+ code,
772
+ functionName,
773
+ inputs,
774
+ executionStyle,
775
+ this.runtimeLanguage
776
+ );
777
+ }
778
+ async executeCodeInterviewMode(code, functionName, inputs, executionStyle = "function") {
779
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile(this.runtimeLanguage), {
780
+ request: "interview",
781
+ executionStyle,
782
+ functionName
783
+ });
784
+ return this.workerClient.executeCodeInterviewMode(
785
+ code,
786
+ functionName,
787
+ inputs,
788
+ executionStyle,
789
+ this.runtimeLanguage
790
+ );
791
+ }
792
+ };
793
+ function createJavaScriptRuntimeClient(runtimeLanguage, workerClient) {
794
+ return new JavaScriptRuntimeClient(runtimeLanguage, workerClient);
795
+ }
796
+
797
+ // packages/harness-browser/src/pyodide-worker-client.ts
798
+ var EXECUTION_TIMEOUT_MS2 = 1e4;
799
+ var INTERVIEW_MODE_TIMEOUT_MS2 = 5e3;
800
+ var TRACING_TIMEOUT_MS2 = 3e4;
801
+ var INIT_TIMEOUT_MS2 = 12e4;
802
+ var MESSAGE_TIMEOUT_MS2 = 2e4;
803
+ var WORKER_READY_TIMEOUT_MS2 = 1e4;
804
+ var PyodideWorkerClient = class {
805
+ constructor(options) {
806
+ this.options = options;
807
+ this.debug = options.debug ?? process.env.NODE_ENV === "development";
808
+ }
809
+ worker = null;
810
+ pendingMessages = /* @__PURE__ */ new Map();
811
+ messageId = 0;
812
+ isInitializing = false;
813
+ initPromise = null;
814
+ workerReadyPromise = null;
815
+ workerReadyResolve = null;
816
+ workerReadyReject = null;
817
+ debug;
818
+ /**
819
+ * Check if Web Workers are supported
820
+ */
821
+ isSupported() {
822
+ return typeof Worker !== "undefined";
823
+ }
824
+ /**
825
+ * Get or create the worker instance
826
+ */
827
+ getWorker() {
828
+ if (this.worker) return this.worker;
829
+ if (!this.isSupported()) {
830
+ throw new Error("Web Workers are not supported in this environment");
831
+ }
832
+ this.workerReadyPromise = new Promise((resolve, reject) => {
833
+ this.workerReadyResolve = resolve;
834
+ this.workerReadyReject = (error) => reject(error);
835
+ });
836
+ const workerUrl = this.debug && !this.options.workerUrl.includes("?") ? `${this.options.workerUrl}?dev=${Date.now()}` : this.options.workerUrl;
837
+ this.worker = new Worker(workerUrl);
838
+ this.worker.onmessage = (event) => {
839
+ const { id, type, payload } = event.data;
840
+ if (type === "worker-ready") {
841
+ this.workerReadyResolve?.();
842
+ this.workerReadyResolve = null;
843
+ this.workerReadyReject = null;
844
+ if (this.debug) console.log("[PyodideWorkerClient] worker-ready");
845
+ return;
846
+ }
847
+ if (this.debug && !id) {
848
+ console.log("[PyodideWorkerClient] event", { type, payload });
849
+ }
850
+ if (id) {
851
+ const pending = this.pendingMessages.get(id);
852
+ if (pending) {
853
+ this.pendingMessages.delete(id);
854
+ if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);
855
+ if (type === "error") {
856
+ pending.reject(new Error(payload.error));
857
+ } else {
858
+ if (this.debug) console.log("[PyodideWorkerClient] recv", { id, type });
859
+ pending.resolve(payload);
860
+ }
861
+ }
862
+ }
863
+ };
864
+ this.worker.onerror = (error) => {
865
+ console.error("[PyodideWorkerClient] Worker error:", error);
866
+ const workerError = new Error("Worker error");
867
+ this.workerReadyReject?.(workerError);
868
+ this.workerReadyResolve = null;
869
+ this.workerReadyReject = null;
870
+ for (const [id, pending] of this.pendingMessages) {
871
+ if (pending.timeoutId) {
872
+ globalThis.clearTimeout(pending.timeoutId);
873
+ }
874
+ pending.reject(workerError);
875
+ this.pendingMessages.delete(id);
876
+ }
877
+ };
878
+ return this.worker;
879
+ }
880
+ /**
881
+ * Wait for worker bootstrap signal with timeout.
882
+ * Guards against deadlocks when the worker script fails before posting "worker-ready".
883
+ */
884
+ async waitForWorkerReady() {
885
+ const readyPromise = this.workerReadyPromise;
886
+ if (!readyPromise) return;
887
+ await new Promise((resolve, reject) => {
888
+ let settled = false;
889
+ const timeoutId = globalThis.setTimeout(() => {
890
+ if (settled) return;
891
+ settled = true;
892
+ const timeoutError = new Error(
893
+ `Python worker failed to initialize in time (${Math.round(WORKER_READY_TIMEOUT_MS2 / 1e3)}s)`
894
+ );
895
+ if (this.debug) {
896
+ console.warn("[PyodideWorkerClient] worker-ready timeout", { timeoutMs: WORKER_READY_TIMEOUT_MS2 });
897
+ }
898
+ this.terminateAndReset(timeoutError);
899
+ reject(timeoutError);
900
+ }, WORKER_READY_TIMEOUT_MS2);
901
+ readyPromise.then(() => {
902
+ if (settled) return;
903
+ settled = true;
904
+ globalThis.clearTimeout(timeoutId);
905
+ resolve();
906
+ }).catch((error) => {
907
+ if (settled) return;
908
+ settled = true;
909
+ globalThis.clearTimeout(timeoutId);
910
+ reject(error instanceof Error ? error : new Error(String(error)));
911
+ });
912
+ });
913
+ }
914
+ /**
915
+ * Send a message to the worker and wait for a response
916
+ */
917
+ async sendMessage(type, payload, timeoutMs = MESSAGE_TIMEOUT_MS2) {
918
+ const worker = this.getWorker();
919
+ await this.waitForWorkerReady();
920
+ const id = String(++this.messageId);
921
+ return new Promise((resolve, reject) => {
922
+ this.pendingMessages.set(id, {
923
+ resolve,
924
+ reject
925
+ });
926
+ if (this.debug) console.log("[PyodideWorkerClient] send", { id, type });
927
+ const timeoutId = globalThis.setTimeout(() => {
928
+ const pending2 = this.pendingMessages.get(id);
929
+ if (!pending2) return;
930
+ this.pendingMessages.delete(id);
931
+ if (this.debug) console.warn("[PyodideWorkerClient] timeout", { id, type });
932
+ pending2.reject(new Error(`Worker request timed out: ${type}`));
933
+ }, timeoutMs);
934
+ const pending = this.pendingMessages.get(id);
935
+ if (pending) pending.timeoutId = timeoutId;
936
+ worker.postMessage({ id, type, payload });
937
+ });
938
+ }
939
+ /**
940
+ * Execute code with a timeout - terminates worker if execution takes too long
941
+ */
942
+ async executeWithTimeout(executor, timeoutMs = EXECUTION_TIMEOUT_MS2) {
943
+ return new Promise((resolve, reject) => {
944
+ let settled = false;
945
+ const timeoutId = globalThis.setTimeout(() => {
946
+ if (settled) return;
947
+ settled = true;
948
+ if (this.debug) {
949
+ console.warn("[PyodideWorkerClient] Execution timeout - terminating worker");
950
+ }
951
+ this.terminateAndReset();
952
+ const seconds = Math.round(timeoutMs / 1e3);
953
+ reject(new Error(`Execution timed out (possible infinite loop). Code execution was stopped after ${seconds} seconds.`));
954
+ }, timeoutMs);
955
+ executor().then((result) => {
956
+ if (settled) return;
957
+ settled = true;
958
+ globalThis.clearTimeout(timeoutId);
959
+ resolve(result);
960
+ }).catch((error) => {
961
+ if (settled) return;
962
+ settled = true;
963
+ globalThis.clearTimeout(timeoutId);
964
+ reject(error);
965
+ });
966
+ });
967
+ }
968
+ /**
969
+ * Terminate the worker and reset state for recreation
970
+ */
971
+ terminateAndReset(reason = new Error("Worker was terminated")) {
972
+ this.workerReadyReject?.(reason);
973
+ if (this.worker) {
974
+ this.worker.terminate();
975
+ this.worker = null;
976
+ }
977
+ this.initPromise = null;
978
+ this.isInitializing = false;
979
+ this.workerReadyPromise = null;
980
+ this.workerReadyResolve = null;
981
+ for (const [, pending] of this.pendingMessages) {
982
+ if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);
983
+ pending.reject(reason);
984
+ }
985
+ this.pendingMessages.clear();
986
+ }
987
+ /**
988
+ * Initialize Pyodide in the worker
989
+ */
990
+ async init() {
991
+ if (this.initPromise) {
992
+ return this.initPromise;
993
+ }
994
+ if (this.isInitializing) {
995
+ await new Promise((resolve) => setTimeout(resolve, 100));
996
+ return this.init();
997
+ }
998
+ this.isInitializing = true;
999
+ this.initPromise = (async () => {
1000
+ try {
1001
+ return await this.sendMessage("init", void 0, INIT_TIMEOUT_MS2);
1002
+ } catch (error) {
1003
+ const message = error instanceof Error ? error.message : String(error);
1004
+ const shouldRetry = message.includes("Worker request timed out: init") || message.includes("Worker was terminated") || message.includes("Worker error") || message.includes("failed to initialize in time");
1005
+ if (!shouldRetry) {
1006
+ throw error;
1007
+ }
1008
+ if (this.debug) {
1009
+ console.warn("[PyodideWorkerClient] init failed, resetting worker and retrying once", { message });
1010
+ }
1011
+ this.terminateAndReset();
1012
+ return this.sendMessage("init", void 0, INIT_TIMEOUT_MS2);
1013
+ }
1014
+ })();
1015
+ try {
1016
+ const result = await this.initPromise;
1017
+ return result;
1018
+ } catch (error) {
1019
+ this.initPromise = null;
1020
+ throw error;
1021
+ } finally {
1022
+ this.isInitializing = false;
1023
+ }
1024
+ }
1025
+ /**
1026
+ * Execute Python code with tracing for step-by-step visualization
1027
+ * @param options.maxLineEvents - Max line events before abort (for complexity analysis, use higher values)
1028
+ */
1029
+ async executeWithTracing(code, functionName, inputs, options, executionStyle = "function") {
1030
+ await this.init();
1031
+ try {
1032
+ return await this.executeWithTimeout(
1033
+ () => this.sendMessage("execute-with-tracing", {
1034
+ code,
1035
+ functionName,
1036
+ inputs,
1037
+ executionStyle,
1038
+ options
1039
+ }, TRACING_TIMEOUT_MS2 + 5e3),
1040
+ // Message timeout slightly longer than execution timeout
1041
+ TRACING_TIMEOUT_MS2
1042
+ );
1043
+ } catch (error) {
1044
+ const errorMessage = error instanceof Error ? error.message : String(error);
1045
+ const isClientTimeout = errorMessage.includes("Execution timed out") || errorMessage.includes("possible infinite loop");
1046
+ if (isClientTimeout) {
1047
+ return {
1048
+ success: false,
1049
+ error: errorMessage,
1050
+ trace: [],
1051
+ executionTimeMs: TRACING_TIMEOUT_MS2,
1052
+ consoleOutput: [],
1053
+ traceLimitExceeded: true,
1054
+ timeoutReason: "client-timeout",
1055
+ lineEventCount: 0,
1056
+ traceStepCount: 0
1057
+ };
1058
+ }
1059
+ throw error;
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Execute Python code without tracing (for running tests)
1064
+ */
1065
+ async executeCode(code, functionName, inputs, executionStyle = "function") {
1066
+ await this.init();
1067
+ return this.executeWithTimeout(
1068
+ () => this.sendMessage("execute-code", {
1069
+ code,
1070
+ functionName,
1071
+ inputs,
1072
+ executionStyle
1073
+ }, EXECUTION_TIMEOUT_MS2 + 5e3),
1074
+ EXECUTION_TIMEOUT_MS2
1075
+ );
1076
+ }
1077
+ /**
1078
+ * Execute Python code in interview mode - 5 second timeout, generic error messages
1079
+ * Does not reveal which line caused the timeout
1080
+ */
1081
+ async executeCodeInterviewMode(code, functionName, inputs, executionStyle = "function") {
1082
+ await this.init();
1083
+ try {
1084
+ const result = await this.executeWithTimeout(
1085
+ () => this.sendMessage("execute-code-interview", {
1086
+ code,
1087
+ functionName,
1088
+ inputs,
1089
+ executionStyle
1090
+ }, INTERVIEW_MODE_TIMEOUT_MS2 + 2e3),
1091
+ INTERVIEW_MODE_TIMEOUT_MS2
1092
+ );
1093
+ if (!result.success && result.error) {
1094
+ const normalizedError = result.error.toLowerCase();
1095
+ const isTimeoutOrResourceLimit = normalizedError.includes("timed out") || normalizedError.includes("execution timeout") || normalizedError.includes("infinite loop") || normalizedError.includes("interview_guard_triggered") || normalizedError.includes("memory-limit") || normalizedError.includes("line-limit") || normalizedError.includes("single-line-limit") || normalizedError.includes("recursion-limit");
1096
+ if (isTimeoutOrResourceLimit) {
1097
+ return {
1098
+ success: false,
1099
+ output: null,
1100
+ error: "Time Limit Exceeded",
1101
+ consoleOutput: result.consoleOutput ?? []
1102
+ };
1103
+ }
1104
+ }
1105
+ return result;
1106
+ } catch (error) {
1107
+ const errorMsg = error instanceof Error ? error.message : String(error);
1108
+ if (errorMsg.includes("timed out") || errorMsg.includes("Execution timeout")) {
1109
+ return {
1110
+ success: false,
1111
+ output: null,
1112
+ error: "Time Limit Exceeded",
1113
+ consoleOutput: []
1114
+ };
1115
+ }
1116
+ return {
1117
+ success: false,
1118
+ output: null,
1119
+ error: errorMsg,
1120
+ consoleOutput: []
1121
+ };
1122
+ }
1123
+ }
1124
+ /**
1125
+ * Check the status of the worker
1126
+ */
1127
+ async getStatus() {
1128
+ return this.sendMessage("status");
1129
+ }
1130
+ /**
1131
+ * Analyze Python code using AST (off main thread)
1132
+ * Returns CodeFacts with semantic information about the code
1133
+ */
1134
+ async analyzeCode(code) {
1135
+ await this.init();
1136
+ return this.sendMessage("analyze-code", { code }, 5e3);
1137
+ }
1138
+ /**
1139
+ * Terminate the worker and clean up resources
1140
+ */
1141
+ terminate() {
1142
+ this.terminateAndReset();
1143
+ }
1144
+ };
1145
+
1146
+ // packages/harness-core/src/trace-adapters/python.ts
1147
+ function adaptPythonTraceExecutionResult(result) {
1148
+ return adaptTraceExecutionResult("python", result);
1149
+ }
1150
+
1151
+ // packages/harness-browser/src/python-runtime-client.ts
1152
+ var PythonRuntimeClient = class {
1153
+ constructor(workerClient) {
1154
+ this.workerClient = workerClient;
1155
+ }
1156
+ async init() {
1157
+ return this.workerClient.init();
1158
+ }
1159
+ async executeWithTracing(code, functionName, inputs, options, executionStyle = "function") {
1160
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile("python"), {
1161
+ request: "trace",
1162
+ executionStyle,
1163
+ functionName
1164
+ });
1165
+ const rawResult = await this.workerClient.executeWithTracing(
1166
+ code,
1167
+ functionName,
1168
+ inputs,
1169
+ options,
1170
+ executionStyle
1171
+ );
1172
+ return adaptPythonTraceExecutionResult(rawResult);
1173
+ }
1174
+ async executeCode(code, functionName, inputs, executionStyle = "function") {
1175
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile("python"), {
1176
+ request: "execute",
1177
+ executionStyle,
1178
+ functionName
1179
+ });
1180
+ return this.workerClient.executeCode(
1181
+ code,
1182
+ functionName,
1183
+ inputs,
1184
+ executionStyle
1185
+ );
1186
+ }
1187
+ async executeCodeInterviewMode(code, functionName, inputs, executionStyle = "function") {
1188
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile("python"), {
1189
+ request: "interview",
1190
+ executionStyle,
1191
+ functionName
1192
+ });
1193
+ return this.workerClient.executeCodeInterviewMode(
1194
+ code,
1195
+ functionName,
1196
+ inputs,
1197
+ executionStyle
1198
+ );
1199
+ }
1200
+ };
1201
+ function createPythonRuntimeClient(workerClient) {
1202
+ return new PythonRuntimeClient(workerClient);
1203
+ }
1204
+
1205
+ // packages/harness-browser/src/runtime-assets.ts
1206
+ var DEFAULT_ASSET_BASE_URL = "/workers";
1207
+ var DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS = Object.freeze({
1208
+ pythonWorker: "pyodide-worker.js",
1209
+ pythonRuntimeCore: "pyodide/runtime-core.js",
1210
+ pythonSnippets: "generated-python-harness-snippets.js",
1211
+ javascriptWorker: "javascript-worker.js",
1212
+ typescriptCompiler: "vendor/typescript.js"
1213
+ });
1214
+ function isExplicitAssetPath(pathname) {
1215
+ return pathname.startsWith("/") || pathname.startsWith("./") || pathname.startsWith("../") || pathname.startsWith("http://") || pathname.startsWith("https://") || pathname.startsWith("data:") || pathname.startsWith("blob:");
1216
+ }
1217
+ function stripTrailingSlash(value) {
1218
+ return value.replace(/\/+$/, "");
1219
+ }
1220
+ function trimLeadingSlash(value) {
1221
+ return value.replace(/^\/+/, "");
1222
+ }
1223
+ function resolveAssetPath(baseUrl, pathname) {
1224
+ if (isExplicitAssetPath(pathname)) {
1225
+ return pathname;
1226
+ }
1227
+ const normalizedBase = stripTrailingSlash(baseUrl || DEFAULT_ASSET_BASE_URL);
1228
+ const normalizedPath = trimLeadingSlash(pathname);
1229
+ return `${normalizedBase}/${normalizedPath}`;
1230
+ }
1231
+ function resolveBrowserHarnessAssets(options = {}) {
1232
+ const assetBaseUrl = options.assetBaseUrl ?? DEFAULT_ASSET_BASE_URL;
1233
+ const assets = options.assets ?? {};
1234
+ return {
1235
+ pythonWorker: resolveAssetPath(assetBaseUrl, assets.pythonWorker ?? DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS.pythonWorker),
1236
+ pythonRuntimeCore: resolveAssetPath(
1237
+ assetBaseUrl,
1238
+ assets.pythonRuntimeCore ?? DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS.pythonRuntimeCore
1239
+ ),
1240
+ pythonSnippets: resolveAssetPath(assetBaseUrl, assets.pythonSnippets ?? DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS.pythonSnippets),
1241
+ javascriptWorker: resolveAssetPath(
1242
+ assetBaseUrl,
1243
+ assets.javascriptWorker ?? DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS.javascriptWorker
1244
+ ),
1245
+ typescriptCompiler: resolveAssetPath(
1246
+ assetBaseUrl,
1247
+ assets.typescriptCompiler ?? DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS.typescriptCompiler
1248
+ )
1249
+ };
1250
+ }
1251
+
1252
+ // packages/harness-browser/src/browser-harness.ts
1253
+ var BrowserHarnessRuntime = class {
1254
+ assets;
1255
+ supportedLanguages = SUPPORTED_LANGUAGES;
1256
+ pythonWorkerClient;
1257
+ javaScriptWorkerClient;
1258
+ clients;
1259
+ constructor(options = {}) {
1260
+ this.assets = resolveBrowserHarnessAssets(options);
1261
+ this.pythonWorkerClient = new PyodideWorkerClient({
1262
+ workerUrl: this.assets.pythonWorker,
1263
+ debug: options.debug
1264
+ });
1265
+ this.javaScriptWorkerClient = new JavaScriptWorkerClient({
1266
+ workerUrl: this.assets.javascriptWorker,
1267
+ debug: options.debug
1268
+ });
1269
+ this.clients = {
1270
+ python: createPythonRuntimeClient(this.pythonWorkerClient),
1271
+ javascript: createJavaScriptRuntimeClient("javascript", this.javaScriptWorkerClient),
1272
+ typescript: createJavaScriptRuntimeClient("typescript", this.javaScriptWorkerClient)
1273
+ };
1274
+ }
1275
+ getClient(language) {
1276
+ const client = this.clients[language];
1277
+ if (!client) {
1278
+ throw new Error(`Runtime for language "${language}" is not implemented yet.`);
1279
+ }
1280
+ return client;
1281
+ }
1282
+ getProfile(language) {
1283
+ return getLanguageRuntimeProfile(language);
1284
+ }
1285
+ getSupportedLanguageProfiles() {
1286
+ return getSupportedLanguageProfiles();
1287
+ }
1288
+ isLanguageSupported(language) {
1289
+ return isLanguageSupported(language);
1290
+ }
1291
+ disposeLanguage(language) {
1292
+ if (language === "python") {
1293
+ this.pythonWorkerClient.terminate();
1294
+ return;
1295
+ }
1296
+ this.javaScriptWorkerClient.terminate();
1297
+ }
1298
+ dispose() {
1299
+ this.pythonWorkerClient.terminate();
1300
+ this.javaScriptWorkerClient.terminate();
1301
+ }
1302
+ };
1303
+ function createBrowserHarness(options = {}) {
1304
+ return new BrowserHarnessRuntime(options);
1305
+ }
1306
+ export {
1307
+ DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS,
1308
+ LANGUAGE_RUNTIME_PROFILES,
1309
+ SUPPORTED_LANGUAGES,
1310
+ assertRuntimeRequestSupported,
1311
+ createBrowserHarness,
1312
+ getLanguageRuntimeProfile,
1313
+ getSupportedLanguageProfiles,
1314
+ isLanguageSupported,
1315
+ resolveBrowserHarnessAssets
1316
+ };
1317
+ //# sourceMappingURL=browser.js.map