### Install Extism Go SDK Source: https://extism.org/docs/quickstart/host-quickstart Install the Extism Go SDK using `go get`. This command fetches and installs the SDK package. ```bash go get github.com/extism/go-sdk ``` -------------------------------- ### Install Extism.runtime.all Source: https://extism.org/docs/quickstart/host-quickstart Installs the Extism native runtime packages for all supported operating systems. ```bash dotnet add package Extism.runtime.all ``` -------------------------------- ### Build and Install C++ SDK Source: https://extism.org/docs/quickstart/host-quickstart Builds and installs the Extism C++ SDK using CMake. This involves configuring, building, and installing the library. ```bash cmake -B build cmake --build build -j sudo cmake --install build ``` -------------------------------- ### Install JS PDK Source: https://extism.org/docs/quickstart/plugin-quickstart Download and run the installation script for the Extism JS compiler. ```bash curl -O https://raw.githubusercontent.com/extism/js-pdk/main/install.sh sh install.sh ``` -------------------------------- ### Install Extism Runtime for C Source: https://extism.org/docs/quickstart/host-quickstart Installs the Extism Runtime shared object using the Extism CLI. This is a prerequisite for using the Extism C SDK. ```bash sudo extism lib install #=> Fetching https://github.com/extism/extism/releases/download/v1.0.0/libextism-aarch64-apple-darwin-v1.0.0.tar.gz #=> Copying libextism.dylib to /usr/local/lib/libextism.dylib #=> Copying extism.h to /usr/local/include/extism.h ``` -------------------------------- ### Install xtp CLI Source: https://extism.org/docs/concepts/testing Use this command to download and install the xtp test runner CLI. ```shell curl https://static.dylibso.com/cli/install.sh | sudo sh ``` -------------------------------- ### Install Extism.Sdk Source: https://extism.org/docs/quickstart/host-quickstart Adds the Extism.Sdk NuGet package to your .NET project. ```bash dotnet add package Extism.Sdk ``` -------------------------------- ### Install Extism Runtime Source: https://extism.org/docs/quickstart/host-quickstart Command to install the required Extism runtime library. ```bash sudo extism lib install #=> Fetching https://github.com/extism/extism/releases/download/v1.0.0/libextism-aarch64-apple-darwin-v1.0.0.tar.gz #=> Copying libextism.dylib to /usr/local/lib/libextism.dylib #=> Copying extism.h to /usr/local/include/extism.h ``` -------------------------------- ### Install Extism Runtime CLI Source: https://extism.org/docs/quickstart/host-quickstart Installs the Extism Runtime using the Extism CLI. This command fetches the shared object and header files. ```bash sudo extism lib install #=> Fetching https://github.com/extism/extism/releases/download/v1.0.0/libextism-aarch64-apple-darwin-v1.0.0.tar.gz #=> Copying libextism.dylib to /usr/local/lib/libextism.dylib #=> Copying extism.h to /usr/local/include/extism.h ``` -------------------------------- ### Install WASI Workload Source: https://extism.org/docs/quickstart/plugin-quickstart Install the experimental WASI workload required for .NET plug-in compilation. ```bash dotnet workload install wasi-experimental ``` -------------------------------- ### Install Extism Runtime Source: https://extism.org/docs/quickstart/host-quickstart Install the Extism Runtime using the Extism CLI. This command downloads the shared object and header files. ```bash sudo extism lib install #=> Fetching https://github.com/extism/extism/releases/download/v1.0.0/libextism-aarch64-apple-darwin-v1.0.0.tar.gz #=> Copying libextism.dylib to /usr/local/lib/libextism.dylib #=> Copying extism.h to /usr/local/include/extism.h ``` -------------------------------- ### Install PHP Dependency Source: https://extism.org/docs/quickstart/host-quickstart Composer command to add the Extism PHP SDK. ```bash composer require extism/extism ``` -------------------------------- ### Install Extism JS SDK Source: https://extism.org/docs/quickstart/host-quickstart Install the Extism JavaScript SDK using npm. This is required for Node.js environments. ```bash npm install @extism/extism --save ``` -------------------------------- ### Install Extism Ruby Gem Source: https://extism.org/docs/quickstart/host-quickstart Install the Extism gem using the 'gem install' command if not using bundler. This command installs the gem globally. ```bash gem install extism ``` -------------------------------- ### Install Extism in Docker Source: https://extism.org/docs/install Instructions for installing the Extism runtime within a Docker container environment. ```dockerfile RUN curl -s https://get.extism.org/cli | sh -s -- -y RUN extism lib install ENV LD_LIBRARY_PATH="/usr/local/lib:$LD_LIBRARY_PATH" ``` ```dockerfile ENV LD_LIBRARY_PATH="/usr/local/lib:$LD_LIBRARY_PATH" COPY --from=build /usr/local/include/extism.h /usr/local/include/extism.h COPY --from=build /usr/local/lib/libextism.so /usr/local/lib/libextism.so COPY --from=build /usr/local/lib/libextism.a /usr/local/lib/libextism.a COPY --from=build /usr/local/lib/pkgconfig/extism.pc /usr/local/lib/pkgconfig/extism.pc COPY --from=build /usr/local/lib/pkgconfig/extism-static.pc /usr/local/lib/pkgconfig/extism-static.pc ``` -------------------------------- ### Execute Haskell Example Source: https://extism.org/docs/quickstart/host-quickstart Runs the Haskell example using cabal exec, demonstrating the output of the vowel counting plugin. ```bash cabal exec example # => {"count":3,"total":3,"vowels":"aeiouAEIOU"} ``` -------------------------------- ### Install Extism CLI Source: https://extism.org/docs/install Commands to install the Extism CLI tool to the default or a specific directory. ```bash curl -s https://get.extism.org/cli | sh ``` ```bash curl -s https://get.extism.org/cli | sh -s -- -o $HOME/.local/bin ``` ```bash curl -s https://get.extism.org/cli | sh -s -- -h ``` -------------------------------- ### Go Plugin Calling Host Function Source: https://extism.org/docs/concepts/host-functions This Go plugin demonstrates how to call a host-provided function ('hello_world') and how to expose a function ('say_hello') to the host. It uses pdk.InputString to get input, pdk.AllocateString to prepare output, and pdk.OutputMemory to send results back. ```go package main import ( "strconv" "github.com/extism/go-pdk" ) // `hello_world` declared below, is a function provided by the host and is linked as a WebAssembly // "import" available to the plug-in. By adding the `export $function_name` annotation, the TinyGo // compiler knows that this is an external function. //export hello_world func hello_world(x uint64) uint64 //export say_hello func say_hello() int32 { input := pdk.InputString() // Create output, this will be passed through `hello_world` output := "Hello, " + input mem := pdk.AllocateString(output) // Call `hello_world` host function, it accepts an offset in memory and // returns an offset in memory offs := hello_world(mem.Offset()) mem = pdk.FindMemory(offs) pdk.OutputMemory(mem) return 0 } func main() {} ``` -------------------------------- ### Install Extism Python Package Source: https://extism.org/docs/quickstart/host-quickstart Install the Extism Python package using pip or poetry. This command installs the Extism library for use in Python projects. ```bash # using pip $ pip install extism # using poetry $ poetry add extism=^1.0.0 ``` -------------------------------- ### Check libextism version Source: https://extism.org/docs/install Verify the currently installed version of the libextism library. ```bash extism lib check v0.5.0 ``` -------------------------------- ### Manage Extism Runtime Library Source: https://extism.org/docs/install Commands to install, update, or relocate the Extism shared library. ```bash sudo extism lib install ``` ```bash sudo -E env "PATH=$PATH" extism lib install ``` ```bash sudo extism lib install --version git ``` ```bash extism lib install --prefix ~/.local ``` -------------------------------- ### Install Build Dependencies for C++ SDK Source: https://extism.org/docs/quickstart/host-quickstart Installs necessary build tools like cmake and jsoncpp for the C++ SDK on Debian and macOS. ```bash # on Debian sudo apt install cmake jsoncpp # on macOS brew install cmake jsoncpp ``` -------------------------------- ### Install Extism Rust Crate Source: https://extism.org/docs/quickstart/host-quickstart Add the Extism Rust crate as a dependency in your `Cargo.toml` file. Specify the desired version. ```toml [dependencies] extism = "1.0.0" ``` -------------------------------- ### Write XTP Test Plugin to Verify Plugin Behavior Source: https://extism.org/docs/concepts/testing This Go code defines an XTP test plugin that calls the `run` function of another Extism plugin and verifies its output. It uses the `xtp-test-go` library for calling the plugin function. This snippet is part of a larger testing setup. ```go package main import ( "fmt" "strings" // import the test harness library xtptest "github.com/dylibso/xtp-test-go" ) //go:export test func test() int32 { // call the `run` function in the `kvplugin` project, & verify the output output := xtptest.CallString("run", nil) ``` -------------------------------- ### Get Extism version Source: https://extism.org/docs/concepts/runtime-apis Returns the current version string of the Extism runtime. ```c const char *extism_version(void); ``` -------------------------------- ### Get plugin output data Source: https://extism.org/docs/concepts/runtime-apis Retrieves the output data buffer from the plugin. ```c const uint8_t *extism_plugin_output_data(ExtismPlugin *plugin); ``` -------------------------------- ### Generate an AssemblyScript Plugin with Extism CLI Source: https://extism.org/docs/quickstart/plugin-quickstart Use the Extism CLI to generate a new plugin project template for AssemblyScript. This command also includes npm installation for dependencies. ```bash extism gen plugin -l AssemblyScript -o plugin cd plugin npm install ``` -------------------------------- ### Initialize a Plugin with a Manifest Source: https://extism.org/docs/concepts/manifest Create a plugin instance by providing a dictionary containing the WASM binary data and memory constraints. ```python wasm = open("../wasm/code.wasm", 'rb').read() wasm_hash = hashlib.sha256(wasm).hexdigest() manifest = { "wasm": [ { "data": wasm, "hash": wasm_hash } ], "memory": { "max_pages": 5 } } plugin = context.plugin(manifest) ``` -------------------------------- ### Build .NET Plug-in Source: https://extism.org/docs/quickstart/plugin-quickstart Compile the .NET project into a WASM binary. ```bash dotnet build ``` -------------------------------- ### Compile Go Plugin Source: https://extism.org/docs/quickstart/plugin-quickstart Build the Go plugin using make. ```bash make ``` -------------------------------- ### Generate C# Plug-in Source: https://extism.org/docs/quickstart/plugin-quickstart Initialize a new C# plug-in project using the Extism CLI. ```bash extism gen plugin -l C# -o plugin ``` -------------------------------- ### Load Plugin in OCaml Source: https://extism.org/docs/quickstart/host-quickstart Initialize a plugin from a manifest in OCaml. ```ocaml open Extism let wasm = Manifest.Wasm.url "https://github.com/extism/plugins/releases/latest/download/count_vowels.wasm" let manifest = Manifest.create [wasm] let plugin = Plugin.of_manifest_exn manifest ``` -------------------------------- ### Build Extism from source with custom features Source: https://extism.org/docs/concepts/configuration Use these commands to clone the repository and compile the runtime with specific optional features enabled. ```bash git clone git@github.com:extism/extism.git cd extism cargo build --release --features http,register-http,register-filesystem,nn # once complete, a libextism.so or libextism.dylib should be in the target/release/ directory. ``` -------------------------------- ### View CLI Help Source: https://extism.org/docs/install Displays the available commands and flags for the Extism CLI. ```bash Usage: extism [command] Available Commands: call Call a plugin function completion Generate the autocompletion script for the specified shell help Help about any command lib Manage libextism Flags: --github-token string Github access token, can also be set using the $GITHUB_TOKEN env variable -h, --help help for extism -q, --quiet Enable additional logging -v, --verbose Enable additional logging --version version for extism Use "extism [command] --help" for more information about a command. ``` -------------------------------- ### Generate F# Plug-in Source: https://extism.org/docs/quickstart/plugin-quickstart Initialize a new F# plug-in project using the Extism CLI. ```bash extism gen plugin -l F# -o plugin ``` -------------------------------- ### Get plugin error Source: https://extism.org/docs/concepts/runtime-apis Retrieves the error string associated with a plugin. ```c const char *extism_plugin_error(ExtismPlugin *plugin); ``` -------------------------------- ### Generate C Plug-in Source: https://extism.org/docs/quickstart/plugin-quickstart Initialize a new C plug-in project and update submodules. ```bash extism gen plugin -l C -o plugin cd ./plugin git submodule update --init --recursive ``` -------------------------------- ### Get plugin memory length Source: https://extism.org/docs/concepts/runtime-apis Retrieves the length of an allocated memory block. ```c ExtismSize extism_current_plugin_memory_length(ExtismCurrentPlugin *plugin, ExtismSize n); ``` -------------------------------- ### Run xtp CLI tests for kvplugin Source: https://extism.org/docs/concepts/testing Compile Go projects to Wasm and run tests using the xtp CLI. Use the --mock-host argument to specify the host Wasm file for stitching pieces together. ```bash xtp plugin test kvplugin.wasm --with kvtest.wasm --mock-host kvhost.wasm ``` -------------------------------- ### Get plugin cancellation handle Source: https://extism.org/docs/concepts/runtime-apis Retrieves a handle used for cancelling a running plugin. ```c const ExtismCancelHandle *extism_plugin_cancel_handle(const ExtismPlugin *plugin); ``` -------------------------------- ### View Extism CLI call command help Source: https://extism.org/docs/install Display available flags and configuration options for the call command. ```bash Usage: extism call [flags] wasm_file function Flags: --allow-host stringArray Allow access to an HTTP host, if no hosts are listed then all requests will fail. Globs may be used for wildcards --allow-path stringArray Allow a path to be accessed from inside the Wasm sandbox, a path can be either a plain path or a map from HOST_PATH:GUEST_PATH --config stringArray Set config values, should be in KEY=VALUE format -h, --help help for call --http-response-max extism_http_request Maximum HTTP response size in bytes when using extism_http_request (default -1) -i, --input string Input data --link stringArray Additional modules to link --log-level string Set log level: trace, debug, warn, info, error --loop int Number of times to call the function (default 1) -m, --manifest When set the input file will be parsed as a JSON encoded Extism manifest instead of a WASM file --memory-max int Maximum number of pages to allocate --set-config config Create config object using JSON, this will be merged with any config arguments --stdin Read input from stdin --timeout uint Timeout in milliseconds --var-max int Maximum size in bytes of Extism var store (default -1) --wasi Enable WASI Global Flags: --github-token string Github access token, can also be set using the $GITHUB_TOKEN env variable -q, --quiet Suppress output -v, --verbose Enable additional logging ``` -------------------------------- ### Add Rust Wasm Target Source: https://extism.org/docs/quickstart/plugin-quickstart Ensure the required Wasm target is installed via rustup. ```bash rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Load Extism Plugin in C Source: https://extism.org/docs/quickstart/host-quickstart Initializes an Extism plugin in C by providing a manifest URL. Error handling is included for plugin loading failures. ```c #include #include #include #include #include int main(void) { const char *manifest = "{\"wasm\": [{\"url\": " ``` ```c "https://github.com/extism/plugins/releases/latest/" "download/count_vowels.wasm"}]}"; char *errmsg = NULL; ExtismPlugin *plugin = extism_plugin_new( (const uint8_t *)manifest, strlen(manifest), NULL, 0, true, &errmsg); if (plugin == NULL) { fprintf(stderr, "ERROR: %s\n", errmsg); extism_plugin_new_error_free(errmsg); exit(1); } // ... } ``` -------------------------------- ### Implement Mock Host Functions in Go Source: https://extism.org/docs/concepts/testing This Go code implements mock host functions `kv_read` and `kv_write` using the Extism PDK. It simulates an in-memory key-value store. Use this as a mock host when testing plugins. ```go package main import ( // to simulate Host Functions, use the PDK to manage host/guest memory. pdk "github.com/extism/go-pdk" ) // this is our in-memory KV store (e.g. a mock database) var kv map[string]string = make(map[string]string) // This export will be made available to the plugin as an import function //go:export kv_read func kv_read(key uint64) uint64 { // find the memory block that contains the key, read the bytes, and look up the // corresponding value in the KV store keyMem := pdk.FindMemory(key) k := string(keyMem.ReadBytes()) // if the entry is not found, return 0 v, ok := kv[k] if !ok { return 0 } // allocate a new memory block for the value, write the value bytes, and return the offset valMem := pdk.AllocateString(v) return valMem.Offset() } // This export will be made available to the plugin as an import function //go:export kv_write func kv_write(key uint64, value uint64) { // find the memory block that contains the key and value, read their bytes, // and store the key-value pair in the KV store keyMem := pdk.FindMemory(key) valueMem := pdk.FindMemory(value) k := string(keyMem.ReadBytes()) v := string(valueMem.ReadBytes()) kv[k] = v } func main() {} ``` -------------------------------- ### Remove Legacy Extism CLI Source: https://extism.org/docs/install Removes the older Python-based version of the CLI if previously installed. ```bash pip3 uninstall extism_cli --break-system-packages which extism # shouldn't print anything, if it does, delete it ``` -------------------------------- ### Get plugin output length Source: https://extism.org/docs/concepts/runtime-apis Returns the size of the data returned by the last plugin execution. ```c ExtismSize extism_plugin_output_length(ExtismPlugin *plugin); ``` -------------------------------- ### Memory Management Functions Source: https://extism.org/docs/concepts/runtime-apis Functions for allocating, getting the length of, and freeing memory within the currently running plugin. ```APIDOC ## `extism_current_plugin_memory_alloc` ### Description Allocate a memory block in the currently running plugin. ### Method N/A (C function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` ```APIDOC ## `extism_current_plugin_memory_length` ### Description Get the length of an allocated block. ### Method N/A (C function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` ```APIDOC ## `extism_current_plugin_memory_free` ### Description Free an allocated memory block. ### Method N/A (C function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Add Extism SDK Packages for C# Source: https://extism.org/docs/quickstart/host-quickstart Add the Extism.runtime.all and Extism.Sdk NuGet packages to your C# project. These packages provide the necessary Extism runtime and SDK. ```bash dotnet add package Extism.runtime.all dotnet add package Extism.Sdk ``` -------------------------------- ### Install Extism Dependency in Elixir Source: https://extism.org/docs/quickstart/host-quickstart Adds the Extism Elixir package to your project's dependencies. This requires a Rust toolchain for building. ```elixir def deps do [ {:extism, "1.0.0"} ] end ``` -------------------------------- ### Initialize C++ Plugin with Manifest Source: https://extism.org/docs/quickstart/host-quickstart Initializes an Extism plugin in C++ using a Wasm URL from a manifest. The constructor handles loading the plugin. ```cpp #include int main(void) { const auto manifest = extism::Manifest::wasmURL("https://github.com/extism/plugins/releases/" "latest/download/count_vowels.wasm"); extism::Plugin plugin(manifest, true); } ``` -------------------------------- ### Load Plugin in PHP Source: https://extism.org/docs/quickstart/host-quickstart Initialize a plugin using a URL-based WASM source in PHP. ```php 1. Rust 2. JavaScript 3. Go 4. Zig 5. C# 6. F# 7. C 8. Haskell 9. AssemblyScript ``` -------------------------------- ### Extism Manifest Schema Definition Source: https://extism.org/docs/concepts/manifest A comprehensive example of the manifest structure, including WASM loading methods, memory limits, allowed hosts, and configuration maps. ```python { # The "wasm" key describes the wasm code needed to build the plugin. # There are a few ways to load wasm code: "wasm": [ # you can point to a file: { # a file path for a plugin on disk "path": "./code/myplugin.wasm", # an optional name "name": "main", # the optional sha256 hash in hex form (it's optional, but recommended) "hash": "15c66d72f683e0225c774134b42ba6e04275a7a56b0a522af538d029650f15a8", }, # or, you can pass raw binary data for the code already in memory: { # the base64-encoded raw bytes of the wasm module "data": open("../wasm/code.wasm", 'rb').read(), # an optional name "name": "main", # the optional sha256 hash in hex form (it's optional, but recommended) "hash": "15c66d72f683e0225c774134b42ba6e04275a7a56b0a522af538d029650f15a8", }, # or, you can load a remote resource with a URL: { # a URL to some wasm code "url": "https://example.com/mycode.wasm", # optional headers you may need to get the data, e.g. auth headers "headers": { "X-API-KEY": "34b42ba6e04275", "User-Agent": "extism", }, # optional HTTP method to use, (default: GET) "method": "GET", # an optional name "name": "main", # the optional sha256 hash in hex form (it's optional, but recommended) "hash": "15c66d72f683e0225c774134b42ba6e04275a7a56b0a522af538d029650f15a8", }, ] # Describes the limits on the memory the plugin may be allocated. "memory": { # The max amount of pages the plugin can allocate # One page is 64Kib. e.g. 16 pages would require 1MiB. "max_pages": 4, # The max size of an Extism HTTP response in bytes "max_http_response_bytes": 4096, # The max size of all Extism vars in bytes "max_var_bytes": 4096 }, # An optional set of hosts this plugin can communicate with. # This only has an effect if the plugin makes HTTP requests. # Note: if left empty then no hosts are allowed and if `null` then all hosts are allowed. "allowed_hosts": [ "example.com", "extism.org", ], # An optional set of mappings between the host's filesystem and the paths a plugin can access. # This only has an effect if the plugin is provided with WASI capabilities. # Note: if left empty or `null`, then no file access is granted. "allowed_paths": { "/path/on/disk": "plugin/path", "another/path": "/", }, # The "config" key is a free-form map that can be passed to the plugin. # A plugin author must know the arbitrary data this map may contain, so your own documentation should include some information about the "config" passed in. "config": { "mykey": "myvalue" } } ``` -------------------------------- ### Call Extism Export Function in Elixir Source: https://extism.org/docs/quickstart/host-quickstart Calls the 'count_vowels' export function on an Extism plugin and prints the JSON output. This example assumes the plugin is already loaded. ```elixir {:ok, output} = Extism.Plugin.call(plugin, "count_vowels", "Hello, World!") # => {"count": 3, "total": 3, "vowels": "aeiouAEIOU"} ``` -------------------------------- ### Generate Go Plugin Source: https://extism.org/docs/quickstart/plugin-quickstart Scaffold a new Go plugin project. ```bash extism gen plugin -l Go -o plugin ``` -------------------------------- ### Call Extism Export Function in Java Source: https://extism.org/docs/quickstart/host-quickstart Calls the 'count_vowels' export function on an Extism plugin and prints the JSON output. This example assumes the plugin is already loaded. ```java public static void main(String[] args) { // ... var output = plugin.call("count_vowels", "Hello, World!"); System.out.println(output); } ``` -------------------------------- ### Provide mock input data via xtp CLI Source: https://extism.org/docs/concepts/testing Pass text directly using --mock-input-data or load it from a file using --mock-input-file when testing plugins with the xtp CLI. ```bash xtp plugin test plugin.wasm --with test.wasm --mock-input-data "this is my mock input data" ``` -------------------------------- ### Configure logging Source: https://extism.org/docs/concepts/runtime-apis Sets the global log file path and the minimum log level. ```c bool extism_log_file(const char *filename, const char *log_level); ``` -------------------------------- ### Load a plugin in C# Source: https://extism.org/docs/quickstart/host-quickstart Import the necessary Extism namespaces and load a plugin from a URL. The manifest is created using UrlWasmSource, and the plugin is instantiated with WASI enabled. ```csharp using System; using Extism.Sdk; var manifest = new Manifest(new UrlWasmSource("https://github.com/extism/plugins/releases/latest/download/count_vowels.wasm")); using var plugin = new Plugin(manifest, new HostFunction[] { }, withWasi: true); ``` -------------------------------- ### Load a plugin in Ruby Source: https://extism.org/docs/quickstart/host-quickstart Import the Extism library and load a plugin from a URL. The manifest is created from the URL of the WebAssembly plugin. ```ruby require 'extism' url = "https://github.com/extism/plugins/releases/latest/download/count_vowels.wasm" manifest = Extism::Manifest.from_url(url) plugin = Extism::Plugin.new(manifest) ``` -------------------------------- ### Build Rust Plugin for Release Source: https://extism.org/docs/quickstart/plugin-quickstart Compile with the release flag for optimized performance and smaller binary size. ```bash cargo build --target wasm32-unknown-unknown --release ``` -------------------------------- ### Generate a Zig Plugin with Extism CLI Source: https://extism.org/docs/quickstart/plugin-quickstart Use the Extism CLI to generate a new plugin project template for Zig. This command initializes the necessary project files. ```bash extism gen plugin -l Zig -o plugin ``` -------------------------------- ### Compile C Plug-in Source: https://extism.org/docs/quickstart/plugin-quickstart Compile the C source code into a WASM binary using clang. ```bash clang -o plugin.wasm --target=wasm32-unknown-unknown -nostdlib -Wl,--no-entry -mexec-model=reactor -Wl,--export=greet ./src/plugin.c ``` -------------------------------- ### JS PDK Help Source: https://extism.org/docs/quickstart/plugin-quickstart View usage information for the extism-js compiler. ```bash extism-js error: The following required arguments were not provided: USAGE: extism-js -i -o For more information try --help ``` -------------------------------- ### Load Plugin from URL in Haskell Source: https://extism.org/docs/quickstart/host-quickstart Initializes a new Extism plugin in Haskell using a Wasm URL from a manifest. Requires unwrapping the result. ```haskell module Main where import Extism main = do let wasm = wasmURL "GET" "https://github.com/extism/plugins/releases/latest/download/count_vowels.wasm" plugin <- unwrap <$> newPlugin (manifest [wasm]) [] True ``` -------------------------------- ### Load a plugin in Python Source: https://extism.org/docs/quickstart/host-quickstart Import the Extism library and load a plugin from a URL. The manifest is defined as a dictionary containing the plugin URL. ```python import extism url = "https://github.com/extism/plugins/releases/latest/download/count_vowels.wasm" manifest = {"wasm": [{"url": url}]} plugin = extism.Plugin(manifest) ``` -------------------------------- ### Compile Zig Plugin with Zig Build Source: https://extism.org/docs/quickstart/plugin-quickstart Compile the Zig plugin using the 'zig build' command. Ensure that 'src/root.zig' and related references are removed if using 'zig init'. ```bash zig build ``` -------------------------------- ### Load Plugin and Call Export Function (F#) Source: https://extism.org/docs/quickstart/host-quickstart Loads a WebAssembly plugin from a URL and calls the 'count_vowels' export function, passing a string and printing the JSON-encoded result. Requires the Extism.Sdk package. ```fsharp open System open Extism.Sdk open Extism.Sdk.Native let uri = Uri("https://github.com/extism/plugins/releases/latest/download/count_vowels.wasm") let manifest = Manifest(new UrlWasmSource(uri)) let plugin = new Plugin(manifest, Array.Empty(), withWasi = true) ``` ```fsharp let output = plugin.Call("count_vowels", "Hello, World!") System.Console.WriteLine(output) ``` ```bash dotnet run # => {"count":3,"total":3,"vowels":"aeiouAEIOU"} ``` -------------------------------- ### Configure mock input data in xtp.toml Source: https://extism.org/docs/concepts/testing Configure mock input data within the xtp.toml file using the 'mock_input' field. Data can be provided inline via 'data' or loaded from a file using 'file'. ```toml # path or url locating the wasm plugin to test bin = "https://raw.githubusercontent.com/extism/extism/main/wasm/code.wasm" [[test]] # label this test something recognizable to see in CLI output name = "basic" # build the test wasm module, is run before the test build = "cd examples/countvowels && tinygo build -o test.wasm -target wasi test.go" # the wasm module to use as the test with = "examples/countvowels/test.wasm" # provide mock input data to the plugin test call, returned to a 'MockInput' type of function call mock_input = { data = "this is my mock input data" } [[test]] name = "basic - file input" build = "cd examples/countvowels && tinygo build -o test.wasm -target wasi test.go" with = "examples/countvowels/test.wasm" # load mock input data from a file instead of inline mock_input = { file = "examples/countvowels/test.go" } ``` -------------------------------- ### Add Java Dependency Source: https://extism.org/docs/quickstart/host-quickstart Configuration for adding the Extism Java SDK to build files. ```xml org.extism.sdk extism 1.0.0 ``` ```gradle implementation 'org.extism.sdk:extism:1.0.0' ``` -------------------------------- ### Zig Extism Plugin Implementation Source: https://extism.org/docs/quickstart/plugin-quickstart A Zig plugin that exports a 'greet' function. It retrieves input from the Extism host, formats a greeting, and returns it. ```zig const std = @import("std"); const extism_pdk = @import("extism-pdk"); const Plugin = extism_pdk.Plugin; const allocator = std.heap.wasm_allocator; export fn greet() i32 { const plugin = Plugin.init(allocator); const name = plugin.getInput() catch unreachable; defer allocator.free(name); const output = std.fmt.allocPrint(allocator, "Hello, {s}!", .{name}) catch unreachable; plugin.output(output); return 0; } ``` -------------------------------- ### Load Extism Plugin in Go Source: https://extism.org/docs/quickstart/host-quickstart Load a WASM plug-in in Go using `extism.NewPlugin`. This requires defining a manifest with the plug-in's URL. ```go package main import ( "context" "fmt" "github.com/extism/go-sdk" "os" ) func main() { manifest := extism.Manifest{ Wasm: []extism.Wasm{ extism.WasmUrl{ Url: "https://github.com/extism/plugins/releases/latest/download/count_vowels.wasm", }, }, } ctx := context.Background() config := extism.PluginConfig{} plugin, err := extism.NewPlugin(ctx, manifest, config, []extism.HostFunction{}) if err != nil { fmt.Printf("Failed to initialize plugin: %v\n", err) os.Exit(1) } } ``` -------------------------------- ### Configure OCaml Dependencies Source: https://extism.org/docs/quickstart/host-quickstart Dune configuration files for OCaml projects using Extism. ```lisp (libraries extism) ``` ```lisp (package (depends (extism))) ``` -------------------------------- ### Load Extism Plugin in Java Source: https://extism.org/docs/quickstart/host-quickstart Loads a WebAssembly plugin from a URL using the Extism Java SDK. Ensure the necessary dependencies are included in your project. ```java import org.extism.sdk.manifest.Manifest; import org.extism.sdk.wasm.UrlWasmSource; import org.extism.sdk.Plugin; public static void main(String[] args) { var url = "https://github.com/extism/plugins/releases/latest/download/count_vowels.wasm"; var manifest = new Manifest(List.of(UrlWasmSource.fromUrl(url))); var plugin = new Plugin(manifest, false, null); } ``` -------------------------------- ### Create Extism Plugin Interacting with Host Functions Source: https://extism.org/docs/concepts/testing This Go code defines an Extism plugin that imports and uses `kv_read` and `kv_write` host functions. It writes a value to the simulated KV store and then reads it back, updating its state. The plugin's final state is set as its output. ```go package main import ( // this is a normal Extism plugin, so we import the PDK pdk "github.com/extism/go-pdk" ) // the `kv_read` and `kv_write` functions below are imported from the host, // (which we exported in the previous tab) //go:wasmimport extism:host/user kv_read func kv_read(key uint64) uint64 //go:wasmimport extism:host/user kv_write func kv_write(key uint64, value uint64) //go:export run func run() int32 { // allocate a key and value to write to the KV store key := pdk.AllocateString("key") value := pdk.AllocateString("value") kv_write(key.Offset(), value.Offset()) // immediately read the key back from the KV store, just to verify that it was written readVal := kv_read(key.Offset()) if readVal != 0 { // if we found a value, read it from memory and append it to the plugin's state // (we'll test the state output in the `kvtest` project) readValMem := pdk.FindMemory(readVal) varVal := pdk.GetVar("key") // grow the var state in the plugin by appending the read value pdk.SetVar("key", append(varVal, readValMem.ReadBytes()...)) } else { pdk.SetVar("key", []byte("")) } // return the plugin's state as the output so we can test it in the `kvtest` project pdk.Output(pdk.GetVar("key")) return 0 } func main() {} ``` -------------------------------- ### Manifest Structure and Usage Source: https://extism.org/docs/concepts/manifest This snippet demonstrates how to create a manifest object in Python, including loading WASM code and setting memory limits. ```APIDOC ## Creating a Manifest ### Description This example shows how to construct a manifest object in Python, specifying WASM code and memory constraints for an Extism plugin. ### Method N/A (Code Example) ### Endpoint N/A ### Parameters N/A ### Request Example ```python import hashlib wasm = open("../wasm/code.wasm", 'rb').read() wasm_hash = hashlib.sha256(wasm).hexdigest() manifest = { "wasm": [ { "data": wasm, "hash": wasm_hash } ], "memory": { "max_pages": 5 } } # Assuming 'context' is an initialized Extism context object # plugin = context.plugin(manifest) ``` ### Response N/A ``` -------------------------------- ### Generate Rust Plugin Source: https://extism.org/docs/quickstart/plugin-quickstart Use the Extism CLI to scaffold a new Rust plugin project. ```bash extism gen plugin -l Rust -o plugin ``` -------------------------------- ### Load Plugin and Call Export Function (C#) Source: https://extism.org/docs/quickstart/host-quickstart Loads a WebAssembly plugin and calls the 'count_vowels' export function, passing a string and printing the JSON-encoded result. Requires the Extism.Sdk package. ```csharp var output = plugin.Call("count_vowels", "Hello, World!"); Console.WriteLine(output); ``` ```bash dotnet run # => {"count":3,"total":3,"vowels":"aeiouAEIOU"} ``` -------------------------------- ### Run Rust Plugin Source: https://extism.org/docs/quickstart/plugin-quickstart Execute the compiled Wasm module using the Extism CLI. ```bash extism call target/wasm32-unknown-unknown/debug/rust_pdk_template.wasm greet --input "Benjamin" # => Hello, Benjamin! ``` -------------------------------- ### Configure PHP Minimum Stability Source: https://extism.org/docs/quickstart/host-quickstart Required composer.json configuration for development stability. ```json { "minimum-stability": "dev", } ``` -------------------------------- ### Manifest Schema Details Source: https://extism.org/docs/concepts/manifest Detailed explanation of the Extism manifest schema, covering WASM loading options, memory configuration, allowed hosts, paths, and custom configuration. ```APIDOC ## Extism Manifest Schema ### Description This section details the structure and available fields within the Extism manifest JSON schema, used to define plugin properties and runtime constraints. ### Method N/A (Schema Definition) ### Endpoint N/A ### Parameters N/A ### Request Body #### `wasm` (array) - Required Describes the WebAssembly code needed to build the plugin. Can include: - `path` (string): File path for a plugin on disk. - `name` (string, optional): An optional name for the WASM module. - `hash` (string, optional): The SHA256 hash in hex form (recommended). - `data` (binary): Raw binary data of the WASM module (base64 encoded). - `url` (string): URL to load WASM code from. - `headers` (object, optional): HTTP headers for fetching WASM from a URL. - `method` (string, optional): HTTP method to use (default: GET). #### `memory` (object) - Optional Describes limits on memory the plugin may allocate. - `max_pages` (integer): Maximum number of pages the plugin can allocate (1 page = 64 KiB). - `max_http_response_bytes` (integer, optional): Maximum size of an Extism HTTP response in bytes. - `max_var_bytes` (integer, optional): Maximum size of all Extism variables in bytes. #### `allowed_hosts` (array of strings) - Optional An optional set of hosts the plugin can communicate with via HTTP requests. If empty, no hosts are allowed. If null, all hosts are allowed. #### `allowed_paths` (object) - Optional An optional set of mappings between the host's filesystem and paths accessible by the plugin (requires WASI capabilities). If empty or null, no file access is granted. - Key (string): Path on the host filesystem. - Value (string): Corresponding path within the plugin's accessible filesystem. #### `config` (object) - Optional A free-form map of arbitrary data that can be passed to the plugin. Plugin authors must document the expected configuration. ### Request Example ```json { "wasm": [ { "path": "./code/myplugin.wasm", "name": "main", "hash": "15c66d72f683e0225c774134b42ba6e04275a7a56b0a522af538d029650f15a8" }, { "url": "https://example.com/mycode.wasm", "headers": { "X-API-KEY": "34b42ba6e04275" }, "method": "GET", "name": "sidecar" } ], "memory": { "max_pages": 4, "max_http_response_bytes": 4096 }, "allowed_hosts": ["example.com"], "allowed_paths": { "/data": "/app/data" }, "config": { "api_endpoint": "https://api.example.com" } } ``` ### Response N/A ``` -------------------------------- ### Free host function Source: https://extism.org/docs/concepts/runtime-apis Releases resources associated with an ExtismFunction. ```c void extism_function_free(ExtismFunction *ptr); ``` -------------------------------- ### Compile Rust Plugin Source: https://extism.org/docs/quickstart/plugin-quickstart Build the plugin for the wasm32-unknown-unknown target. ```bash cargo build --target wasm32-unknown-unknown ``` -------------------------------- ### Run a Zig Plugin with Extism CLI Source: https://extism.org/docs/quickstart/plugin-quickstart Execute a compiled Zig plugin using the Extism CLI. The path to the compiled Wasm module is specified. ```bash extism call ./zig-out/bin/zig-pdk-template.wasm greet --input "Benjamin" ``` -------------------------------- ### Run a C Plugin with Extism CLI Source: https://extism.org/docs/quickstart/plugin-quickstart Execute a compiled C plugin using the Extism CLI's 'call' command. Ensure the plugin.wasm file is available. ```bash extism call plugin.wasm greet --input "Benjamin" ``` -------------------------------- ### AssemblyScript Extism Plugin Implementation Source: https://extism.org/docs/quickstart/plugin-quickstart An AssemblyScript plugin that exports a 'greet' function. It takes string input from the host and outputs a greeting string. ```typescript import { Config, Host, Var } from "@extism/as-pdk"; function myAbort( message: string | null, fileName: string | null, lineNumber: u32, columnNumber: u32, ): void {} export function greet(): i32 { const name = Host.inputString(); Host.outputString("Hello, " + name); return 0; } ``` -------------------------------- ### Load Plugin from Manifest in Zig Source: https://extism.org/docs/quickstart/host-quickstart Loads a plugin using a manifest that specifies a Wasm URL. Ensure the GeneralPurposeAllocator is deinitialized. ```zig // First require the library const extism = @import("extism"); const std = @import("std"); const wasm_url = extism.manifest.WasmUrl{ .url = "https://github.com/extism/plugins/releases/latest/download/count_vowels.wasm" }; const manifest = .{ .wasm = &[_]extism.manifest.Wasm{.{ .wasm_url= wasm_url }} }; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer std.debug.assert(gpa.deinit() == .ok); const allocator = gpa.allocator(); var plugin = try extism.Plugin.initFromManifest( allocator, manifest, &[_]extism.Function{}, false, ); defer plugin.deinit(); ``` -------------------------------- ### Build Extism Project with CMake Source: https://extism.org/docs/quickstart/host-quickstart Build the Extism C++ project using CMake. This command generates build files and compiles the project. ```bash cmake -B build && cmake --build build ``` -------------------------------- ### Generate a Haskell Plugin with Extism CLI Source: https://extism.org/docs/quickstart/plugin-quickstart Use the Extism CLI to generate a new plugin project template for Haskell. This command sets up the basic project structure. ```bash extism gen plugin -l Haskell -o plugin ``` -------------------------------- ### Build JS Plugin Source: https://extism.org/docs/quickstart/plugin-quickstart Compile the JavaScript plugin to Wasm. ```bash npm run build ```