Extensions¶
INFINITY.JS supports native extensions written in C/C++ or Delphi/Pascal that can extend the runtime with custom functionality. Extensions are dynamically loaded libraries (.dll on Windows, .so on Linux) that expose functions to the JavaScript runtime through a standardized interface.
Note
No extensions ship with INFINITY.JS. The release archive contains templates for your own extensions in C and Delphi (folder extensions, including the libmujs headers).
Overview¶
Native extensions allow you to:
- Access system APIs not directly available in JavaScript
- Integrate third-party libraries (e.g., image processing, OCR, hardware access)
- Optimize performance-critical code by implementing it in native code
- Extend the runtime with custom namespaces, classes, and functions
Extensions are loaded into the INFINITY.JS runtime at startup and registered as modules. Like built-in modules, they are loaded into a script with infinity.loadModule() and accessed through the infinity namespace.
Extension Architecture¶
Each extension must implement five required exported functions:
| Function | Purpose |
|---|---|
IFVersion() | Returns the extension version string |
IFNamespace() | Returns the module name of the extension (used with infinity.loadModule()) |
IFLoadExtension() | Called once when the extension is loaded |
IFUnloadExtension() | Called once when the extension is unloaded |
IFInitRuntime() | Called when a script loads the module with infinity.loadModule(), to register functions and properties. The infinity object is on top of the stack. |
If one of these exports is missing, the extension is not loaded and an error is written to the log file.
Creating Extensions¶
C/C++ Extensions¶
Required Files¶
- Header file (
example.h) - Declares exported functions - Source file (
example.cor.cpp) - Implements the extension logic - MuJS header (
libmujs.h) - JavaScript engine interface - Compile script - Platform-specific build script
Example Extension (C)¶
example.h:
#ifdef __cplusplus
extern "C" {
#endif
#if defined(_MSC_VER)
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
#include "libmujs.h"
extern DLLEXPORT const char *IFVersion();
extern DLLEXPORT const char *IFNamespace();
extern DLLEXPORT void IFLoadExtension();
extern DLLEXPORT void IFUnloadExtension();
extern DLLEXPORT void IFInitRuntime(js_State *J);
#ifdef __cplusplus
}
#endif
example.c:
#include <stdio.h>
#include "example.h"
#include "MuJS/lib/libmujs.c"
// JavaScript function: infinity.example.echo(text)
void IFEchoJs(js_State *J) {
if (js_isdefined(J, 1) == 0)
js_syntaxerror(J, "Invalid number of parameters");
else
js_pushstring(J, js_tostring(J, 1));
}
// Return extension version
DLLEXPORT const char *IFVersion() {
return "1.0.0";
}
// Return JavaScript namespace
DLLEXPORT const char *IFNamespace() {
return "infinity.example";
}
// Called when extension is loaded
DLLEXPORT void IFLoadExtension() {
// Initialize extension resources here
}
// Called when extension is unloaded
DLLEXPORT void IFUnloadExtension() {
// Clean up extension resources here
}
// Register functions and properties in the JavaScript runtime
DLLEXPORT void IFInitRuntime(js_State *J) {
js_newobject(J);
// Add a string property
js_pushstring(J, "Some property value");
js_defproperty(J, -2, "stringProp", 0);
// Add a function
js_newcfunction(J, IFEchoJs, "echo", 1);
js_defproperty(J, -2, "echo", JS_READONLY | JS_DONTCONF);
// Register the namespace as property "example" of the infinity object
js_defproperty(J, -2, "example", JS_READONLY | JS_DONTCONF);
}
Warning
Never call js_freestate() in an extension. The js_State belongs to the INFINITY.JS runtime and is still used after IFInitRuntime() returns.
Compiling C Extensions¶
The template in the release archive contains build scripts for both platforms:
Windows (x64, Visual C++ command prompt):
CL /O2 /arch:SSE2 /MT /LD example.c
Linux (x64):
gcc -O3 -fpic -c example.c -o example.o
gcc -shared -o example.so example.o
Delphi/Pascal Extensions¶
Example Extension (Delphi)¶
example.dpr:
library example;
uses
libmujs,
System.SysUtils;
{$R *.res}
procedure IFEchoJs(State: PJS_State); cdecl;
begin
if JS_IsDefined(State, 1) = 0 then
JS_SyntaxError(State, 'Invalid number of parameters')
else
JS_PushString(State, JS_ToString(State, 1));
end;
function IFVersion: MarshaledAString; cdecl;
begin
Result := MarshaledAString(StringToCESU8('1.0.0'));
end;
function IFNamespace: MarshaledAString; cdecl;
begin
Result := MarshaledAString(StringToCESU8('infinity.example'));
end;
procedure IFLoadExtension; cdecl;
begin
if not InitMuJS(ExtractFilePath(ParamStr(0))) then
raise Exception.Create('Cannot initialize javascript engine');
end;
procedure IFUnloadExtension; cdecl;
begin
CloseMuJS;
end;
procedure IFInitRuntime(State: PJS_State); cdecl;
begin
JS_NewObject(State);
JS_PushString(State, 'Some property value');
JS_DefProperty(State, -2, 'stringProp', 0);
JS_NewCFunction(State, @IFEchoJs, 'echo', 1);
JS_DefProperty(State, -2, 'echo', JS_READONLY or JS_DONTCONF);
JS_DefProperty(State, -2, 'example', JS_READONLY or JS_DONTCONF);
end;
exports
IFVersion,
IFNamespace,
IFLoadExtension,
IFUnloadExtension,
IFInitRuntime;
end.
MuJS JavaScript Engine Interface¶
INFINITY.JS uses the MuJS JavaScript engine. Extensions interact with the runtime through the MuJS C API.
Common MuJS Functions¶
Stack Operations¶
// Push values onto the stack
js_pushstring(J, "text"); // Push string
js_pushnumber(J, 42); // Push number
js_pushboolean(J, 1); // Push boolean
js_pushnull(J); // Push null
js_pushundefined(J); // Push undefined
// Get values from the stack
const char *str = js_tostring(J, index);
double num = js_tonumber(J, index);
int bool = js_toboolean(J, index);
Object Creation¶
// Create a new object
js_newobject(J);
// Add properties
js_pushstring(J, "value");
js_defproperty(J, -2, "propertyName", 0);
// Create a new function
js_newcfunction(J, MyFunction, "functionName", argCount);
Type Checking¶
int js_isundefined(J, index);
int js_isnull(J, index);
int js_isboolean(J, index);
int js_isnumber(J, index);
int js_isstring(J, index);
int js_isobject(J, index);
int js_isdefined(J, index); // Not null or undefined
Error Handling¶
js_error(J, "Error message");
js_syntaxerror(J, "Syntax error message");
js_typeerror(J, "Type error message");
Installing Extensions¶
Extensions must be placed in the extensions folder next to the INFINITY.JS executable of the platform:
infinity/
bin/
win-x64/
infinity.exe
extensions/
example.dll
linux-x64/
infinity
extensions/
example.so
Loading Extensions¶
On startup, the runtime loads all *.dll files (Windows) or *.so files (Linux) from the extensions folder and registers each extension as a module under the name returned by IFNamespace(). The log file shows whether an extension was loaded successfully ("Script extension ... successfully loaded and registered") or why it failed. infinity -listModules lists the loaded extensions together with the built-in modules.
A script uses the extension like a built-in module:
infinity.loadModule('infinity.example');
console.log(infinity.example.stringProp); // "Some property value"
let result = infinity.example.echo('Hello from extension!');
console.log(result); // "Hello from extension!"
Extension Namespaces¶
The name returned by IFNamespace() is the module name for infinity.loadModule(). Where the functions appear in JavaScript is decided by IFInitRuntime(): it defines a property on the infinity object, which is on top of the stack when the function is called. Use the same name for both, so that the module name matches the access pattern:
IFNamespace() | Property defined in IFInitRuntime() | Access Pattern |
|---|---|---|
infinity.example | example | infinity.example.functionName() |
infinity.mylib | mylib | infinity.mylib.functionName() |
Note: Choose a name that doesn't conflict with a built-in module, and start it with infinity. to maintain consistency with the runtime API.
Advanced Topics¶
Managing State¶
Extensions can maintain their own state between calls:
// Global state
static int call_count = 0;
void MyFunction(js_State *J) {
call_count++;
js_pushnumber(J, call_count);
}
Working with Objects¶
void CreateComplexObject(js_State *J) {
// Create main object
js_newobject(J);
// Add nested object
js_newobject(J);
js_pushstring(J, "nested value");
js_defproperty(J, -2, "nestedProp", 0);
js_defproperty(J, -2, "nested", 0);
// Add array
js_newarray(J);
js_pushstring(J, "item1");
js_setindex(J, -2, 0);
js_pushstring(J, "item2");
js_setindex(J, -2, 1);
js_defproperty(J, -2, "items", 0);
}
Error Handling in Extensions¶
void SafeFunction(js_State *J) {
if (js_isdefined(J, 1) == 0) {
js_error(J, "Missing required parameter");
return;
}
const char *param = js_tostring(J, 1);
// Perform operation
if (operation_failed) {
js_error(J, "Operation failed: reason");
return;
}
// Return result
js_pushstring(J, result);
}
Memory Management¶
void MyFunction(js_State *J) {
// Allocate resources
char *buffer = malloc(1024);
// Use resources
// ...
// Important: Free your own resources before returning
// (the js_State belongs to the runtime - never free it)
free(buffer);
js_pushundefined(J);
}
Keep in mind that js_error() and the other error functions don't return (they jump back into the runtime), so free your own resources before raising an error.
Templates¶
The release archive contains two templates in the extensions folder, which you can use as a starting point for your own extensions:
example c- C extension with header file,libmujs.hand build scriptsexample delphi- Delphi library project withlibmujs.pas
Best Practices¶
- Version Your Extensions
- Return meaningful version strings from
IFVersion() -
Document breaking changes
-
Use Descriptive Namespaces
- Choose clear, unique namespace names
-
Avoid conflicts with existing modules
-
Validate Parameters
- Always check parameter count and types
-
Provide clear error messages
-
Clean Up Resources
- Release memory in
IFUnloadExtension() -
Free allocated resources properly
-
Thread Safety
- INFINITY.JS is multi-threaded
-
Use appropriate synchronization for shared state
-
Error Handling
- Use
js_error()for runtime errors - Provide descriptive error messages
-
Don't crash - return errors gracefully
-
Documentation
- Document your extension's API
- Provide usage examples
- Include type definitions if possible
Platform-Specific Considerations¶
Windows¶
- Use
.dllextension - Export functions using
__declspec(dllexport) - Compile with MSVC or MinGW/GCC
Linux¶
- Use
.soextension - Compile with
-fPICflag - Build for x64 and glibc based distributions (like the runtime)
Debugging Extensions¶
Logging¶
Use INFINITY.JS's console output from extensions:
void MyFunction(js_State *J) {
// Log to console: console.log("...")
js_getglobal(J, "console");
js_getproperty(J, -1, "log"); // function
js_copy(J, -2); // this = console
js_pushstring(J, "Debug message from extension");
js_call(J, 1); // one argument
js_pop(J, 2); // result and console
js_pushundefined(J);
}
Testing¶
Create test scripts to verify extension functionality:
infinity.loadModule('infinity.example');
try {
let result = infinity.example.echo('test');
if (result === 'test')
console.info('Echo test passed');
else
console.error('Echo test failed: ' + result);
} catch (e) {
console.error('Echo test failed: ' + e);
}
Troubleshooting¶
Extension Not Loading¶
- Verify the file is in the
extensionsfolder next to the INFINITY.JS executable (win-x64/extensionsorlinux-x64/extensions) - Check the log file for the error message of the extension loader
- Ensure all five required functions are exported (with C linkage, without name decoration)
- Make sure the extension is built for x64 and all libraries it depends on can be found
- Run
infinity -listModulesto check whether the extension is registered
Crashes¶
- Check for memory leaks
- Verify proper stack management
- Ensure thread safety
- Add error handling for edge cases
Incorrect Results¶
- Validate input parameters
- Check return value types
- Verify stack operations
- Test with various inputs
Resources¶
- Extension templates: folders
extensions/example candextensions/example delphiof the release archive - MuJS documentation: https://mujs.com/