### Execute JavaScript with Console Logging in C# Source: https://github.com/sebastienros/jint/blob/main/README.md This example demonstrates how to set up a Jint engine, define a .NET action (Console.WriteLine) accessible as 'log' in JavaScript, and then execute a JavaScript script that calls this function. It shows basic script execution and interop. ```csharp var engine = new Engine() .SetValue("log", new Action(Console.WriteLine)); engine.Execute(@" function hello() { log('Hello World'); }; hello(); "); ``` -------------------------------- ### Implement Custom Jint Execution Constraint Source: https://github.com/sebastienros/jint/blob/main/README.md Allows for custom resource management by deriving from the `Constraint` base class. Implement `Reset` for pre-execution setup and `Check` to enforce specific requirements, throwing an exception if conditions are not met. This example demonstrates a CPU usage constraint. ```csharp public abstract class Constraint { /// Called before script is run and useful when you use an engine object for multiple executions. public abstract void Reset(); // Called before each statement to check if your requirements are met; if not - throws an exception. public abstract void Check(); } class MyCPUConstraint : Constraint { public override void Reset() { } public override void Check() { var cpuUsage = GetCPUUsage(); if (cpuUsage > 0.8) // 80% { throw new OperationCancelledException(); } } } var engine = new Engine(options => { options.Constraint(new MyCPUConstraint()); }); ``` -------------------------------- ### Configure Jint Engine Culture for Number Formatting in C# Source: https://github.com/sebastienros/jint/blob/main/README.md This C# example demonstrates how to set a specific culture (e.g., 'fr-FR') for the Jint engine. This affects how JavaScript's number formatting methods, like `toString()` and `toLocaleString()`, behave, ensuring locale-aware output. ```csharp var FR = CultureInfo.GetCultureInfo("fr-FR"); var engine = new Engine(cfg => cfg.Culture(FR)); engine.Execute("new Number(1.23).toString()") // 1.23 engine.Execute("new Number(1.23).toLocaleString()") // 1,23 ``` -------------------------------- ### Instantiate and Use Generic .NET Types in JavaScript with Jint Source: https://github.com/sebastienros/jint/blob/main/README.md This JavaScript example, executed within a Jint engine, demonstrates how to work with generic .NET types. It shows how to declare a generic type like `List` and then instantiate and use it, including adding elements and accessing properties like 'Count'. ```javascript jint> var ListOfString = System.Collections.Generic.List(System.String); jint> var list = new ListOfString(); jint> list.Add('foo'); jint> list.Add(1); // automatically converted to String jint> list.Count; // 2 ``` -------------------------------- ### Define and Import Jint Modules from JavaScript Source: https://github.com/sebastienros/jint/blob/main/README.md Allows defining modules directly using JavaScript source code strings. This is useful for embedding small modules or when modules are generated dynamically. The example shows adding a module named 'user' and then importing it. ```csharp engine.Modules.Add("user", "export const name = 'John';"); var ns = engine.Modules.Import("user"); var name = ns.Get("name").AsString(); ``` -------------------------------- ### Reset Cancellation Token for Jint Engine Source: https://github.com/sebastienros/jint/blob/main/README.md Demonstrates how to reset the cancellation token for an engine when reusing it for multiple executions. This ensures that each execution starts with a fresh cancellation token, allowing for proper control over script termination. ```csharp var engine = new Engine(options => { options.CancellationToken(new CancellationToken(true)); }); var constraint = engine.Constraints.Find(); for (var i = 0; i < 10; i++) { using (var tcs = new CancellationTokenSource(TimeSpan.FromSeconds(10))) { constraint.Reset(tcs.Token); engine.SetValue("a", 1); engine.Execute("a++"); } } ``` -------------------------------- ### Use System Namespace and Create Shortcuts in JavaScript with CLR Enabled Source: https://github.com/sebastienros/jint/blob/main/README.md When CLR access is enabled in Jint, the 'System' namespace becomes globally available in JavaScript, allowing direct interaction with .NET classes like StreamWriter and Console. This example shows creating a StreamWriter, writing to a file, and disposing of it, as well as creating a shortcut for Console.WriteLine. ```javascript jint> var file = new System.IO.StreamWriter('log.txt'); jint> file.WriteLine('Hello World !'); jint> file.Dispose(); ``` ```javascript jint> var log = System.Console.WriteLine; jint> log('Hello World !'); => "Hello World !" ``` -------------------------------- ### Manipulate .NET Objects from JavaScript in C# Source: https://github.com/sebastienros/jint/blob/main/README.md This example illustrates passing a .NET object (a Person instance) to the Jint engine and then modifying its properties using JavaScript. The changes made in JavaScript are reflected back in the original .NET object, demonstrating object interop. ```csharp var p = new Person { Name = "Mickey Mouse" }; var engine = new Engine() .SetValue("p", p) .Execute("p.Name = 'Minnie'"); Assert.AreEqual("Minnie", p.Name); ``` -------------------------------- ### Enable and Use Jint Modules with File Path Source: https://github.com/sebastienros/jint/blob/main/README.md Enables the Jint module system, restricting module resolution to a specified base path. This allows scripts to import and export variables across multiple files, organizing code and improving reusability. The example shows enabling modules and importing a script. ```csharp var engine = new Engine(options => { options.EnableModules(@"C:\Scripts"); }) var ns = engine.Modules.Import("./my-module.js"); var value = ns.Get("value").AsString(); ``` -------------------------------- ### Define and Import Jint Modules with .NET CLR Exports Source: https://github.com/sebastienros/jint/blob/main/README.md Enables the creation of modules that export .NET CLR types and values. This facilitates seamless integration between Jint scripts and the .NET environment. The example defines a 'lib' module exporting a C# class and a value, then uses it in a 'custom' module. ```csharp // Create the module 'lib' with the class MyClass and the variable version engine.Modules.Add("lib", builder => builder .ExportType() .ExportValue("version", 15) ); // Create a user-defined module and do something with 'lib' engine.Modules.Add("custom", @" import { MyClass, version } from 'lib'; const x = new MyClass(); export const result as x.doSomething(); "); // Import the user-defined module; this will execute the import chain var ns = engine.Modules.Import("custom"); // The result contains "live" bindings to the module var id = ns.Get("result").AsInteger(); ``` -------------------------------- ### Invoke JavaScript Functions by Reference and Name in C# Source: https://github.com/sebastienros/jint/blob/main/README.md These examples demonstrate two ways to invoke a JavaScript function from C#: first, by executing a script that defines the function and then invoking it using the `Invoke` method with the function name and arguments; second, directly using the `Invoke` method after the function has been defined. ```csharp var result = new Engine() .Execute("function add(a, b) { return a + b; }") .Invoke("add",1, 2); // -> 3 ``` ```csharp var engine = new Engine() .Execute("function add(a, b) { return a + b; }"); engine.Invoke("add", 1, 2); // -> 3 ``` -------------------------------- ### Implement Custom Object Converters in Jint Source: https://context7.com/sebastienros/jint/llms.txt Customize the conversion of CLR objects to JavaScript values by implementing the `IObjectConverter` interface and registering custom converters. This allows for specific handling of types like Guid and DateTimeOffset. ```csharp // Custom converter for specific types public class GuidConverter : IObjectConverter { public bool TryConvert(Engine engine, object value, out JsValue result) { if (value is Guid guid) { result = guid.ToString(); return true; } result = JsValue.Undefined; return false; } } public class DateTimeOffsetConverter : IObjectConverter { public bool TryConvert(Engine engine, object value, out JsValue result) { if (value is DateTimeOffset dto) { // Convert to JavaScript Date result = engine.Construct("Date", dto.ToUnixTimeMilliseconds()); return true; } result = JsValue.Undefined; return false; } } // Register converters var engine = new Engine(options => options .AddObjectConverter() .AddObjectConverter(new DateTimeOffsetConverter())); // Now Guid values automatically convert to strings engine.SetValue("id", Guid.NewGuid()); engine.Execute("console.log(typeof id); // string"); // DateTimeOffset converts to Date engine.SetValue("timestamp", DateTimeOffset.Now); engine.Execute("console.log(timestamp instanceof Date); // true"); ``` -------------------------------- ### Get JavaScript Values into .NET Source: https://context7.com/sebastienros/jint/llms.txt Explains how to retrieve values from JavaScript execution contexts into .NET using `GetValue()` and `Evaluate()`. It details converting JavaScript types (string, number, boolean, array, object, date) to their .NET equivalents using `JsValue` extension methods. ```csharp var engine = new Engine(); engine.Execute(@" var name = 'JavaScript'; var count = 42; var active = true; var items = [1, 2, 3, 4, 5]; var config = { host: 'localhost', port: 8080 }; var today = new Date(); "); // Get primitive values var name = engine.GetValue("name").AsString(); var count = engine.GetValue("count").AsNumber(); var active = engine.GetValue("active").AsBoolean(); Console.WriteLine($"{name}, {count}, {active}"); // JavaScript, 42, True // Get array and iterate var items = engine.GetValue("items").AsArray(); foreach (var item in items) { Console.Write($"{item.AsNumber()} "); // 1 2 3 4 5 } // Get object as dynamic/dictionary var config = engine.GetValue("config").ToObject() as IDictionary; Console.WriteLine($"{config["host"]}:{config["port"]}"); // localhost:8080 // Get Date as DateTime var today = engine.GetValue("today").AsDate().ToDateTime(); Console.WriteLine(today.ToString("yyyy-MM-dd")); // Type checking before conversion var value = engine.Evaluate("42"); if (value.IsNumber()) Console.WriteLine(value.AsNumber()); if (value.IsString()) Console.WriteLine(value.AsString()); if (value.IsArray()) Console.WriteLine(value.AsArray().Length); if (value.IsObject()) Console.WriteLine(value.AsObject()); ``` -------------------------------- ### Build and Run Jint REPL Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Commands to build and run the Jint REPL (Read-Eval-Print Loop) for quick JavaScript testing. This includes building the project and executing it with various command-line options. ```bash # Build the REPL dotnet build Jint.Repl --configuration Release # Run the REPL dotnet run --project Jint.Repl --configuration Release ``` -------------------------------- ### Build Solution and Projects (Bash) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Commands to build the entire .NET solution or specific projects within it. Ensures the latest compiled code is used by avoiding the --no-build flag. ```bash # Build entire solution dotnet build --configuration Release # Build specific project dotnet build --configuration Release Jint/Jint.csproj ``` -------------------------------- ### Create and Configure Jint Engine in C# Source: https://context7.com/sebastienros/jint/llms.txt Demonstrates how to create a basic Jint engine instance and a more configured instance with options like strict mode, CLR interop, memory limits, timeouts, statement limits, recursion limits, CLR exception handling, time zone, and culture. It also shows basic code execution and evaluation. ```csharp using Jint; using Jint.Native; using System.Globalization; // Basic engine creation var engine = new Engine(); // Engine with fluent configuration var configuredEngine = new Engine(options => options .Strict() // Enable strict mode (improves performance) .AllowClr() // Enable CLR interop .LimitMemory(4_000_000) // Limit memory to 4 MB .TimeoutInterval(TimeSpan.FromSeconds(5)) // Set 5 second timeout .MaxStatements(10000) // Limit to 10,000 statements .LimitRecursion(100) // Limit recursion depth to 100 .CatchClrExceptions() // Convert CLR exceptions to JS errors .LocalTimeZone(TimeZoneInfo.Utc) // Set time zone .Culture(CultureInfo.InvariantCulture)); // Set culture // Execute simple code engine.Execute("var x = 10;"); var result = engine.Evaluate("x * 2"); Console.WriteLine(result.AsNumber()); // Output: 20 ``` -------------------------------- ### Jint REPL Command Line Options Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Lists the available command-line options for the Jint REPL. These options control script execution, file input, timeouts, and help messages. ```bash -f, --file Execute JavaScript file -t, --timeout Set execution timeout in seconds -h, --help Show help message ``` -------------------------------- ### Import .NET Namespaces and Instantiate Types in JavaScript Source: https://github.com/sebastienros/jint/blob/main/README.md This JavaScript snippet, used within a Jint engine configured with CLR access, demonstrates how to import a .NET namespace ('Foo') and then create an instance of a type ('Bar') from that namespace. It also shows calling a method on the instantiated object. ```javascript jint> var Foo = importNamespace('Foo'); jint> var bar = new Foo.Bar(); jint> log(bar.ToString()); ``` -------------------------------- ### Test JavaScript with Temporary File in Jint REPL Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Shows how to test JavaScript code stored in a temporary file using the Jint REPL, specifying the file path and a timeout. ```bash # Test with a temporary file echo 'var x = 5; x * 2' > /tmp/test.js dotnet run --project Jint.Repl --configuration Release -- -f /tmp/test.js -t 10 ``` -------------------------------- ### Property Key Optimization (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Explains Jint's optimizations for property keys, including `KnownKeys.cs` for pre-computed common names and the use of `HybridDictionary` and `StringDictionarySlim` for efficient property storage. ```csharp // `KnownKeys.cs` contains pre-computed common property names // `HybridDictionary` switches between list and hash based on property count // `StringDictionarySlim` for string-only dictionary keys ``` -------------------------------- ### Jint Architecture Overview (Text) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Illustrates the layered interpreter architecture of Jint, showing the flow from parsing to runtime and interop. Highlights the role of the Acornima Parser, AST, Interpreter, Runtime, and Interop layers. ```text Acornima Parser (external) → AST → Interpreter → Runtime → Interop ``` -------------------------------- ### Test JSON Parsing in Jint REPL Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Demonstrates testing JSON parsing functionality within the Jint REPL by piping a JSON string to be parsed. ```bash # Test JSON parsing echo 'JSON.parse("[1,2,3]")' | dotnet run --project Jint.Repl --configuration Release -- -t 10 ``` -------------------------------- ### Engine Class Structure (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Describes the main API entry point for Jint, the Engine class, which is split across multiple partial files. It manages execution context, intrinsics, and realms, and is configurable via the Options class. ```csharp // Main API entry point split across multiple partial files (Engine.cs, Engine.Advanced.cs, Engine.Modules.cs, etc.) // Manages execution context stack, intrinsics (built-in objects), and realms // Configuration via `Options` class (constraints, CLR interop, modules, debugging) ``` -------------------------------- ### Execute JavaScript File with Timeout in Jint REPL Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Demonstrates how to execute a JavaScript file using the Jint REPL with a specified timeout. This is a recommended practice to prevent infinite loops. ```bash # Execute a file with 10 second timeout (recommended default) dotnet run --project Jint.Repl --configuration Release -- -f script.js -t 10 ``` -------------------------------- ### Execute Multiline JavaScript from Stdin in Jint REPL Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Illustrates executing multiline JavaScript code piped from stdin to the Jint REPL with a timeout. This uses a 'here document' for easy script input. ```bash # Execute multiline script from stdin cat << 'EOF' | dotnet run --project Jint.Repl --configuration Release -- -t 10 var result = []; for (var i = 0; i < 5; i++) { result.push(i * 2); } JSON.stringify(result); EOF ``` -------------------------------- ### Run Tests (Bash) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Commands to execute all tests, specific test projects, test classes, or test methods within the Jint project. Tests should be run in Release mode for optimal performance. ```bash # Run all tests dotnet test --configuration Release # Run specific test project dotnet test --configuration Release Jint.Tests/Jint.Tests.csproj # Run specific test class dotnet test --configuration Release --filter "FullyQualifiedName~Jint.Tests.Runtime.EngineTests" # Run specific test method dotnet test --configuration Release --filter "FullyQualifiedName~Jint.Tests.Runtime.EngineTests.CanEvaluateScripts" # Run Test262 conformance tests dotnet test --configuration Release Jint.Tests.Test262/Jint.Tests.Test262.csproj ``` -------------------------------- ### Test Simple Expression in Jint REPL Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md A quick pattern for testing a simple JavaScript expression using the Jint REPL by piping the expression to the command. ```bash # Test a simple expression echo "Math.sqrt(16)" | dotnet run --project Jint.Repl --configuration Release -- -t 10 ``` -------------------------------- ### Execute JavaScript Code with Jint in C# Source: https://context7.com/sebastienros/jint/llms.txt Illustrates how to execute JavaScript code using Jint's `Execute()` and `Evaluate()` methods. `Execute()` returns the engine instance for chaining, while `Evaluate()` returns the result of the last expression. It also shows how to set .NET values as JavaScript variables and optimize script execution by preparing scripts. ```csharp var engine = new Engine(); // Execute returns the engine (for chaining) engine .Execute("function greet(name) { return 'Hello, ' + name + '!'; }") .Execute("var message = greet('World');"); // Evaluate returns the result value var greeting = engine.Evaluate("greet('Jint')"); Console.WriteLine(greeting.AsString()); // Output: Hello, Jint! // Chain multiple operations var result = new Engine() .SetValue("x", 10) .SetValue("y", 20) .Evaluate("x + y") .AsNumber(); Console.WriteLine(result); // Output: 30 // Parse once, execute multiple times (performance optimization) var script = Engine.PrepareScript("x * x"); for (int i = 1; i <= 5; i++) { var squared = new Engine() .SetValue("x", i) .Evaluate(script); Console.WriteLine($"{i}^2 = {squared}"); // 1, 4, 9, 16, 25 } ``` -------------------------------- ### Lazy Initialization Pattern (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Describes the lazy initialization pattern used in Jint, particularly for built-in objects (Intrinsics), to optimize startup time. Properties are initialized only upon their first access. ```csharp // Built-in objects (Intrinsics) are lazily initialized to reduce startup time // Properties are typically null until first access ``` -------------------------------- ### Evaluate JavaScript Expression and Convert to .NET Type in C# Source: https://github.com/sebastienros/jint/blob/main/README.md This snippet shows how to initialize a Jint engine, set a JavaScript variable 'x' to a .NET value (3), evaluate a JavaScript expression ('x * x'), and then convert the JavaScript result back to a .NET object. It highlights expression evaluation and type conversion. ```csharp var square = new Engine() .SetValue("x", 3) // define a new variable .Evaluate("x * x") // evaluate a statement .ToObject(); // converts the value to .NET ``` -------------------------------- ### Define Modules Programmatically in Jint Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Demonstrates how to programmatically define modules within the Jint engine. This allows exporting C# types and values to be used within JavaScript. ```csharp engine.Modules.Add("lib", builder => builder .ExportType() .ExportValue("version", 1) ); ``` -------------------------------- ### Execute JavaScript from Stdin with Timeout in Jint REPL Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Shows how to pipe JavaScript code to the Jint REPL for execution, including setting a timeout. This is useful for testing small snippets or scripts dynamically. ```bash # Execute from stdin with timeout echo "1 + 2" | dotnet run --project Jint.Repl --configuration Release -- -t 10 ``` -------------------------------- ### Runtime Components (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Outlines key components within the Jint Runtime, including TypeConverter for JavaScript type coercion, Intrinsics for built-in constructors and prototypes, and Realm for encapsulating global environments. ```csharp // **TypeConverter.cs** (1,048 lines): All JavaScript type coercion (ToPrimitive, ToNumber, ToString, ToObject, etc.) // **Intrinsics.cs**: Singleton containing all built-in object constructors and prototypes (lazily initialized) // **Realm.cs**: ECMAScript Realm encapsulating global environment and intrinsics // **Environments/**: Scope chain implementation (GlobalEnvironment, FunctionEnvironment, DeclarativeEnvironment, etc.) ``` -------------------------------- ### Enable Modules with Directory Path in Jint Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Configures the Jint engine to enable module support, specifying a base directory for module resolution. This allows importing JavaScript modules from the file system. ```csharp var engine = new Engine(options => options.EnableModules(@"C:\\Scripts")); var ns = engine.Modules.Import("./my-module.js"); ``` -------------------------------- ### Invoke JavaScript Functions from .NET Source: https://context7.com/sebastienros/jint/llms.txt Demonstrates how to call JavaScript functions by name or reference from C#. It covers automatic type conversion between .NET and JavaScript, passing .NET objects as arguments, and invoking functions with a specific 'this' context. ```csharp var engine = new Engine(); // Define functions in JavaScript engine.Execute(@" function multiply(a, b) { return a * b; } function createPerson(name, age) { return { name: name, age: age, greet: function() { return 'Hi, I am ' + this.name; } }; } var calculator = { add: function(a, b) { return a + b; }, subtract: function(a, b) { return a - b; } }; "); // Invoke function by name var product = engine.Invoke("multiply", 6, 7); Console.WriteLine(product.AsNumber()); // Output: 42 // Invoke with .NET objects as arguments var person = engine.Invoke("createPerson", "Charlie", 28); var greeting = engine.Invoke(person.AsObject().Get("greet")); Console.WriteLine(greeting.AsString()); // Output: Hi, I am Charlie // Get function reference and call directly var addFunc = engine.GetValue("calculator").AsObject().Get("add"); var sum = engine.Call(addFunc, JsValue.Undefined, new JsValue[] { 10, 20 }); Console.WriteLine(sum.AsNumber()); // Output: 30 // Invoke with thisObj context engine.Execute("function showThis() { return this.value; }"); var obj = new JsObject(engine); obj.Set("value", 100); var result = engine.Invoke("showThis", obj, Array.Empty()); Console.WriteLine(result.AsNumber()); // Output: 100 ``` -------------------------------- ### Modules Component (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Explains the ES6 module system support in Jint, including module resolution, loading, and handling of cyclic dependencies. Modules can be defined from JavaScript source or programmatically. ```csharp // ES6 module system with import/export support // ModuleLoader handles module resolution and loading // Supports cyclic dependencies via CyclicModule // Modules can be defined from JavaScript source or programmatically via ModuleBuilder ``` -------------------------------- ### Handle JavaScript Promises in C# with Jint Source: https://context7.com/sebastienros/jint/llms.txt Demonstrates how to synchronously wait for JavaScript Promise resolution using `UnwrapIfPromise()`. It covers basic promise handling, timeouts, cancellation, and async/await patterns within JavaScript executed by Jint. ```csharp var engine = new Engine(); // Basic promise handling engine.Execute(@"\n var promise = new Promise((resolve, reject) => {\n setTimeout(() => resolve('Success!'), 100);\n });\n"); var promise = engine.GetValue("promise"); var result = promise.UnwrapIfPromise(); // Blocks until resolved Console.WriteLine(result.AsString()); // Output: Success! // Promise with timeout engine.Execute(@"\n var slowPromise = new Promise((resolve) => {\n // This would take too long\n });\n"); try { var slowResult = engine.GetValue("slowPromise") .UnwrapIfPromise(TimeSpan.FromSeconds(2)); } catch (PromiseRejectedException ex) { Console.WriteLine("Promise timed out or was rejected"); } // Promise with cancellation var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(1)); try { var cancelableResult = engine.GetValue("slowPromise") .UnwrapIfPromise(cts.Token); } catch (OperationCanceledException) { Console.WriteLine("Promise was cancelled"); } // Async/await in JavaScript engine.Execute(@"\n async function fetchData() {\n return await Promise.resolve({ data: [1, 2, 3] });\n }\n var dataPromise = fetchData();\n"); var data = engine.GetValue("dataPromise").UnwrapIfPromise(); Console.WriteLine(data.AsObject().Get("data").AsArray().Length); // 3 ``` -------------------------------- ### Configure Jint Execution Constraints Source: https://github.com/sebastienros/jint/blob/main/README.md Sets limits on memory, execution time, and statements during script execution. These constraints help prevent resource exhaustion and ensure scripts complete within defined boundaries. The `Engine` is configured with options to enforce these limits. ```csharp var engine = new Engine(options => { // Limit memory allocations to 4 MB options.LimitMemory(4_000_000); // Set a timeout to 4 seconds. options.TimeoutInterval(TimeSpan.FromSeconds(4)); // Set limit of 1000 executed statements. options.MaxStatements(1000); // Use a cancellation token. options.CancellationToken(cancellationToken); } ``` -------------------------------- ### Partial Classes Pattern (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Details the use of partial classes in Jint to manage large classes by splitting them into multiple files. This pattern, seen in classes like Engine and Intrinsics, aims to keep related functionality organized. ```csharp // Large classes are split: Engine.*.cs, Intrinsics.*.cs, ObjectInstance.*.cs, etc. // Keep related functionality together when editing ``` -------------------------------- ### Configure Jint Execution Constraints Source: https://context7.com/sebastienros/jint/llms.txt Set limits on memory usage, execution time, statement count, and recursion depth to sandbox untrusted scripts. These constraints help prevent resource exhaustion and infinite loops. ```csharp var memoryLimitedEngine = new Engine(options => options .LimitMemory(4_000_000)); // 4 MB limit try { memoryLimitedEngine.Execute(@" var arr = []; while(true) { arr.push(new Array(10000)); } "); } catch (MemoryLimitExceededException ex) { Console.WriteLine("Memory limit exceeded!"); } var timedEngine = new Engine(options => options .TimeoutInterval(TimeSpan.FromSeconds(2))); try { timedEngine.Execute("while(true) {}"); // Infinite loop } catch (TimeoutException) { Console.WriteLine("Script timed out!"); } var statementLimitedEngine = new Engine(options => options .MaxStatements(1000)); try { statementLimitedEngine.Execute(@" for(var i = 0; i < 10000; i++) { var x = i; } "); } catch (StatementsCountOverflowException) { Console.WriteLine("Too many statements!"); } var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var cancelableEngine = new Engine(options => options .CancellationToken(cts.Token)); var recursionLimitedEngine = new Engine(options => options .LimitRecursion(50)); try { recursionLimitedEngine.Execute(@" function recurse(n) { return recurse(n + 1); } recurse(0); "); } catch (RecursionDepthOverflowException) { Console.WriteLine("Recursion limit reached!"); } ``` -------------------------------- ### Enable and Use ES6 Modules in Jint Source: https://context7.com/sebastienros/jint/llms.txt Configure Jint to load JavaScript modules from a specified base path or define them programmatically using source code or CLR type exports. This allows for modular script organization and reuse. ```csharp // Enable modules from a base path var engine = new Engine(options => options .EnableModules(@"C:\\Scripts")); // Load and use a module from file // File: C:\\Scripts\\math.js // export function add(a, b) { return a + b; } // export const PI = 3.14159; var mathModule = engine.Modules.Import("./math.js"); var addFunc = mathModule.Get("add"); var pi = mathModule.Get("PI").AsNumber(); Console.WriteLine(pi); // 3.14159 // Define modules programmatically with source code engine.Modules.Add("utils", @" export function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } export const VERSION = '1.0.0'; "); var utilsModule = engine.Modules.Import("utils"); var version = utilsModule.Get("VERSION").AsString(); Console.WriteLine(version); // 1.0.0 // Define modules with CLR types using ModuleBuilder engine.Modules.Add("services", builder => builder .ExportType() .ExportType("StringBuilder") .ExportValue("apiUrl", "https://api.example.com") .ExportFunction("log", (args) => { Console.WriteLine(string.Join(", ", args)); return JsValue.Undefined; }) .ExportObject("config", new { timeout = 5000, retries = 3 })); // Use the CLR module from JavaScript engine.Modules.Add("app", @" import { HttpClient, StringBuilder, apiUrl, log, config } from 'services'; log('API URL:', apiUrl); log('Timeout:', config.timeout); export const client = new HttpClient(); "); var appModule = engine.Modules.Import("app"); ``` -------------------------------- ### Enable and Use Debugging Support in Jint Source: https://context7.com/sebastienros/jint/llms.txt Configures the Jint engine for debugging, allowing stepping through JavaScript code, setting breakpoints, and inspecting variables. It shows how to handle step events and debugger statements using the `Debugger` property. ```csharp var engine = new Engine(options => options .DebugMode() .DebuggerStatementHandling(DebuggerStatementHandling.Script) .InitialStepMode(StepMode.Into)); // Handle step events engine.Debugger.Step += (sender, info) => { Console.WriteLine($"Line {info.Location.Start.Line}: {info.CurrentStatement}"); // Inspect local variables foreach (var scope in info.CurrentScopes) { foreach (var binding in scope.BindingNames) { var value = scope.GetBindingValue(binding); Console.WriteLine($" {binding} = {value}"); } } return StepMode.Into; // Continue stepping }; // Handle debugger statements engine.Debugger.Break += (sender, info) => { Console.WriteLine("Hit debugger statement!"); return StepMode.Over; }; engine.Execute(@"\n var x = 10; debugger; // Triggers Break event var y = x * 2; var z = y + 5; "); ``` -------------------------------- ### Load Custom Assemblies in Jint Engine Configuration in C# Source: https://github.com/sebastienros/jint/blob/main/README.md This C# code configures a Jint engine to allow CLR access and specifically load types from a custom assembly (e.g., the assembly containing the 'Bar' type). This allows the engine to interact with types defined in your own .NET projects. ```csharp var engine = new Engine(cfg => cfg .AllowClr(typeof(Bar).Assembly) ); ``` -------------------------------- ### Handle JavaScript and CLR Exceptions in Jint Source: https://context7.com/sebastienros/jint/llms.txt Illustrates exception handling within Jint. It covers catching JavaScript exceptions directly in .NET, configuring the engine to convert CLR exceptions to JavaScript errors, and implementing selective CLR exception handling. ```csharp // Catch JavaScript exceptions in .NET var engine = new Engine(); try { engine.Execute("throw new Error('Something went wrong');"); } catch (JavaScriptException ex) { Console.WriteLine($"JS Error: {ex.Message}"); Console.WriteLine($"Location: {ex.Location}"); Console.WriteLine($"Stack: {ex.JavaScriptStackTrace}"); } // Catch CLR exceptions in JavaScript var engineWithClrExceptions = new Engine(options => options .AllowClr() .CatchClrExceptions()); // Convert all CLR exceptions to JS errors engineWithClrExceptions.SetValue("riskyOperation", new Action(() => { throw new InvalidOperationException("CLR error occurred"); })); engineWithClrExceptions.Execute(@"\n try { riskyOperation(); } catch (e) { console.log('Caught CLR exception: ' + e.message); } "); // Selective exception handling var selectiveEngine = new Engine(options => options .CatchClrExceptions(ex => ex is ArgumentException)); // Only catch ArgumentExceptions selectiveEngine.SetValue("validateInput", new Action(input => { if (string.IsNullOrEmpty(input)) throw new ArgumentException("Input cannot be empty"); })); selectiveEngine.Execute(@"\n try { validateInput(''); } catch (e) { console.log('Validation failed: ' + e.message); } "); ``` -------------------------------- ### Interpreter Components (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Describes the Jint Interpreter's structure, which uses specialized handler classes for each statement and expression type. It also mentions caching mechanisms for compiled function metadata. ```csharp // **Statements/**: One handler class per statement type (JintIfStatement, JintForStatement, JintTryStatement, etc.) // **Expressions/**: One handler class per expression type (JintBinaryExpression, JintCallExpression, JintMemberExpression, etc.) // AST nodes are evaluated via specialized Jint* handler classes // Caching: JintFunctionDefinition caches compiled function metadata for reuse ``` -------------------------------- ### Enable CLR Access in Jint Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Enables access to the Common Language Runtime (CLR) from within Jint scripts. This allows JavaScript code to interact with .NET objects and methods, but should be used with caution due to security implications. ```csharp var engine = new Engine(cfg => cfg.AllowClr()); ``` -------------------------------- ### Set .NET Values for JavaScript in Jint (C#) Source: https://context7.com/sebastienros/jint/llms.txt Shows how to use the `SetValue()` method in Jint to expose .NET primitive types, delegates (as JavaScript functions), .NET objects (POCOs), and anonymous objects to JavaScript code. These values are automatically converted to their JavaScript equivalents. ```csharp using Jint; using Jint.Native; var engine = new Engine(); // Set primitive values engine.SetValue("number", 42); engine.SetValue("text", "Hello"); engine.SetValue("flag", true); engine.SetValue("nothing", JsValue.Null); // Set a delegate as a JavaScript function engine.SetValue("log", new Action(Console.WriteLine)); engine.SetValue("add", new Func((a, b) => a + b)); engine.Execute("log(add(5, 3));"); // Output: 8 // Set a .NET object (POCO) var person = new Person { Name = "Alice", Age = 30 }; engine.SetValue("person", person); engine.Execute("person.Name = 'Bob'; person.Age = 25;"); Console.WriteLine($"{person.Name}, {person.Age}"); // Output: Bob, 25 // Set anonymous objects engine.SetValue("config", new { Host = "localhost", Port = 8080, Enabled = true }); var host = engine.Evaluate("config.Host").AsString(); Console.WriteLine(host); // Output: localhost public class Person { public string Name { get; set; } public int Age { get; set; } } ``` -------------------------------- ### ECMAScript Spec References (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Indicates that Jint's code includes comments referencing specific sections of the TC39 ECMAScript specification. These references are crucial for maintaining compliance and implementing new features according to standards. ```csharp // Code includes TC39 spec section references in comments (e.g., `// https://tc39.es/ecma262/#sec-...`) // Maintain these references when implementing new features // The to follow TC 39 spec when possible // The test files are located in ..\test262\test when source code needed ``` -------------------------------- ### ECMAScript Compliance Goals (Text) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md States Jint's commitment to adhering to the ECMAScript specification as closely as possible, avoiding non-standard extensions, and supporting both strict and sloppy modes with defined behavior differences. ```text - Follow ECMAScript specification behavior as closely as practical - Do not introduce non-standard language extensions - Support both strict and sloppy mode with spec-defined differences ``` -------------------------------- ### Interop Components (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Details the Jint Interop components responsible for bridging JavaScript and .NET code. This includes wrapping .NET objects, exposing CLR types, and handling method calls and type conversions. ```csharp // **ObjectWrapper.cs**: Wraps .NET objects for JavaScript access // **TypeReference.cs**: Exposes CLR types to JavaScript (e.g., `System.String`) // **ClrFunction.cs**: Wraps .NET methods/delegates as JavaScript functions // **DefaultTypeConverter.cs**: Bidirectional conversion between JS values and CLR types // **Reflection/**: Type discovery and method binding with caching ``` -------------------------------- ### Object Pooling Pattern (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Highlights the use of object pooling in Jint for Reference, Arguments, and JsValue arrays to minimize garbage collection pressure. Specific pool classes like `ReferencePool` and `JsValueArrayPool` are mentioned. ```csharp // Reference, Arguments, and JsValue arrays are pooled to reduce GC pressure // Use `ReferencePool`, `ArgumentsInstancePool`, `JsValueArrayPool` ``` -------------------------------- ### CLR Interop and Type References in Jint Source: https://context7.com/sebastienros/jint/llms.txt Enables direct access to .NET types and namespaces from JavaScript using `AllowClr()`, `TypeReference`, and `importNamespace()`. This allows for seamless integration of .NET functionalities, including generic types and custom classes, within JavaScript code. ```csharp // Enable CLR access var engine = new Engine(options => options.AllowClr(typeof(File).Assembly)); // Use .NET types directly from JavaScript engine.Execute(@" var file = new System.IO.StreamWriter('output.txt'); file.WriteLine('Hello from JavaScript!'); file.Close(); var guid = System.Guid.NewGuid().ToString(); var now = System.DateTime.Now; "); // Import a namespace for convenience engine.Execute(@" var IO = importNamespace('System.IO'); var content = IO.File.ReadAllText('output.txt'); "); // Expose a specific type reference engine.SetValue("StringBuilder", TypeReference.CreateTypeReference(engine)); var result = engine.Evaluate(@" var sb = new StringBuilder(); sb.Append('Hello'); sb.Append(' '); sb.Append('World'); sb.ToString(); "); Console.WriteLine(result.AsString()); // Output: Hello World // Use generic types engine.Execute(@" var ListOfString = System.Collections.Generic.List(System.String); var list = new ListOfString(); list.Add('apple'); list.Add('banana'); list.Count; // 2 "); // Custom type with methods public class Calculator { public double Add(double a, double b) => a + b; public double Multiply(double a, double b) => a * b; public static double Pi => Math.PI; } engine.SetValue("Calculator", TypeReference.CreateTypeReference(engine)); engine.Execute(@" var calc = new Calculator(); var sum = calc.Add(5, 3); // 8 var pi = Calculator.Pi; // 3.14159... "); ``` -------------------------------- ### JsValue Type System (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Details the JsValue type system in Jint, which serves as the abstract base for all JavaScript values. It includes primitive types and object types, with built-in JavaScript objects organized by type in the Jint/Native/ directory. ```csharp // `JsValue` is the abstract base class for all JavaScript values // Primitive types: JsUndefined, JsNull, JsBoolean, JsNumber, JsString, JsBigInt, JsSymbol // Object types: ObjectInstance and derived classes (JsArray, JsDate, JsMap, JsSet, JsPromise, etc.) // All built-in JavaScript objects are in `Jint/Native/` organized by type (Array/, Date/, Error/, Function/, etc.) ``` -------------------------------- ### Add Specific CLR Type Reference in Jint in C# Source: https://github.com/sebastienros/jint/blob/main/README.md This C# code shows how to explicitly make a specific .NET type available in the Jint engine's JavaScript environment. It uses `TypeReference.CreateTypeReference(engine)` to create a reference to the type 'TheType', which can then be used in JavaScript. ```csharp engine.SetValue("TheType", TypeReference.CreateTypeReference(engine)); ``` -------------------------------- ### Type Flags Pattern (C#) Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Describes the use of the `InternalTypes` enum in Jint for efficient type checking without casting. Type flags are employed in performance-critical code paths to speed up operations. ```csharp // `InternalTypes` enum enables fast type checking without casting // Many hot paths use type flags for performance ``` -------------------------------- ### Set Timeout Interval Constraint in Jint Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Sets a timeout interval for script execution in Jint, ensuring that scripts do not run indefinitely. This helps prevent denial-of-service attacks and hangs. ```csharp options.TimeoutInterval(TimeSpan.FromSeconds(4)); ``` -------------------------------- ### Set Memory Limit Constraint in Jint Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Configures the Jint engine to enforce a memory limit, preventing excessive memory consumption during script execution. This is a crucial security and stability feature. ```csharp options.LimitMemory(4_000_000); ``` -------------------------------- ### Set Maximum Statements Constraint in Jint Source: https://github.com/sebastienros/jint/blob/main/CLAUDE.md Limits the maximum number of statements that can be executed within a single script in Jint. This is another measure to prevent resource abuse and infinite loops. ```csharp options.MaxStatements(1000); ``` -------------------------------- ### Configure Jint Engine Time Zone in C# Source: https://github.com/sebastienros/jint/blob/main/README.md This C# code configures a Jint engine to use a specific time zone ('Pacific Standard Time') for JavaScript's Date object operations. This ensures consistent date/time behavior regardless of the host system's default time zone. ```csharp var PST = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); var engine = new Engine(cfg => cfg.LocalTimeZone(PST)); engine.Execute("new Date().toString()"); // Wed Dec 31 1969 16:00:00 GMT-08:00 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.