@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 @@
1
+ {"version":3,"sources":["../../packages/harness-browser/src/pyodide-worker-client.ts","../../packages/harness-browser/src/javascript-worker-client.ts"],"sourcesContent":["/**\n * Pyodide Worker Client\n * \n * TypeScript client for communicating with the Pyodide Web Worker.\n * Provides a promise-based API for executing Python code off the main thread.\n */\n\nimport type { CodeExecutionResult, ExecutionResult } from '../../harness-core/src/types';\n\ntype MessageId = string;\nexport type ExecutionStyle = 'function' | 'solution-method' | 'ops-class';\n\nexport interface PyodideWorkerClientOptions {\n workerUrl: string;\n debug?: boolean;\n}\n\ninterface PendingMessage {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timeoutId?: ReturnType<typeof globalThis.setTimeout>;\n}\n\ninterface WorkerMessage {\n id?: MessageId;\n type: string;\n payload?: unknown;\n}\n\ninterface InitResult {\n success: boolean;\n loadTimeMs: number;\n}\n\ninterface StatusResult {\n isReady: boolean;\n isLoading: boolean;\n}\n\n// Execution timeout in milliseconds for simple code execution (10 seconds)\nconst EXECUTION_TIMEOUT_MS = 10000;\n\n// Interview mode timeout - shorter, no detailed error info (5 seconds)\nconst INTERVIEW_MODE_TIMEOUT_MS = 5000;\n\n// Tracing timeout - longer because Python heuristic detection handles infinite loops\n// This is just a safety net for truly stuck executions\nconst TRACING_TIMEOUT_MS = 30000;\n\n// Initial Pyodide load timeout can be significantly higher on first boot/network-constrained setups\nconst INIT_TIMEOUT_MS = 120000;\n\n// Message timeout for non-execution operations (20 seconds)\nconst MESSAGE_TIMEOUT_MS = 20000;\n// Worker bootstrap timeout - prevents deadlock when worker never emits \"worker-ready\"\nconst WORKER_READY_TIMEOUT_MS = 10000;\n\nexport class PyodideWorkerClient {\n private worker: Worker | null = null;\n private pendingMessages = new Map<MessageId, PendingMessage>();\n private messageId = 0;\n private isInitializing = false;\n private initPromise: Promise<InitResult> | null = null;\n private workerReadyPromise: Promise<void> | null = null;\n private workerReadyResolve: (() => void) | null = null;\n private workerReadyReject: ((error: Error) => void) | null = null;\n private readonly debug: boolean;\n\n constructor(private readonly options: PyodideWorkerClientOptions) {\n this.debug = options.debug ?? process.env.NODE_ENV === 'development';\n }\n\n /**\n * Check if Web Workers are supported\n */\n isSupported(): boolean {\n return typeof Worker !== 'undefined';\n }\n\n /**\n * Get or create the worker instance\n */\n private getWorker(): Worker {\n if (this.worker) return this.worker;\n\n if (!this.isSupported()) {\n throw new Error('Web Workers are not supported in this environment');\n }\n\n // Create promise that resolves when worker signals it's ready\n this.workerReadyPromise = new Promise((resolve, reject) => {\n this.workerReadyResolve = resolve;\n this.workerReadyReject = (error: Error) => reject(error);\n });\n\n const workerUrl =\n this.debug && !this.options.workerUrl.includes('?')\n ? `${this.options.workerUrl}?dev=${Date.now()}`\n : this.options.workerUrl;\n this.worker = new Worker(workerUrl);\n \n this.worker.onmessage = (event: MessageEvent<WorkerMessage>) => {\n const { id, type, payload } = event.data;\n\n // Handle worker-ready signal\n if (type === 'worker-ready') {\n this.workerReadyResolve?.();\n this.workerReadyResolve = null;\n this.workerReadyReject = null;\n if (this.debug) console.log('[PyodideWorkerClient] worker-ready');\n return;\n }\n\n if (this.debug && !id) {\n console.log('[PyodideWorkerClient] event', { type, payload });\n }\n\n // Handle responses to our messages\n if (id) {\n const pending = this.pendingMessages.get(id);\n if (pending) {\n this.pendingMessages.delete(id);\n if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);\n \n if (type === 'error') {\n pending.reject(new Error((payload as { error: string }).error));\n } else {\n if (this.debug) console.log('[PyodideWorkerClient] recv', { id, type });\n pending.resolve(payload);\n }\n }\n }\n };\n\n this.worker.onerror = (error) => {\n console.error('[PyodideWorkerClient] Worker error:', error);\n const workerError = new Error('Worker error');\n this.workerReadyReject?.(workerError);\n this.workerReadyResolve = null;\n this.workerReadyReject = null;\n // Reject all pending messages and clear their timeouts\n for (const [id, pending] of this.pendingMessages) {\n if (pending.timeoutId) {\n globalThis.clearTimeout(pending.timeoutId);\n }\n pending.reject(workerError);\n this.pendingMessages.delete(id);\n }\n };\n\n return this.worker;\n }\n\n /**\n * Wait for worker bootstrap signal with timeout.\n * Guards against deadlocks when the worker script fails before posting \"worker-ready\".\n */\n private async waitForWorkerReady(): Promise<void> {\n const readyPromise = this.workerReadyPromise;\n if (!readyPromise) return;\n\n await new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const timeoutId = globalThis.setTimeout(() => {\n if (settled) return;\n settled = true;\n const timeoutError = new Error(\n `Python worker failed to initialize in time (${Math.round(WORKER_READY_TIMEOUT_MS / 1000)}s)`\n );\n if (this.debug) {\n console.warn('[PyodideWorkerClient] worker-ready timeout', { timeoutMs: WORKER_READY_TIMEOUT_MS });\n }\n this.terminateAndReset(timeoutError);\n reject(timeoutError);\n }, WORKER_READY_TIMEOUT_MS);\n\n readyPromise\n .then(() => {\n if (settled) return;\n settled = true;\n globalThis.clearTimeout(timeoutId);\n resolve();\n })\n .catch((error) => {\n if (settled) return;\n settled = true;\n globalThis.clearTimeout(timeoutId);\n reject(error instanceof Error ? error : new Error(String(error)));\n });\n });\n }\n\n /**\n * Send a message to the worker and wait for a response\n */\n private async sendMessage<T>(type: string, payload?: unknown, timeoutMs: number = MESSAGE_TIMEOUT_MS): Promise<T> {\n const worker = this.getWorker();\n \n // Wait for worker to be ready before sending messages\n await this.waitForWorkerReady();\n \n const id = String(++this.messageId);\n\n return new Promise<T>((resolve, reject) => {\n this.pendingMessages.set(id, {\n resolve: resolve as (value: unknown) => void,\n reject,\n });\n\n if (this.debug) console.log('[PyodideWorkerClient] send', { id, type });\n\n const timeoutId = globalThis.setTimeout(() => {\n const pending = this.pendingMessages.get(id);\n if (!pending) return;\n this.pendingMessages.delete(id);\n if (this.debug) console.warn('[PyodideWorkerClient] timeout', { id, type });\n pending.reject(new Error(`Worker request timed out: ${type}`));\n }, timeoutMs);\n\n const pending = this.pendingMessages.get(id);\n if (pending) pending.timeoutId = timeoutId;\n\n worker.postMessage({ id, type, payload });\n });\n }\n\n /**\n * Execute code with a timeout - terminates worker if execution takes too long\n */\n private async executeWithTimeout<T>(\n executor: () => Promise<T>,\n timeoutMs: number = EXECUTION_TIMEOUT_MS\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let settled = false;\n \n const timeoutId = globalThis.setTimeout(() => {\n if (settled) return;\n settled = true;\n \n // Terminate the stuck worker and clear state\n if (this.debug) {\n console.warn('[PyodideWorkerClient] Execution timeout - terminating worker');\n }\n this.terminateAndReset();\n \n const seconds = Math.round(timeoutMs / 1000);\n reject(new Error(`Execution timed out (possible infinite loop). Code execution was stopped after ${seconds} seconds.`));\n }, timeoutMs);\n \n executor()\n .then((result) => {\n if (settled) return;\n settled = true;\n globalThis.clearTimeout(timeoutId);\n resolve(result);\n })\n .catch((error) => {\n if (settled) return;\n settled = true;\n globalThis.clearTimeout(timeoutId);\n reject(error);\n });\n });\n }\n\n /**\n * Terminate the worker and reset state for recreation\n */\n private terminateAndReset(reason: Error = new Error('Worker was terminated')): void {\n this.workerReadyReject?.(reason);\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n }\n this.initPromise = null;\n this.isInitializing = false;\n this.workerReadyPromise = null;\n this.workerReadyResolve = null;\n \n // Reject all pending messages\n for (const [, pending] of this.pendingMessages) {\n if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);\n pending.reject(reason);\n }\n this.pendingMessages.clear();\n }\n\n /**\n * Initialize Pyodide in the worker\n */\n async init(): Promise<InitResult> {\n // Return existing promise if already initializing\n if (this.initPromise) {\n return this.initPromise;\n }\n\n if (this.isInitializing) {\n // Wait for existing init to complete\n await new Promise((resolve) => setTimeout(resolve, 100));\n return this.init();\n }\n\n this.isInitializing = true;\n\n this.initPromise = (async () => {\n try {\n return await this.sendMessage<InitResult>('init', undefined, INIT_TIMEOUT_MS);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n const shouldRetry =\n message.includes('Worker request timed out: init') ||\n message.includes('Worker was terminated') ||\n message.includes('Worker error') ||\n message.includes('failed to initialize in time');\n\n if (!shouldRetry) {\n throw error;\n }\n\n if (this.debug) {\n console.warn('[PyodideWorkerClient] init failed, resetting worker and retrying once', { message });\n }\n\n this.terminateAndReset();\n return this.sendMessage<InitResult>('init', undefined, INIT_TIMEOUT_MS);\n }\n })();\n \n try {\n const result = await this.initPromise;\n return result;\n } catch (error) {\n this.initPromise = null;\n throw error;\n } finally {\n this.isInitializing = false;\n }\n }\n\n /**\n * Execute Python code with tracing for step-by-step visualization\n * @param options.maxLineEvents - Max line events before abort (for complexity analysis, use higher values)\n */\n async executeWithTracing(\n code: string,\n functionName: string | null,\n inputs: Record<string, unknown>,\n options?: {\n maxTraceSteps?: number;\n maxLineEvents?: number;\n maxSingleLineHits?: number;\n minimalTrace?: boolean;\n },\n executionStyle: ExecutionStyle = 'function'\n ): Promise<ExecutionResult> {\n // Ensure Pyodide is initialized\n await this.init();\n \n // Use longer timeout for tracing - Python heuristic detection handles infinite loops\n try {\n return await this.executeWithTimeout(\n () => this.sendMessage<ExecutionResult>('execute-with-tracing', {\n code,\n functionName,\n inputs,\n executionStyle,\n options,\n }, TRACING_TIMEOUT_MS + 5000), // Message timeout slightly longer than execution timeout\n TRACING_TIMEOUT_MS\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const isClientTimeout =\n errorMessage.includes('Execution timed out') ||\n errorMessage.includes('possible infinite loop');\n\n if (isClientTimeout) {\n return {\n success: false,\n error: errorMessage,\n trace: [],\n executionTimeMs: TRACING_TIMEOUT_MS,\n consoleOutput: [],\n traceLimitExceeded: true,\n timeoutReason: 'client-timeout',\n lineEventCount: 0,\n traceStepCount: 0,\n };\n }\n\n throw error;\n }\n }\n\n /**\n * Execute Python code without tracing (for running tests)\n */\n async executeCode(\n code: string,\n functionName: string,\n inputs: Record<string, unknown>,\n executionStyle: ExecutionStyle = 'function'\n ): Promise<CodeExecutionResult> {\n // Ensure Pyodide is initialized\n await this.init();\n \n return this.executeWithTimeout(\n () => this.sendMessage<CodeExecutionResult>('execute-code', {\n code,\n functionName,\n inputs,\n executionStyle,\n }, EXECUTION_TIMEOUT_MS + 5000),\n EXECUTION_TIMEOUT_MS\n );\n }\n\n /**\n * Execute Python code in interview mode - 5 second timeout, generic error messages\n * Does not reveal which line caused the timeout\n */\n async executeCodeInterviewMode(\n code: string,\n functionName: string,\n inputs: Record<string, unknown>,\n executionStyle: ExecutionStyle = 'function'\n ): Promise<CodeExecutionResult> {\n // Ensure Pyodide is initialized\n await this.init();\n \n try {\n const result = await this.executeWithTimeout(\n () => this.sendMessage<CodeExecutionResult>('execute-code-interview', {\n code,\n functionName,\n inputs,\n executionStyle,\n }, INTERVIEW_MODE_TIMEOUT_MS + 2000),\n INTERVIEW_MODE_TIMEOUT_MS\n );\n \n // Sanitize error messages in interview mode - don't reveal line numbers for timeouts\n if (!result.success && result.error) {\n // Keep basic error types but remove line-specific info for timeouts\n const normalizedError = result.error.toLowerCase();\n const isTimeoutOrResourceLimit =\n normalizedError.includes('timed out') ||\n normalizedError.includes('execution timeout') ||\n normalizedError.includes('infinite loop') ||\n normalizedError.includes('interview_guard_triggered') ||\n normalizedError.includes('memory-limit') ||\n normalizedError.includes('line-limit') ||\n normalizedError.includes('single-line-limit') ||\n normalizedError.includes('recursion-limit');\n\n if (isTimeoutOrResourceLimit) {\n return {\n success: false,\n output: null,\n error: 'Time Limit Exceeded',\n consoleOutput: result.consoleOutput ?? [],\n };\n }\n }\n \n return result;\n } catch (error) {\n // Handle timeout from executeWithTimeout\n const errorMsg = error instanceof Error ? error.message : String(error);\n if (errorMsg.includes('timed out') || errorMsg.includes('Execution timeout')) {\n return {\n success: false,\n output: null,\n error: 'Time Limit Exceeded',\n consoleOutput: [],\n };\n }\n return {\n success: false,\n output: null,\n error: errorMsg,\n consoleOutput: [],\n };\n }\n }\n\n /**\n * Check the status of the worker\n */\n async getStatus(): Promise<StatusResult> {\n return this.sendMessage<StatusResult>('status');\n }\n\n /**\n * Analyze Python code using AST (off main thread)\n * Returns CodeFacts with semantic information about the code\n */\n async analyzeCode(code: string): Promise<unknown> {\n // Ensure Pyodide is initialized\n await this.init();\n \n // Use a shorter timeout for analysis (5 seconds should be plenty)\n return this.sendMessage<unknown>('analyze-code', { code }, 5000);\n }\n\n /**\n * Terminate the worker and clean up resources\n */\n terminate(): void {\n this.terminateAndReset();\n }\n}\n\n/**\n * Check if the worker client is supported\n */\nexport function isWorkerSupported(): boolean {\n return typeof Worker !== 'undefined';\n}\n","import type { CodeExecutionResult, ExecutionResult } from '../../harness-core/src/types';\n\ntype MessageId = string;\nexport type JavaScriptExecutionStyle = 'function' | 'solution-method' | 'ops-class';\nexport type JavaScriptWorkerLanguage = 'javascript' | 'typescript';\n\nexport interface JavaScriptWorkerClientOptions {\n workerUrl: string;\n debug?: boolean;\n}\n\ninterface PendingMessage {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timeoutId?: ReturnType<typeof setTimeout>;\n}\n\ninterface WorkerMessage {\n id?: MessageId;\n type: string;\n payload?: unknown;\n}\n\ninterface InitResult {\n success: boolean;\n loadTimeMs: number;\n}\n\nconst EXECUTION_TIMEOUT_MS = 7000;\nconst INTERVIEW_MODE_TIMEOUT_MS = 5000;\nconst TRACING_TIMEOUT_MS = 7000;\nconst INIT_TIMEOUT_MS = 10000;\nconst MESSAGE_TIMEOUT_MS = 12000;\nconst WORKER_READY_TIMEOUT_MS = 10000;\n\nexport class JavaScriptWorkerClient {\n private worker: Worker | null = null;\n private pendingMessages = new Map<MessageId, PendingMessage>();\n private messageId = 0;\n private isInitializing = false;\n private initPromise: Promise<InitResult> | null = null;\n private workerReadyPromise: Promise<void> | null = null;\n private workerReadyResolve: (() => void) | null = null;\n private workerReadyReject: ((error: Error) => void) | null = null;\n private readonly debug: boolean;\n\n constructor(private readonly options: JavaScriptWorkerClientOptions) {\n this.debug = options.debug ?? process.env.NODE_ENV === 'development';\n }\n\n isSupported(): boolean {\n return typeof Worker !== 'undefined';\n }\n\n private getWorker(): Worker {\n if (this.worker) return this.worker;\n\n if (!this.isSupported()) {\n throw new Error('Web Workers are not supported in this environment');\n }\n\n this.workerReadyPromise = new Promise((resolve, reject) => {\n this.workerReadyResolve = resolve;\n this.workerReadyReject = (error: Error) => reject(error);\n });\n\n const workerUrl =\n this.debug && !this.options.workerUrl.includes('?')\n ? `${this.options.workerUrl}?dev=${Date.now()}`\n : this.options.workerUrl;\n this.worker = new Worker(workerUrl);\n\n this.worker.onmessage = (event: MessageEvent<WorkerMessage>) => {\n const { id, type, payload } = event.data;\n\n if (type === 'worker-ready') {\n this.workerReadyResolve?.();\n this.workerReadyResolve = null;\n this.workerReadyReject = null;\n if (this.debug) console.log('[JavaScriptWorkerClient] worker-ready');\n return;\n }\n\n if (id) {\n const pending = this.pendingMessages.get(id);\n if (!pending) return;\n\n this.pendingMessages.delete(id);\n if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);\n\n if (type === 'error') {\n pending.reject(new Error((payload as { error: string }).error));\n return;\n }\n\n pending.resolve(payload);\n }\n };\n\n this.worker.onerror = (error) => {\n console.error('[JavaScriptWorkerClient] Worker error:', error);\n const workerError = new Error('Worker error');\n this.workerReadyReject?.(workerError);\n this.workerReadyResolve = null;\n this.workerReadyReject = null;\n\n for (const [id, pending] of this.pendingMessages) {\n if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);\n pending.reject(workerError);\n this.pendingMessages.delete(id);\n }\n };\n\n return this.worker;\n }\n\n private async waitForWorkerReady(): Promise<void> {\n const readyPromise = this.workerReadyPromise;\n if (!readyPromise) return;\n\n await new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const timeoutId = globalThis.setTimeout(() => {\n if (settled) return;\n settled = true;\n const timeoutError = new Error(\n `JavaScript worker failed to initialize in time (${Math.round(WORKER_READY_TIMEOUT_MS / 1000)}s)`\n );\n this.terminateAndReset(timeoutError);\n reject(timeoutError);\n }, WORKER_READY_TIMEOUT_MS);\n\n readyPromise\n .then(() => {\n if (settled) return;\n settled = true;\n globalThis.clearTimeout(timeoutId);\n resolve();\n })\n .catch((error) => {\n if (settled) return;\n settled = true;\n globalThis.clearTimeout(timeoutId);\n reject(error instanceof Error ? error : new Error(String(error)));\n });\n });\n }\n\n private async sendMessage<T>(\n type: string,\n payload?: unknown,\n timeoutMs: number = MESSAGE_TIMEOUT_MS\n ): Promise<T> {\n const worker = this.getWorker();\n await this.waitForWorkerReady();\n const id = String(++this.messageId);\n\n return new Promise<T>((resolve, reject) => {\n this.pendingMessages.set(id, {\n resolve: resolve as (value: unknown) => void,\n reject,\n });\n\n const timeoutId = globalThis.setTimeout(() => {\n const pending = this.pendingMessages.get(id);\n if (!pending) return;\n this.pendingMessages.delete(id);\n pending.reject(new Error(`Worker request timed out: ${type}`));\n }, timeoutMs);\n\n const pending = this.pendingMessages.get(id);\n if (pending) pending.timeoutId = timeoutId;\n\n worker.postMessage({ id, type, payload });\n });\n }\n\n private async executeWithTimeout<T>(executor: () => Promise<T>, timeoutMs: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let settled = false;\n\n const timeoutId = globalThis.setTimeout(() => {\n if (settled) return;\n settled = true;\n this.terminateAndReset();\n reject(\n new Error(\n `Execution timed out (possible infinite loop). Code execution was stopped after ${Math.round(timeoutMs / 1000)} seconds.`\n )\n );\n }, timeoutMs);\n\n executor()\n .then((result) => {\n if (settled) return;\n settled = true;\n globalThis.clearTimeout(timeoutId);\n resolve(result);\n })\n .catch((error) => {\n if (settled) return;\n settled = true;\n globalThis.clearTimeout(timeoutId);\n reject(error);\n });\n });\n }\n\n private terminateAndReset(reason: Error = new Error('Worker was terminated')): void {\n this.workerReadyReject?.(reason);\n if (this.worker) {\n this.worker.terminate();\n this.worker = null;\n }\n this.initPromise = null;\n this.isInitializing = false;\n this.workerReadyPromise = null;\n this.workerReadyResolve = null;\n this.workerReadyReject = null;\n\n for (const [, pending] of this.pendingMessages) {\n if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);\n pending.reject(reason);\n }\n this.pendingMessages.clear();\n }\n\n async init(): Promise<InitResult> {\n if (this.initPromise) return this.initPromise;\n\n if (this.isInitializing) {\n await new Promise((resolve) => globalThis.setTimeout(resolve, 100));\n return this.init();\n }\n\n this.isInitializing = true;\n this.initPromise = this.sendMessage<InitResult>('init', undefined, INIT_TIMEOUT_MS);\n\n try {\n return await this.initPromise;\n } catch (error) {\n this.initPromise = null;\n throw error;\n } finally {\n this.isInitializing = false;\n }\n }\n\n async executeWithTracing(\n code: string,\n functionName: string | null,\n inputs: Record<string, unknown>,\n options?: {\n maxTraceSteps?: number;\n maxLineEvents?: number;\n maxSingleLineHits?: number;\n minimalTrace?: boolean;\n },\n executionStyle: JavaScriptExecutionStyle = 'function',\n language: JavaScriptWorkerLanguage = 'javascript'\n ): Promise<ExecutionResult> {\n await this.init();\n return this.executeWithTimeout(\n () =>\n this.sendMessage<ExecutionResult>(\n 'execute-with-tracing',\n {\n code,\n functionName,\n inputs,\n options,\n executionStyle,\n language,\n },\n TRACING_TIMEOUT_MS + 2000\n ),\n TRACING_TIMEOUT_MS\n );\n }\n\n async executeCode(\n code: string,\n functionName: string,\n inputs: Record<string, unknown>,\n executionStyle: JavaScriptExecutionStyle = 'function',\n language: JavaScriptWorkerLanguage = 'javascript'\n ): Promise<CodeExecutionResult> {\n await this.init();\n return this.executeWithTimeout(\n () =>\n this.sendMessage<CodeExecutionResult>(\n 'execute-code',\n {\n code,\n functionName,\n inputs,\n executionStyle,\n language,\n },\n EXECUTION_TIMEOUT_MS + 2000\n ),\n EXECUTION_TIMEOUT_MS\n );\n }\n\n async executeCodeInterviewMode(\n code: string,\n functionName: string,\n inputs: Record<string, unknown>,\n executionStyle: JavaScriptExecutionStyle = 'function',\n language: JavaScriptWorkerLanguage = 'javascript'\n ): Promise<CodeExecutionResult> {\n await this.init();\n\n try {\n const result = await this.executeWithTimeout(\n () =>\n this.sendMessage<CodeExecutionResult>(\n 'execute-code-interview',\n {\n code,\n functionName,\n inputs,\n executionStyle,\n language,\n },\n INTERVIEW_MODE_TIMEOUT_MS + 2000\n ),\n INTERVIEW_MODE_TIMEOUT_MS\n );\n\n if (!result.success && result.error) {\n const normalized = result.error.toLowerCase();\n const isTimeoutOrResourceLimit =\n normalized.includes('timed out') ||\n normalized.includes('infinite loop') ||\n normalized.includes('line-limit') ||\n normalized.includes('single-line-limit') ||\n normalized.includes('recursion-limit') ||\n normalized.includes('trace-limit') ||\n normalized.includes('line events') ||\n normalized.includes('trace steps') ||\n normalized.includes('call depth');\n if (isTimeoutOrResourceLimit) {\n return {\n success: false,\n output: null,\n error: 'Time Limit Exceeded',\n consoleOutput: result.consoleOutput ?? [],\n };\n }\n }\n\n return result;\n } catch {\n return {\n success: false,\n output: null,\n error: 'Time Limit Exceeded',\n consoleOutput: [],\n };\n }\n }\n\n terminate(): void {\n this.terminateAndReset();\n }\n}\n\nexport function isJavaScriptWorkerSupported(): boolean {\n return typeof Worker !== 'undefined';\n}\n"],"mappings":";AAwCA,IAAM,uBAAuB;AAG7B,IAAM,4BAA4B;AAIlC,IAAM,qBAAqB;AAG3B,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAE3B,IAAM,0BAA0B;AAEzB,IAAM,sBAAN,MAA0B;AAAA,EAW/B,YAA6B,SAAqC;AAArC;AAC3B,SAAK,QAAQ,QAAQ,SAAS,QAAQ,IAAI,aAAa;AAAA,EACzD;AAAA,EAZQ,SAAwB;AAAA,EACxB,kBAAkB,oBAAI,IAA+B;AAAA,EACrD,YAAY;AAAA,EACZ,iBAAiB;AAAA,EACjB,cAA0C;AAAA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AAM,2BACJ,WAAW,SAAS,WAAW,KAC/B,WAAW,SAAS,eAAe,KACnC,WAAW,SAAS,YAAY,KAChC,WAAW,SAAS,mBAAmB,KACvC,WAAW,SAAS,iBAAiB,KACrC,WAAW,SAAS,aAAa,KACjC,WAAW,SAAS,aAAa,KACjC,WAAW,SAAS,aAAa,KACjC,WAAW,SAAS,YAAY;AAClC,YAAI,0BAA0B;AAC5B,iBAAO;AAAA,YACL,SAAS;AAAA,YACT,QAAQ;AAAA,YACR,OAAO;AAAA,YACP,eAAe,OAAO,iBAAiB,CAAC;AAAA,UAC1C;AAAA,QACF;AAAA,MACF;AAEA,aAAO;AAAA,IACT,QAAQ;AACN,aAAO;AAAA,QACL,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,OAAO;AAAA,QACP,eAAe,CAAC;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,YAAkB;AAChB,SAAK,kBAAkB;AAAA,EACzB;AACF;AAEO,SAAS,8BAAuC;AACrD,SAAO,OAAO,WAAW;AAC3B;","names":["pending","EXECUTION_TIMEOUT_MS","INTERVIEW_MODE_TIMEOUT_MS","TRACING_TIMEOUT_MS","INIT_TIMEOUT_MS","MESSAGE_TIMEOUT_MS","WORKER_READY_TIMEOUT_MS","pending"]}
@@ -0,0 +1,549 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // packages/harness-javascript/src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ TYPESCRIPT_RUNTIME_DECLARATIONS: () => TYPESCRIPT_RUNTIME_DECLARATIONS,
24
+ executeJavaScriptCode: () => executeJavaScriptCode,
25
+ executeJavaScriptWithTracing: () => executeJavaScriptWithTracing,
26
+ executeTypeScriptCode: () => executeTypeScriptCode,
27
+ withTypeScriptRuntimeDeclarations: () => withTypeScriptRuntimeDeclarations
28
+ });
29
+ module.exports = __toCommonJS(src_exports);
30
+
31
+ // packages/harness-javascript/src/typescript-runtime-declarations.ts
32
+ var TYPESCRIPT_RUNTIME_DECLARATIONS = `
33
+ declare class ListNode {
34
+ val: any;
35
+ next: ListNode | SerializedListNode | SerializedRef | null;
36
+ prev?: ListNode | SerializedListNode | SerializedRef | null;
37
+ constructor(val?: any, next?: ListNode | null);
38
+ }
39
+
40
+ declare class TreeNode {
41
+ val: any;
42
+ left: TreeNode | SerializedTreeNode | SerializedRef | null;
43
+ right: TreeNode | SerializedTreeNode | SerializedRef | null;
44
+ constructor(val?: any, left?: TreeNode | null, right?: TreeNode | null);
45
+ }
46
+
47
+ type SerializedRef = { __ref__: string };
48
+
49
+ type SerializedListNode = {
50
+ __id__?: string;
51
+ __type__?: 'ListNode';
52
+ val?: any;
53
+ next?: SerializedListNode | SerializedRef | ListNode | null;
54
+ prev?: SerializedListNode | SerializedRef | ListNode | null;
55
+ };
56
+
57
+ type SerializedTreeNode = {
58
+ __id__?: string;
59
+ __type__?: 'TreeNode';
60
+ val?: any;
61
+ left?: SerializedTreeNode | SerializedRef | TreeNode | null;
62
+ right?: SerializedTreeNode | SerializedRef | TreeNode | null;
63
+ };
64
+ `;
65
+ function withTypeScriptRuntimeDeclarations(sourceCode) {
66
+ return `${sourceCode}
67
+
68
+ ${TYPESCRIPT_RUNTIME_DECLARATIONS}
69
+ `;
70
+ }
71
+
72
+ // packages/harness-javascript/src/javascript-executor.ts
73
+ var typeScriptModulePromise = null;
74
+ async function getTypeScriptModule() {
75
+ if (!typeScriptModulePromise) {
76
+ const specifier = "typescript";
77
+ typeScriptModulePromise = import(
78
+ /* webpackIgnore: true */
79
+ specifier
80
+ );
81
+ }
82
+ return typeScriptModulePromise;
83
+ }
84
+ function performanceNow() {
85
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
86
+ return performance.now();
87
+ }
88
+ return Date.now();
89
+ }
90
+ function formatConsoleArg(value) {
91
+ if (typeof value === "string") return value;
92
+ if (typeof value === "number" || typeof value === "boolean" || value === null || value === void 0) {
93
+ return String(value);
94
+ }
95
+ try {
96
+ return JSON.stringify(value);
97
+ } catch {
98
+ return String(value);
99
+ }
100
+ }
101
+ function createConsoleProxy(output) {
102
+ const capture = (...args) => {
103
+ output.push(args.map(formatConsoleArg).join(" "));
104
+ };
105
+ return {
106
+ ...console,
107
+ log: capture,
108
+ info: capture,
109
+ warn: capture,
110
+ error: capture,
111
+ debug: capture
112
+ };
113
+ }
114
+ function isLikelyTreeNodeValue(value) {
115
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
116
+ const hasValue = "val" in value || "value" in value;
117
+ const hasTreeLinks = "left" in value || "right" in value;
118
+ return hasValue && hasTreeLinks;
119
+ }
120
+ function isLikelyListNodeValue(value) {
121
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
122
+ const hasValue = "val" in value || "value" in value;
123
+ const hasTreeLinks = "left" in value || "right" in value;
124
+ const hasListLinks = "next" in value || "prev" in value;
125
+ return hasValue && hasListLinks && !hasTreeLinks;
126
+ }
127
+ function serializeValue(value, depth = 0, seen = /* @__PURE__ */ new WeakSet(), nodeRefState = { ids: /* @__PURE__ */ new Map(), nextId: 1 }) {
128
+ if (depth > 48) return "<max depth>";
129
+ if (value === null || value === void 0) return value;
130
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
131
+ return value;
132
+ }
133
+ if (typeof value === "bigint") {
134
+ return Number.isSafeInteger(Number(value)) ? Number(value) : String(value);
135
+ }
136
+ if (typeof value === "function") {
137
+ return "<function>";
138
+ }
139
+ if (Array.isArray(value)) {
140
+ return value.map((item) => serializeValue(item, depth + 1, seen));
141
+ }
142
+ if (value instanceof Set) {
143
+ return {
144
+ __type__: "set",
145
+ values: [...value].map((item) => serializeValue(item, depth + 1, seen, nodeRefState))
146
+ };
147
+ }
148
+ if (value instanceof Map) {
149
+ return {
150
+ __type__: "map",
151
+ entries: [...value.entries()].map(([k, v]) => [
152
+ serializeValue(k, depth + 1, seen, nodeRefState),
153
+ serializeValue(v, depth + 1, seen, nodeRefState)
154
+ ])
155
+ };
156
+ }
157
+ if (typeof value === "object") {
158
+ if (isLikelyTreeNodeValue(value) || isLikelyListNodeValue(value)) {
159
+ const objectValue = value;
160
+ const nodeValue = value;
161
+ const existingId = nodeRefState.ids.get(objectValue);
162
+ if (existingId) {
163
+ return { __ref__: existingId };
164
+ }
165
+ const isTree = isLikelyTreeNodeValue(value);
166
+ const nodePrefix = isTree ? "tree" : "list";
167
+ const nodeId = `${nodePrefix}-${nodeRefState.nextId++}`;
168
+ nodeRefState.ids.set(objectValue, nodeId);
169
+ if (isTree) {
170
+ return {
171
+ __type__: "TreeNode",
172
+ __id__: nodeId,
173
+ val: serializeValue(nodeValue.val ?? nodeValue.value ?? null, depth + 1, seen, nodeRefState),
174
+ left: serializeValue(nodeValue.left ?? null, depth + 1, seen, nodeRefState),
175
+ right: serializeValue(nodeValue.right ?? null, depth + 1, seen, nodeRefState)
176
+ };
177
+ }
178
+ return {
179
+ __type__: "ListNode",
180
+ __id__: nodeId,
181
+ val: serializeValue(nodeValue.val ?? nodeValue.value ?? null, depth + 1, seen, nodeRefState),
182
+ next: serializeValue(nodeValue.next ?? null, depth + 1, seen, nodeRefState),
183
+ ..."prev" in nodeValue ? { prev: serializeValue(nodeValue.prev ?? null, depth + 1, seen, nodeRefState) } : {}
184
+ };
185
+ }
186
+ if (seen.has(value)) return "<cycle>";
187
+ seen.add(value);
188
+ const out = {};
189
+ for (const [k, v] of Object.entries(value)) {
190
+ out[k] = serializeValue(v, depth + 1, seen, nodeRefState);
191
+ }
192
+ seen.delete(value);
193
+ return out;
194
+ }
195
+ return String(value);
196
+ }
197
+ function extractUserErrorLine(error) {
198
+ if (typeof error === "object" && error && "__tracecodeLine" in error) {
199
+ const line2 = Number(error.__tracecodeLine);
200
+ if (Number.isFinite(line2)) return line2;
201
+ }
202
+ const stack = typeof error === "object" && error && "stack" in error ? String(error.stack ?? "") : "";
203
+ if (!stack) return void 0;
204
+ const match = stack.match(/<anonymous>:(\d+):\d+/);
205
+ if (!match) return void 0;
206
+ const line = Number.parseInt(match[1], 10);
207
+ return Number.isFinite(line) ? line : void 0;
208
+ }
209
+ function isPlainObjectRecord(value) {
210
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
211
+ return Object.prototype.toString.call(value) === "[object Object]";
212
+ }
213
+ function collectReferenceTargets(value, byId, seen) {
214
+ if (value === null || value === void 0) return;
215
+ if (typeof value !== "object") return;
216
+ if (seen.has(value)) return;
217
+ seen.add(value);
218
+ if (Array.isArray(value)) {
219
+ for (const item of value) {
220
+ collectReferenceTargets(item, byId, seen);
221
+ }
222
+ return;
223
+ }
224
+ if (!isPlainObjectRecord(value)) return;
225
+ if (typeof value.__id__ === "string" && value.__id__.length > 0 && !byId.has(value.__id__)) {
226
+ byId.set(value.__id__, value);
227
+ }
228
+ for (const nested of Object.values(value)) {
229
+ collectReferenceTargets(nested, byId, seen);
230
+ }
231
+ }
232
+ function resolveReferenceGraph(value, byId, resolved) {
233
+ if (value === null || value === void 0) return value;
234
+ if (typeof value !== "object") return value;
235
+ if (resolved.has(value)) {
236
+ return resolved.get(value);
237
+ }
238
+ if (Array.isArray(value)) {
239
+ const out2 = [];
240
+ resolved.set(value, out2);
241
+ for (const item of value) {
242
+ out2.push(resolveReferenceGraph(item, byId, resolved));
243
+ }
244
+ return out2;
245
+ }
246
+ if (!isPlainObjectRecord(value)) {
247
+ return value;
248
+ }
249
+ const keys = Object.keys(value);
250
+ if (keys.length === 1 && typeof value.__ref__ === "string") {
251
+ const target = byId.get(value.__ref__);
252
+ if (!target) return null;
253
+ return resolveReferenceGraph(target, byId, resolved);
254
+ }
255
+ const out = {};
256
+ resolved.set(value, out);
257
+ for (const [key, nested] of Object.entries(value)) {
258
+ out[key] = resolveReferenceGraph(nested, byId, resolved);
259
+ }
260
+ return out;
261
+ }
262
+ function normalizeInputs(inputs) {
263
+ if (!inputs || typeof inputs !== "object" || Array.isArray(inputs)) return {};
264
+ const byId = /* @__PURE__ */ new Map();
265
+ collectReferenceTargets(inputs, byId, /* @__PURE__ */ new WeakSet());
266
+ if (byId.size === 0) {
267
+ return inputs;
268
+ }
269
+ const hydrated = resolveReferenceGraph(inputs, byId, /* @__PURE__ */ new WeakMap());
270
+ if (!hydrated || typeof hydrated !== "object" || Array.isArray(hydrated)) {
271
+ return inputs;
272
+ }
273
+ return hydrated;
274
+ }
275
+ function collectSimpleParameterNames(ts, functionLikeNode) {
276
+ const names = [];
277
+ for (const parameter of functionLikeNode.parameters ?? []) {
278
+ if (!ts.isIdentifier(parameter.name)) {
279
+ return null;
280
+ }
281
+ if (parameter.name.text === "this") {
282
+ continue;
283
+ }
284
+ names.push(parameter.name.text);
285
+ }
286
+ return names;
287
+ }
288
+ function getPropertyNameText(ts, name) {
289
+ if (!name) return null;
290
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
291
+ return name.text;
292
+ }
293
+ return null;
294
+ }
295
+ function findFunctionLikeNode(ts, sourceFile, functionName, executionStyle) {
296
+ let found = null;
297
+ const visit = (node) => {
298
+ if (found) return;
299
+ if (executionStyle === "solution-method" && ts.isClassDeclaration(node) && node.name?.text === "Solution") {
300
+ for (const member of node.members) {
301
+ if (found) break;
302
+ if (ts.isMethodDeclaration(member) && getPropertyNameText(ts, member.name) === functionName) {
303
+ found = member;
304
+ break;
305
+ }
306
+ if (ts.isPropertyDeclaration(member) && getPropertyNameText(ts, member.name) === functionName && member.initializer && (ts.isArrowFunction(member.initializer) || ts.isFunctionExpression(member.initializer))) {
307
+ found = member.initializer;
308
+ break;
309
+ }
310
+ }
311
+ return;
312
+ }
313
+ if (executionStyle === "function") {
314
+ if (ts.isFunctionDeclaration(node) && node.name?.text === functionName) {
315
+ found = node;
316
+ return;
317
+ }
318
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === functionName && node.initializer && (ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer))) {
319
+ found = node.initializer;
320
+ return;
321
+ }
322
+ }
323
+ ts.forEachChild(node, visit);
324
+ };
325
+ visit(sourceFile);
326
+ return found;
327
+ }
328
+ async function resolveOrderedInputKeys(code, functionName, inputs, executionStyle) {
329
+ const fallbackKeys = Object.keys(inputs);
330
+ if (!functionName || executionStyle === "ops-class" || fallbackKeys.length <= 1) {
331
+ return fallbackKeys;
332
+ }
333
+ try {
334
+ const ts = await getTypeScriptModule();
335
+ const sourceFile = ts.createSourceFile("runtime-input.js", code, ts.ScriptTarget.ES2020, true, ts.ScriptKind.JS);
336
+ const target = findFunctionLikeNode(ts, sourceFile, functionName, executionStyle);
337
+ if (!target) {
338
+ return fallbackKeys;
339
+ }
340
+ const parameterNames = collectSimpleParameterNames(ts, target);
341
+ if (!parameterNames || parameterNames.length === 0) {
342
+ return fallbackKeys;
343
+ }
344
+ const matchedKeys = parameterNames.filter((name) => Object.prototype.hasOwnProperty.call(inputs, name));
345
+ if (matchedKeys.length === 0) {
346
+ return fallbackKeys;
347
+ }
348
+ const extras = fallbackKeys.filter((key) => !matchedKeys.includes(key));
349
+ return [...matchedKeys, ...extras];
350
+ } catch {
351
+ return fallbackKeys;
352
+ }
353
+ }
354
+ function buildRunner(code, executionStyle, argNames) {
355
+ if (executionStyle === "function") {
356
+ return new Function(
357
+ "console",
358
+ "__functionName",
359
+ ...argNames,
360
+ `"use strict";
361
+ ${code}
362
+ let __target;
363
+ try {
364
+ __target = eval(__functionName);
365
+ } catch (_err) {
366
+ __target = undefined;
367
+ }
368
+ if (typeof __target !== 'function') {
369
+ throw new Error('Function "' + __functionName + '" not found');
370
+ }
371
+ return __target(${argNames.join(", ")});`
372
+ );
373
+ }
374
+ if (executionStyle === "solution-method") {
375
+ return new Function(
376
+ "console",
377
+ "__functionName",
378
+ ...argNames,
379
+ `"use strict";
380
+ ${code}
381
+ if (typeof Solution !== 'function') {
382
+ throw new Error('Class "Solution" not found');
383
+ }
384
+ const __solver = new Solution();
385
+ const __method = __solver[__functionName];
386
+ if (typeof __method !== 'function') {
387
+ throw new Error('Method "Solution.' + __functionName + '" not found');
388
+ }
389
+ return __method.call(__solver, ${argNames.join(", ")});`
390
+ );
391
+ }
392
+ if (executionStyle === "ops-class") {
393
+ return new Function(
394
+ "console",
395
+ "__className",
396
+ "__operations",
397
+ "__arguments",
398
+ `"use strict";
399
+ ${code}
400
+ if (!Array.isArray(__operations) || !Array.isArray(__arguments)) {
401
+ throw new Error('ops-class execution requires inputs.operations and inputs.arguments (or ops/args)');
402
+ }
403
+ if (__operations.length !== __arguments.length) {
404
+ throw new Error('operations and arguments must have the same length');
405
+ }
406
+ let __targetClass;
407
+ try {
408
+ __targetClass = eval(__className);
409
+ } catch (_err) {
410
+ __targetClass = undefined;
411
+ }
412
+ if (typeof __targetClass !== 'function') {
413
+ throw new Error('Class "' + __className + '" not found');
414
+ }
415
+ let __instance = null;
416
+ const __out = [];
417
+ for (let __i = 0; __i < __operations.length; __i++) {
418
+ const __op = __operations[__i];
419
+ let __callArgs = __arguments[__i];
420
+ if (__callArgs === null || __callArgs === undefined) {
421
+ __callArgs = [];
422
+ }
423
+ if (!Array.isArray(__callArgs)) {
424
+ __callArgs = [__callArgs];
425
+ }
426
+ if (__i === 0) {
427
+ __instance = new __targetClass(...__callArgs);
428
+ __out.push(null);
429
+ continue;
430
+ }
431
+ if (!__instance || typeof __instance[__op] !== 'function') {
432
+ throw new Error('Required method "' + __op + '" is not implemented on ' + (__className || 'target class'));
433
+ }
434
+ __out.push(__instance[__op](...__callArgs));
435
+ }
436
+ return __out;`
437
+ );
438
+ }
439
+ throw new Error(`Execution style "${executionStyle}" is not supported for JavaScript runtime yet.`);
440
+ }
441
+ function getOpsClassInputs(inputs) {
442
+ const operations = Array.isArray(inputs.operations) ? inputs.operations : Array.isArray(inputs.ops) ? inputs.ops : null;
443
+ const argumentsList = Array.isArray(inputs.arguments) ? inputs.arguments : Array.isArray(inputs.args) ? inputs.args : null;
444
+ return { operations, argumentsList };
445
+ }
446
+ async function transpileTypeScript(code) {
447
+ const ts = await getTypeScriptModule();
448
+ const transpileInput = withTypeScriptRuntimeDeclarations(code);
449
+ const transpiled = ts.transpileModule(transpileInput, {
450
+ compilerOptions: {
451
+ target: ts.ScriptTarget.ES2020,
452
+ module: ts.ModuleKind.None,
453
+ strict: false,
454
+ esModuleInterop: true
455
+ },
456
+ reportDiagnostics: true,
457
+ fileName: "solution.ts"
458
+ });
459
+ const diagnostics = Array.isArray(transpiled.diagnostics) ? transpiled.diagnostics : [];
460
+ const errors = diagnostics.filter((diag) => diag.category === ts.DiagnosticCategory.Error);
461
+ if (errors.length > 0) {
462
+ const first = errors[0];
463
+ const messageText = ts.flattenDiagnosticMessageText(first.messageText, "\n");
464
+ let lineNumber;
465
+ if (first.file && typeof first.start === "number") {
466
+ const position = first.file.getLineAndCharacterOfPosition(first.start);
467
+ lineNumber = position.line + 1;
468
+ }
469
+ const error = new Error(
470
+ lineNumber ? `TypeScript transpilation failed (line ${lineNumber}): ${messageText}` : `TypeScript transpilation failed: ${messageText}`
471
+ );
472
+ if (lineNumber) {
473
+ error.__tracecodeLine = lineNumber;
474
+ }
475
+ throw error;
476
+ }
477
+ return transpiled.outputText;
478
+ }
479
+ async function executeJavaScriptCode(code, functionName, inputs, executionStyle = "function") {
480
+ const consoleOutput = [];
481
+ const consoleProxy = createConsoleProxy(consoleOutput);
482
+ const normalizedInputs = normalizeInputs(inputs);
483
+ try {
484
+ let output;
485
+ if (executionStyle === "ops-class") {
486
+ const { operations, argumentsList } = getOpsClassInputs(normalizedInputs);
487
+ const runner = buildRunner(code, executionStyle, []);
488
+ output = await Promise.resolve(runner(consoleProxy, functionName, operations, argumentsList));
489
+ } else {
490
+ const inputKeys = await resolveOrderedInputKeys(code, functionName, normalizedInputs, executionStyle);
491
+ const argNames = inputKeys.map((_, index) => `__arg${index}`);
492
+ const argValues = inputKeys.map((key) => normalizedInputs[key]);
493
+ const runner = buildRunner(code, executionStyle, argNames);
494
+ output = await Promise.resolve(runner(consoleProxy, functionName, ...argValues));
495
+ }
496
+ return {
497
+ success: true,
498
+ output: serializeValue(output),
499
+ consoleOutput
500
+ };
501
+ } catch (error) {
502
+ return {
503
+ success: false,
504
+ output: null,
505
+ error: error instanceof Error ? error.message : String(error),
506
+ errorLine: extractUserErrorLine(error),
507
+ consoleOutput
508
+ };
509
+ }
510
+ }
511
+ async function executeJavaScriptWithTracing(code, functionName, inputs, executionStyle = "function") {
512
+ const startedAt = performanceNow();
513
+ const codeResult = await executeJavaScriptCode(code, functionName ?? "", inputs, executionStyle);
514
+ const executionTimeMs = performanceNow() - startedAt;
515
+ if (!codeResult.success) {
516
+ return {
517
+ success: false,
518
+ error: codeResult.error,
519
+ errorLine: codeResult.errorLine,
520
+ trace: [],
521
+ executionTimeMs,
522
+ consoleOutput: codeResult.consoleOutput ?? [],
523
+ lineEventCount: 0,
524
+ traceStepCount: 0
525
+ };
526
+ }
527
+ return {
528
+ success: true,
529
+ output: codeResult.output,
530
+ trace: [],
531
+ executionTimeMs,
532
+ consoleOutput: codeResult.consoleOutput ?? [],
533
+ lineEventCount: 0,
534
+ traceStepCount: 0
535
+ };
536
+ }
537
+ async function executeTypeScriptCode(code, functionName, inputs, executionStyle = "function") {
538
+ const transpiledCode = await transpileTypeScript(code);
539
+ return executeJavaScriptCode(transpiledCode, functionName, inputs, executionStyle);
540
+ }
541
+ // Annotate the CommonJS export names for ESM import in node:
542
+ 0 && (module.exports = {
543
+ TYPESCRIPT_RUNTIME_DECLARATIONS,
544
+ executeJavaScriptCode,
545
+ executeJavaScriptWithTracing,
546
+ executeTypeScriptCode,
547
+ withTypeScriptRuntimeDeclarations
548
+ });
549
+ //# sourceMappingURL=javascript.cjs.map