### Instance Configuration Example Source: https://github.com/telecter/cmd-launcher/blob/main/README.md An example `instance.toml` file showing configurable options for a Minecraft instance, including game version, mod loader, Java path, memory allocation, and window resolution. ```toml game_version = '1.21.8' mod_loader = 'fabric' mod_loader_version = '0.16.14' [config] # Path to a Java executable. If blank, a Mojang-provided JVM will be downloaded. java = '/usr/bin/java' # Extra arguments to pass to the JVM java_args = '' # Path to a custom JAR to use instead of the normal Minecraft client custom_jar = '' # Minimum game memory, in MB min_memory = 512 # Maximum game memory, in MB max_memory = 4096 # Game window resolution [config.resolution] width = 1708 height = 960 ``` -------------------------------- ### launcher.FetchInstance / launcher.FetchAllInstances Source: https://context7.com/telecter/cmd-launcher/llms.txt Retrieves instance information. `FetchInstance` gets details for a specific instance, while `FetchAllInstances` lists all available instances. ```APIDOC ## launcher.FetchInstance / launcher.FetchAllInstances ### Description Retrieves instance information. `FetchInstance` reads and parses the `instance.toml` for a specific instance (migrating legacy JSON configs automatically). `FetchAllInstances` enumerates every valid instance under `env.InstancesDir`. ### Method `launcher.FetchInstance(name string) (*Instance, error)` `launcher.FetchAllInstances() ([]Instance, error)` ### Parameters #### Path Parameters (for FetchInstance) - **name** (string) - Required - The name of the instance to fetch. ### Request Example ```go import ( "fmt" "log" "github.com/telecter/cmd-launcher/pkg/launcher" ) // Fetch a single instance inst, err := launcher.FetchInstance("FabricInstance") if err != nil { log.Fatal(err) } fmt.Println(inst.GameVersion, inst.Loader) // List all instances all, err := launcher.FetchAllInstances() if err != nil { log.Fatal(err) } for _, i := range all { fmt.Printf("- %s (%s)\n", i.Name, i.GameVersion) } ``` ### Response #### Success Response (200) - **Instance** (*Instance) - For `FetchInstance`, the details of the requested instance. - **Name** (string) - **GameVersion** (string) - **Loader** (string) - **LoaderVersion** (string) - **Config** (InstanceConfig) - **[]Instance** - For `FetchAllInstances`, a slice containing all found instances. #### Response Example (for FetchInstance) ```json { "Name": "FabricInstance", "GameVersion": "1.21.8", "Loader": "fabric", "LoaderVersion": "0.16.14", "Config": { "WindowResolution": { "Width": 1920, "Height": 1080 }, "MinMemory": 512, "MaxMemory": 4096 } } ``` #### Error Response - `error`: An error object if fetching instances fails. ``` -------------------------------- ### Prepare Launch Environment Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Prepare the launch environment using `launcher.Prepare` with the instance, launch options, and an event watcher. Launch options allow customization of start behavior and overriding instance configuration. ```go env, err := launcher.Prepare(inst, launcher.LaunchOptions{ Session: auth.Session{ Username: "Dinnerbone", }, InstanceConfig: inst.Config, }, myWatcher) ``` -------------------------------- ### Install from Main Branch via go install Source: https://context7.com/telecter/cmd-launcher/llms.txt Installs the latest commit from the main branch of cmd-launcher using `go install`. This is useful for testing development versions. ```bash go install github.com/telecter/cmd-launcher@main ``` -------------------------------- ### Instance Configuration TOML Example Source: https://context7.com/telecter/cmd-launcher/llms.txt Example configuration for a Minecraft instance stored in `instance.toml`. This file defines game version, mod loader, and loader version. ```toml game_version = '1.21.8' mod_loader = 'fabric' mod_loader_version = '0.16.14' [config] ``` -------------------------------- ### Install Latest cmd-launcher Source: https://github.com/telecter/cmd-launcher/blob/main/README.md Use this command to install the latest version of cmd-launcher. Replace 'latest' with 'main' for the most recent commit. ```bash go install github.com/telecter/cmd-launcher@latest ``` -------------------------------- ### Start Minecraft Instance and Connect to Server Source: https://context7.com/telecter/cmd-launcher/llms.txt Launches the 'FabricInstance' Minecraft instance and automatically connects to the specified server 'play.hypixel.net:25565'. Use the `-s` flag for server address. ```bash cmd-launcher start FabricInstance -s play.hypixel.net:25565 ``` -------------------------------- ### launcher.Launch / launcher.ConsoleRunner Source: https://context7.com/telecter/cmd-launcher/llms.txt Starts the game process using a provided LaunchEnvironment and a Runner function. ```APIDOC ## launcher.Launch / launcher.ConsoleRunner – Start the Game Takes the `LaunchEnvironment` from `Prepare` and runs the Java process via a user-supplied `Runner` function. ### Parameters * **env** (*launcher.LaunchEnvironment) - The prepared launch environment. * **runner** (func(*exec.Cmd) error) - A function that executes the command. `launcher.ConsoleRunner` is a built-in option that pipes stdio to the terminal. ### Returns * **error** - An error if the game process fails to start or run. ### Example ```go import ( "log" "os" "os/exec" "github.com/telecter/cmd-launcher/pkg/launcher" ) // Use the built-in ConsoleRunner (pipes stdin/stdout/stderr to the terminal) if err := launcher.Launch(env, launcher.ConsoleRunner); err != nil { log.Fatal(err) } // Custom runner: capture game logs to a file logFile, _ := os.Create("game.log") defer logFile.Close() customRunner := func(cmd *exec.Cmd) error { cmd.Stdout = logFile cmd.Stderr = logFile cmd.Stdin = os.Stdin return cmd.Run() } if err := launcher.Launch(env, customRunner); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Start Minecraft Instance Source: https://github.com/telecter/cmd-launcher/blob/main/README.md Starts a Minecraft instance by its name. Game options can be overridden using command-line flags. Verbosity can be adjusted with the --verbosity flag (info, extra, debug). ```bash cmd-launcher start CoolInstance ``` -------------------------------- ### Start Minecraft Instance with Increased Verbosity Source: https://context7.com/telecter/cmd-launcher/llms.txt Launches 'FabricInstance' with increased logging verbosity. Use `--verbosity` with values like `extra` or `debug` for more detailed output. ```bash cmd-launcher start FabricInstance --verbosity extra ``` -------------------------------- ### Start Minecraft Instance in Online Mode Source: https://context7.com/telecter/cmd-launcher/llms.txt Prepares and launches the 'FabricInstance' Minecraft instance. If a Microsoft account is stored, it automatically uses online mode. ```bash cmd-launcher start FabricInstance ``` -------------------------------- ### Start Minecraft Instance with Custom JVM and Memory Source: https://context7.com/telecter/cmd-launcher/llms.txt Launches 'FabricInstance', overriding the default JVM path and memory settings. Use `--jvm` for the Java executable path, `--min-memory` and `--max-memory` for RAM allocation. ```bash cmd-launcher start FabricInstance --jvm /usr/lib/jvm/java-21/bin/java \ --min-memory 1024 --max-memory 8192 ``` -------------------------------- ### Implement a Custom Game Runner Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Define a runner function that accepts an `*exec.Cmd` to control how the game is executed and monitored. This example copies I/O streams to the console. ```go func myRunner(cmd *exec.Cmd) error { cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } ``` -------------------------------- ### Launch the Game with a Runner Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Start the game using the prepared launch environment and a defined runner function. `launcher.ConsoleRunner` is a pre-built implementation for common console I/O redirection. ```go err := launcher.Launch(env, myRunner) ``` -------------------------------- ### Start Minecraft in Offline Mode Source: https://github.com/telecter/cmd-launcher/blob/main/README.md Starts Minecraft in offline mode by providing a username via the -u or --username flag. ```bash cmd-launcher start -u ``` -------------------------------- ### Start Minecraft Instance and Open World Source: https://context7.com/telecter/cmd-launcher/llms.txt Launches the 'FabricInstance' Minecraft instance and opens the singleplayer world named 'My World'. Use the `-w` flag to specify the world name. ```bash cmd-launcher start FabricInstance -w "My World" ``` -------------------------------- ### Start Minecraft Instance in Offline Mode Source: https://context7.com/telecter/cmd-launcher/llms.txt Launches the 'FabricInstance' Minecraft instance in offline mode using the provided username 'Steve'. The `-u` flag forces offline mode. ```bash cmd-launcher start FabricInstance -u Steve ``` -------------------------------- ### Authenticate with Device Code Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Poll the authentication endpoint using the device code response obtained from FetchDeviceCode to get the user's session. ```go session, err := auth.AuthenticateWithCode(resp) ``` -------------------------------- ### Get OAuth2 Auth URL Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Generate the authentication URL for the user to visit. This is the first step in the OAuth2 auth code flow. ```go url := auth.AuthCodeURL() ``` -------------------------------- ### Get Authentication Data Source: https://github.com/telecter/cmd-launcher/wiki/Home Obtain authentication tokens, username, and UUID for online mode using getAuthData from auth.ts. This function initiates the Microsoft OAuth2 flow in the default web browser. ```javascript const [accessToken, username, uuid] = await getAuthData(); ``` -------------------------------- ### Prepare Launch Environment with Event Watcher Source: https://context7.com/telecter/cmd-launcher/llms.txt Downloads necessary files and sets up the launch environment. Use the EventWatcher to receive progress updates during preparation. ```go import ( "fmt" "log" "github.com/telecter/cmd-launcher/pkg/auth" "github.com/telecter/cmd-launcher/pkg/launcher" ) inst, _ := launcher.FetchInstance("FabricInstance") // EventWatcher receives typed events during preparation myWatcher := func(event any) { switch e := event.(type) { case launcher.MetadataResolvedEvent: fmt.Println("Metadata fetched") case launcher.LibrariesResolvedEvent: fmt.Printf("Libraries: %d total\n", e.Total) case launcher.AssetsResolvedEvent: fmt.Printf("Assets: %d total\n", e.Total) case launcher.DownloadingEvent: fmt.Printf("Downloading: %d/%d\n", e.Completed, e.Total) case launcher.PostProcessingEvent: fmt.Println("Running Forge post-processors...") } } env, err := launcher.Prepare(&inst, launcher.LaunchOptions{ Session: auth.Session{ Username: "Dinnerbone", UUID: "61699b2e-d327-4a01-9f1e-0ea8c3f06bc6", AccessToken: "", }, InstanceConfig: inst.Config, QuickPlayServer: "play.hypixel.net:25565", // optional Demo: false, DisableChat: false, }, myWatcher) if err != nil { log.Fatalf("prepare: %v", err) } fmt.Println("Java:", env.Java) fmt.Println("Main class:", env.MainClass) ``` -------------------------------- ### launcher.Prepare Source: https://context7.com/telecter/cmd-launcher/llms.txt Downloads necessary files and builds the launch environment, providing progress updates via an EventWatcher. ```APIDOC ## launcher.Prepare – Download Files and Build Launch Environment Downloads all missing libraries, assets, and the Java runtime (if needed), then constructs the full `LaunchEnvironment`. An `EventWatcher` callback receives progress events. ### Parameters * **instance** (*launcher.Instance) - The instance to prepare. * **options** (*launcher.LaunchOptions) - Options for the launch, including session details and configuration. * **watcher** (func(event any)) - A callback function to receive progress events during preparation. ### Returns * **env** (*launcher.LaunchEnvironment) - The prepared launch environment. * **err** (error) - An error if preparation fails. ### Example ```go import ( "fmt" "log" "github.com/telecter/cmd-launcher/pkg/auth" "github.com/telecter/cmd-launcher/pkg/launcher" ) inst, _ := launcher.FetchInstance("FabricInstance") // EventWatcher receives typed events during preparation myWatcher := func(event any) { switch e := event.(type) { case launcher.MetadataResolvedEvent: fmt.Println("Metadata fetched") case launcher.LibrariesResolvedEvent: fmt.Printf("Libraries: %d total\n", e.Total) case launcher.AssetsResolvedEvent: fmt.Printf("Assets: %d total\n", e.Total) case launcher.DownloadingEvent: fmt.Printf("Downloading: %d/%d\n", e.Completed, e.Total) case launcher.PostProcessingEvent: fmt.Println("Running Forge post-processors...") } } env, err := launcher.Prepare(&inst, launcher.LaunchOptions{ Session: auth.Session{ Username: "Dinnerbone", UUID: "61699b2e-d327-4a01-9f1e-0ea8c3f06bc6", AccessToken: "", }, InstanceConfig: inst.Config, QuickPlayServer: "play.hypixel.net:25565", // optional Demo: false, DisableChat: false, }, myWatcher) if err != nil { log.Fatalf("prepare: %v", err) } fmt.Println("Java:", env.Java) fmt.Println("Main class:", env.MainClass) ``` ``` -------------------------------- ### Build and Run from Source Source: https://context7.com/telecter/cmd-launcher/llms.txt Clones the repository, navigates into the directory, and then builds or runs the cmd-launcher binary using Go commands. ```bash git clone https://github.com/telecter/cmd-launcher cd cmd-launcher go build . # produces ./cmd-launcher binary go run . # compile-and-run in place ``` -------------------------------- ### Create a New Instance with `launcher.CreateInstance` Source: https://context7.com/telecter/cmd-launcher/llms.txt Resolves game and loader versions, creates the instance directory, and writes the initial `instance.toml`. Supports specifying game version, loader type and version, resolution, and memory limits. ```go import ( "fmt" "log" "github.com/telecter/cmd-launcher/internal/meta" "github.com/telecter/cmd-launcher/pkg/launcher" ) inst, err := launcher.CreateInstance(launcher.InstanceOptions{ Name: "FabricInstance", GameVersion: "1.21.8", // or "release", "snapshot" Loader: meta.LoaderFabric, LoaderVersion: "latest", // or e.g. "0.16.14" Config: launcher.InstanceConfig{ WindowResolution: struct { Width int `toml:"width" json:"width"` Height int `toml:"height" json:"height"` }{Width: 1920, Height: 1080}, MinMemory: 512, MaxMemory: 4096, }, }) if err != nil { log.Fatalf("create instance: %v", err) } fmt.Printf("Created %s (MC %s, Fabric %s)\n", inst.Name, inst.GameVersion, inst.LoaderVersion) // → Created FabricInstance (MC 1.21.8, Fabric 0.16.14) ``` -------------------------------- ### Create a New Game Instance Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Use `CreateInstance` to set up a new game instance with specified version, name, loader, and configuration. The loader can be Quilt, Fabric, or Vanilla. ```go inst, err := launcher.CreateInstance(launcher.InstanceOptions{ GameVersion: "1.21.5", Name: "MyInstance", Loader: launcher.LoaderQuilt, LoaderVersion: "latest", Config: launcher.InstanceConfig{} }) ``` -------------------------------- ### Retrieve Instances with `launcher.FetchInstance` and `launcher.FetchAllInstances` Source: https://context7.com/telecter/cmd-launcher/llms.txt Fetches a single instance by name, automatically migrating legacy configs. `FetchAllInstances` lists all valid instances under `env.InstancesDir`. ```go import ( "fmt" "log" "github.com/telecter/cmd-launcher/pkg/launcher" ) // Fetch a single instance inst, err := launcher.FetchInstance("FabricInstance") if err != nil { log.Fatal(err) } fmt.Println(inst.GameVersion, inst.Loader) // List all instances all, err := launcher.FetchAllInstances() if err != nil { log.Fatal(err) } for _, i := range all { fmt.Printf("- %s (%s)\n", i.Name, i.GameVersion) } ``` -------------------------------- ### Prepare Launch Environment Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Prepares the launch environment for a game instance, including session details and instance configuration. ```APIDOC ## Prepare Launch Environment ### Description Prepares the launch environment for a game instance. ### Method `launcher.Prepare` ### Parameters #### Instance - **inst** (Instance) - Required - The game instance to prepare. #### LaunchOptions - **Session** (auth.Session) - Required - Session information, including username. - **InstanceConfig** (InstanceConfig) - Optional - Overrides the instance's configuration. - **Watcher** (EventWatcher) - Required - A function to handle events during preparation. ### Request Example ```go env, err := launcher.Prepare(inst, launcher.LaunchOptions{ Session: auth.Session{ Username: "Dinnerbone", }, InstanceConfig: inst.Config, }, myWatcher) ``` ### EventWatcher Function Example ```go func myWatcher(event any) { sswitch e := event.(type) { case launcher.DownloadingEvent: // Handle download progress case launcher.LibrariesResolvedEvent: // Handle libraries resolved case launcher.AssetsResolvedEvent: // Handle assets resolved } } ``` ``` -------------------------------- ### launcher.CreateInstance Source: https://context7.com/telecter/cmd-launcher/llms.txt Creates a new Minecraft instance by resolving game and loader versions, setting up the instance directory, and writing the initial configuration file. ```APIDOC ## launcher.CreateInstance ### Description Resolves the exact game and loader versions via Mojang/meta APIs, creates the instance directory, and writes the initial `instance.toml`. ### Method `launcher.CreateInstance(options InstanceOptions) (*Instance, error)` ### Parameters #### Request Body - **options** (InstanceOptions) - Required - Configuration options for the new instance. - **Name** (string) - Required - The name of the instance. - **GameVersion** (string) - Required - The desired Minecraft game version (e.g., "1.21.8", "release", "snapshot"). - **Loader** (string) - Required - The mod loader to use (e.g., `meta.LoaderFabric`). - **LoaderVersion** (string) - Required - The desired loader version (e.g., "latest", "0.16.14"). - **Config** (InstanceConfig) - Optional - Instance-specific configuration. - **WindowResolution** (struct { Width int; Height int }) - Optional - The resolution of the game window. - **Width** (int) - Optional - The width of the window. - **Height** (int) - Optional - The height of the window. - **MinMemory** (int) - Optional - Minimum memory allocation in MB. - **MaxMemory** (int) - Optional - Maximum memory allocation in MB. ### Request Example ```go import ( "fmt" "log" "github.com/telecter/cmd-launcher/internal/meta" "github.com/telecter/cmd-launcher/pkg/launcher" ) inst, err := launcher.CreateInstance(launcher.InstanceOptions{ Name: "FabricInstance", GameVersion: "1.21.8", // or "release", "snapshot" Loader: meta.LoaderFabric, LoaderVersion: "latest", // or e.g. "0.16.14" Config: launcher.InstanceConfig{ WindowResolution: struct { Width int `toml:"width" json:"width"` Height int `toml:"height" json:"height"` }{Width: 1920, Height: 1080}, MinMemory: 512, MaxMemory: 4096, }, }) if err != nil { log.Fatalf("create instance: %v", err) } fmt.Printf("Created %s (MC %s, Fabric %s)\n", inst.Name, inst.GameVersion, inst.LoaderVersion) // → Created FabricInstance (MC 1.21.8, Fabric 0.16.14) ``` ### Response #### Success Response (200) - **Instance** (*Instance) - The created instance object. - **Name** (string) - **GameVersion** (string) - **Loader** (string) - **LoaderVersion** (string) - **Config** (InstanceConfig) #### Response Example ```json { "Name": "FabricInstance", "GameVersion": "1.21.8", "Loader": "fabric", "LoaderVersion": "0.16.14", "Config": { "WindowResolution": { "Width": 1920, "Height": 1080 }, "MinMemory": 512, "MaxMemory": 4096 } } ``` #### Error Response - `error`: An error object if instance creation fails. ``` -------------------------------- ### Prepare Minecraft Instance Without Launching Source: https://context7.com/telecter/cmd-launcher/llms.txt Downloads and prepares all necessary files for 'FabricInstance' without actually launching the game. Use the `--prepare` flag for this action. ```bash cmd-launcher start FabricInstance --prepare ``` -------------------------------- ### Manage Instances with `Instance.Rename`, `Instance.WriteConfig`, and `launcher.RemoveInstance` Source: https://context7.com/telecter/cmd-launcher/llms.txt Provides methods to rename an instance, update its configuration and persist changes, and remove an instance entirely. ```go import ( "log" "github.com/telecter/cmd-launcher/pkg/launcher" ) inst, err := launcher.FetchInstance("FabricInstance") if err != nil { log.Fatal(err) } // Rename if err := inst.Rename("Fabric121"); err != nil { log.Fatal(err) } // Update config and persist inst.Config.MaxMemory = 8192 if err := inst.WriteConfig(); err != nil { log.Fatal(err) } // Delete if err := launcher.RemoveInstance("Fabric121"); err != nil { log.Fatal(err) } ``` -------------------------------- ### Launch Game Instance with Java Arguments Source: https://github.com/telecter/cmd-launcher/wiki/Home Use this command to spawn the Java executable with the necessary arguments for launching the game. Ensure `javaArgs` and `gameArgs` are populated correctly, and use `versionData.mainClass` or `fabricData.mainClass` as appropriate. ```javascript new Deno.Command("path/to/java/executable", { args: [...javaArgs, versionData.mainClass, ...gameArgs] }).spawn(); ``` -------------------------------- ### Create Instance Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Creates a new game instance with specified options. Options include game version, instance name, mod loader type and version, and configuration. ```APIDOC ## Create Instance ### Description Creates a new game instance with specified options. ### Method `launcher.CreateInstance` ### Parameters #### InstanceOptions - **GameVersion** (string) - Required - The version of the game to use. - **Name** (string) - Required - The name of the instance. - **Loader** (string) - Required - The mod loader to use. Can be `LoaderQuilt`, `LoaderFabric`, or `LoaderVanilla`. - **LoaderVersion** (string) - Optional - The version of the mod loader. Can be `latest` or a specific version. - **Config** (InstanceConfig) - Optional - Configuration for the instance. ### Request Example ```go inst, err := launcher.CreateInstance(launcher.InstanceOptions{ GameVersion: "1.21.5", Name: "MyInstance", Loader: launcher.LoaderQuilt, LoaderVersion: "latest", Config: launcher.InstanceConfig{} }) ``` ``` -------------------------------- ### Initialize Launcher Directories with `env.SetDirs` Source: https://context7.com/telecter/cmd-launcher/llms.txt Sets all launcher data directories relative to a custom root. Must be called before any other API call if a non-default location is needed. By default, the root is `~/.minecraft`. ```go package main import ( "log" env "github.com/telecter/cmd-launcher/pkg" ) func main() { // Use a custom root directory if err := env.SetDirs("/opt/my-launcher"); err != nil { log.Fatal(err) } // env.InstancesDir → /opt/my-launcher/instances // env.LibrariesDir → /opt/my-launcher/libraries // env.AssetsDir → /opt/my-launcher/assets // env.JavaDir → /opt/my-launcher/java // env.AuthStorePath → /opt/my-launcher/account.json } ``` -------------------------------- ### Download Game Libraries Source: https://github.com/telecter/cmd-launcher/wiki/Home Iterate through versionData.libraries and use fetchLibrary to download each library to the specified root directory. Store the returned paths in a list. Libraries are only downloaded if they do not already exist. ```javascript import { downloadLibrary } from "./api.ts"; const paths = []; for (const library of versionData.libraries) { const path = await downloadLibrary(library, rootDirectory); paths.push(path); } ``` -------------------------------- ### Instance Management (Rename, WriteConfig, RemoveInstance) Source: https://context7.com/telecter/cmd-launcher/llms.txt Provides methods for managing existing instances, including renaming, updating configuration, and deleting instances. ```APIDOC ## Instance Management (Rename, WriteConfig, RemoveInstance) ### Description Manages existing instances. The `Instance` object provides methods to rename and update its configuration, which is then persisted. `launcher.RemoveInstance` deletes an instance. ### Method - `inst.Rename(newName string) error` - `inst.WriteConfig() error` - `launcher.RemoveInstance(name string) error` ### Parameters #### Path Parameters (for RemoveInstance) - **name** (string) - Required - The name of the instance to remove. #### Parameters (for Rename) - **newName** (string) - Required - The new name for the instance. ### Request Example ```go import ( "log" "github.com/telecter/cmd-launcher/pkg/launcher" ) inst, err := launcher.FetchInstance("FabricInstance") if err != nil { log.Fatal(err) } // Rename if err := inst.Rename("Fabric121"); err != nil { log.Fatal(err) } // Update config and persist inst.Config.MaxMemory = 8192 if err := inst.WriteConfig(); err != nil { log.Fatal(err) } // Delete if err := launcher.RemoveInstance("Fabric121"); err != nil { log.Fatal(err) } ``` ### Response #### Success Response No explicit return value on success; errors are returned if the operation fails. #### Error Response - `error`: An error object if renaming, writing config, or removing the instance fails. ``` -------------------------------- ### Fetch Instance Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Retrieves an existing game instance by its name. ```APIDOC ## Fetch Instance ### Description Retrieves an existing game instance by its name. ### Method `launcher.FetchInstance` ### Parameters #### Instance Name - **name** (string) - Required - The name of the instance to fetch. ### Request Example ```go inst, err := launcher.FetchInstance("MyInstance") ``` ``` -------------------------------- ### Launch Game with ConsoleRunner or Custom Runner Source: https://context7.com/telecter/cmd-launcher/llms.txt Launches the game process using the prepared LaunchEnvironment. ConsoleRunner pipes I/O to the terminal, while a custom runner allows redirecting output. ```go import ( "log" "os" "os/exec" "github.com/telecter/cmd-launcher/pkg/launcher" ) // Use the built-in ConsoleRunner (pipes stdin/stdout/stderr to the terminal) if err := launcher.Launch(env, launcher.ConsoleRunner); err != nil { log.Fatal(err) } // Custom runner: capture game logs to a file logFile, _ := os.Create("game.log") defer logFile.Close() customRunner := func(cmd *exec.Cmd) error { cmd.Stdout = logFile cmd.Stderr = logFile cmd.Stdin = os.Stdin return cmd.Run() } if err := launcher.Launch(env, customRunner); err != nil { log.Fatal(err) } ``` -------------------------------- ### Fetch an Existing Game Instance Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Retrieve an already created instance by its name using `FetchInstance`. Instances can also be removed with `RemoveInstance` or renamed using their `.Rename` method. ```go inst, err := launcher.FetchInstance("MyInstance") ``` -------------------------------- ### Launch Game Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Launches the game using a prepared launch environment and a custom runner function. ```APIDOC ## Launch Game ### Description Launches the game using a prepared launch environment and a custom runner function. ### Method `launcher.Launch` ### Parameters #### Launch Environment - **env** (LaunchEnvironment) - Required - The prepared launch environment. #### Runner Function - **runner** (func(*exec.Cmd) error) - Required - A function to execute and monitor the game process. ### Request Example ```go err := launcher.Launch(env, myRunner) ``` ### Runner Function Example ```go func myRunner(cmd *exec.Cmd) error { cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } ``` ### Console Runner `launcher.ConsoleRunner` is a pre-built runner that copies I/O streams to the console. ``` -------------------------------- ### Download Fabric Mod Loader Libraries Source: https://github.com/telecter/cmd-launcher/wiki/Home Fetch Fabric meta data using getFabricMeta, then iterate through its libraries and download them using fetchFabricLibrary. Store the resulting paths in the same list as other libraries. Libraries are only downloaded if they do not already exist. ```javascript import { getFabricMeta, fetchFabricLibrary } from "./fabric.ts"; const paths = []; const fabricMeta = await getFabricMeta("1.20.4"); for (const fabricLibrary of fabricMeta.libraries) { const path = await fetchFabricLibrary(fabricLibrary, rootDirectory); paths.push(path); } ``` -------------------------------- ### Download Game Version Data Source: https://github.com/telecter/cmd-launcher/wiki/Home Use getVersionData to fetch all necessary information for launching a specific game version. The returned data should be typed. ```javascript import { getVersionData } from "./api.ts"; const versionData = await getVersionData("1.20.4"); ``` -------------------------------- ### Download Minecraft Client Source: https://github.com/telecter/cmd-launcher/wiki/Home Use the download function from util.ts to download the Minecraft client JAR file to the specified instance directory. The client URL is found in versionData.downloads.client.url. ```javascript import { download } from "./util.ts" await download(versionData.downloads.client.url, `${instanceDir}/client.jar`); ``` -------------------------------- ### List All Minecraft Instances Source: https://context7.com/telecter/cmd-launcher/llms.txt Lists all created Minecraft instances, displaying their index, name, version, and type (mod loader). ```bash cmd-launcher inst list ``` -------------------------------- ### Create Minecraft Instance Source: https://github.com/telecter/cmd-launcher/blob/main/README.md Creates a new Minecraft instance with a specified game version and mod loader. If no version is supplied, the latest release is used. Supported loaders include Forge, NeoForge, Fabric, and Quilt. ```sh cmd-launcher inst create -v 1.21.8 -l fabric CoolInstance ``` -------------------------------- ### Update Instance Configuration Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Updates the configuration of an existing game instance and writes the changes. ```APIDOC ## Update Instance Configuration ### Description Updates the configuration of an existing game instance and writes the changes. ### Method `instance.WriteConfig` ### Parameters #### Instance Configuration - **Config** (InstanceConfig) - Required - The new configuration for the instance. ### Request Example ```go inst.Config.MaxRam = 4096 // Example: Change max RAM inst.WriteConfig() ``` ``` -------------------------------- ### env.SetDirs Source: https://context7.com/telecter/cmd-launcher/llms.txt Initializes the launcher's data directories relative to a custom root path. This function must be called before any other API calls if a non-default location is required. ```APIDOC ## env.SetDirs ### Description Initializes launcher data directories relative to a custom root. Defaults to `~/.minecraft`. Must be called before any other API call if a non-default location is needed. ### Method `env.SetDirs(rootPath string)` ### Parameters #### Path Parameters - **rootPath** (string) - Required - The custom root directory for launcher data. ### Request Example ```go import ( "log" env "github.com/telecter/cmd-launcher/pkg" ) func main() { // Use a custom root directory if err := env.SetDirs("/opt/my-launcher"); err != nil { log.Fatal(err) } // env.InstancesDir → /opt/my-launcher/instances // env.LibrariesDir → /opt/my-launcher/libraries // env.AssetsDir → /opt/my-launcher/assets // env.JavaDir → /opt/my-launcher/java // env.AuthStorePath → /opt/my-launcher/account.json } ``` ### Response #### Success Response No explicit return value on success, errors are returned if the operation fails. #### Error Response - `error`: An error object if directory initialization fails. ``` -------------------------------- ### Define an Event Watcher Function Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Implement an `EventWatcher` function to respond to events during instance preparation, such as download progress or asset resolution. This is useful for creating progress indicators. ```go func myWatcher(event any) { switch e := event.(type) { case launcher.DownloadingEvent: ... case launcher.LibrariesResolvedEvent: ... case launcher.AssetsResolvedEvent: ... } } ``` -------------------------------- ### auth.FetchDeviceCode / auth.AuthenticateWithCode Source: https://context7.com/telecter/cmd-launcher/llms.txt Facilitates the OAuth2 Device Code Flow for headless environments. ```APIDOC ## auth.FetchDeviceCode / auth.AuthenticateWithCode – OAuth2 Device Code Flow Ideal for headless or no-browser environments. Displays a short code and URL for the user to authenticate on any device. ### Initialization * Set `auth.ClientID` to your Azure application client ID. ### Returns * **session** (*auth.Session) - The authenticated session. * **err** (error) - An error if fetching the device code or authenticating fails. ### Example ```go import ( "fmt" "log" "github.com/telecter/cmd-launcher/pkg/auth" ) func init() { auth.ClientID = "your-azure-app-client-id" } // 1. Fetch device code resp, err := auth.FetchDeviceCode() if err != nil { log.Fatal(err) } fmt.Printf("Go to %s and enter code: %s\n", resp.VerificationURI, resp.UserCode) // 2. Poll until authenticated (blocks until done or expired) session, err := auth.AuthenticateWithCode(resp) if err != nil { log.Fatal(err) } fmt.Printf("Authenticated as %s (UUID: %s)\n", session.Username, session.UUID) ``` ``` -------------------------------- ### Download Game Assets Source: https://github.com/telecter/cmd-launcher/wiki/Home First, obtain asset data using getAndSaveAssetData with the versionData.assetIndex. Then, iterate over the assetData.objects and use fetchAsset to download each asset to the root directory. ```javascript import { getAndSaveAssetData, fetchAsset } from "./api.ts"; const assetData = await getAndSaveAssetData(versionData.assetIndex, rootDirectory); for (const asset of Object.values(assetData) { await fetchAsset(asset, rootDirectory); } ``` -------------------------------- ### Create Vanilla Minecraft Instance Source: https://context7.com/telecter/cmd-launcher/llms.txt Creates a new Minecraft instance named 'MyVanilla' using the latest stable release version. This command automatically resolves the game version and mod loader. ```bash cmd-launcher inst create MyVanilla ``` -------------------------------- ### Update Instance Configuration Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md To modify an instance's configuration, update its `Config` field and then call the instance's `WriteConfig` method. ```go inst.Config = launcher.InstanceConfig{} inst.WriteConfig() ``` -------------------------------- ### Create NeoForge Instance Source: https://context7.com/telecter/cmd-launcher/llms.txt Creates a new Minecraft instance named 'NeoForgeInstance' for version 1.21.8 using the NeoForge mod loader. The `-l` flag specifies the mod loader type. ```bash cmd-launcher inst create -v 1.21.8 -l neoforge NeoForgeInstance ``` -------------------------------- ### Create Quilt Instance with Pinned Loader Version Source: https://context7.com/telecter/cmd-launcher/llms.txt Creates a new Minecraft instance named 'QuiltInstance' for version 1.21.5, pinning the Quilt loader to version 0.26.4. Use `--loader-version` to specify a particular loader version. ```bash cmd-launcher inst create -v 1.21.5 -l quilt --loader-version 0.26.4 QuiltInstance ``` -------------------------------- ### Initialize Authentication Client ID Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Set your Azure app's Client ID and Redirect URI. The Redirect URI is needed for the auth code flow and must include a port. ```go // You will want to put this in the init() function or sometime before you run any authentication functions func init() { auth.ClientID = "your client ID" // needed if you want to use the auth code flow, which requires a redirect auth.RedirectURI = "your redirect URI" } ``` -------------------------------- ### Create Fabric Instance with Specific Version Source: https://context7.com/telecter/cmd-launcher/llms.txt Creates a new Minecraft instance named 'FabricInstance' for version 1.21.8 with the latest Fabric loader. Specify the game version with `-v` and mod loader with `-l`. ```bash cmd-launcher inst create -v 1.21.8 -l fabric FabricInstance ``` -------------------------------- ### Fetch OAuth2 Device Code Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Initiate the OAuth2 device code flow by fetching a device code and authentication URI. Display the UserCode and VerificationURI to the user. ```go resp, err := auth.FetchDeviceCode() ``` -------------------------------- ### Login with Microsoft Account Source: https://github.com/telecter/cmd-launcher/blob/main/README.md Logs in a Microsoft account for online play. The default web browser will open for authentication, but this can be bypassed with the --no-browser flag. ```bash cmd-launcher auth login ``` -------------------------------- ### Search Promoted Forge Versions Source: https://context7.com/telecter/cmd-launcher/llms.txt Searches for promoted versions of the Forge mod loader. Use `--kind forge` to filter for Forge versions. ```bash cmd-launcher search --kind forge ``` -------------------------------- ### Authenticate Microsoft Account via Device Code Flow Source: https://context7.com/telecter/cmd-launcher/llms.txt Logs in to a Microsoft account using the device code flow, which does not require a browser. Use the `--no-browser` flag for this authentication method. ```bash cmd-launcher auth login --no-browser ``` -------------------------------- ### Search Fabric Loader Versions Source: https://context7.com/telecter/cmd-launcher/llms.txt Searches for all available Fabric mod loader versions. Use the `--kind` flag to specify the type of version to search for. ```bash cmd-launcher search --kind fabric ``` -------------------------------- ### Search Quilt Versions Source: https://context7.com/telecter/cmd-launcher/llms.txt Searches for Quilt mod loader versions matching the pattern '0.26'. The `--kind` flag specifies 'quilt'. ```bash cmd-launcher search 0.26 --kind quilt ``` -------------------------------- ### auth.AuthCodeURL / auth.AuthenticateWithRedirect Source: https://context7.com/telecter/cmd-launcher/llms.txt Handles the OAuth2 Authorization Code Flow by opening a browser and listening for the redirect. ```APIDOC ## auth.AuthCodeURL / auth.AuthenticateWithRedirect – OAuth2 Authorization Code Flow Opens a local HTTP server on the redirect URI's port to receive the auth code after the user authenticates in their browser. ### Initialization * Set `auth.ClientID` to your Azure application client ID. * Set `auth.RedirectURI` to your registered redirect URI (e.g., `http://localhost:9999/callback`). ### Returns * **session** (*auth.Session) - The authenticated session. * **err** (error) - An error if the authentication process fails. ### Example ```go import ( "fmt" "log" "net/url" "github.com/pkg/browser" "github.com/telecter/cmd-launcher/pkg/auth" ) func init() { auth.ClientID = "your-azure-app-client-id" auth.RedirectURI, _ = url.Parse("http://localhost:9999/callback") } // 1. Build the auth URL and open it authURL := auth.AuthCodeURL() browser.OpenURL(authURL.String()) // 2. Block until the redirect is received, then exchange the code session, err := auth.AuthenticateWithRedirect( "Login successful! You may close this tab.", "Login failed.", ) if err != nil { log.Fatal(err) } fmt.Printf("Authenticated as %s\n", session.Username) ``` ``` -------------------------------- ### Rename Instance Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Renames an existing game instance. ```APIDOC ## Rename Instance ### Description Renames an existing game instance. ### Method `instance.Rename` ### Parameters #### New Name - **newName** (string) - Required - The new name for the instance. ### Request Example `inst.Rename("NewInstanceName")` ``` -------------------------------- ### Search Minecraft or Mod Loader Versions Source: https://github.com/telecter/cmd-launcher/blob/main/README.md Use the 'search' command to find game versions or specific mod loader versions (Fabric, Quilt, Forge). It defaults to searching for game versions if no kind is specified. ```bash cmd-launcher search [] [--kind {versions, fabric, quilt, forge}] ``` -------------------------------- ### auth.ReadFromCache / auth.Authenticate Source: https://context7.com/telecter/cmd-launcher/llms.txt Loads the cached session tokens from disk and refreshes them if necessary. ```APIDOC ## auth.ReadFromCache / auth.Authenticate – Load and Refresh Stored Session Loads the cached token store from disk and refreshes any expired tokens through the MSA → XBL → XSTS → Minecraft chain. Returns `auth.ErrNoAccount` if no account has been added yet. ### Returns * **session** (*auth.Session) - The authenticated session. * **err** (error) - An error if reading from cache or authentication fails. Returns `auth.ErrNoAccount` if no account is found. ### Example ```go import ( "errors" "fmt" "log" "github.com/telecter/cmd-launcher/pkg/auth" ) // Load cached tokens at startup if err := auth.ReadFromCache(); err != nil { log.Fatal(err) } // Get a valid session, refreshing tokens as needed session, err := auth.Authenticate() if errors.Is(err, auth.ErrNoAccount) { fmt.Println("No account – please log in first") } else if err != nil { log.Fatalf("auth: %v", err) } else { fmt.Printf("Logged in as %s (%s)\n", session.Username, session.UUID) } ``` ``` -------------------------------- ### Create Forge Instance Source: https://context7.com/telecter/cmd-launcher/llms.txt Creates a new Minecraft instance named 'ForgeInstance' for version 1.20.1, using the Forge mod loader. This command selects the latest applicable Forge version for the specified game version. ```bash cmd-launcher inst create -v 1.20.1 -l forge ForgeInstance ``` -------------------------------- ### Search Versions in Reverse Order Source: https://context7.com/telecter/cmd-launcher/llms.txt Searches for Minecraft versions matching '1.20' and reverses the order of the results. Use the `--reverse` flag to change the sort order. ```bash cmd-launcher search 1.20 --reverse ``` -------------------------------- ### OAuth2 Authorization Code Flow Source: https://context7.com/telecter/cmd-launcher/llms.txt Initiates an OAuth2 authorization code flow by opening a browser and listening for the redirect. Requires setting ClientID and RedirectURI. ```go import ( "fmt" "log" "net/url" "github.com/pkg/browser" "github.com/telecter/cmd-launcher/pkg/auth" ) func init() { auth.ClientID = "your-azure-app-client-id" auth.RedirectURI, _ = url.Parse("http://localhost:9999/callback") } // 1. Build the auth URL and open it authURL := auth.AuthCodeURL() browser.OpenURL(authURL.String()) // 2. Block until the redirect is received, then exchange the code session, err := auth.AuthenticateWithRedirect( "Login successful! You may close this tab.", "Login failed.", ) if err != nil { log.Fatal(err) } fmt.Printf("Authenticated as %s\n", session.Username) ``` -------------------------------- ### Load and Refresh Stored Session Source: https://context7.com/telecter/cmd-launcher/llms.txt Loads cached tokens from disk and refreshes expired ones. Returns ErrNoAccount if no account is found, requiring an initial login. ```go import ( "errors" "fmt" "log" "github.com/telecter/cmd-launcher/pkg/auth" ) // Load cached tokens at startup if err := auth.ReadFromCache(); err != nil { log.Fatal(err) } // Get a valid session, refreshing tokens as needed session, err := auth.Authenticate() if errors.Is(err, auth.ErrNoAccount) { fmt.Println("No account – please log in first") } else if err != nil { log.Fatalf("auth: %v", err) } else { fmt.Printf("Logged in as %s (%s)\n", session.Username, session.UUID) } ``` -------------------------------- ### Search Minecraft Versions Source: https://context7.com/telecter/cmd-launcher/llms.txt Searches for Minecraft versions matching the query '1.21'. This is the default search behavior. ```bash cmd-launcher search 1.21 ``` -------------------------------- ### OAuth2 Device Code Flow Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Initiates the OAuth2 device code flow by fetching device codes and then authenticating using the provided code. ```APIDOC ## OAuth2 Device Code Flow ### Description This flow allows users to authenticate on a separate device by displaying a user code and verification URI. ### Fetch Device Code #### Method Call the `FetchDeviceCode` function to get the device code and verification URI. #### Code ```go resp, err := auth.FetchDeviceCode() ``` ### Authenticate with Code #### Description Poll the endpoint for authentication updates using the device code response to get a session. #### Method Call the `AuthenticateWithCode` function with the device code response. #### Code ```go session, err := auth.AuthenticateWithCode(resp) ``` ``` -------------------------------- ### Log Out Microsoft Account Source: https://context7.com/telecter/cmd-launcher/llms.txt Removes the currently stored Microsoft account credentials from cmd-launcher. ```bash cmd-launcher auth logout ``` -------------------------------- ### OAuth2 Auth Code Flow Source: https://github.com/telecter/cmd-launcher/blob/main/docs/API.md Initiates the OAuth2 auth code flow by generating an authentication URL and then authenticating using the redirect. ```APIDOC ## Initialize Authentication ### Description Initialize the ClientID and RedirectURI before performing authentication. ### Code ```go func init() { auth.ClientID = "your client ID" auth.RedirectURI = "your redirect URI" } ``` ## OAuth2 Auth Code Flow ### Description This flow involves generating an authentication URL, directing the user to it, and then authenticating with the redirect. ### Get Auth URL #### Method Call the `AuthCodeURL` function to get the authentication URL. #### Code ```go url := auth.AuthCodeURL() ``` ### Authenticate with Redirect #### Description After the user authenticates via the redirect URI, call this function to obtain a session. #### Method Call the `AuthenticateWithRedirect` function. #### Code ```go session, err := auth.AuthenticateWithRedirect() ``` ```