@tracecode/harness 0.9.2 → 0.9.3

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.
@@ -1750,45 +1750,600 @@ function normalizeCSharpResult(result, options = {}) {
1750
1750
  };
1751
1751
  }
1752
1752
 
1753
- async function handleMessage(message) {
1754
- if (message.type === 'init') {
1755
- return handleInit(message.payload?.assetBaseUrl);
1756
- }
1753
+ function csharpStringLiteral(value) {
1754
+ return JSON.stringify(String(value ?? ''));
1755
+ }
1757
1756
 
1758
- if (message.type === 'warmup') {
1759
- return warmRuntime(message.payload?.assetBaseUrl);
1757
+ function csharpIdentifier(value) {
1758
+ const text = String(value ?? '');
1759
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(text) ? text : null;
1760
+ }
1761
+
1762
+ function splitCSharpLeadingUsingSource(code) {
1763
+ const lines = String(code ?? '').split(/\r?\n/);
1764
+ const prelude = [];
1765
+ let index = 0;
1766
+ for (; index < lines.length; index += 1) {
1767
+ const line = lines[index] ?? '';
1768
+ const trimmed = line.trim();
1769
+ if (
1770
+ trimmed === '' ||
1771
+ trimmed.startsWith('//') ||
1772
+ /^using\s+/.test(trimmed) && trimmed.endsWith(';') ||
1773
+ /^extern\s+alias\s+/.test(trimmed) && trimmed.endsWith(';')
1774
+ ) {
1775
+ prelude.push(line);
1776
+ continue;
1777
+ }
1778
+ break;
1760
1779
  }
1780
+ return {
1781
+ prelude: prelude.join('\n'),
1782
+ body: lines.slice(index).join('\n'),
1783
+ };
1784
+ }
1761
1785
 
1762
- if (message.type === 'execute-code-batch') {
1763
- const startedAt = now();
1764
- const inputBatch = Array.isArray(message.payload?.inputBatch)
1765
- ? message.payload.inputBatch.map((inputs) => (inputs && typeof inputs === 'object' ? inputs : {}))
1766
- : [];
1767
- if (inputBatch.length === 0) {
1768
- return {
1769
- success: false,
1770
- results: [],
1771
- error: 'C# batch execution requires a non-empty inputBatch array.',
1772
- consoleOutput: [],
1773
- timings: { totalMs: elapsedMs(startedAt) },
1774
- };
1786
+ function indentCSharpSource(code, spaces = 4) {
1787
+ const prefix = ' '.repeat(spaces);
1788
+ return String(code ?? '')
1789
+ .split(/\r?\n/)
1790
+ .map((line) => (line.trim() ? `${prefix}${line}` : line))
1791
+ .join('\n');
1792
+ }
1793
+
1794
+ function buildCSharpBatchScriptSource(payload) {
1795
+ const code = String(payload?.code ?? '');
1796
+ const executionStyle = payload?.executionStyle ?? 'solution-method';
1797
+ const functionName = String(payload?.functionName ?? '');
1798
+ const functionNameLiteral = csharpStringLiteral(functionName);
1799
+
1800
+ if (executionStyle === 'ops-class') {
1801
+ const className = csharpIdentifier(functionName);
1802
+ if (!className) {
1803
+ throw new Error('C# ops-class batch execution requires a simple class name.');
1804
+ }
1805
+ return `${code}
1806
+
1807
+ object? result;
1808
+ {
1809
+ var __tracecodeBatchCases = TraceCode.Internal.TraceCodeJsonInput.Read<System.Text.Json.JsonElement[]>("__tracecodeBatchInputs", 0) ?? System.Array.Empty<System.Text.Json.JsonElement>();
1810
+ var __tracecodeBatchResults = new System.Collections.Generic.List<object?>();
1811
+
1812
+ foreach (var __tracecodeBatchCase in __tracecodeBatchCases)
1813
+ {
1814
+ var __tracecodeBatchClock = System.Diagnostics.Stopwatch.StartNew();
1815
+ var __tracecodeOriginalOut = System.Console.Out;
1816
+ using var __tracecodeCaseOut = new System.IO.StringWriter();
1817
+ try
1818
+ {
1819
+ System.Console.SetOut(__tracecodeCaseOut);
1820
+ object? __tracecodeOutput = __TraceCodeRunOpsCase(__tracecodeBatchCase);
1821
+ __tracecodeBatchClock.Stop();
1822
+ __tracecodeBatchResults.Add(new System.Collections.Generic.Dictionary<string, object?>
1823
+ {
1824
+ ["success"] = true,
1825
+ ["output"] = __tracecodeOutput,
1826
+ ["consoleOutput"] = __TraceCodeSplitConsole(__tracecodeCaseOut.ToString()),
1827
+ ["timings"] = new System.Collections.Generic.Dictionary<string, object?> { ["runMs"] = __tracecodeBatchClock.Elapsed.TotalMilliseconds },
1828
+ });
1829
+ }
1830
+ catch (System.Exception __tracecodeError)
1831
+ {
1832
+ __tracecodeBatchClock.Stop();
1833
+ __tracecodeBatchResults.Add(new System.Collections.Generic.Dictionary<string, object?>
1834
+ {
1835
+ ["success"] = false,
1836
+ ["error"] = __tracecodeError.GetBaseException().Message,
1837
+ ["output"] = null,
1838
+ ["consoleOutput"] = __TraceCodeSplitConsole(__tracecodeCaseOut.ToString()),
1839
+ ["timings"] = new System.Collections.Generic.Dictionary<string, object?> { ["runMs"] = __tracecodeBatchClock.Elapsed.TotalMilliseconds },
1840
+ });
1841
+ }
1842
+ finally
1843
+ {
1844
+ System.Console.SetOut(__tracecodeOriginalOut);
1845
+ }
1846
+ }
1847
+
1848
+ result = __tracecodeBatchResults;
1849
+ }
1850
+
1851
+ object? __TraceCodeRunOpsCase(System.Text.Json.JsonElement __tracecodeRawCase)
1852
+ {
1853
+ string[] __tracecodeOperations = __TraceCodeReadCaseValue<string[]>(__tracecodeRawCase, "operations", 0) ?? System.Array.Empty<string>();
1854
+ System.Text.Json.JsonElement[][] __tracecodeArguments = __TraceCodeReadCaseValue<System.Text.Json.JsonElement[][]>(__tracecodeRawCase, "arguments", 1) ?? System.Array.Empty<System.Text.Json.JsonElement[]>();
1855
+ if (__tracecodeOperations.Length != __tracecodeArguments.Length)
1856
+ {
1857
+ throw new System.InvalidOperationException("operations and arguments must have the same length");
1858
+ }
1859
+
1860
+ System.Type __tracecodeTargetType = typeof(${className});
1861
+ object? __tracecodeInstance = null;
1862
+ var __tracecodeOutput = new System.Collections.Generic.List<object?>();
1863
+ for (int __tracecodeIndex = 0; __tracecodeIndex < __tracecodeOperations.Length; __tracecodeIndex++)
1864
+ {
1865
+ string __tracecodeOperation = __tracecodeOperations[__tracecodeIndex];
1866
+ System.Text.Json.JsonElement[] __tracecodeRawArgs = __tracecodeIndex < __tracecodeArguments.Length ? __tracecodeArguments[__tracecodeIndex] : System.Array.Empty<System.Text.Json.JsonElement>();
1867
+ if (__tracecodeInstance is null && (__tracecodeIndex == 0
1868
+ || string.Equals(__tracecodeOperation, ${csharpStringLiteral(className)}, System.StringComparison.OrdinalIgnoreCase)
1869
+ || string.Equals(__tracecodeOperation, "__init__", System.StringComparison.OrdinalIgnoreCase)))
1870
+ {
1871
+ var __tracecodeConstructor = __tracecodeTargetType
1872
+ .GetConstructors(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
1873
+ .FirstOrDefault(__tracecodeCandidate => __tracecodeCandidate.GetParameters().Length == __tracecodeRawArgs.Length)
1874
+ ?? throw new System.InvalidOperationException($"No constructor with {__tracecodeRawArgs.Length} arguments.");
1875
+ __tracecodeInstance = __tracecodeConstructor.Invoke(__TraceCodeConvertArgs(__tracecodeRawArgs, __tracecodeConstructor.GetParameters()));
1876
+ __tracecodeOutput.Add(null);
1877
+ continue;
1878
+ }
1879
+
1880
+ if (__tracecodeInstance is null)
1881
+ {
1882
+ throw new System.InvalidOperationException("Ops-class operation invoked before constructor.");
1883
+ }
1884
+
1885
+ var __tracecodeMethod = __tracecodeTargetType
1886
+ .GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
1887
+ .FirstOrDefault(__tracecodeCandidate =>
1888
+ string.Equals(__tracecodeCandidate.Name, __tracecodeOperation, System.StringComparison.OrdinalIgnoreCase)
1889
+ && __tracecodeCandidate.GetParameters().Length == __tracecodeRawArgs.Length)
1890
+ ?? throw new System.InvalidOperationException($"No method {__tracecodeOperation} with {__tracecodeRawArgs.Length} arguments.");
1891
+ object?[] __tracecodeArgs = __TraceCodeConvertArgs(__tracecodeRawArgs, __tracecodeMethod.GetParameters());
1892
+ object? __tracecodeResult = __tracecodeMethod.Invoke(__tracecodeInstance, __tracecodeArgs);
1893
+ __tracecodeOutput.Add(__tracecodeMethod.ReturnType == typeof(void) ? null : __tracecodeResult);
1894
+ }
1895
+ return __tracecodeOutput;
1896
+ }
1897
+
1898
+ object?[] __TraceCodeConvertArgs(System.Text.Json.JsonElement[] __tracecodeRawArgs, System.Reflection.ParameterInfo[] __tracecodeParameters)
1899
+ {
1900
+ object?[] __tracecodeConverted = new object?[__tracecodeParameters.Length];
1901
+ for (int __tracecodeIndex = 0; __tracecodeIndex < __tracecodeParameters.Length; __tracecodeIndex++)
1902
+ {
1903
+ System.Type __tracecodeTargetType = __tracecodeParameters[__tracecodeIndex].ParameterType;
1904
+ if (__tracecodeTargetType.IsByRef)
1905
+ {
1906
+ __tracecodeTargetType = __tracecodeTargetType.GetElementType() ?? typeof(object);
1907
+ }
1908
+ __tracecodeConverted[__tracecodeIndex] = TraceCode.Internal.TraceCodeJsonInput.Convert(__tracecodeRawArgs[__tracecodeIndex], __tracecodeTargetType);
1909
+ }
1910
+ return __tracecodeConverted;
1911
+ }
1912
+
1913
+ T? __TraceCodeReadCaseValue<T>(System.Text.Json.JsonElement __tracecodeRawCase, string __tracecodeName, int __tracecodeIndex)
1914
+ {
1915
+ if (__TraceCodeTryGetCaseValue(__tracecodeRawCase, __tracecodeName, __tracecodeIndex, out var __tracecodeValue))
1916
+ {
1917
+ return (T?)TraceCode.Internal.TraceCodeJsonInput.Convert(__tracecodeValue, typeof(T));
1918
+ }
1919
+ return default;
1920
+ }
1921
+
1922
+ bool __TraceCodeTryGetCaseValue(System.Text.Json.JsonElement __tracecodeRawCase, string __tracecodeName, int __tracecodeIndex, out System.Text.Json.JsonElement __tracecodeValue)
1923
+ {
1924
+ if (__tracecodeRawCase.ValueKind == System.Text.Json.JsonValueKind.Object)
1925
+ {
1926
+ if (__tracecodeRawCase.TryGetProperty(__tracecodeName, out __tracecodeValue))
1927
+ {
1928
+ return true;
1929
+ }
1930
+ int __tracecodePropertyIndex = 0;
1931
+ foreach (var __tracecodeProperty in __tracecodeRawCase.EnumerateObject())
1932
+ {
1933
+ if (__tracecodePropertyIndex == __tracecodeIndex)
1934
+ {
1935
+ __tracecodeValue = __tracecodeProperty.Value;
1936
+ return true;
1937
+ }
1938
+ __tracecodePropertyIndex++;
1939
+ }
1940
+ }
1941
+ __tracecodeValue = default;
1942
+ return false;
1943
+ }
1944
+
1945
+ string[] __TraceCodeSplitConsole(string __tracecodeText) =>
1946
+ __tracecodeText.Replace("\\r\\n", "\\n", System.StringComparison.Ordinal).Split('\\n', System.StringSplitOptions.RemoveEmptyEntries);
1947
+ `;
1948
+ }
1949
+
1950
+ if (executionStyle === 'function' && functionName.trim() === '') {
1951
+ const scriptSource = splitCSharpLeadingUsingSource(code);
1952
+ return `${scriptSource.prelude}
1953
+
1954
+ object? __TraceCodeUserScriptRun()
1955
+ {
1956
+ ${indentCSharpSource(scriptSource.body)}
1957
+ return result;
1958
+ }
1959
+
1960
+ object? result;
1961
+ {
1962
+ var __tracecodeBatchCases = TraceCode.Internal.TraceCodeJsonInput.Read<System.Text.Json.JsonElement[]>("__tracecodeBatchInputs", 0) ?? System.Array.Empty<System.Text.Json.JsonElement>();
1963
+ var __tracecodeBatchResults = new System.Collections.Generic.List<object?>();
1964
+
1965
+ foreach (var __tracecodeBatchCase in __tracecodeBatchCases)
1966
+ {
1967
+ var __tracecodeBatchClock = System.Diagnostics.Stopwatch.StartNew();
1968
+ var __tracecodeOriginalOut = System.Console.Out;
1969
+ using var __tracecodeCaseOut = new System.IO.StringWriter();
1970
+ try
1971
+ {
1972
+ System.Console.SetOut(__tracecodeCaseOut);
1973
+ __TraceCodeSetCurrentInputsJson(__tracecodeBatchCase.GetRawText());
1974
+ object? __tracecodeOutput = __TraceCodeUserScriptRun();
1975
+ __tracecodeBatchClock.Stop();
1976
+ __tracecodeBatchResults.Add(new System.Collections.Generic.Dictionary<string, object?>
1977
+ {
1978
+ ["success"] = true,
1979
+ ["output"] = __tracecodeOutput,
1980
+ ["consoleOutput"] = __TraceCodeSplitConsole(__tracecodeCaseOut.ToString()),
1981
+ ["timings"] = new System.Collections.Generic.Dictionary<string, object?> { ["runMs"] = __tracecodeBatchClock.Elapsed.TotalMilliseconds },
1982
+ });
1983
+ }
1984
+ catch (System.Exception __tracecodeError)
1985
+ {
1986
+ __tracecodeBatchClock.Stop();
1987
+ __tracecodeBatchResults.Add(new System.Collections.Generic.Dictionary<string, object?>
1988
+ {
1989
+ ["success"] = false,
1990
+ ["error"] = __tracecodeError.GetBaseException().Message,
1991
+ ["output"] = null,
1992
+ ["consoleOutput"] = __TraceCodeSplitConsole(__tracecodeCaseOut.ToString()),
1993
+ ["timings"] = new System.Collections.Generic.Dictionary<string, object?> { ["runMs"] = __tracecodeBatchClock.Elapsed.TotalMilliseconds },
1994
+ });
1995
+ }
1996
+ finally
1997
+ {
1998
+ System.Console.SetOut(__tracecodeOriginalOut);
1999
+ }
2000
+ }
2001
+
2002
+ result = __tracecodeBatchResults;
2003
+ }
2004
+
2005
+ void __TraceCodeSetCurrentInputsJson(string __tracecodeInputsJson)
2006
+ {
2007
+ var __tracecodeField = typeof(TraceCode.CSharpHost.CompilerHost).GetField(
2008
+ "currentInputsJson",
2009
+ System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
2010
+ __tracecodeField?.SetValue(null, __tracecodeInputsJson);
2011
+ }
2012
+
2013
+ string[] __TraceCodeSplitConsole(string __tracecodeText) =>
2014
+ __tracecodeText.Replace("\\r\\n", "\\n", System.StringComparison.Ordinal).Split('\\n', System.StringSplitOptions.RemoveEmptyEntries);
2015
+ `;
2016
+ }
2017
+
2018
+ return `${code}
2019
+
2020
+ object? result;
2021
+ {
2022
+ var __tracecodeBatchCases = TraceCode.Internal.TraceCodeJsonInput.Read<System.Text.Json.JsonElement[]>("__tracecodeBatchInputs", 0) ?? System.Array.Empty<System.Text.Json.JsonElement>();
2023
+ var __tracecodeBatchResults = new System.Collections.Generic.List<object?>();
2024
+
2025
+ foreach (var __tracecodeBatchCase in __tracecodeBatchCases)
2026
+ {
2027
+ var __tracecodeBatchClock = System.Diagnostics.Stopwatch.StartNew();
2028
+ var __tracecodeOriginalOut = System.Console.Out;
2029
+ using var __tracecodeCaseOut = new System.IO.StringWriter();
2030
+ try
2031
+ {
2032
+ System.Console.SetOut(__tracecodeCaseOut);
2033
+ object? __tracecodeOutput = __TraceCodeRunSolutionCase(__tracecodeBatchCase);
2034
+ __tracecodeBatchClock.Stop();
2035
+ __tracecodeBatchResults.Add(new System.Collections.Generic.Dictionary<string, object?>
2036
+ {
2037
+ ["success"] = true,
2038
+ ["output"] = __tracecodeOutput,
2039
+ ["consoleOutput"] = __TraceCodeSplitConsole(__tracecodeCaseOut.ToString()),
2040
+ ["timings"] = new System.Collections.Generic.Dictionary<string, object?> { ["runMs"] = __tracecodeBatchClock.Elapsed.TotalMilliseconds },
2041
+ });
2042
+ }
2043
+ catch (System.Exception __tracecodeError)
2044
+ {
2045
+ __tracecodeBatchClock.Stop();
2046
+ __tracecodeBatchResults.Add(new System.Collections.Generic.Dictionary<string, object?>
2047
+ {
2048
+ ["success"] = false,
2049
+ ["error"] = __tracecodeError.GetBaseException().Message,
2050
+ ["output"] = null,
2051
+ ["consoleOutput"] = __TraceCodeSplitConsole(__tracecodeCaseOut.ToString()),
2052
+ ["timings"] = new System.Collections.Generic.Dictionary<string, object?> { ["runMs"] = __tracecodeBatchClock.Elapsed.TotalMilliseconds },
2053
+ });
2054
+ }
2055
+ finally
2056
+ {
2057
+ System.Console.SetOut(__tracecodeOriginalOut);
2058
+ }
2059
+ }
2060
+
2061
+ result = __tracecodeBatchResults;
2062
+ }
2063
+
2064
+ object? __TraceCodeRunSolutionCase(System.Text.Json.JsonElement __tracecodeRawCase)
2065
+ {
2066
+ var __tracecodeMethod = __TraceCodeSelectSolutionMethod(__tracecodeRawCase);
2067
+ var __tracecodeParameters = __tracecodeMethod.GetParameters();
2068
+ object?[] __tracecodeArgs = new object?[__tracecodeParameters.Length];
2069
+ for (int __tracecodeIndex = 0; __tracecodeIndex < __tracecodeParameters.Length; __tracecodeIndex++)
2070
+ {
2071
+ var __tracecodeParameter = __tracecodeParameters[__tracecodeIndex];
2072
+ System.Type __tracecodeTargetType = __TraceCodeParameterType(__tracecodeParameter);
2073
+ if (__tracecodeParameter.IsOut)
2074
+ {
2075
+ __tracecodeArgs[__tracecodeIndex] = __TraceCodeDefaultValue(__tracecodeTargetType);
2076
+ continue;
2077
+ }
2078
+ if (__TraceCodeTryGetCaseValue(__tracecodeRawCase, __tracecodeParameter.Name ?? string.Empty, __tracecodeIndex, out var __tracecodeValue))
2079
+ {
2080
+ __tracecodeArgs[__tracecodeIndex] = TraceCode.Internal.TraceCodeJsonInput.Convert(__tracecodeValue, __tracecodeTargetType);
2081
+ continue;
2082
+ }
2083
+ if (__tracecodeParameter.HasDefaultValue)
2084
+ {
2085
+ __tracecodeArgs[__tracecodeIndex] = __tracecodeParameter.DefaultValue;
2086
+ continue;
2087
+ }
2088
+ throw new System.InvalidOperationException($"Missing input value for parameter \\"{__tracecodeParameter.Name}\\".");
2089
+ }
2090
+
2091
+ object? __tracecodeInstance = __tracecodeMethod.IsStatic ? null : System.Activator.CreateInstance(__tracecodeMethod.DeclaringType!);
2092
+ object? __tracecodeOutput = __tracecodeMethod.Invoke(__tracecodeInstance, __tracecodeArgs);
2093
+ if (__tracecodeMethod.ReturnType == typeof(void))
2094
+ {
2095
+ return __TraceCodeShouldReturnFirstVoidArgument(__tracecodeParameters) ? __tracecodeArgs[0] : null;
2096
+ }
2097
+ return __tracecodeOutput;
2098
+ }
2099
+
2100
+ System.Reflection.MethodInfo __TraceCodeSelectSolutionMethod(System.Text.Json.JsonElement __tracecodeRawCase)
2101
+ {
2102
+ var __tracecodeMethods = typeof(Solution)
2103
+ .GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance)
2104
+ .Where(__tracecodeMethod => string.Equals(__tracecodeMethod.Name, ${functionNameLiteral}, System.StringComparison.Ordinal))
2105
+ .ToArray();
2106
+ if (__tracecodeMethods.Length == 0)
2107
+ {
2108
+ __tracecodeMethods = typeof(Solution)
2109
+ .GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance)
2110
+ .Where(__tracecodeMethod => string.Equals(__tracecodeMethod.Name, ${functionNameLiteral}, System.StringComparison.OrdinalIgnoreCase))
2111
+ .ToArray();
1775
2112
  }
2113
+ if (__tracecodeMethods.Length == 0)
2114
+ {
2115
+ throw new System.InvalidOperationException($"Expected public method Solution.${functionName}.");
2116
+ }
2117
+
2118
+ var __tracecodeCompatible = __tracecodeMethods
2119
+ .Select(__tracecodeMethod => new { Method = __tracecodeMethod, Score = __TraceCodeScoreMethod(__tracecodeMethod, __tracecodeRawCase) })
2120
+ .Where(__tracecodeCandidate => __tracecodeCandidate.Score > int.MinValue)
2121
+ .OrderByDescending(__tracecodeCandidate => __tracecodeCandidate.Method.IsPublic)
2122
+ .ThenByDescending(__tracecodeCandidate => __tracecodeCandidate.Score)
2123
+ .Select(__tracecodeCandidate => __tracecodeCandidate.Method)
2124
+ .FirstOrDefault();
2125
+ return __tracecodeCompatible ?? __tracecodeMethods.FirstOrDefault(__tracecodeMethod => __tracecodeMethod.IsPublic) ?? __tracecodeMethods[0];
2126
+ }
2127
+
2128
+ int __TraceCodeScoreMethod(System.Reflection.MethodInfo __tracecodeMethod, System.Text.Json.JsonElement __tracecodeRawCase)
2129
+ {
2130
+ int __tracecodeScore = 0;
2131
+ var __tracecodeParameters = __tracecodeMethod.GetParameters();
2132
+ for (int __tracecodeIndex = 0; __tracecodeIndex < __tracecodeParameters.Length; __tracecodeIndex++)
2133
+ {
2134
+ var __tracecodeParameter = __tracecodeParameters[__tracecodeIndex];
2135
+ if (__tracecodeParameter.IsOut)
2136
+ {
2137
+ __tracecodeScore += 1;
2138
+ continue;
2139
+ }
2140
+ if (!__TraceCodeTryGetCaseValue(__tracecodeRawCase, __tracecodeParameter.Name ?? string.Empty, __tracecodeIndex, out var __tracecodeValue))
2141
+ {
2142
+ if (__tracecodeParameter.HasDefaultValue)
2143
+ {
2144
+ continue;
2145
+ }
2146
+ return int.MinValue;
2147
+ }
2148
+ try
2149
+ {
2150
+ _ = TraceCode.Internal.TraceCodeJsonInput.Convert(__tracecodeValue, __TraceCodeParameterType(__tracecodeParameter));
2151
+ __tracecodeScore += 4;
2152
+ }
2153
+ catch
2154
+ {
2155
+ return int.MinValue;
2156
+ }
2157
+ }
2158
+ return __tracecodeScore;
2159
+ }
2160
+
2161
+ System.Type __TraceCodeParameterType(System.Reflection.ParameterInfo __tracecodeParameter)
2162
+ {
2163
+ System.Type __tracecodeType = __tracecodeParameter.ParameterType;
2164
+ return __tracecodeType.IsByRef ? __tracecodeType.GetElementType() ?? typeof(object) : __tracecodeType;
2165
+ }
2166
+
2167
+ object? __TraceCodeDefaultValue(System.Type __tracecodeType) =>
2168
+ __tracecodeType.IsValueType && System.Nullable.GetUnderlyingType(__tracecodeType) is null
2169
+ ? System.Activator.CreateInstance(__tracecodeType)
2170
+ : null;
1776
2171
 
1777
- const results = [];
2172
+ bool __TraceCodeShouldReturnFirstVoidArgument(System.Reflection.ParameterInfo[] __tracecodeParameters)
2173
+ {
2174
+ if (__tracecodeParameters.Length == 0)
2175
+ {
2176
+ return false;
2177
+ }
2178
+ var __tracecodeType = __TraceCodeParameterType(__tracecodeParameters[0]);
2179
+ return __tracecodeParameters[0].ParameterType.IsByRef
2180
+ || __tracecodeType.IsArray
2181
+ || (!__tracecodeType.IsPrimitive
2182
+ && __tracecodeType != typeof(string)
2183
+ && __tracecodeType != typeof(decimal)
2184
+ && __tracecodeType != typeof(System.DateTime));
2185
+ }
2186
+
2187
+ bool __TraceCodeTryGetCaseValue(System.Text.Json.JsonElement __tracecodeRawCase, string __tracecodeName, int __tracecodeIndex, out System.Text.Json.JsonElement __tracecodeValue)
2188
+ {
2189
+ if (__tracecodeRawCase.ValueKind == System.Text.Json.JsonValueKind.Object)
2190
+ {
2191
+ if (__tracecodeRawCase.TryGetProperty(__tracecodeName, out __tracecodeValue))
2192
+ {
2193
+ return true;
2194
+ }
2195
+ int __tracecodePropertyIndex = 0;
2196
+ foreach (var __tracecodeProperty in __tracecodeRawCase.EnumerateObject())
2197
+ {
2198
+ if (__tracecodePropertyIndex == __tracecodeIndex)
2199
+ {
2200
+ __tracecodeValue = __tracecodeProperty.Value;
2201
+ return true;
2202
+ }
2203
+ __tracecodePropertyIndex++;
2204
+ }
2205
+ }
2206
+ __tracecodeValue = default;
2207
+ return false;
2208
+ }
2209
+
2210
+ string[] __TraceCodeSplitConsole(string __tracecodeText) =>
2211
+ __tracecodeText.Replace("\\r\\n", "\\n", System.StringComparison.Ordinal).Split('\\n', System.StringSplitOptions.RemoveEmptyEntries);
2212
+ `;
2213
+ }
2214
+
2215
+ function normalizeCSharpBatchEntry(entry, timings = {}) {
2216
+ const source = entry && typeof entry === 'object' ? entry : {};
2217
+ const success = source.success === true;
2218
+ return {
2219
+ success,
2220
+ output: success ? (source.output ?? null) : null,
2221
+ ...(success ? {} : { error: source.error ?? 'C# batch item failed without runtime diagnostics' }),
2222
+ consoleOutput: Array.isArray(source.consoleOutput) ? source.consoleOutput : [],
2223
+ timings: {
2224
+ ...(source.timings && typeof source.timings === 'object' ? source.timings : {}),
2225
+ ...timings,
2226
+ },
2227
+ };
2228
+ }
2229
+
2230
+ async function executeCSharpCodeBatch(message) {
2231
+ const startedAt = now();
2232
+ const inputBatch = Array.isArray(message.payload?.inputBatch)
2233
+ ? message.payload.inputBatch.map((inputs) => (inputs && typeof inputs === 'object' ? inputs : {}))
2234
+ : [];
2235
+ if (inputBatch.length === 0) {
2236
+ return {
2237
+ success: false,
2238
+ results: [],
2239
+ error: 'C# batch execution requires a non-empty inputBatch array.',
2240
+ consoleOutput: [],
2241
+ timings: { totalMs: elapsedMs(startedAt) },
2242
+ };
2243
+ }
2244
+
2245
+ try {
1778
2246
  for (const inputs of inputBatch) {
1779
- results.push(await handleMessage({
1780
- type: 'execute-code',
1781
- payload: { ...message.payload, inputs },
1782
- }));
2247
+ validateCSharpInputsForJson(inputs);
1783
2248
  }
2249
+ } catch (error) {
2250
+ return {
2251
+ success: false,
2252
+ results: [],
2253
+ error: error instanceof Error ? error.message : String(error),
2254
+ consoleOutput: [],
2255
+ timings: { totalMs: elapsedMs(startedAt) },
2256
+ };
2257
+ }
2258
+
2259
+ let source;
2260
+ try {
2261
+ source = buildCSharpBatchScriptSource(message.payload);
2262
+ } catch (error) {
1784
2263
  return {
1785
- success: results.every((result) => result.success === true),
1786
- results,
1787
- consoleOutput: results.flatMap((result) => result.consoleOutput ?? []),
2264
+ success: false,
2265
+ results: [],
2266
+ error: error instanceof Error ? error.message : String(error),
2267
+ consoleOutput: [],
1788
2268
  timings: { totalMs: elapsedMs(startedAt) },
1789
2269
  };
1790
2270
  }
1791
2271
 
2272
+ const request = {
2273
+ source,
2274
+ functionName: '',
2275
+ inputs: { __tracecodeBatchInputs: inputBatch },
2276
+ executionStyle: 'function',
2277
+ trace: false,
2278
+ timeoutMs: message.payload?.timeoutMs,
2279
+ maxTraceSteps: message.payload?.maxTraceSteps,
2280
+ maxLineEvents: message.payload?.maxLineEvents,
2281
+ maxSingleLineHits: message.payload?.maxSingleLineHits,
2282
+ maxStoredEvents: message.payload?.maxStoredEvents,
2283
+ maxPathDepth: message.payload?.maxPathDepth,
2284
+ minimalTrace: message.payload?.minimalTrace,
2285
+ };
2286
+
2287
+ const runtimeStartedAt = now();
2288
+ const runtimeResult = await loadRuntime(message.payload?.assetBaseUrl);
2289
+ const initMs = elapsedMs(runtimeStartedAt) || runtimeResult.timings?.initMs || 0;
2290
+ const hostCallStartedAt = now();
2291
+ const result = normalizeCSharpResult(JSON.parse(executeExport(JSON.stringify(request))), request);
2292
+ const hostCallMs = elapsedMs(hostCallStartedAt);
2293
+ const timings = {
2294
+ ...(result?.timings && typeof result.timings === 'object' ? result.timings : {}),
2295
+ initMs,
2296
+ hostCallMs,
2297
+ totalMs: elapsedMs(startedAt),
2298
+ };
2299
+
2300
+ if (result?.success !== true || !Array.isArray(result.output)) {
2301
+ const failure = {
2302
+ success: false,
2303
+ output: null,
2304
+ error: result?.error ?? 'C# batch execution did not return a result array.',
2305
+ consoleOutput: result?.consoleOutput ?? [],
2306
+ timings,
2307
+ };
2308
+ return {
2309
+ success: false,
2310
+ results: inputBatch.map(() => failure),
2311
+ error: failure.error,
2312
+ consoleOutput: result?.consoleOutput ?? [],
2313
+ executionTimeMs: result?.executionTimeMs,
2314
+ timings,
2315
+ };
2316
+ }
2317
+
2318
+ const results = result.output.map((entry, index) =>
2319
+ normalizeCSharpBatchEntry(entry, index === 0 ? { compileMs: timings.compileMs, hostCallMs, totalMs: timings.totalMs } : { compileMs: 0, hostCallMs: 0 })
2320
+ );
2321
+ const consoleOutput = results.flatMap((entry) => entry.consoleOutput ?? []);
2322
+ return {
2323
+ success: results.length === inputBatch.length && results.every((entry) => entry.success === true),
2324
+ results,
2325
+ consoleOutput,
2326
+ executionTimeMs: result.executionTimeMs,
2327
+ timings: {
2328
+ ...timings,
2329
+ runMs: results.reduce((sum, entry) => sum + (entry.timings?.runMs ?? 0), 0),
2330
+ },
2331
+ };
2332
+ }
2333
+
2334
+ async function handleMessage(message) {
2335
+ if (message.type === 'init') {
2336
+ return handleInit(message.payload?.assetBaseUrl);
2337
+ }
2338
+
2339
+ if (message.type === 'warmup') {
2340
+ return warmRuntime(message.payload?.assetBaseUrl);
2341
+ }
2342
+
2343
+ if (message.type === 'execute-code-batch') {
2344
+ return executeCSharpCodeBatch(message);
2345
+ }
2346
+
1792
2347
  if (
1793
2348
  message.type === 'execute-code' ||
1794
2349
  message.type === 'execute-code-interview' ||
@@ -3615,7 +3615,7 @@ function unzipSync(data, opts) {
3615
3615
  // packages/harness-javascript/package.json
3616
3616
  var package_default = {
3617
3617
  name: "@tracecode/harness-javascript",
3618
- version: "0.9.2",
3618
+ version: "0.9.3",
3619
3619
  description: "JavaScript and TypeScript runtime helpers and browser worker assets for TraceCode harness.",
3620
3620
  license: "AGPL-3.0-only",
3621
3621
  homepage: "https://tracecode.app",