Documentation
¶
Overview ¶
Package core provides headless Risor execution without GUI dependencies. This enables static compilation and smaller binaries for CLI tools and servers.
Index ¶
- Constants
- func GetAppVersion() string
- func SetAppVersion(version string)
- type Context
- func (cb *Context) EnabledModules() map[string]bool
- func (cb *Context) Eval(script string) (any, error)
- func (cb *Context) EvalWithImports(script string, fetchFunc func(path string) (string, error)) (any, error)
- func (cb *Context) ImportScript(source string) error
- func (cb *Context) LoadScript(script string)
- type ImportedModule
- func (m *ImportedModule) Attrs() []object.AttrSpec
- func (m *ImportedModule) Equals(other object.Object) bool
- func (m *ImportedModule) GetAttr(name string) (object.Object, bool)
- func (m *ImportedModule) Inspect() string
- func (m *ImportedModule) Interface() interface{}
- func (m *ImportedModule) IsTruthy() bool
- func (m *ImportedModule) RunOperation(opType op.BinaryOpType, right object.Object) (object.Object, error)
- func (m *ImportedModule) SetAttr(name string, value object.Object) error
- func (m *ImportedModule) Type() object.Type
- type Option
- func WithAppName(name string) Option
- func WithExec() Option
- func WithFilepath() Option
- func WithGlobal(name string, value any) Option
- func WithHTTP() Option
- func WithHTTPImport() Option
- func WithIO() Option
- func WithOS() Option
- func WithRisorOptions(globals ...risor.Option) Option
- func WithSQL() Option
- func WithStrings() Option
- func WithTime() Option
- type Requirements
- type ScriptRunner
- type VersionInfo
Constants ¶
const Version = "0.6.0"
Version is the current version of the fynerisor library
Variables ¶
This section is empty.
Functions ¶
func GetAppVersion ¶
func GetAppVersion() string
GetAppVersion returns the embedding application's version. Returns empty string if not set.
func SetAppVersion ¶
func SetAppVersion(version string)
SetAppVersion sets the embedding application's version. This version is used when scripts call require(["vX.Y.Z"]) to check compatibility with the embedding application, not fynerisor itself.
Example:
func main() {
fynerisor.SetAppVersion("1.2.3")
w := fynerisor.NewApp("My App")
// Scripts can now use: require(["v1.2"])
w.LoadScript(script)
w.ShowAndRun()
}
Scripts should use semantic versioning format: "v1.2.3" or "v1.2"
Types ¶
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context builds Risor execution contexts for non-GUI applications. It provides access to modules (HTTP, SQL, OS, etc.) and import functionality without requiring Fyne or any GUI dependencies.
This enables static compilation for headless scripts, CLI tools, or server applications that need Risor scripting with modules.
func NewContext ¶
NewContext creates a new Risor context for non-GUI applications.
Parameters:
- opts: Optional configuration using functional options (WithHTTP, WithSQL, etc.)
Returns:
- *Context: Execution context for Risor scripts
Example:
ctx := core.NewContext(
core.WithHTTP(),
core.WithSQL(),
core.WithOS(),
)
script := `
require(["@http", "@sql"])
let data = http.get("https://api.example.com/data").json()
print(data)
`
result, err := ctx.Eval(script)
func (*Context) EnabledModules ¶
EnabledModules returns a map of enabled module names.
func (*Context) Eval ¶
Eval evaluates a Risor script and returns the result.
Parameters:
- script: The Risor script source code
Returns:
- any: The script result (converted to Go types)
- error: Any evaluation error
Example:
// Direct eval
ctx := core.NewContext(core.WithHTTP())
result, err := ctx.Eval(`http.get("https://example.com").status`)
// With imports (runtime module scoping)
result, err := ctx.Eval(`
let utils = import("utils.risor")
utils.myUtil(42)
`)
func (*Context) EvalWithImports ¶
func (cb *Context) EvalWithImports(script string, fetchFunc func(path string) (string, error)) (any, error)
EvalWithImports is deprecated. Use runtime import() function instead:
script := `
let utils = import("utils.risor")
require("@http")
let result = utils.myUtil(42)
`
result, err := ctx.Eval(script)
The new import() provides proper module scoping with namespace isolation.
func (*Context) ImportScript ¶
ImportScript is deprecated and has been removed in favor of runtime import(). Use the import() function directly in scripts for module-scoped imports:
let utils = import("utils.risor")
utils.myFunction()
This provides proper namespacing and prevents global scope pollution. The old concatenation-based import system is no longer supported.
func (*Context) LoadScript ¶
LoadScript sets the main script to be executed. Call this after all ImportScript() calls.
type ImportedModule ¶ added in v0.6.0
type ImportedModule struct {
// contains filtered or unexported fields
}
ImportedModule wraps the exported globals from an imported Risor script. It provides GetAttr access to all top-level variables and functions defined in the imported module.
Example:
// math_utils.risor
let add = (a, b) => a + b
let PI = 3.14159
// main.risor
let math = import("math_utils.risor")
print(math.add(5, 3)) // 8
print(math.PI) // 3.14159
func NewImportedModule ¶ added in v0.6.0
func NewImportedModule(name string, globals map[string]object.Object) *ImportedModule
NewImportedModule creates a new module object with the given exports.
func (*ImportedModule) Attrs ¶ added in v0.6.0
func (m *ImportedModule) Attrs() []object.AttrSpec
Attrs returns metadata about the module's exported attributes.
func (*ImportedModule) Equals ¶ added in v0.6.0
func (m *ImportedModule) Equals(other object.Object) bool
Equals compares modules by name.
func (*ImportedModule) GetAttr ¶ added in v0.6.0
func (m *ImportedModule) GetAttr(name string) (object.Object, bool)
GetAttr provides dot notation access to module exports. Returns the exported value and true if found, or nil and false if not found.
func (*ImportedModule) Inspect ¶ added in v0.6.0
func (m *ImportedModule) Inspect() string
Inspect returns a string representation of the module.
func (*ImportedModule) Interface ¶ added in v0.6.0
func (m *ImportedModule) Interface() interface{}
Interface returns the module as a Go value (returns the module itself).
func (*ImportedModule) IsTruthy ¶ added in v0.6.0
func (m *ImportedModule) IsTruthy() bool
IsTruthy returns true (modules are always truthy).
func (*ImportedModule) RunOperation ¶ added in v0.6.0
func (m *ImportedModule) RunOperation(opType op.BinaryOpType, right object.Object) (object.Object, error)
RunOperation is not supported for modules.
func (*ImportedModule) SetAttr ¶ added in v0.6.0
func (m *ImportedModule) SetAttr(name string, value object.Object) error
SetAttr is not supported for modules (they are read-only after import).
func (*ImportedModule) Type ¶ added in v0.6.0
func (m *ImportedModule) Type() object.Type
Type returns the type identifier for this object.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures a Context during creation.
func WithAppName ¶
WithAppName sets the application name exposed to Risor scripts via app.name. This allows scripts to detect which application is running them.
Example:
ctx := core.NewContext(
core.WithAppName("myapp"),
)
Usage in script:
if (app.name == "myapp") {
print("Running in myapp")
}
func WithExec ¶ added in v0.5.1
func WithExec() Option
WithExec enables the exec module for running external commands from Risor scripts. The module provides functions: command, look_path, and exec.
Example:
ctx := core.NewContext(core.WithExec())
Usage in script:
let result = exec(["ls", "-la"]) print(result.stdout)
func WithFilepath ¶
func WithFilepath() Option
WithFilepath enables the filepath module for file path manipulation from Risor scripts.
func WithGlobal ¶ added in v0.6.0
WithGlobal adds a custom global variable to the Risor environment and registers it as a requireable module that can be validated with require(["@name"]).
This allows you to expose custom Go types and their methods to scripts, while enabling scripts to explicitly declare their dependencies for validation.
The global will be:
- Added to the Risor environment (accessible as a global variable)
- Registered in enabledModules (can be validated with require())
- Provide clear error messages if required but not available
Example:
type MyAPI struct { ... }
func (api *MyAPI) GetAttr(name string) (object.Object, bool) { ... }
myAPI := &MyAPI{...}
ctx := core.NewContext(
core.WithGlobal("myapi", myAPI),
)
Usage in script:
require(["v1.0", "@myapi"]) // Validates @myapi is available myapi.DoSomething() // Use the custom API
If a script tries to require @myapi in a different application that doesn't provide it, the require() call will fail with a clear error message instead of causing undefined variable errors later.
This works for any custom object: application APIs, database connections, configuration objects, or any other Go type you want to expose to scripts.
func WithHTTP ¶
func WithHTTP() Option
WithHTTP enables the HTTP module for making HTTP requests from Risor scripts. The module provides functions: get, post, put, delete, and fetch.
Example:
ctx := core.NewContext(core.WithHTTP())
Usage in script:
let response = http.get("https://api.example.com/data")
print(response.status, response.body)
func WithHTTPImport ¶ added in v0.6.0
func WithHTTPImport() Option
WithHTTPImport enables importing Risor modules from HTTP(S) URLs. This is a separate option from WithHTTP() for security reasons.
When enabled, scripts can use import() with HTTP(S) URLs:
let utils = import("https://example.com/utils.risor")
utils.someFunction()
Security considerations:
- Only enable this for trusted scripts or controlled environments
- Imported modules execute with full access to enabled modules
- HTTPS is recommended for production
Example:
ctx := core.NewContext(
core.WithHTTP(),
core.WithHTTPImport(),
)
Usage in script:
require(["@httpimport"])
let remote = import("https://cdn.example.com/mylib.risor")
func WithIO ¶
func WithIO() Option
WithIO enables the IO module for file I/O operations from Risor scripts. The module provides functions: cp and read_all.
Example:
ctx := core.NewContext(core.WithIO())
Usage in script:
io.cp("source.txt", "dest.txt")
let content = io.read_all("file.txt")
func WithOS ¶
func WithOS() Option
WithOS enables the OS module for accessing OS functionality from Risor scripts. The module provides functions: goos, current_user, open_browser, read_file, write_file, and read_dir.
Example:
ctx := core.NewContext(core.WithOS())
Usage in script:
let platform = os.goos()
let user = os.current_user()
os.write_file("test.txt", "Hello!")
func WithRisorOptions ¶ added in v0.6.0
WithRisorOptions adds advanced Risor VM configuration options. These are opaque risor.Option objects for advanced Risor VM configuration. Unlike WithGlobal(), these options are NOT forwarded to imported modules.
Use WithGlobal() instead for named globals that modules should access.
Example:
customFuncs := map[string]any{
"myFunc": func() string { return "hello" },
}
ctx := core.NewContext(
core.WithRisorOptions(risor.WithEnv(customFuncs)),
)
func WithSQL ¶
func WithSQL() Option
WithSQL enables the SQL module for database connectivity from Risor scripts. Supports: MySQL, PostgreSQL, SQLite, SQL Server
Example:
ctx := core.NewContext(core.WithSQL())
Usage in script:
let conn = sql.connect("sqlite3::memory:")
conn.exec("CREATE TABLE users (id INT, name TEXT)")
let rows = conn.query("SELECT * FROM users").collect()
func WithStrings ¶
func WithStrings() Option
WithStrings enables the strings module for string manipulation from Risor scripts.
type Requirements ¶
type Requirements struct {
MinVersion string // Minimum version (e.g., "0.2.0")
ExactVersion string // Exact version if ==v syntax used
RequiredModules []string // List of required modules (e.g., ["sql", "http"])
Imports []string // List of import paths/URLs (e.g., ["utils.risor", "http://..."])
Raw []string // Raw requirement strings
}
Requirements represents parsed script requirements
func AnalyzeRequirements ¶
func AnalyzeRequirements(script string) (*Requirements, error)
AnalyzeRequirements parses a Risor script and extracts all require() calls. This function is useful for external applications that need to understand script dependencies before execution.
It compiles the script and inspects require() calls without executing the full script logic.
Example:
script := `
require(["v0.2", "@sql", "@http"])
let btn = widget.NewButton("Hello", () => {})
`
reqs, err := fynerisor.AnalyzeRequirements(script)
if err != nil {
log.Fatal(err)
}
fmt.Println("Requires version:", reqs.MinVersion)
fmt.Println("Requires modules:", reqs.RequiredModules)
func (*Requirements) RequiresGUI ¶
func (r *Requirements) RequiresGUI() bool
RequiresGUI returns true if the script requires a GUI window (@gui)
func (*Requirements) String ¶
func (r *Requirements) String() string
String returns a human-readable representation of requirements
type ScriptRunner ¶
type ScriptRunner struct {
// contains filtered or unexported fields
}
ScriptRunner manages script execution for headless contexts.
func NewScriptRunner ¶
func NewScriptRunner(globals []risor.Option) *ScriptRunner
NewScriptRunner creates a new script runner with the given globals.
func (*ScriptRunner) Eval ¶
func (sr *ScriptRunner) Eval() (any, error)
Eval executes the loaded script.
Returns:
- any: The result of script execution
- error: Any execution error
func (*ScriptRunner) LoadScript ¶
func (sr *ScriptRunner) LoadScript(script string)
LoadScript sets the script to be executed.
type VersionInfo ¶
type VersionInfo struct {
Version string // Fynerisor library version
AppVersion string // Embedding application version (if set)
RisorCompat string // Compatible Risor version
FyneCompat string // Compatible Fyne version
}
VersionInfo provides detailed version information
func GetVersion ¶
func GetVersion() VersionInfo
GetVersion returns version information for this fynerisor release